{
  "openapi": "3.0.3",
  "info": {
    "title": "Integração Externa - Leads, Oportunidades, Tarefas, Arquivos, Propostas, Chats, Satisfação e Campos Personalizados",
    "version": "1.0.0",
    "description": "Documentação oficial da API externa da Wegly para campos personalizados, leads, oportunidades, tarefas, arquivos, propostas, chats e satisfação (`/integrations/external/custom-fields`, `/integrations/external/files`, `/integrations/external/leads`, `/integrations/external/deals`, `/integrations/external/tasks`, `/integrations/external/proposals`, `/integrations/external/chats` e `/integrations/external/satisfaction`). Todas as descrições estão em português e refletem as regras aplicadas pelo serviço.\n"
  },
  "servers": [
    {
      "url": "https://api.wegly.com.br",
      "description": "Ambiente de produção Wegly"
    }
  ],
  "tags": [
    {
      "name": "Campos Personalizados",
      "description": "Consulta dos campos personalizados disponíveis para uso nas integrações externas."
    },
    {
      "name": "Arquivos",
      "description": "Upload e consulta de arquivos vinculados diretamente a leads ou oportunidades. Arquivos de proposta usam as rotas de anexos em Propostas."
    },
    {
      "name": "Leads",
      "description": "Operações de listagem, criação, consulta e atualização de leads via integração externa."
    },
    {
      "name": "Oportunidades",
      "description": "Operações de criação de oportunidades (deals) via integração externa."
    },
    {
      "name": "Tarefas",
      "description": "Operações de listagem, criação, consulta, atualização e remoção de tarefas vinculadas a leads, oportunidades, entregas, pessoas, organizações ou clientes."
    },
    {
      "name": "Satisfação",
      "description": "Geração de links públicos para formulários de satisfação via integração externa."
    },
    {
      "name": "Propostas",
      "description": "Operações de listagem, criação, consulta, atualização e remoção de propostas via integração externa, incluindo seus anexos (arquivos e documentos da biblioteca)."
    },
    {
      "name": "Chats",
      "description": "Operações principais de listagem, criação, consulta e resumo de não lidas de chats via integração externa."
    }
  ],
  "security": [
    {
      "bearerAuth": []
    }
  ],
  "paths": {
    "/integrations/external/chats": {
      "get": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsList",
        "summary": "Listar chats",
        "description": "Lista WhatsApp e Instagram em ordenação unificada. Reutilize next_cursor para paginação estável. Filtros positivos de agendamento, Copilot e resposta do cliente excluem conversas Instagram. Registros de WhatsApp incluem `ai_attendance`, com o resumo do atendimento por agente de IA. Permissão da chave: crm/chats.read. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "search",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            },
            "description": "No WhatsApp, procura no nome do perfil do contato e no nome da pessoa vinculada; termos com formato de telefone também procuram no número do contato, com ou sem o nono dígito."
          },
          {
            "name": "skip",
            "in": "query",
            "required": false,
            "schema": {
              "type": "number",
              "default": 0
            },
            "description": "Quantidade de registros a pular; valores negativos são normalizados para zero."
          },
          {
            "name": "take",
            "in": "query",
            "required": false,
            "schema": {
              "type": "number",
              "default": 10
            },
            "description": "Quantidade por página. O serviço limita o resultado a 50 registros."
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            },
            "description": "Cursor opaco retornado em next_cursor; substitui o avanço por skip."
          },
          {
            "name": "channel_type",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "enum": [
                "WHATSAPP",
                "INSTAGRAM"
              ]
            },
            "description": "Sem filtro, combina os canais."
          },
          {
            "name": "channel_account_id",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "ID da conta do canal; sem channel_type, direciona a consulta a Instagram."
          },
          {
            "name": "phone_id",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "ID do número WhatsApp; direciona a consulta a WhatsApp."
          },
          {
            "name": "status",
            "in": "query",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/ChatStatusEnum"
            },
            "description": ""
          },
          {
            "name": "archived",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "enum": [
                "include",
                "only"
              ]
            },
            "description": "Padrão exclui arquivados; include inclui todos; only retorna apenas arquivados."
          },
          {
            "name": "priority",
            "in": "query",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/ChatPriorityValue"
            },
            "description": ""
          },
          {
            "name": "responsible_user_id",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "Filtro de responsável do WhatsApp; atualmente exclui Instagram. Um usuário que não é atendente do WhatsApp retorna lista vazia."
          },
          {
            "name": "person_id",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": ""
          },
          {
            "name": "unread_only",
            "in": "query",
            "required": false,
            "schema": {
              "type": "boolean"
            },
            "description": "true considera unread_count > 0 ou is_manually_unread=true."
          },
          {
            "name": "has_scheduled_messages",
            "in": "query",
            "required": false,
            "schema": {
              "type": "boolean"
            },
            "description": "true filtra WhatsApp com mensagem agendada PENDING/PROCESSING, independentemente da data."
          },
          {
            "name": "has_pending_copilot_actions",
            "in": "query",
            "required": false,
            "schema": {
              "type": "boolean"
            },
            "description": "true filtra WhatsApp com ações pendentes de revisão."
          },
          {
            "name": "customer_reply_status",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "enum": [
                "initial_replied",
                "initial_not_replied",
                "not_replied_last_messages"
              ]
            },
            "description": "Filtro de resposta do cliente em conversas WhatsApp."
          },
          {
            "name": "customer_reply_message_count",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 50
            },
            "description": "Quantidade de mensagens sem resposta (padrão efetivo 1), usada por not_replied_last_messages."
          }
        ],
        "responses": {
          "200": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChatListResponse"
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      },
      "post": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsCreate",
        "summary": "Criar chat com template",
        "description": "Cria ou reutiliza um chat WhatsApp e envia o template inicial. Informe wa_contact_id ou person_contact_id. assigned_agent_id é ID do agente, não do usuário. A rota não recebe arquivos: mídia de cabeçalho do template deve ser informada por URL. Permissão da chave: crm/chats.create. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateExternalChat"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChatSummary"
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      }
    },
    "/integrations/external/chats/{id}": {
      "get": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsFindOne",
        "summary": "Consultar detalhes do chat",
        "description": "Consulta WhatsApp ou Instagram. A estrutura de mídia e os metadados de canal variam conforme channel_type. Permissão da chave: crm/chats.read. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          }
        ],
        "responses": {
          "200": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "anyOf": [
                    {
                      "$ref": "#/components/schemas/ChatDetails"
                    },
                    {
                      "$ref": "#/components/schemas/ChatInstagramDetails"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      }
    },
    "/integrations/external/chats/{id}/messages": {
      "get": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsMessages",
        "summary": "Listar mensagens",
        "description": "Mensagens de WhatsApp ou Instagram. total representa toda a consulta. quoted_message.page indica a página da mensagem citada. Permissão da chave: crm/chats.read. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          },
          {
            "name": "search",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            },
            "description": "Busca textual, quando suportada pela operação."
          },
          {
            "name": "skip",
            "in": "query",
            "required": false,
            "schema": {
              "type": "number",
              "default": 0
            },
            "description": "Quantidade de registros a pular; valores negativos são normalizados para zero."
          },
          {
            "name": "take",
            "in": "query",
            "required": false,
            "schema": {
              "type": "number",
              "default": 20
            },
            "description": "Quantidade por página. O serviço limita o resultado a 100 registros."
          },
          {
            "name": "order",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "enum": [
                "asc",
                "desc"
              ],
              "default": "desc"
            },
            "description": "Ordenação cronológica das mensagens/eventos."
          }
        ],
        "responses": {
          "200": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChatMessageListResponse"
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      },
      "post": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsSendMessage",
        "summary": "Enviar mensagem",
        "description": "Envio síncrono WhatsApp: aguarda o retorno imediato do provedor. Exige conteúdo ou anexos; fora da janela é necessário template. Texto e arquivos podem gerar vários records. Tipos interactive e location exigem as rotas próprias. Envio manual pode atribuir responsável e pausar fluxo WhatsApp ativo. `type` assume text quando omitido; para template, envie type=template e não envie body, pois o texto é enviado no lugar do template. Com type=template, os arquivos enviados servem apenas como mídia do cabeçalho. Cada arquivo aceita até 100 MB (16 MB para áudio); a falha de um arquivo volta em records com status=failed, ainda com resposta 201. Permissão da chave: crm/chats.write. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SendExternalChatMessage"
              },
              "examples": {
                "texto": {
                  "value": {
                    "type": "text",
                    "body": "Olá, tudo bem?"
                  }
                },
                "template": {
                  "value": {
                    "type": "template",
                    "template": {
                      "name": "saudacao_inicial",
                      "language": "pt_BR"
                    },
                    "template_fields": [
                      {
                        "component": "BODY",
                        "type": "TEXT",
                        "index": 1,
                        "value": "João"
                      }
                    ]
                  }
                }
              }
            },
            "multipart/form-data": {
              "schema": {
                "$ref": "#/components/schemas/SendExternalChatMessageMultipart"
              },
              "encoding": {
                "template": {
                  "contentType": "application/json"
                },
                "template_fields": {
                  "contentType": "application/json"
                },
                "files": {
                  "style": "form",
                  "explode": true
                },
                "file": {
                  "style": "form",
                  "explode": true
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChatMessagesResponse"
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      }
    },
    "/integrations/external/chats/notifications/unread": {
      "get": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsUnreadNotifications",
        "summary": "Consultar notificações não lidas",
        "description": "Agrega WhatsApp e Instagram no escopo acessível. unread_messages_total soma mensagens; unread_chats_total também considera marcação manual de não lido. Conversas arquivadas não entram na contagem. Permissão da chave: crm/chats.read. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "responses": {
          "200": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChatUnreadSummary"
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      }
    },
    "/integrations/external/custom-fields": {
      "get": {
        "tags": [
          "Campos Personalizados"
        ],
        "summary": "Listagem de campos personalizados",
        "description": "Retorna os campos personalizados cadastrados para a empresa associada à chave de integração. - O resultado respeita o escopo da empresa da chave. - O ator da operação é o usuário que criou a chave, reaproveitando as mesmas regras do módulo interno. - `entity_type` permite filtrar por campos de lead (`1`), oportunidade (`2`), entrega (`3`) ou proposta (`4`). - `status` permite limitar o retorno para campos ativos (`1`) ou inativos (`0`).\n",
        "parameters": [
          {
            "$ref": "#/components/parameters/CustomFieldSearch"
          },
          {
            "$ref": "#/components/parameters/Skip"
          },
          {
            "name": "take",
            "in": "query",
            "description": "Quantidade de registros a retornar. Envie explicitamente para limitar a página.",
            "schema": {
              "type": "integer",
              "minimum": 1
            }
          },
          {
            "$ref": "#/components/parameters/CustomFieldEntityType"
          },
          {
            "$ref": "#/components/parameters/CustomFieldStatus"
          }
        ],
        "responses": {
          "200": {
            "description": "Lista paginada de campos personalizados cadastrados.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "total": {
                      "type": "integer",
                      "description": "Quantidade total de registros que atendem aos filtros."
                    },
                    "records": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/ExternalCustomField"
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/custom-field.read` ausente na chave ou usuário criador da chave inativo."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          },
          "400": {
            "description": "Parâmetros de consulta inválidos."
          }
        }
      }
    },
    "/integrations/external/deals": {
      "get": {
        "tags": [
          "Oportunidades"
        ],
        "summary": "Listagem de oportunidades",
        "description": "Retorna oportunidades da empresa associada à chave de integração com paginação e filtros. A visibilidade segue o usuário criador da chave (público, equipe/responsável ou privado).\n\n\nFiltros de tarefas relacionadas não são suportados nesta API externa: pending_task_status, task_start_date_from, task_start_date_to, task_type_ids e related_task_completion_scope retornam 400 quando informados. Resumos de chats dependem de crm/chats.read na própria chave; sem essa permissão, as flags são false e as coleções vazias. count_only=true retorna total e records: [], sem projetar dados adicionais.",
        "parameters": [
          {
            "name": "search",
            "in": "query",
            "description": "Busca textual por título ou código (quando numérico).",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "skip",
            "in": "query",
            "description": "Quantidade de registros a pular (offset). Padrão 0.",
            "schema": {
              "type": "integer",
              "minimum": 0,
              "default": 0
            }
          },
          {
            "name": "take",
            "in": "query",
            "description": "Limite de registros da página. Envie explicitamente para limitar o resultado; sem take, a consulta não aplica limite de página.",
            "schema": {
              "type": "integer",
              "minimum": 1
            }
          },
          {
            "name": "status",
            "in": "query",
            "description": "Status da oportunidade (1 = aberta, 2 = ganha, 3 = perdida).",
            "schema": {
              "$ref": "#/components/schemas/OpportunityStatusEnum"
            }
          },
          {
            "name": "stage_id",
            "in": "query",
            "description": "Filtra pelo ID do estágio.",
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          },
          {
            "name": "pipeline_id",
            "in": "query",
            "description": "Filtra pelo ID do pipeline (funil).",
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          },
          {
            "name": "archived",
            "in": "query",
            "description": "Controle de arquivamento de oportunidades.",
            "schema": {
              "$ref": "#/components/schemas/OpportunityArchivedFilter"
            }
          },
          {
            "name": "temperature",
            "in": "query",
            "description": "Temperatura da oportunidade (1 = frio, 2 = morno, 3 = quente).",
            "schema": {
              "$ref": "#/components/schemas/OpportunityTemperature"
            }
          },
          {
            "name": "crm_lead_source_id",
            "in": "query",
            "description": "Filtra pela origem de lead (UUID). Compara com a origem efetiva: a da aquisição mais recente e, na falta dela, a gravada no registro.",
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          },
          {
            "name": "lead_sources",
            "in": "query",
            "description": "Lista de origens separadas por vírgula ou array. Aceita IDs, nomes de origem e o valor `unknown` (sem origem). Sem `attribution_mode`, compara com a origem efetiva do registro.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "won",
            "in": "query",
            "description": "Filtro de ganhos (include = inclui ganhos, only = somente ganhos).",
            "schema": {
              "$ref": "#/components/schemas/LeadResultFilter"
            }
          },
          {
            "name": "lost",
            "in": "query",
            "description": "Filtro de perdas (include = inclui perdidos, only = somente perdidos).",
            "schema": {
              "$ref": "#/components/schemas/LeadResultFilter"
            }
          },
          {
            "name": "quality_rating_from",
            "in": "query",
            "description": "Nota mínima de qualificação (1 a 5).",
            "schema": {
              "type": "integer",
              "enum": [
                1,
                2,
                3,
                4,
                5
              ]
            }
          },
          {
            "name": "quality_rating_to",
            "in": "query",
            "description": "Nota máxima de qualificação (1 a 5).",
            "schema": {
              "type": "integer",
              "enum": [
                1,
                2,
                3,
                4,
                5
              ]
            }
          },
          {
            "name": "campaigns",
            "in": "query",
            "description": "Códigos ou textos de campanha (suporta lista ou string separada por vírgulas).",
            "schema": {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "ad_sets",
            "in": "query",
            "description": "Códigos ou textos de conjuntos de anúncios.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "contents",
            "in": "query",
            "description": "Códigos ou textos de conteúdo.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "displayed_on",
            "in": "query",
            "description": "Locais de exibição.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "conversion_tools",
            "in": "query",
            "description": "Ferramentas de conversão.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "creatives",
            "in": "query",
            "description": "Criativos utilizados.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "search_terms",
            "in": "query",
            "description": "Termos de busca (utm_search_term/utm_term).",
            "schema": {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "urls",
            "in": "query",
            "description": "URLs de conversão.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "products",
            "in": "query",
            "description": "IDs de produtos vinculados ao lead ou propostas.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string",
                "format": "uuid"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "responsible_id",
            "in": "query",
            "description": "Filtra pelo responsável (UUID).",
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          },
          {
            "name": "created_from",
            "in": "query",
            "description": "Data inicial de criação (ISO8601).",
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "created_to",
            "in": "query",
            "description": "Data final de criação (ISO8601).",
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "expected_close_from",
            "in": "query",
            "description": "Data inicial prevista de fechamento (ISO8601).",
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "expected_close_to",
            "in": "query",
            "description": "Data final prevista de fechamento (ISO8601).",
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "last_activity_from",
            "in": "query",
            "description": "Data inicial da última atividade (ISO8601).",
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "last_activity_to",
            "in": "query",
            "description": "Data final da última atividade (ISO8601).",
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "won_from",
            "in": "query",
            "description": "Data inicial de ganho (ISO8601).",
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "won_to",
            "in": "query",
            "description": "Data final de ganho (ISO8601).",
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "lost_from",
            "in": "query",
            "description": "Data inicial de perda (ISO8601).",
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "lost_to",
            "in": "query",
            "description": "Data final de perda (ISO8601).",
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "order_by",
            "in": "query",
            "description": "Campo para ordenação; os valores aceitos diferem entre leads e oportunidades.",
            "schema": {
              "$ref": "#/components/schemas/OpportunityOrderBy"
            }
          },
          {
            "name": "order_direction",
            "in": "query",
            "description": "Direção de ordenação.",
            "schema": {
              "$ref": "#/components/schemas/LeadOrderDirection"
            }
          },
          {
            "name": "only_new",
            "in": "query",
            "description": "Quando true, retorna apenas leads sem visualizações. A consulta por ID registra uma visualização do criador da chave e tira o registro deste filtro.",
            "schema": {
              "type": "boolean"
            }
          },
          {
            "name": "only_without_quality_rating",
            "in": "query",
            "description": "Quando true, retorna apenas leads sem nota de qualidade.",
            "schema": {
              "type": "boolean"
            }
          },
          {
            "name": "without_lead_source",
            "in": "query",
            "description": "Quando true, retorna apenas leads sem origem associada.",
            "schema": {
              "type": "boolean"
            }
          },
          {
            "name": "all_statuses",
            "in": "query",
            "description": "Quando true, ignora todos os filtros de status (inclui abertos, ganhos, perdidos e arquivados).",
            "schema": {
              "type": "boolean"
            }
          },
          {
            "name": "crm_loss_reason_ids",
            "in": "query",
            "description": "Lista de IDs de motivos de perda (UUID ou literal `unknown` para leads sem motivo).",
            "schema": {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "tags",
            "in": "query",
            "description": "Lista de IDs de tags (UUIDs) separados por vírgula ou array.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "person_id",
            "in": "query",
            "description": "Filtra pelo identificador de pessoa participante.",
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          },
          {
            "name": "organization_id",
            "in": "query",
            "description": "Filtra pelo identificador de organização.",
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          },
          {
            "name": "created_by",
            "in": "query",
            "description": "Filtra pelo identificador de usuário criador.",
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          },
          {
            "name": "excluded_ids",
            "in": "query",
            "description": "IDs de registros a excluir, separados por vírgula ou parâmetro repetido.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string",
                "format": "uuid"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "partner_ids",
            "in": "query",
            "description": "IDs de parceiros associados, separados por vírgula ou parâmetro repetido.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string",
                "format": "uuid"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "follower_ids",
            "in": "query",
            "description": "IDs de usuários seguidores, separados por vírgula ou parâmetro repetido.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string",
                "format": "uuid"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "responsible_ids",
            "in": "query",
            "description": "IDs de responsáveis, separados por vírgula ou parâmetro repetido.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string",
                "format": "uuid"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "icp_ids",
            "in": "query",
            "description": "IDs de ICPs associados, separados por vírgula ou parâmetro repetido.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string",
                "format": "uuid"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "only_followed_by_me",
            "in": "query",
            "description": "Somente registros seguidos pelo usuário que criou a chave.",
            "schema": {
              "type": "boolean"
            }
          },
          {
            "name": "without_icp",
            "in": "query",
            "description": "Somente registros sem ICP.",
            "schema": {
              "type": "boolean"
            }
          },
          {
            "name": "only_without_score",
            "in": "query",
            "description": "Somente registros sem pontuação de lead score.",
            "schema": {
              "type": "boolean"
            }
          },
          {
            "name": "count_only",
            "in": "query",
            "description": "Retorna apenas total e records vazio, sem projection_context.",
            "schema": {
              "type": "boolean"
            }
          },
          {
            "name": "abandoned",
            "in": "query",
            "description": "Aplica o critério de abandono configurado pela empresa.",
            "schema": {
              "type": "boolean"
            }
          },
          {
            "name": "score_from",
            "in": "query",
            "description": "Limite mínimo de lead score.",
            "schema": {
              "type": "integer",
              "minimum": 0,
              "maximum": 100
            }
          },
          {
            "name": "score_to",
            "in": "query",
            "description": "Limite máximo de lead score.",
            "schema": {
              "type": "integer",
              "minimum": 0,
              "maximum": 100
            }
          },
          {
            "name": "attribution_mode",
            "in": "query",
            "description": "Modo de atribuição para os filtros de marketing; modos por período dependem dos limites temporais correspondentes.",
            "schema": {
              "type": "string",
              "enum": [
                "any_touch",
                "current_attribution",
                "last_touch_at_won",
                "last_touch_at_period_end",
                "last_touch_at_created_period_end"
              ]
            }
          },
          {
            "name": "stagnation_status",
            "in": "query",
            "description": "Estado de estagnação na etapa.",
            "schema": {
              "type": "string",
              "enum": [
                "not_stagnant",
                "stagnant",
                "stagnant_with_future_task"
              ]
            }
          },
          {
            "name": "customer_reply_status",
            "in": "query",
            "description": "Situação da resposta do cliente no WhatsApp.",
            "schema": {
              "type": "string",
              "enum": [
                "initial_replied",
                "initial_not_replied",
                "not_replied_last_messages"
              ]
            }
          },
          {
            "name": "customer_reply_message_count",
            "in": "query",
            "description": "Quantidade de mensagens consideradas pelo filtro de últimas mensagens sem resposta.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 50,
              "default": 1
            }
          },
          {
            "name": "custom_field_filters",
            "in": "query",
            "description": "Array serializado em JSON; cada filtro exige id e aceita value, option_id ou option_ids, conforme o tipo do campo.",
            "schema": {
              "type": "string",
              "description": "JSON serializado de um array de filtros.",
              "example": "[{\"id\":\"123e4567-e89b-42d3-a456-426614174000\",\"value\":\"Enterprise\"}]"
            }
          },
          {
            "name": "lead_created_from",
            "in": "query",
            "description": "Início do período de criação do lead associado.",
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "lead_created_to",
            "in": "query",
            "description": "Fim do período de criação do lead associado.",
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "only_without_expected_close_date",
            "in": "query",
            "description": "Somente oportunidades sem data prevista de fechamento.",
            "schema": {
              "type": "boolean"
            }
          },
          {
            "name": "crm_gain_reason_ids",
            "in": "query",
            "description": "IDs de motivos de ganho, separados por vírgula ou parâmetro repetido.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            "style": "form",
            "explode": false
          }
        ],
        "responses": {
          "200": {
            "description": "Lista paginada de oportunidades.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "total": {
                      "type": "integer"
                    },
                    "records": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/OpportunitySummary"
                      }
                    },
                    "projection_context": {
                      "$ref": "#/components/schemas/CrmProjectionContext"
                    }
                  },
                  "required": [
                    "total",
                    "records"
                  ]
                }
              }
            }
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/deal.read` ausente na chave."
          },
          "400": {
            "description": "Filtro inválido ou filtro de tarefas relacionadas não suportado pela API externa."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      },
      "post": {
        "tags": [
          "Oportunidades"
        ],
        "summary": "Criação de oportunidades",
        "description": "Cria uma oportunidade (deal) usando a chave de integração, aplicando as mesmas validações internas: estágio/responsável padrão quando omitidos (um `responsible_id` inativo ou arquivado é substituído pelo usuário master da conta, com nota automática), conflito proibido entre `organization_id` e `organization`, origem manual aceita apenas por `crm_lead_source_id` (`lead_source` não é suportado), deduplicação de pessoa quando `avoid_duplicate` e `duplicate_check_types` forem enviados, rastreio de marketing por `wegly_code` (quando `crm_lead_source_id` também é enviado, é ele que define a origem retornada em `deal_source`), fallback de origem por `wegly_source`/`utm_source` e extração automática de parâmetros da `url_conversion`, criação de ferramenta de conversão quando necessário e registro opcional de nota inicial/seguidores. Consentimento top-level, alias legado e URL são validados antes da idempotência e da deduplicação; divergência retorna 400 sem reservar evento, alterar pessoa ou criar oportunidade.\n\n\nAceita x-idempotency-key no header ou idempotency_key no body. Uma criação já concluída retorna o mesmo id, code e title com measurement_consent efetivo. Uma tentativa ainda em processamento retorna 409. Se a criação falhar depois de iniciada (referência inexistente, campo personalizado obrigatório ausente ou erro em seguidores/nota), a chave fica consumida e continua retornando 409; envie uma nova chave. Todos os campos personalizados obrigatórios da entidade precisam ser enviados. Seguidores e nota são gravados depois do registro: se falharem, a resposta é de erro, mas o registro permanece criado. Webhooks e notificações podem ser entregues de forma assíncrona após a resposta. measurement_consent é canônico; valores conflitantes com marketing.measurement_consent ou a URL retornam 400 antes das mutações.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateExternalOpportunity"
              },
              "examples": {
                "criacaoOportunidade": {
                  "summary": "Cadastro de oportunidade com rastreio e deduplicação de pessoa",
                  "value": {
                    "title": "Implementação completa CRM",
                    "value": 75000.5,
                    "measurement_consent": "GRANTED",
                    "expected_close_date": "2024-03-15T00:00:00.000Z",
                    "quality_rating": 4,
                    "quality_reason": "Cliente com budget aprovado",
                    "visibility": 0,
                    "temperature": 3,
                    "crm_lead_source_id": "a6e77b5f-4d66-4e78-b15f-c0e8a16db962",
                    "marketing": {
                      "url_conversion": "https://landing.wegly.com.br/obrigado?wegly_code=OPP123&utm_campaign=crm-enterprise&gclid=XYZ"
                    },
                    "tags": [
                      "3f6f2a5e-1c7b-4d2a-9e8f-5a4b3c2d1e0f",
                      "7b1d9c4e-2a3f-4b5c-8d6e-0f1a2b3c4d5e"
                    ],
                    "person": {
                      "name": "Roberto Martins",
                      "contacts": [
                        {
                          "type": 0,
                          "value": "(11) 99988-7766"
                        }
                      ],
                      "avoid_duplicate": true,
                      "duplicate_check_types": [
                        0
                      ]
                    },
                    "organization": {
                      "name": "Tech Innovators S.A."
                    },
                    "followers": [
                      {
                        "user_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
                        "role_id": "b2c3d4e5-f6a7-8901-bcde-f23456789012"
                      }
                    ],
                    "note": {
                      "content": "Oportunidade originada da campanha enterprise.",
                      "is_pinned": true
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Oportunidade criada com sucesso.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpportunityCreateResult"
                }
              }
            }
          },
          "400": {
            "description": "Validação de dados falhou (IDs inexistentes, `lead_source` não suportado, conflitos de parâmetros, etc). Inclui telefone fora do formato de 10 ou 11 dígitos, campo personalizado obrigatório ausente e responsável inexistente."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/deal.create` ausente na chave ou usuário criador da chave inativo."
          },
          "409": {
            "description": "Já existe uma criação em processamento para esta chave de idempotência, ou a chave foi consumida por uma tentativa que falhou depois de iniciada."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        },
        "parameters": [
          {
            "name": "x-idempotency-key",
            "in": "header",
            "required": false,
            "description": "Chave da tentativa lógica de criação. Tem prioridade sobre idempotency_key no body; mantenha a mesma chave ao repetir uma chamada sem resposta e use uma nova depois de uma criação que falhou após iniciada.",
            "schema": {
              "type": "string"
            }
          }
        ]
      }
    },
    "/integrations/external/deals/{id}": {
      "get": {
        "tags": [
          "Oportunidades"
        ],
        "summary": "Consulta de oportunidade",
        "description": "Retorna detalhes completos da oportunidade informada, incluindo propostas e produtos diretos associados. O `id` pode ser UUID ou o código numérico interno.\n\n\nOs resumos de chats dependem exclusivamente de crm/chats.read na chave. Sem esse grant, flags são false e listas de chats são vazias. A resposta inclui valuation e projection_context para os valores comerciais e seus critérios de exibição. Cada consulta registra uma visualização do usuário criador da chave: views_count aumenta e o registro deixa de aparecer em only_new=true.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "UUID ou código sequencial do registro."
          }
        ],
        "responses": {
          "200": {
            "description": "Detalhes da oportunidade.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpportunityDetails"
                }
              }
            }
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/deal.read` ausente na chave."
          },
          "404": {
            "description": "Oportunidade não encontrada ou inacessível ao usuário da chave."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      },
      "put": {
        "tags": [
          "Oportunidades"
        ],
        "summary": "Atualização de oportunidade",
        "description": "Atualiza campos da oportunidade. O campo `lead_source` não é aceito; use `crm_lead_source_id`. Conflitos entre `organization_id` e `organization` são rejeitados. Pessoas marcadas com `delete: true` em `persons_id` são removidas; `organization_id: null` remove a organização. `marketing` corrige a aquisição atual (omitidos são preservados e `null` limpa o valor) e `crm_lead_source_id: null` remove a origem. `custom_fields`, quando enviado com itens, substitui todas as respostas. `tags` são acrescentadas às existentes. `value` é ignorado quando a oportunidade negocia por produtos ou por proposta. `status` não preenche `won_date`/`lost_date` automaticamente e gera o webhook `deal.updated`, não `deal.won`/`deal.lost`. Consentimento top-level, alias legado e URL são validados antes de qualquer mutação; divergência retorna 400 sem atualizar a oportunidade ou associações.\n\n\nO campo title é obrigatório. Retorna um resumo da atualização; consulte GET para obter as associações atualizadas. organization_id: null remove a organização; persons_id com delete: true remove participantes.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID do registro."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateExternalOpportunity"
              },
              "examples": {
                "atualizacaoConsentimento": {
                  "summary": "Atualização do consentimento de mensuração",
                  "value": {
                    "title": "Implementação completa CRM",
                    "measurement_consent": "DENIED"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Oportunidade atualizada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpportunityUpdateResult"
                }
              }
            }
          },
          "400": {
            "description": "Validação de dados falhou (IDs inexistentes, conflitos de parâmetros, estágio inválido, etc)."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/deal.update` ausente na chave ou usuário criador da chave inativo."
          },
          "404": {
            "description": "Oportunidade não encontrada ou inacessível ao usuário da chave."
          },
          "409": {
            "description": "Oportunidade alterado por outra operação durante a atualização. Consulte o registro e reenvie."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      }
    },
    "/integrations/external/files": {
      "get": {
        "tags": [
          "Arquivos"
        ],
        "summary": "Listagem de arquivos por contexto",
        "description": "Lista arquivos vinculados a um lead ou negócio. - É obrigatório informar exatamente um contexto entre `crm_lead_id`, `crm_deal_id`, `lead_code` ou `deal_code`. - `lead_code` e `deal_code` resolvem o registro acessível do usuário criador da chave antes da consulta. - O retorno segue o formato plano do módulo interno, com URL assinada por arquivo.\n",
        "parameters": [
          {
            "$ref": "#/components/parameters/Search"
          },
          {
            "$ref": "#/components/parameters/Skip"
          },
          {
            "name": "take",
            "in": "query",
            "description": "Quantidade de registros a retornar. Envie explicitamente para limitar a página.",
            "schema": {
              "type": "integer",
              "minimum": 1
            }
          },
          {
            "name": "crm_lead_id",
            "in": "query",
            "description": "UUID do lead de contexto.",
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          },
          {
            "name": "crm_deal_id",
            "in": "query",
            "description": "UUID do negócio de contexto.",
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          },
          {
            "name": "lead_code",
            "in": "query",
            "description": "Código numérico interno do lead de contexto.",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "deal_code",
            "in": "query",
            "description": "Código numérico interno do negócio de contexto.",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Lista paginada de arquivos do contexto solicitado.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalFilesListResponse"
                }
              }
            }
          },
          "400": {
            "description": "Validação de dados falhou (contexto ausente ou múltiplo)."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/file.read` ausente na chave."
          },
          "404": {
            "description": "Lead ou negócio não encontrado, ou fora do escopo de leitura do usuário criador da chave."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      }
    },
    "/integrations/external/files/{id}": {
      "get": {
        "tags": [
          "Arquivos"
        ],
        "summary": "Detalhe de arquivo",
        "description": "Retorna os metadados de um arquivo individual e a URL assinada correspondente. O arquivo precisa estar vinculado a um lead ou negócio visível ao usuário criador da chave.\n",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "UUID do arquivo.",
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Metadados completos do arquivo solicitado.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalFileResponse"
                }
              }
            }
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/file.read` ausente na chave."
          },
          "404": {
            "description": "Arquivo não encontrado, fora do escopo público de lead/negócio ou sem acesso ao vínculo relacionado."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      },
      "delete": {
        "tags": [
          "Arquivos"
        ],
        "summary": "Remoção lógica de arquivo",
        "description": "Remove logicamente um arquivo individual e ajusta os totais do lote relacionado. O arquivo precisa estar vinculado a um lead ou negócio visível ao usuário criador da chave.\n",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "UUID do arquivo.",
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Arquivo removido logicamente com sucesso.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean",
                      "enum": [
                        true
                      ]
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/file.delete` ausente na chave, usuário criador da chave inativo ou sem acesso ao arquivo: é preciso ser administrador, autor do arquivo ou do lote, ou supervisor da equipe do autor."
          },
          "404": {
            "description": "Arquivo não encontrado, fora do escopo público de lead/negócio ou sem acesso ao vínculo relacionado."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      }
    },
    "/integrations/external/files/batches": {
      "post": {
        "tags": [
          "Arquivos"
        ],
        "summary": "Upload de arquivos para lead ou negócio",
        "description": "Cria um lote de arquivos pela API pública de integrações externas. - É obrigatório informar exatamente um contexto entre `crm_lead_id`, `crm_deal_id`, `lead_code` ou `deal_code`. - Os arquivos devem ser enviados em `file` ou `files`. - Os formatos suportados são `markdown (.md/.markdown)`, `pdf`, `docx`, `xls`, `xlsx` e `txt`. - Cada arquivo aceita até 100 MB e a requisição, até 2.000 MB no total; acima disso, retorna 400. - O ator da operação é o usuário criador da chave. - Para anexar arquivos a uma proposta, use as rotas de anexos da proposta. - O lote é salvo com `source = 1` (API) e reaproveita o fluxo interno de arquivos, inclusive timeline e URLs assinadas.\n",
        "requestBody": {
          "required": true,
          "content": {
            "multipart/form-data": {
              "schema": {
                "$ref": "#/components/schemas/ExternalFilesCreateBatchRequest"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Lote criado com sucesso e já vinculado ao lead ou negócio informado.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalFileBatchResponse"
                }
              }
            }
          },
          "400": {
            "description": "Validação de dados falhou (contexto ausente/conflitante, tipo de arquivo inválido, arquivo acima de 100 MB, requisição acima de 2.000 MB ou nenhum arquivo enviado)."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/file.create` ausente na chave ou usuário criador da chave inativo."
          },
          "404": {
            "description": "Lead ou negócio não encontrado, ou fora do escopo de leitura do usuário criador da chave."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      }
    },
    "/integrations/external/leads": {
      "get": {
        "tags": [
          "Leads"
        ],
        "summary": "Listagem de leads",
        "description": "Retorna leads da empresa associada à chave de integração com paginação e filtros. A visibilidade do resultado considera as regras de acesso do usuário criador da chave (visibilidade 1 = time e 0 = privado, conforme as regras de acesso do CRM).\n\n\nFiltros de tarefas relacionadas não são suportados nesta API externa: pending_task_status, task_start_date_from, task_start_date_to, task_type_ids e related_task_completion_scope retornam 400 quando informados. Resumos de chats dependem de crm/chats.read na própria chave; sem essa permissão, as flags são false e as coleções vazias. count_only=true retorna total e records: [], sem projetar dados adicionais.",
        "parameters": [
          {
            "name": "search",
            "in": "query",
            "description": "Busca textual por título ou código (quando numérico).",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "skip",
            "in": "query",
            "description": "Quantidade de registros a pular (offset). Padrão 0.",
            "schema": {
              "type": "integer",
              "minimum": 0,
              "default": 0
            }
          },
          {
            "name": "take",
            "in": "query",
            "description": "Limite de registros da página. Envie explicitamente para limitar o resultado; sem take, a consulta não aplica limite de página.",
            "schema": {
              "type": "integer",
              "minimum": 1
            }
          },
          {
            "name": "status",
            "in": "query",
            "description": "Filtra status. 1 = aberto; 2 = ganho; 3 = perdido. A validação também aceita 0.",
            "schema": {
              "type": "integer",
              "enum": [
                0,
                1,
                2,
                3
              ]
            }
          },
          {
            "name": "stage_id",
            "in": "query",
            "description": "Filtra pelo ID do estágio.",
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          },
          {
            "name": "pipeline_id",
            "in": "query",
            "description": "Filtra pelo ID do pipeline (funil).",
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          },
          {
            "name": "archived",
            "in": "query",
            "description": "Controle de arquivamento (include = inclui arquivados, only = apenas arquivados).",
            "schema": {
              "$ref": "#/components/schemas/LeadArchivedFilter"
            }
          },
          {
            "name": "crm_lead_source_id",
            "in": "query",
            "description": "Filtra pela origem de lead (UUID). Compara com a origem efetiva: a da aquisição mais recente e, na falta dela, a gravada no registro.",
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          },
          {
            "name": "lead_sources",
            "in": "query",
            "description": "Lista de origens separadas por vírgula ou array. Aceita IDs, nomes de origem e o valor `unknown` (sem origem). Sem `attribution_mode`, compara com a origem efetiva do registro.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "won",
            "in": "query",
            "description": "Filtro de ganhos (include = inclui ganhos, only = somente ganhos).",
            "schema": {
              "$ref": "#/components/schemas/LeadResultFilter"
            }
          },
          {
            "name": "lost",
            "in": "query",
            "description": "Filtro de perdas (include = inclui perdidos, only = somente perdidos).",
            "schema": {
              "$ref": "#/components/schemas/LeadResultFilter"
            }
          },
          {
            "name": "quality_rating_from",
            "in": "query",
            "description": "Nota mínima de qualificação (1 a 5).",
            "schema": {
              "type": "integer",
              "enum": [
                1,
                2,
                3,
                4,
                5
              ]
            }
          },
          {
            "name": "quality_rating_to",
            "in": "query",
            "description": "Nota máxima de qualificação (1 a 5).",
            "schema": {
              "type": "integer",
              "enum": [
                1,
                2,
                3,
                4,
                5
              ]
            }
          },
          {
            "name": "campaigns",
            "in": "query",
            "description": "Códigos ou textos de campanha (suporta lista ou string separada por vírgulas).",
            "schema": {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "ad_sets",
            "in": "query",
            "description": "Códigos ou textos de conjuntos de anúncios.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "contents",
            "in": "query",
            "description": "Códigos ou textos de conteúdo.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "displayed_on",
            "in": "query",
            "description": "Locais de exibição.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "conversion_tools",
            "in": "query",
            "description": "Ferramentas de conversão.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "creatives",
            "in": "query",
            "description": "Criativos utilizados.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "search_terms",
            "in": "query",
            "description": "Termos de busca (utm_search_term/utm_term).",
            "schema": {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "urls",
            "in": "query",
            "description": "URLs de conversão.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "products",
            "in": "query",
            "description": "IDs de produtos vinculados ao lead ou propostas.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string",
                "format": "uuid"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "responsible_id",
            "in": "query",
            "description": "Filtra pelo responsável (UUID).",
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          },
          {
            "name": "created_from",
            "in": "query",
            "description": "Data inicial de criação (ISO8601).",
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "created_to",
            "in": "query",
            "description": "Data final de criação (ISO8601).",
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "last_activity_from",
            "in": "query",
            "description": "Data inicial da última atividade (ISO8601).",
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "last_activity_to",
            "in": "query",
            "description": "Data final da última atividade (ISO8601).",
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "won_from",
            "in": "query",
            "description": "Data inicial de ganho (ISO8601).",
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "won_to",
            "in": "query",
            "description": "Data final de ganho (ISO8601).",
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "lost_from",
            "in": "query",
            "description": "Data inicial de perda (ISO8601).",
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "lost_to",
            "in": "query",
            "description": "Data final de perda (ISO8601).",
            "schema": {
              "type": "string",
              "format": "date-time"
            }
          },
          {
            "name": "order_by",
            "in": "query",
            "description": "Campo para ordenação; os valores aceitos diferem entre leads e oportunidades.",
            "schema": {
              "$ref": "#/components/schemas/LeadOrderBy"
            }
          },
          {
            "name": "order_direction",
            "in": "query",
            "description": "Direção de ordenação.",
            "schema": {
              "$ref": "#/components/schemas/LeadOrderDirection"
            }
          },
          {
            "name": "only_new",
            "in": "query",
            "description": "Quando true, retorna apenas leads sem visualizações. A consulta por ID registra uma visualização do criador da chave e tira o registro deste filtro.",
            "schema": {
              "type": "boolean"
            }
          },
          {
            "name": "only_without_quality_rating",
            "in": "query",
            "description": "Quando true, retorna apenas leads sem nota de qualidade.",
            "schema": {
              "type": "boolean"
            }
          },
          {
            "name": "without_lead_source",
            "in": "query",
            "description": "Quando true, retorna apenas leads sem origem associada.",
            "schema": {
              "type": "boolean"
            }
          },
          {
            "name": "all_statuses",
            "in": "query",
            "description": "Quando true, ignora todos os filtros de status (inclui abertos, ganhos, perdidos e arquivados).",
            "schema": {
              "type": "boolean"
            }
          },
          {
            "name": "crm_loss_reason_ids",
            "in": "query",
            "description": "Lista de IDs de motivos de perda (UUID ou literal `unknown` para leads sem motivo).",
            "schema": {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "tags",
            "in": "query",
            "description": "Lista de IDs de tags (UUIDs) separados por vírgula ou array.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "person_id",
            "in": "query",
            "description": "Filtra pelo identificador de pessoa participante.",
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          },
          {
            "name": "organization_id",
            "in": "query",
            "description": "Filtra pelo identificador de organização.",
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          },
          {
            "name": "created_by",
            "in": "query",
            "description": "Filtra pelo identificador de usuário criador.",
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          },
          {
            "name": "excluded_ids",
            "in": "query",
            "description": "IDs de registros a excluir, separados por vírgula ou parâmetro repetido.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string",
                "format": "uuid"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "partner_ids",
            "in": "query",
            "description": "IDs de parceiros associados, separados por vírgula ou parâmetro repetido.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string",
                "format": "uuid"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "follower_ids",
            "in": "query",
            "description": "IDs de usuários seguidores, separados por vírgula ou parâmetro repetido.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string",
                "format": "uuid"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "responsible_ids",
            "in": "query",
            "description": "IDs de responsáveis, separados por vírgula ou parâmetro repetido.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string",
                "format": "uuid"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "icp_ids",
            "in": "query",
            "description": "IDs de ICPs associados, separados por vírgula ou parâmetro repetido.",
            "schema": {
              "type": "array",
              "items": {
                "type": "string",
                "format": "uuid"
              }
            },
            "style": "form",
            "explode": false
          },
          {
            "name": "only_followed_by_me",
            "in": "query",
            "description": "Somente registros seguidos pelo usuário que criou a chave.",
            "schema": {
              "type": "boolean"
            }
          },
          {
            "name": "without_icp",
            "in": "query",
            "description": "Somente registros sem ICP.",
            "schema": {
              "type": "boolean"
            }
          },
          {
            "name": "only_without_score",
            "in": "query",
            "description": "Somente registros sem pontuação de lead score.",
            "schema": {
              "type": "boolean"
            }
          },
          {
            "name": "count_only",
            "in": "query",
            "description": "Retorna apenas total e records vazio, sem projection_context.",
            "schema": {
              "type": "boolean"
            }
          },
          {
            "name": "abandoned",
            "in": "query",
            "description": "Aplica o critério de abandono configurado pela empresa.",
            "schema": {
              "type": "boolean"
            }
          },
          {
            "name": "score_from",
            "in": "query",
            "description": "Limite mínimo de lead score.",
            "schema": {
              "type": "integer",
              "minimum": 0,
              "maximum": 100
            }
          },
          {
            "name": "score_to",
            "in": "query",
            "description": "Limite máximo de lead score.",
            "schema": {
              "type": "integer",
              "minimum": 0,
              "maximum": 100
            }
          },
          {
            "name": "attribution_mode",
            "in": "query",
            "description": "Modo de atribuição para os filtros de marketing; modos por período dependem dos limites temporais correspondentes.",
            "schema": {
              "type": "string",
              "enum": [
                "any_touch",
                "current_attribution",
                "last_touch_at_won",
                "last_touch_at_period_end",
                "last_touch_at_created_period_end"
              ]
            }
          },
          {
            "name": "stagnation_status",
            "in": "query",
            "description": "Estado de estagnação na etapa.",
            "schema": {
              "type": "string",
              "enum": [
                "not_stagnant",
                "stagnant",
                "stagnant_with_future_task"
              ]
            }
          },
          {
            "name": "customer_reply_status",
            "in": "query",
            "description": "Situação da resposta do cliente no WhatsApp.",
            "schema": {
              "type": "string",
              "enum": [
                "initial_replied",
                "initial_not_replied",
                "not_replied_last_messages"
              ]
            }
          },
          {
            "name": "customer_reply_message_count",
            "in": "query",
            "description": "Quantidade de mensagens consideradas pelo filtro de últimas mensagens sem resposta.",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 50,
              "default": 1
            }
          },
          {
            "name": "custom_field_filters",
            "in": "query",
            "description": "Array serializado em JSON; cada filtro exige id e aceita value, option_id ou option_ids, conforme o tipo do campo.",
            "schema": {
              "type": "string",
              "description": "JSON serializado de um array de filtros.",
              "example": "[{\"id\":\"123e4567-e89b-42d3-a456-426614174000\",\"value\":\"Enterprise\"}]"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Lista paginada de leads com campos consolidados.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "total": {
                      "type": "integer",
                      "description": "Quantidade total de registros que atendem aos filtros."
                    },
                    "records": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/LeadSummary"
                      }
                    },
                    "projection_context": {
                      "$ref": "#/components/schemas/CrmProjectionContext"
                    }
                  },
                  "required": [
                    "total",
                    "records"
                  ]
                }
              }
            }
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/lead.read` ausente na chave."
          },
          "400": {
            "description": "Filtro inválido ou filtro de tarefas relacionadas não suportado pela API externa."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      },
      "post": {
        "tags": [
          "Leads"
        ],
        "summary": "Criação de lead",
        "description": "Cria um lead na empresa vinculada à chave de integração usando o usuário que criou a chave como ator padrão. - O estágio padrão é a primeira etapa do funil primário se `stage_id` não for informado. - Se `responsible_id` não for enviado, o responsável será o criador da chave. Se o usuário informado estiver inativo ou arquivado, o lead é atribuído ao usuário master da conta e recebe uma nota automática sobre a substituição; usuário inexistente ou de outra empresa retorna 400. - A única forma de informar uma origem manual é por `crm_lead_source_id`. O campo `lead_source` não é aceito nesta API. - A visibilidade padrão é privada (`visibility = 0`). - Quando `marketing.wegly_code` corresponder a um tracker ativo da empresa e `crm_lead_source_id` não for enviado, a origem do lead é a do tracker. Se os dois forem enviados, o tracker continua vinculado à aquisição, mas a origem retornada em `lead_source` e usada nos filtros é a de `crm_lead_source_id`. - Quando não houver tracker nem `crm_lead_source_id`, `marketing.wegly_source` ou `marketing.utm_source` busca/cria a origem automaticamente (`wegly_source` tem prioridade); `IG`, em qualquer caixa, é tratado como a origem `Instagram`. - `marketing.url_conversion` é parseada automaticamente para preencher parâmetros `wegly_code`, `wegly_source`, `wegly_campaign`, `wegly_ad_set`, `wegly_content`, `wegly_displayed_on`, `wegly_conversion_tool`, `utm_*`, `gclid` e `fbclid` faltantes; valores enviados manualmente prevalecem sobre os extraídos da URL. - Consentimento top-level, alias legado e URL são normalizados antes da idempotência e da deduplicação; qualquer divergência retorna 400 sem reservar evento, alterar pessoa ou criar lead. - Deduplicação de pessoa: quando `person.avoid_duplicate = true` e `duplicate_check_types` estiver preenchido, o serviço busca contatos existentes (pelos tipos informados) e reaproveita a pessoa encontrada, adicionando contatos faltantes. Nesse caso, a pessoa é incluída automaticamente em `persons_id`.\n\n\nAceita x-idempotency-key no header ou idempotency_key no body. Uma criação já concluída retorna o mesmo id, code e title com measurement_consent efetivo. Uma tentativa ainda em processamento retorna 409. Se a criação falhar depois de iniciada (referência inexistente, campo personalizado obrigatório ausente ou erro em seguidores/nota), a chave fica consumida e continua retornando 409; envie uma nova chave. Todos os campos personalizados obrigatórios da entidade precisam ser enviados. Seguidores e nota são gravados depois do registro: se falharem, a resposta é de erro, mas o registro permanece criado. Webhooks e notificações podem ser entregues de forma assíncrona após a resposta. measurement_consent é canônico; valores conflitantes com marketing.measurement_consent ou a URL retornam 400 antes das mutações. Contatos devem ficar em person.contacts: phone e email no primeiro nível são rejeitados com 400.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateExternalLead"
              },
              "examples": {
                "criacaoBasica": {
                  "summary": "Cadastro mínimo com rastreio de marketing",
                  "value": {
                    "title": "Lead vindo do site",
                    "visibility": 0,
                    "crm_lead_source_id": "6d5b7dd0-3e0a-48bd-a99d-f8df1fd74d33",
                    "measurement_consent": "GRANTED",
                    "marketing": {
                      "url_conversion": "https://meusite.com/obrigado?wegly_code=ABC123&utm_campaign=lancamento"
                    },
                    "person": {
                      "name": "Maria Souza",
                      "contacts": [
                        {
                          "type": 0,
                          "value": "(11) 98888-7777"
                        }
                      ],
                      "avoid_duplicate": true,
                      "duplicate_check_types": [
                        0
                      ]
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Lead criado com sucesso.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string",
                      "format": "uuid"
                    },
                    "code": {
                      "type": "integer",
                      "description": "Código sequencial interno do lead."
                    },
                    "title": {
                      "type": "string"
                    },
                    "measurement_consent": {
                      "$ref": "#/components/schemas/MeasurementConsent"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Validação de dados falhou (ex. `lead_source` não suportado, conflito de organização ou IDs inexistentes). Inclui telefone fora do formato de 10 ou 11 dígitos, campo personalizado obrigatório ausente e responsável inexistente."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/lead.create` ausente na chave ou usuário criador da chave inativo."
          },
          "409": {
            "description": "Já existe uma criação em processamento para esta chave de idempotência, ou a chave foi consumida por uma tentativa que falhou depois de iniciada."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        },
        "parameters": [
          {
            "name": "x-idempotency-key",
            "in": "header",
            "required": false,
            "description": "Chave da tentativa lógica de criação. Tem prioridade sobre idempotency_key no body; mantenha a mesma chave ao repetir uma chamada sem resposta e use uma nova depois de uma criação que falhou após iniciada.",
            "schema": {
              "type": "string"
            }
          }
        ]
      }
    },
    "/integrations/external/leads/{id}": {
      "get": {
        "tags": [
          "Leads"
        ],
        "summary": "Consulta de lead",
        "description": "Retorna detalhes completos do lead informado. O `id` pode ser UUID ou o código numérico interno. Considera visibilidade do usuário criador da chave.\n\n\nOs resumos de chats dependem exclusivamente de crm/chats.read na chave. Sem esse grant, flags são false e listas de chats são vazias. A resposta inclui valuation e projection_context para os valores comerciais e seus critérios de exibição. Cada consulta registra uma visualização do usuário criador da chave: views_count aumenta e o registro deixa de aparecer em only_new=true.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "UUID ou código sequencial do registro."
          }
        ],
        "responses": {
          "200": {
            "description": "Detalhes do lead.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LeadDetails"
                }
              }
            }
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/lead.read` ausente na chave."
          },
          "404": {
            "description": "Lead não encontrado ou inacessível ao usuário da chave."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      },
      "put": {
        "tags": [
          "Leads"
        ],
        "summary": "Atualização de lead",
        "description": "Atualiza campos do lead. Somente campos enviados são considerados. - O campo `lead_source` não é aceito nesta API; utilize `crm_lead_source_id`. - Enviar ao mesmo tempo `organization_id` e `organization` resulta em erro. - Para remover a organização vinculada, envie `organization_id` como `null`. - `persons_id` aceita marcação com `delete: true` para remover participantes; remover uma pessoa que não participa do lead é ignorado, mas um `person_id` inexistente retorna 404. Em leads ganhos ou perdidos, a remoção de participante ou de organização retorna 404 depois de as demais alterações já terem sido aplicadas. - Quando `marketing` é enviado, os campos informados corrigem a aquisição atual do lead: omitidos são preservados e `null` limpa o valor; uma aquisição nova só é criada quando o lead ainda não tem nenhuma. `crm_lead_source_id: null` remove a origem do lead e da aquisição atual. - `custom_fields`, quando enviado com itens, substitui todas as respostas do lead. - `person` sempre cadastra uma nova pessoa e a torna a principal; use `persons_id` para associar uma pessoa existente. - Consentimento top-level, alias legado e URL são normalizados antes de qualquer mutação; divergência retorna 400 sem atualizar o lead ou suas associações.\n\n\nO campo title é obrigatório. Retorna um resumo da atualização; consulte GET para obter as associações atualizadas. organization_id: null remove a organização; persons_id com delete: true remove participantes.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID do registro."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateExternalLead"
              },
              "examples": {
                "atualizacaoParticipantes": {
                  "summary": "Inclusão e remoção de participantes e organização",
                  "value": {
                    "title": "Lead ajustado",
                    "measurement_consent": "DENIED",
                    "persons_id": [
                      {
                        "person_id": "2c7f0b73-1b5b-4ce0-9b8c-22c55c7cc111"
                      },
                      {
                        "person_id": "9c1de125-7d0a-4e9f-8f8a-8b233c6f6e99",
                        "delete": true
                      }
                    ],
                    "organization_id": null,
                    "custom_fields": [
                      {
                        "id": "f0d82e2b-a6b0-48e9-a4f2-6d3d2e6e9d11",
                        "value": "Prioritário"
                      }
                    ]
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Lead atualizado.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LeadUpdateResult"
                }
              }
            }
          },
          "400": {
            "description": "Validação de dados falhou (IDs inexistentes, conflitos de parâmetros, estágio inválido, etc)."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/lead.update` ausente na chave ou usuário criador da chave inativo."
          },
          "404": {
            "description": "Lead não encontrado ou inacessível ao usuário da chave."
          },
          "409": {
            "description": "Lead alterado por outra operação durante a atualização. Consulte o registro e reenvie."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      }
    },
    "/integrations/external/proposals": {
      "get": {
        "tags": [
          "Propostas"
        ],
        "summary": "Listagem de propostas",
        "description": "Retorna as propostas da empresa associada à chave de integração que estejam visíveis para o usuário criador da chave, com filtros por lead, negócio, autor, status, proposta principal, status do negócio, faixa de valor e períodos. O filtro `deal_code` converte o código numérico do negócio para o ID interno antes da consulta; quando o código não existe, retorna `records=[]` e `total=0`. Por padrão, os registros não incluem `delivery_schedule`. Com `include_delivery_schedule=true`, cada registro inclui obrigatoriamente o cronograma calculado ou `null` quando não houver cronograma. As configurações salvas de prazo não são expostas. Ordenação padrão por `created_at` decrescente, ajustável por `order_by` e `order_direction`; paginação padrão `skip=0` e `take=10`, com `take` máximo de 100.",
        "parameters": [
          {
            "$ref": "#/components/parameters/ProposalSearch"
          },
          {
            "$ref": "#/components/parameters/Skip"
          },
          {
            "$ref": "#/components/parameters/ProposalTake"
          },
          {
            "$ref": "#/components/parameters/ProposalDealId"
          },
          {
            "$ref": "#/components/parameters/ProposalLeadId"
          },
          {
            "$ref": "#/components/parameters/ProposalCreatedBy"
          },
          {
            "$ref": "#/components/parameters/ProposalStatus"
          },
          {
            "$ref": "#/components/parameters/ProposalApproved"
          },
          {
            "$ref": "#/components/parameters/ProposalArchived"
          },
          {
            "$ref": "#/components/parameters/ProposalCode"
          },
          {
            "$ref": "#/components/parameters/ProposalIsPrimary"
          },
          {
            "$ref": "#/components/parameters/ProposalDealStatus"
          },
          {
            "$ref": "#/components/parameters/ProposalMinValue"
          },
          {
            "$ref": "#/components/parameters/ProposalMaxValue"
          },
          {
            "$ref": "#/components/parameters/ProposalCreatedFrom"
          },
          {
            "$ref": "#/components/parameters/ProposalCreatedTo"
          },
          {
            "$ref": "#/components/parameters/ProposalValidFrom"
          },
          {
            "$ref": "#/components/parameters/ProposalValidTo"
          },
          {
            "$ref": "#/components/parameters/ProposalRejectedFrom"
          },
          {
            "$ref": "#/components/parameters/ProposalRejectedTo"
          },
          {
            "$ref": "#/components/parameters/ProposalDealCode"
          },
          {
            "$ref": "#/components/parameters/ProposalIncludeDeliverySchedule"
          },
          {
            "$ref": "#/components/parameters/ProposalOrderBy"
          },
          {
            "$ref": "#/components/parameters/ProposalOrderDirection"
          }
        ],
        "responses": {
          "200": {
            "description": "Lista paginada de propostas.",
            "content": {
              "application/json": {
                "schema": {
                  "oneOf": [
                    {
                      "$ref": "#/components/schemas/ProposalListResponse"
                    },
                    {
                      "$ref": "#/components/schemas/ProposalListResponseWithDeliverySchedule"
                    }
                  ],
                  "description": "Sem o parâmetro (ou com `false`), usa a variante sem `delivery_schedule`. Com `include_delivery_schedule=true`, usa a variante em que a propriedade está presente em todos os registros e pode ser `null`."
                }
              }
            }
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/proposal.read` ausente na chave."
          },
          "400": {
            "description": "Filtro inválido, `take` fora do intervalo de 1 a 100, período ou faixa de valor invertidos ou `deal_code` não numérico."
          },
          "409": {
            "description": "Múltiplos negócios encontrados para deal_code."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      },
      "post": {
        "tags": [
          "Propostas"
        ],
        "summary": "Criação de proposta",
        "description": "Cria uma proposta comercial usando o usuário criador da chave como ator. Exige ao menos um item e exatamente um contexto: lead_id ou negócio (deal_id/deal_code). O contexto deve estar aberto e permitir negociação por proposta. Se deal_id e deal_code forem enviados juntos, deal_id prevalece. Itens sem product_id podem resolver produtos por sku; também aceitam item livre ou criação inline por new_product. Negócios com produtos associados bloqueiam a criação. Inclui suporte a custom_fields e delivery_schedule; retorna os detalhes completos.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateExternalProposal"
              },
              "examples": {
                "propostaBasica": {
                  "summary": "Proposta vinculada a negócio com item resolvido por SKU",
                  "value": {
                    "deal_code": "1032",
                    "title": "Proposta comercial CRM Enterprise",
                    "notes": "Validade de 15 dias.",
                    "valid_until": "2026-10-05T23:59:59.000Z",
                    "items": [
                      {
                        "sku": "CRM-ENT-001",
                        "quantity": 1,
                        "unit_price": 2499.9,
                        "name": "Licença CRM Enterprise"
                      }
                    ]
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Proposta criada com sucesso.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProposalDetails"
                }
              }
            }
          },
          "400": {
            "description": "Validação de dados falhou (itens ausentes, desconto inválido, negócio com produtos associados, etc)."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/proposal.create` ausente na chave."
          },
          "404": {
            "description": "Lead, negócio, produto, aprovador ou proposta relacionada não encontrados no escopo da empresa, ou lead/negócio fora do escopo de leitura do usuário criador da chave."
          },
          "409": {
            "description": "Múltiplos negócios encontrados para o `deal_code` informado."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      }
    },
    "/integrations/external/proposals/{id}": {
      "get": {
        "tags": [
          "Propostas"
        ],
        "summary": "Consulta de proposta",
        "description": "Retorna os detalhes completos de uma proposta da empresa da chave que esteja visível para o usuário criador da chave. Os anexos não fazem parte do retorno; consulte a listagem de anexos da proposta.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da proposta."
          }
        ],
        "responses": {
          "200": {
            "description": "Detalhes completos da proposta.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProposalDetails"
                }
              }
            }
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/proposal.read` ausente na chave."
          },
          "404": {
            "description": "Proposta não encontrada ou fora do escopo de leitura do usuário criador da chave."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      },
      "put": {
        "tags": [
          "Propostas"
        ],
        "summary": "Atualização de proposta",
        "description": "Atualiza parcialmente a proposta. Em items: com id atualiza, com id e delete=true remove, sem id adiciona; itens omitidos são preservados e ao menos um deve permanecer. quantity é obrigatória nos itens enviados sem remoção. Se deal_code for enviado, prevalece sobre deal_id. delivery_schedule omitido preserva, objeto substitui integralmente e null remove. custom_fields enviado substitui o conjunto de respostas. Contextos fechados bloqueiam a alteração. Mudança de total com condições de pagamento existentes exige sua revisão no CRM; payment_options não está declarado no DTO externo.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da proposta."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateExternalProposal"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Proposta atualizada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProposalDetails"
                }
              }
            }
          },
          "400": {
            "description": "Validação de dados falhou ou regra de negócio não foi atendida."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/proposal.update` ausente na chave."
          },
          "404": {
            "description": "Proposta, negócio, produto ou lead não encontrados, ou fora do escopo de leitura do usuário criador da chave."
          },
          "409": {
            "description": "Múltiplos negócios para deal_code ou proposta alterada concorrentemente."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      },
      "delete": {
        "tags": [
          "Propostas"
        ],
        "summary": "Remoção de proposta",
        "description": "Realiza a exclusão lógica da proposta e devolve o identificador removido.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da proposta."
          }
        ],
        "responses": {
          "200": {
            "description": "Proposta removida logicamente.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProposalDeleteResult"
                }
              }
            }
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/proposal.delete` ausente na chave."
          },
          "404": {
            "description": "Proposta não encontrada ou fora do escopo de leitura do usuário criador da chave."
          },
          "400": {
            "description": "Contexto da proposta encerrado ou outra restrição de negócio impede exclusão."
          },
          "409": {
            "description": "Proposta alterada concorrentemente; consulte novamente antes de reenviar."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      }
    },
    "/integrations/external/proposals/{id}/attachments": {
      "get": {
        "tags": [
          "Propostas"
        ],
        "summary": "Listagem de anexos da proposta",
        "description": "Lista os anexos da proposta, arquivos enviados e documentos da biblioteca de documentos da Wegly, ordenados por `position`. O ator é o usuário criador da chave, que precisa enxergar a proposta pelo lead ou pelo negócio de origem. Envios iniciados no CRM e ainda não concluídos (`status = UPLOADING`) aparecem somente para quem os iniciou.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da proposta."
          }
        ],
        "responses": {
          "200": {
            "description": "Total e anexos da proposta.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProposalAttachmentListResponse"
                }
              }
            }
          },
          "400": {
            "description": "Identificador da proposta em formato inválido."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/proposal.read` ausente na chave ou usuário criador da chave inativo."
          },
          "404": {
            "description": "Proposta não encontrada ou fora do escopo de leitura do usuário criador da chave."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      }
    },
    "/integrations/external/proposals/{id}/attachments/files": {
      "post": {
        "tags": [
          "Propostas"
        ],
        "summary": "Envio de arquivos para a proposta",
        "description": "Anexa arquivos enviados por `multipart/form-data` nos campos `files` ou `file`, somando até 10 arquivos por requisição e até 20 MB por arquivo. Os formatos aceitos são PDF, DOCX, XLS, XLSX, TXT, MD, CSV, JPG/JPEG, PNG, WEBP, GIF, MP3 e MP4, validados por extensão, MIME declarado e conteúdo do arquivo. Cada proposta aceita até 50 anexos. Exige as permissões `crm/proposal.update` e `crm/file.create` na chave e no usuário criador da chave, além de lead ou negócio aberto e não arquivado. A inclusão é registrada no histórico da proposta.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da proposta."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "multipart/form-data": {
              "schema": {
                "$ref": "#/components/schemas/ProposalAttachmentFilesUploadRequest"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Anexos criados, na ordem de `position`.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/ProposalAttachment"
                  }
                }
              }
            }
          },
          "400": {
            "description": "Nenhum arquivo enviado, mais de 10 arquivos, formato, MIME ou conteúdo inválido, limite de 50 anexos atingido ou lead ou negócio da proposta fechado ou arquivado."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/proposal.update` ou `crm/file.create` ausente na chave ou no usuário criador da chave."
          },
          "404": {
            "description": "Proposta não encontrada ou fora do escopo de leitura do usuário criador da chave."
          },
          "413": {
            "description": "Arquivo acima de 20 MB."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      }
    },
    "/integrations/external/proposals/{id}/attachments/documents": {
      "post": {
        "tags": [
          "Propostas"
        ],
        "summary": "Criação de documento anexado à proposta",
        "description": "Cria um documento na biblioteca de documentos da Wegly, com conteúdo inicial opcional em Markdown, e o anexa à proposta. O documento pertence ao usuário criador da chave, nasce `PRIVATE` por padrão e pode ser lido pelos anexos por quem enxerga a proposta. Remover o anexo não apaga o documento da biblioteca. Exige as permissões `crm/proposal.update` e `crm/document.create` na chave e no usuário criador da chave, além de lead ou negócio aberto e não arquivado. A inclusão é registrada no histórico da proposta.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da proposta."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateProposalAttachmentDocument"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Documento criado e anexado à proposta.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProposalAttachment"
                }
              }
            }
          },
          "400": {
            "description": "Payload inválido, conteúdo com imagem de outro documento ou menção a usuário fora da empresa, limite de 50 anexos atingido ou lead ou negócio da proposta fechado ou arquivado."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/proposal.update` ou `crm/document.create` ausente na chave ou no usuário criador da chave, ou pasta sem permissão de criação."
          },
          "404": {
            "description": "Proposta ou pasta não encontrada, ou proposta fora do escopo de leitura do usuário criador da chave."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      }
    },
    "/integrations/external/proposals/{id}/attachments/library": {
      "post": {
        "tags": [
          "Propostas"
        ],
        "summary": "Anexação de itens da biblioteca à proposta",
        "description": "Vincula documentos existentes da biblioteca de documentos da Wegly e copia arquivos do Drive da biblioteca para a proposta. Aceita até 20 itens por requisição, somando `document_ids` e `file_ids`. Documentos já anexados são ignorados e devolvidos na resposta. Um documento sem visibilidade `COMPANY` só pode ser anexado se o usuário criador da chave puder compartilhá-lo. Exige `crm/proposal.update` e `crm/document.read` na chave; quando há `file_ids`, exige também `crm/file.create` na chave e no usuário criador. O lead ou negócio precisa estar aberto e não arquivado.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da proposta."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AttachProposalLibraryItems"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Anexos correspondentes aos itens informados, incluindo documentos que já estavam anexados.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/ProposalAttachment"
                  }
                }
              }
            }
          },
          "400": {
            "description": "Nenhum item informado, lista inválida, mais de 20 itens, limite de 50 anexos atingido ou lead ou negócio da proposta fechado ou arquivado."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/proposal.update`, `crm/document.read` ou `crm/file.create` ausente, ou documento que o usuário criador da chave não pode compartilhar."
          },
          "404": {
            "description": "Proposta, documento ou arquivo da biblioteca não encontrado ou fora do alcance do usuário criador da chave."
          },
          "409": {
            "description": "O documento foi anexado à proposta por outra requisição simultânea."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      }
    },
    "/integrations/external/proposals/{id}/attachments/{attachmentId}": {
      "delete": {
        "tags": [
          "Propostas"
        ],
        "summary": "Remoção de anexo da proposta",
        "description": "Remove o anexo da proposta. Um documento continua existindo na biblioteca. Exige `crm/proposal.update` na chave e no usuário criador da chave, além de lead ou negócio aberto e não arquivado. A remoção é registrada no histórico da proposta.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da proposta."
          },
          {
            "name": "attachmentId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID do anexo. O anexo precisa pertencer à proposta informada em `id`."
          }
        ],
        "responses": {
          "200": {
            "description": "Anexo removido.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProposalAttachmentRemoveResult"
                }
              }
            }
          },
          "400": {
            "description": "Identificador inválido ou lead ou negócio da proposta fechado ou arquivado."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/proposal.update` ausente na chave ou no usuário criador da chave."
          },
          "404": {
            "description": "Proposta ou anexo não encontrado, inclusive quando o anexo pertence a outra proposta."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      }
    },
    "/integrations/external/proposals/{id}/attachments/{attachmentId}/document": {
      "get": {
        "tags": [
          "Propostas"
        ],
        "summary": "Leitura de documento anexado",
        "description": "Retorna o conteúdo de um documento da biblioteca anexado à proposta, página por página, em Markdown. A leitura é derivada da proposta e não exige acesso próprio do usuário criador da chave ao documento na biblioteca. Sem `version_scope`, usa a versão publicada quando existir e, caso contrário, o rascunho atual.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da proposta."
          },
          {
            "name": "attachmentId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID do anexo. O anexo precisa pertencer à proposta informada em `id`."
          },
          {
            "name": "version_scope",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "enum": [
                "DRAFT",
                "PUBLISHED"
              ]
            },
            "description": "`DRAFT` lê o rascunho atual e `PUBLISHED` a versão publicada."
          }
        ],
        "responses": {
          "200": {
            "description": "Metadados do documento e páginas na ordem de leitura.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProposalAttachmentDocumentContent"
                }
              }
            }
          },
          "400": {
            "description": "Identificador ou `version_scope` inválido, ou anexo que não é um documento da biblioteca."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/proposal.read` ou `crm/document.read` ausente na chave."
          },
          "404": {
            "description": "Proposta ou anexo não encontrado, documento na lixeira ou versão publicada inexistente."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      },
      "put": {
        "tags": [
          "Propostas"
        ],
        "summary": "Atualização de documento anexado",
        "description": "Atualiza o título e/ou substitui o conteúdo da página principal de um documento anexado. A alteração é feita no documento da biblioteca e vale para todas as propostas que o anexam. Exige `crm/proposal.read` e `crm/document.update` na chave e acesso de edição do usuário criador da chave ao documento; não depende de o lead ou negócio estar aberto. Sem `title` e sem `content_markdown`, devolve o anexo sem alterações.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da proposta."
          },
          {
            "name": "attachmentId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID do anexo. O anexo precisa pertencer à proposta informada em `id`."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateProposalAttachmentDocument"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Anexo com o documento atualizado.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProposalAttachment"
                }
              }
            }
          },
          "400": {
            "description": "Payload inválido, título vazio ou anexo que não é um documento da biblioteca."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/proposal.read` ou `crm/document.update` ausente na chave, ou usuário criador da chave sem acesso de edição ao documento."
          },
          "404": {
            "description": "Proposta ou anexo não encontrado, ou documento na lixeira."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      }
    },
    "/integrations/external/proposals/{id}/attachments/{attachmentId}/download-url": {
      "get": {
        "tags": [
          "Propostas"
        ],
        "summary": "Link de download de arquivo anexado",
        "description": "Gera uma URL assinada, válida por 15 minutos, que força o download do arquivo anexado com o nome original. Atende apenas anexos do tipo arquivo.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da proposta."
          },
          {
            "name": "attachmentId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID do anexo. O anexo precisa pertencer à proposta informada em `id`."
          }
        ],
        "responses": {
          "200": {
            "description": "URL temporária de download.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProposalAttachmentDownloadUrl"
                }
              }
            }
          },
          "400": {
            "description": "Identificador inválido, anexo que não é um arquivo ou arquivo ainda em envio."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/proposal.read` ou `crm/file.read` ausente na chave."
          },
          "404": {
            "description": "Proposta ou anexo não encontrado, inclusive quando o anexo pertence a outra proposta."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      }
    },
    "/integrations/external/satisfaction/forms/{id}/share-links": {
      "post": {
        "tags": [
          "Satisfação"
        ],
        "summary": "Criação de link público de satisfação",
        "description": "Cria um link público tokenizado para resposta de um formulário de satisfação. O endpoint usa a empresa da chave de integração, exige permissão `crm/satisfaction.links.create`, resolve o usuário ator como o criador da chave e reaproveita as mesmas validações internas de formulário, pessoa, oportunidade, entrega, expiração e limite de uso.\n",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID do formulário de satisfação que receberá o link público."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateExternalSatisfactionShareLink"
              },
              "examples": {
                "linkParaOportunidade": {
                  "summary": "Link vinculado a uma oportunidade",
                  "value": {
                    "crm_person_id": "9ad35656-fbd1-4c7f-819c-a9cf2db0cc75",
                    "crm_deal_id": "5122f05d-842e-4e50-a79d-cf750f18e4ab",
                    "expires_at": "2027-03-31T23:59:59.000Z",
                    "max_uses": 1
                  }
                },
                "linkParaEntrega": {
                  "summary": "Link vinculado a uma entrega",
                  "value": {
                    "crm_person_id": "9ad35656-fbd1-4c7f-819c-a9cf2db0cc75",
                    "crm_delivery_id": "3b67628a-2b38-430e-bb86-ccdf1c985b36",
                    "max_uses": 1
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Link público criado com sucesso.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalSatisfactionShareLinkResponse"
                }
              }
            }
          },
          "400": {
            "description": "Validação de dados falhou, `crm_deal_id` e `crm_delivery_id` foram enviados juntos ou `max_uses` está fora do intervalo permitido."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/satisfaction.links.create` ausente na chave ou usuário criador da chave inativo."
          },
          "404": {
            "description": "Formulário, pessoa, oportunidade ou entrega não encontrados no escopo da empresa da chave."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      }
    },
    "/integrations/external/tasks": {
      "get": {
        "tags": [
          "Tarefas"
        ],
        "summary": "Listagem de tarefas",
        "description": "Retorna tarefas da empresa associada à chave de integração. A listagem reaproveita o mesmo escopo do módulo interno e permite filtrar tarefas vinculadas a leads, oportunidades, entregas, pessoas, organizações ou clientes.\n\nUse hierarchy_mode=grouped para retornar árvores em subtasks (total conta raízes). include_non_actionable=true inclui eventos importados de agendas; o padrão lista tarefas acionáveis. Sem parâmetros `order_*`, a ordem é por criação decrescente; tarefas sem data aparecem antes das demais, exceto com `without_date_time=true`.",
        "parameters": [
          {
            "$ref": "#/components/parameters/TaskSearch"
          },
          {
            "$ref": "#/components/parameters/TaskSkip"
          },
          {
            "name": "take",
            "in": "query",
            "description": "Quantidade de registros a retornar. Envie explicitamente para limitar a página; sem este parâmetro, todos os registros são retornados.",
            "schema": {
              "type": "integer",
              "minimum": 1
            }
          },
          {
            "$ref": "#/components/parameters/TaskLeadId"
          },
          {
            "$ref": "#/components/parameters/TaskDealId"
          },
          {
            "$ref": "#/components/parameters/TaskDeliveryId"
          },
          {
            "$ref": "#/components/parameters/TaskPersonId"
          },
          {
            "$ref": "#/components/parameters/TaskOrganizationId"
          },
          {
            "$ref": "#/components/parameters/TaskCustomerId"
          },
          {
            "$ref": "#/components/parameters/TaskResponsibleId"
          },
          {
            "$ref": "#/components/parameters/TaskTypeId"
          },
          {
            "$ref": "#/components/parameters/TaskStageId"
          },
          {
            "$ref": "#/components/parameters/TaskPriority"
          },
          {
            "$ref": "#/components/parameters/TaskOnlyPending"
          },
          {
            "$ref": "#/components/parameters/TaskExecutionPeriod"
          },
          {
            "$ref": "#/components/parameters/TaskIsPersonal"
          },
          {
            "$ref": "#/components/parameters/TaskIsMeeting"
          },
          {
            "$ref": "#/components/parameters/TaskIsRecurring"
          },
          {
            "$ref": "#/components/parameters/TaskWithoutDateTime"
          },
          {
            "$ref": "#/components/parameters/TaskMeetingResult"
          },
          {
            "$ref": "#/components/parameters/TaskStartDateFrom"
          },
          {
            "$ref": "#/components/parameters/TaskStartDateTo"
          },
          {
            "$ref": "#/components/parameters/TaskCompletedAtFrom"
          },
          {
            "$ref": "#/components/parameters/TaskCompletedAtTo"
          },
          {
            "$ref": "#/components/parameters/TaskCreatedAtFrom"
          },
          {
            "$ref": "#/components/parameters/TaskCreatedAtTo"
          },
          {
            "$ref": "#/components/parameters/TaskOrderPriority"
          },
          {
            "$ref": "#/components/parameters/TaskOrderStartDate"
          },
          {
            "$ref": "#/components/parameters/TaskOrderCreatedAt"
          },
          {
            "$ref": "#/components/parameters/TaskOrderUpdatedAt"
          },
          {
            "name": "parent_task_id",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          },
          {
            "name": "hierarchy_mode",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "enum": [
                "flat",
                "grouped"
              ],
              "default": "flat",
              "description": "grouped retorna raízes com subtasks; total conta raízes e os filtros valem para as raízes, não para as subtarefas devolvidas."
            }
          },
          {
            "name": "tag_id",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          },
          {
            "name": "tag_ids",
            "in": "query",
            "required": false,
            "schema": {
              "type": "array",
              "items": {
                "type": "string",
                "format": "uuid"
              },
              "uniqueItems": true
            },
            "style": "form",
            "explode": false,
            "description": "UUIDs separados por vírgulas; aceita também array na query."
          },
          {
            "name": "completed_last",
            "in": "query",
            "required": false,
            "schema": {
              "type": "boolean",
              "description": "Agrupa pendentes antes de concluídas mantendo a ordenação em cada grupo."
            }
          },
          {
            "name": "include_non_actionable",
            "in": "query",
            "required": false,
            "schema": {
              "type": "boolean",
              "default": false,
              "description": "Inclui eventos importados de agendas que não são tarefas acionáveis."
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Lista paginada de tarefas.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalTaskListResponse"
                }
              }
            }
          },
          "400": {
            "description": "Query inválida."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/task.read` ausente na chave ou usuário criador da chave inativo."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      },
      "post": {
        "tags": [
          "Tarefas"
        ],
        "summary": "Criação de tarefa",
        "description": "Cria uma tarefa via integração externa, usando o usuário criador da chave como ator. A tarefa pode ser vinculada a exatamente um contexto principal entre lead, oportunidade, entrega, pessoa, organização ou cliente, conforme as regras do módulo interno. Vínculo com lead ou oportunidade exige `start_date`. Quando omitidos, `responsible_id` assume o usuário criador da chave e `crm_task_stage_id` assume a primeira etapa ativa que não seja de conclusão.\n",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateExternalTask"
              },
              "examples": {
                "tarefaDeal": {
                  "summary": "Tarefa vinculada a uma oportunidade",
                  "value": {
                    "crm_task_type_id": "c5bb4fd2-5098-4e19-ae9e-6f9bf0be8458",
                    "crm_deal_id": "2b56f4df-c7d7-4f0a-8db0-93e2f83dd7db",
                    "title": "Reunião de kick-off",
                    "description": "Validar participantes e escopo inicial.",
                    "priority": 2,
                    "start_date": "2026-03-06T13:00:00.000Z",
                    "end_date": "2026-03-06T14:00:00.000Z",
                    "has_time": true,
                    "reminders_minutes": [
                      15,
                      60
                    ]
                  }
                },
                "tarefaDelivery": {
                  "summary": "Tarefa vinculada a uma entrega",
                  "value": {
                    "crm_task_type_id": "c5bb4fd2-5098-4e19-ae9e-6f9bf0be8458",
                    "crm_delivery_id": "f45250ba-9aa3-45ab-9c8b-a24504160f01",
                    "title": "Enviar prévia da entrega",
                    "priority": 1,
                    "start_date": "2026-03-07T10:00:00.000Z",
                    "has_time": false
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Tarefa criada com sucesso.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalTask"
                }
              }
            }
          },
          "400": {
            "description": "Validação de payload, conflito de vínculos, datas inválidas, regra de reunião/recorrência não atendida, ou tipo, etapa, responsável, tag ou registro vinculado não encontrado."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/task.create` ausente na chave, tarefa pai fora do alcance do usuário criador da chave ou usuário criador da chave inativo."
          },
          "404": {
            "description": "Tarefa pai informada em `parent_task_id` não encontrada."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      }
    },
    "/integrations/external/tasks/{id}": {
      "get": {
        "tags": [
          "Tarefas"
        ],
        "summary": "Consulta de tarefa",
        "description": "Retorna o detalhamento de uma tarefa específica visível ao usuário criador da chave de integração.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da tarefa."
          }
        ],
        "responses": {
          "200": {
            "description": "Detalhes completos da tarefa.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalTask"
                }
              }
            }
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/task.read` ausente na chave ou usuário criador da chave inativo."
          },
          "404": {
            "description": "Tarefa não encontrada ou fora do alcance do usuário criador da chave."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      },
      "put": {
        "tags": [
          "Tarefas"
        ],
        "summary": "Atualização de tarefa",
        "description": "Atualiza uma tarefa existente via integração externa. Em tarefas recorrentes, `recurrence_scope` define se a alteração afeta apenas a ocorrência atual, futuras, abertas ou toda a série. Enviar um campo de vínculo (`crm_*_id`) substitui o vínculo atual. A resposta pode trazer uma tarefa com outro `id`: no reagendamento de reunião (`meeting_outcome: 4` com nova data) e quando a regra de recorrência é criada ou alterada.\n",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da tarefa."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateExternalTask"
              },
              "examples": {
                "remarcar": {
                  "summary": "Remarcar tarefa",
                  "value": {
                    "title": "Reunião de kick-off atualizada",
                    "start_date": "2026-03-06T14:00:00.000Z",
                    "end_date": "2026-03-06T15:00:00.000Z",
                    "has_time": true,
                    "recurrence_scope": "only_this"
                  }
                },
                "concluir": {
                  "summary": "Concluir tarefa",
                  "value": {
                    "is_completed": true
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Tarefa atualizada com sucesso. No reagendamento de reunião e na criação ou alteração de recorrência, o corpo traz a nova tarefa, com `id` diferente do informado no caminho.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalTask"
                }
              }
            }
          },
          "400": {
            "description": "Payload inválido, conflito de dados, escopo de recorrência inválido, regra de agenda não atendida, ou tarefa, tipo, etapa, responsável, tag ou vínculo não encontrado."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/task.update` ausente na chave, tarefa ou tarefa pai fora do alcance do usuário criador da chave ou usuário criador da chave inativo."
          },
          "404": {
            "description": "Tarefa pai informada em `parent_task_id` não encontrada."
          },
          "409": {
            "description": "A tarefa foi alterada desde a versão informada em expected_updated_at ou durante a operação.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      },
      "delete": {
        "tags": [
          "Tarefas"
        ],
        "summary": "Remoção de tarefa",
        "description": "Remove logicamente uma tarefa. Para tarefas recorrentes, `recurrence_scope` pode controlar se a remoção vale apenas para a ocorrência atual, futuras, abertas ou toda a série. As subtarefas também são removidas. Sem `recurrence_scope`, vale `only_this`.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da tarefa."
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/RemoveExternalTask"
              },
              "examples": {
                "apenasEsta": {
                  "summary": "Remover apenas esta ocorrência",
                  "value": {
                    "recurrence_scope": "only_this"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Tarefa removida logicamente.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalTaskDeleteResult"
                }
              }
            }
          },
          "400": {
            "description": "Tarefa não encontrada ou escopo de recorrência inválido."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/task.delete` ausente na chave, tarefa fora do alcance do usuário criador da chave ou usuário criador da chave inativo."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      }
    },
    "/integrations/external/leads/{id}/followers": {
      "post": {
        "tags": [
          "Leads"
        ],
        "summary": "Adicionar seguidor ao lead",
        "description": "Adiciona ou reativa um usuário como seguidor do lead usando o usuário criador da chave de integração como ator. Se o usuário já for seguidor ativo, a função e as observações são atualizadas sem duplicar o vínculo.\n",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID do lead."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/LeadFollowerInput"
              },
              "examples": {
                "seguidorLead": {
                  "summary": "Adicionar seguidor ao lead",
                  "value": {
                    "user_id": "fcb47a3c-a2d9-45c8-b1a1-1da8f9627f9f",
                    "role_id": "6bb94eb7-50df-4f88-9862-7ef8f4b9607c",
                    "notes": "Acompanhar retorno do formulário externo."
                  }
                }
              }
            }
          }
        },
        "responses": {
          "400": {
            "description": "Payload inválido, usuário alvo inexistente/inativo ou função de seguidor inválida."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/lead.update` ausente na chave."
          },
          "404": {
            "description": "Lead não encontrado ou inacessível ao usuário da chave."
          },
          "201": {
            "description": "Lista atualizada de seguidores do lead.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LeadFollowersResponse"
                }
              }
            }
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      }
    },
    "/integrations/external/leads/{id}/followers/{user_id}": {
      "delete": {
        "tags": [
          "Leads"
        ],
        "summary": "Remover seguidor do lead",
        "description": "Remove logicamente um usuário da lista de seguidores do lead usando o usuário criador da chave de integração como ator.\n",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID do lead."
          },
          {
            "name": "user_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID do usuário seguidor a ser removido do lead."
          }
        ],
        "responses": {
          "200": {
            "description": "Seguidor removido do lead.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FollowerRemoveResponse"
                }
              }
            }
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/lead.update` ausente na chave."
          },
          "404": {
            "description": "Lead não encontrado, inacessível ao usuário da chave ou seguidor não encontrado para este lead."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      }
    },
    "/integrations/external/deals/{id}/followers": {
      "post": {
        "tags": [
          "Oportunidades"
        ],
        "summary": "Adicionar seguidor à oportunidade",
        "description": "Adiciona ou reativa um usuário como seguidor da oportunidade usando o usuário criador da chave de integração como ator. Se o usuário já for seguidor ativo, a função e as observações são atualizadas sem duplicar o vínculo.\n",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da oportunidade."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/OpportunityFollowerInput"
              },
              "examples": {
                "seguidorOportunidade": {
                  "summary": "Adicionar seguidor à oportunidade",
                  "value": {
                    "user_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
                    "role_id": "b2c3d4e5-f6a7-8901-bcde-f23456789012",
                    "notes": "Acompanhar proposta enviada pelo parceiro."
                  }
                }
              }
            }
          }
        },
        "responses": {
          "400": {
            "description": "Payload inválido, usuário alvo inexistente/inativo ou função de seguidor inválida."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/deal.update` ausente na chave."
          },
          "404": {
            "description": "Oportunidade não encontrada ou inacessível ao usuário da chave."
          },
          "201": {
            "description": "Lista atualizada de seguidores da oportunidade.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpportunityFollowersResponse"
                }
              }
            }
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      }
    },
    "/integrations/external/deals/{id}/followers/{user_id}": {
      "delete": {
        "tags": [
          "Oportunidades"
        ],
        "summary": "Remover seguidor da oportunidade",
        "description": "Remove logicamente um usuário da lista de seguidores da oportunidade usando o usuário criador da chave de integração como ator.\n",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da oportunidade."
          },
          {
            "name": "user_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID do usuário seguidor a ser removido da oportunidade."
          }
        ],
        "responses": {
          "200": {
            "description": "Seguidor removido da oportunidade.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FollowerRemoveResponse"
                }
              }
            }
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão `crm/deal.update` ausente na chave."
          },
          "404": {
            "description": "Oportunidade não encontrada, inacessível ao usuário da chave ou seguidor não encontrado para esta oportunidade."
          },
          "429": {
            "description": "Limite de requisições atingido.",
            "headers": {
              "Retry-After": {
                "description": "Tempo de espera em segundos, quando enviado.",
                "schema": {
                  "type": "integer"
                }
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExternalApiError"
                }
              }
            }
          }
        }
      }
    },
    "/integrations/external/chats/{id}/assignable-agents": {
      "get": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsAssignableAgents",
        "summary": "Listar agentes elegíveis",
        "description": "Lista agentes que podem atuar no número WhatsApp ou na conta Instagram. Permissão da chave: crm/chats.read. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          }
        ],
        "responses": {
          "200": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChatAssignableAgentsResponse"
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      }
    },
    "/integrations/external/chats/{id}/history": {
      "get": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsHistory",
        "summary": "Consultar histórico operacional",
        "description": "Eventos operacionais de WhatsApp ou Instagram, do mais recente para o mais antigo. Permissão da chave: crm/chats.read. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          },
          {
            "name": "skip",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer",
              "minimum": 0,
              "default": 0
            },
            "description": ""
          },
          {
            "name": "take",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 100,
              "default": 20
            },
            "description": ""
          }
        ],
        "responses": {
          "200": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChatHistoryResponse"
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      }
    },
    "/integrations/external/chats/{id}/status": {
      "patch": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsStatus",
        "summary": "Atualizar status",
        "description": "WhatsApp: altera entre OPEN, RESOLVED e SNOOZED, registrando o histórico. Permissão da chave: crm/chats.update. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateExternalChatStatus"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChatDetails"
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      }
    },
    "/integrations/external/chats/{id}/priority": {
      "patch": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsPriority",
        "summary": "Atualizar prioridade",
        "description": "WhatsApp: 0 baixa, 1 normal, 2 alta, 3 urgente. Permissão da chave: crm/chats.update. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateExternalChatPriority"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChatDetails"
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      }
    },
    "/integrations/external/chats/{id}/archive": {
      "patch": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsArchive",
        "summary": "Arquivar chat",
        "description": "Arquiva um chat WhatsApp e registra o evento operacional. Permissão da chave: crm/chats.update. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          }
        ],
        "responses": {
          "200": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChatDetails"
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      }
    },
    "/integrations/external/chats/{id}/unarchive": {
      "patch": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsUnarchive",
        "summary": "Desarquivar chat",
        "description": "Desarquiva um chat WhatsApp e registra o evento operacional. Permissão da chave: crm/chats.update. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          }
        ],
        "responses": {
          "200": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChatDetails"
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      }
    },
    "/integrations/external/chats/{id}/read": {
      "post": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsRead",
        "summary": "Marcar chat como lido",
        "description": "WhatsApp ou Instagram. Zera unread_count e remove a marcação manual de não lido. Permissão da chave: crm/chats.update. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          }
        ],
        "responses": {
          "201": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "anyOf": [
                    {
                      "$ref": "#/components/schemas/ChatDetails"
                    },
                    {
                      "$ref": "#/components/schemas/ChatInstagramDetails"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      }
    },
    "/integrations/external/chats/{id}/unread": {
      "post": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsUnread",
        "summary": "Marcar chat como não lido",
        "description": "WhatsApp ou Instagram. Ativa is_manually_unread sem exigir nova mensagem do contato. Permissão da chave: crm/chats.update. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          }
        ],
        "responses": {
          "201": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "anyOf": [
                    {
                      "$ref": "#/components/schemas/ChatDetails"
                    },
                    {
                      "$ref": "#/components/schemas/ChatInstagramDetails"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      }
    },
    "/integrations/external/chats/{id}/create-person": {
      "post": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsCreatePerson",
        "summary": "Criar ou vincular pessoa ao chat",
        "description": "WhatsApp ou Instagram. person_id vincula pessoa existente; sem ele, cria pessoa com os dados informados e vincula o contato do canal. Permissão da chave: crm/chats.update e crm/person.create. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateExternalChatPerson"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "anyOf": [
                    {
                      "$ref": "#/components/schemas/ChatDetails"
                    },
                    {
                      "$ref": "#/components/schemas/ChatInstagramDetails"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      }
    },
    "/integrations/external/chats/{id}/participants": {
      "post": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsAddParticipant",
        "summary": "Adicionar participante",
        "description": "Adiciona um usuário elegível como participante do chat WhatsApp. Permissão da chave: crm/chats.update. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AddExternalChatParticipant"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChatDetails"
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      }
    },
    "/integrations/external/chats/{id}/participants/{userId}": {
      "delete": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsRemoveParticipant",
        "summary": "Remover participante",
        "description": "Remove participante do chat WhatsApp. Não permite remover o responsável atual. Permissão da chave: crm/chats.update. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          },
          {
            "name": "userId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID do usuário participante."
          }
        ],
        "responses": {
          "200": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChatDetails"
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      }
    },
    "/integrations/external/chats/{id}/responsible": {
      "patch": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsResponsible",
        "summary": "Atualizar responsável",
        "description": "WhatsApp ou Instagram. update_chat=true por padrão. update_leads/update_deals=false por padrão; quando habilitados, propagam aos leads/oportunidades abertos, não arquivados e não excluídos associados à pessoa, exigindo também crm/lead.update e/ou crm/deal.update na chave. Permissão da chave: crm/chats.update. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateExternalChatResponsible"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "anyOf": [
                    {
                      "$ref": "#/components/schemas/ChatDetails"
                    },
                    {
                      "$ref": "#/components/schemas/ChatInstagramDetails"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      }
    },
    "/integrations/external/chats/{id}/timeline": {
      "get": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsTimeline",
        "summary": "Consultar timeline de mensagens e ligações",
        "description": "Timeline WhatsApp com eventos MESSAGE e CALL em uma paginação global. Com search, pesquisa corpo de mensagens e não inclui ligações. Permissão da chave: crm/chats.read. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          },
          {
            "name": "search",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            },
            "description": "Busca textual, quando suportada pela operação."
          },
          {
            "name": "skip",
            "in": "query",
            "required": false,
            "schema": {
              "type": "number",
              "default": 0
            },
            "description": "Quantidade de registros a pular; valores negativos são normalizados para zero."
          },
          {
            "name": "take",
            "in": "query",
            "required": false,
            "schema": {
              "type": "number",
              "default": 20
            },
            "description": "Quantidade por página. O serviço limita o resultado a 100 registros."
          },
          {
            "name": "order",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "enum": [
                "asc",
                "desc"
              ],
              "default": "desc"
            },
            "description": "Ordenação cronológica das mensagens/eventos."
          }
        ],
        "responses": {
          "200": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChatTimelineResponse"
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      }
    },
    "/integrations/external/chats/{id}/templates": {
      "get": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsTemplates",
        "summary": "Listar templates disponíveis",
        "description": "Templates WhatsApp da WABA associada ao chat. Retorna um array direto, com required_fields para orientar o preenchimento; não usa envelope total/records. Permissão da chave: crm/chats.read. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          },
          {
            "name": "category",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "enum": [
                "AUTHENTICATION",
                "MARKETING",
                "UTILITY",
                "SERVICE"
              ]
            },
            "description": ""
          }
        ],
        "responses": {
          "200": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/ChatTemplate"
                  }
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      }
    },
    "/integrations/external/chats/{id}/messages/interactive": {
      "post": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsInteractive",
        "summary": "Enviar mensagem interativa",
        "description": "WhatsApp: botões ou lista, dentro da janela de atendimento. IDs de opções devem ser únicos. button exige 1 a 3 buttons; list exige button e sections com até 10 linhas no total. Permissão da chave: crm/chats.write. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SendExternalChatInteractive"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChatMessagesResponse"
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      }
    },
    "/integrations/external/chats/{id}/messages/location": {
      "post": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsLocation",
        "summary": "Enviar localização",
        "description": "Envia coordenadas em um chat WhatsApp dentro da janela de atendimento. Na versão atual da API, o corpo é validado como mensagem interativa e a rota retorna 400 (\"Payload da mensagem interativa inválido.\") mesmo com latitude e longitude válidas. Permissão da chave: crm/chats.write. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SendExternalChatLocation"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChatMessagesResponse"
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      }
    },
    "/integrations/external/chats/{id}/messages/typing": {
      "post": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsTyping",
        "summary": "Sinalizar digitação",
        "description": "WhatsApp. is_typing=true utiliza uma mensagem inbound das últimas 24 horas: informe reference_wamid ou permita localizar a mais recente elegível. is_typing=false retorna confirmação local sem novo envio à Meta e com reference_wamid=null. Permissão da chave: crm/chats.write. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SendExternalChatTyping"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChatTypingResponse"
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      }
    },
    "/integrations/external/chats/{id}/messages/{messageId}": {
      "patch": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsEditMessage",
        "summary": "Solicitar edição de mensagem (não suportada)",
        "description": "A implementação atual registra a tentativa para auditoria e retorna HTTP 400: a API oficial da Meta não suporta edição de mensagens enviadas via WhatsApp Business Platform. Não há resposta de sucesso implementada. Permissão da chave: crm/chats.update. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          },
          {
            "name": "messageId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID local da mensagem (não o WAMID)."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/EditExternalChatMessage"
              }
            }
          }
        },
        "responses": {
          "400": {
            "description": "A API oficial da Meta não suporta edição de mensagens enviadas via WhatsApp Business Platform."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      },
      "delete": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsDeleteMessage",
        "summary": "Excluir mensagem enviada",
        "description": "WhatsApp: somente mensagens da empresa. Solicita exclusão ao provedor; recusa da Meta retorna 400. Em sucesso retorna a mensagem atualizada, com status deleted. Permissão da chave: crm/chats.delete. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          },
          {
            "name": "messageId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID local da mensagem (não o WAMID)."
          }
        ],
        "responses": {
          "200": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChatMessage"
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      }
    },
    "/integrations/external/chats/{id}/messages/{messageId}/reaction": {
      "post": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsReact",
        "summary": "Aplicar reação",
        "description": "Aplica reação à mensagem e retorna a mensagem atualizada. Suporta WhatsApp e Instagram conforme permissões e regras do provedor. No Instagram, aceita apenas love, like, dislike, smile, angry, sad e wow, pelo nome ou pelo emoji correspondente; outras reações retornam 400. Permissão da chave: crm/chats.update. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          },
          {
            "name": "messageId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID local da mensagem (não o WAMID)."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ReactExternalChatMessage"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "anyOf": [
                    {
                      "$ref": "#/components/schemas/ChatMessage"
                    },
                    {
                      "$ref": "#/components/schemas/ChatInstagramMessage"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      },
      "delete": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsRemoveReaction",
        "summary": "Remover reação",
        "description": "Remove reação da empresa e retorna a mensagem atualizada. Suporta WhatsApp e Instagram. Permissão da chave: crm/chats.update. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          },
          {
            "name": "messageId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID local da mensagem (não o WAMID)."
          }
        ],
        "responses": {
          "200": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "anyOf": [
                    {
                      "$ref": "#/components/schemas/ChatMessage"
                    },
                    {
                      "$ref": "#/components/schemas/ChatInstagramMessage"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      }
    },
    "/integrations/external/chats/{id}/scheduled-messages": {
      "post": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsCreateScheduled",
        "summary": "Agendar mensagem",
        "description": "Agendamento WhatsApp. scheduled_at deve estar no futuro. Texto/anexos só podem ser agendados dentro de session_expires_at; após a janela é obrigatório template. cancel_on_inbound=true cancela o envio pendente se houver interação inbound. Permissão da chave: crm/chats.write. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateExternalChatScheduledMessage"
              }
            },
            "multipart/form-data": {
              "schema": {
                "$ref": "#/components/schemas/CreateExternalChatScheduledMessageMultipart"
              },
              "encoding": {
                "template": {
                  "contentType": "application/json"
                },
                "template_fields": {
                  "contentType": "application/json"
                },
                "files": {
                  "style": "form",
                  "explode": true
                },
                "file": {
                  "style": "form",
                  "explode": true
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChatScheduledMessage"
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      },
      "get": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsScheduledMessages",
        "summary": "Listar mensagens agendadas",
        "description": "Agendamentos WhatsApp ordenados por scheduled_at ascendente. total considera toda a consulta. Permissão da chave: crm/chats.read. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          },
          {
            "name": "search",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            },
            "description": "Aceito pelo DTO compartilhado, mas atualmente não aplica busca aos agendamentos."
          },
          {
            "name": "skip",
            "in": "query",
            "required": false,
            "schema": {
              "type": "number",
              "default": 0
            },
            "description": "Quantidade de registros a pular; valores negativos são normalizados para zero."
          },
          {
            "name": "take",
            "in": "query",
            "required": false,
            "schema": {
              "type": "number",
              "default": 20
            },
            "description": "Quantidade por página. O serviço limita o resultado a 100 registros."
          },
          {
            "name": "status",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "enum": [
                "PENDING",
                "PROCESSING",
                "SENT",
                "CANCELED",
                "FAILED"
              ]
            },
            "description": ""
          }
        ],
        "responses": {
          "200": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChatScheduledMessageResponse"
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      }
    },
    "/integrations/external/chats/{id}/scheduled-messages/{scheduledMessageId}": {
      "patch": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsUpdateScheduled",
        "summary": "Atualizar mensagem agendada",
        "description": "Somente PENDING pode ser editado. Campos ausentes preservam o valor atual. Novos arquivos substituem todos os anexos; replace_files=true sem arquivos limpa os anexos. Revalida data futura e janela de atendimento. Agendamentos criados por agente de IA não podem ser editados e retornam 400; o cancelamento continua disponível. Permissão da chave: crm/chats.write. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          },
          {
            "name": "scheduledMessageId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da mensagem agendada."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateExternalChatScheduledMessage"
              }
            },
            "multipart/form-data": {
              "schema": {
                "$ref": "#/components/schemas/UpdateExternalChatScheduledMessageMultipart"
              },
              "encoding": {
                "template": {
                  "contentType": "application/json"
                },
                "template_fields": {
                  "contentType": "application/json"
                },
                "files": {
                  "style": "form",
                  "explode": true
                },
                "file": {
                  "style": "form",
                  "explode": true
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChatScheduledMessage"
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      }
    },
    "/integrations/external/chats/{id}/scheduled-messages/{scheduledMessageId}/cancel": {
      "post": {
        "tags": [
          "Chats"
        ],
        "operationId": "externalChatsCancelScheduled",
        "summary": "Cancelar mensagem agendada",
        "description": "Somente PENDING pode ser cancelado. Retorna o agendamento com status CANCELED e cancel_reason USER_REQUEST; reason é opcional. Permissão da chave: crm/chats.write. O acesso também respeita a empresa e as permissões do usuário criador da chave.",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da conversa."
          },
          {
            "name": "scheduledMessageId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            },
            "description": "UUID da mensagem agendada."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CancelExternalChatScheduledMessage"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Operação realizada.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChatScheduledMessage"
                }
              }
            }
          },
          "400": {
            "description": "Payload ou regra de negócio inválidos."
          },
          "401": {
            "description": "Chave de integração ausente, inválida, inativa ou expirada, ou domínio de origem não autorizado para a chave."
          },
          "403": {
            "description": "Permissão da chave ou do usuário insuficiente para o recurso."
          },
          "404": {
            "description": "Conversa ou recurso associado não encontrado no escopo acessível."
          },
          "429": {
            "description": "Limite de requisições da integração excedido."
          },
          "500": {
            "description": "Falha interna ou na comunicação com o provedor."
          }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "API key",
        "description": "Chave de integração com prefixo wegly_, enviada em Authorization: Bearer <chave>. Não é JWT. A chave deve estar ativa, não excluída e dentro da validade. Com allowed_domain, Origin (ou Referer na ausência de Origin) precisa informar o hostname permitido. A empresa e as permissões são obtidas pela chave."
      }
    },
    "parameters": {
      "CustomFieldSearch": {
        "name": "search",
        "in": "query",
        "description": "Busca textual pelo nome do campo personalizado.",
        "schema": {
          "type": "string"
        }
      },
      "Search": {
        "name": "search",
        "in": "query",
        "description": "Busca pelo nome do arquivo.",
        "schema": {
          "type": "string"
        }
      },
      "Skip": {
        "name": "skip",
        "in": "query",
        "description": "Quantidade de registros a pular (offset). Padrão 0.",
        "schema": {
          "type": "integer",
          "minimum": 0,
          "default": 0
        }
      },
      "CustomFieldEntityType": {
        "name": "entity_type",
        "in": "query",
        "description": "Filtra pelo tipo de entidade do campo personalizado.",
        "schema": {
          "$ref": "#/components/schemas/CustomFieldEntityType"
        }
      },
      "CustomFieldStatus": {
        "name": "status",
        "in": "query",
        "description": "Filtra pelo status do campo personalizado.",
        "schema": {
          "$ref": "#/components/schemas/CustomFieldStatus"
        }
      },
      "ProposalSearch": {
        "name": "search",
        "in": "query",
        "description": "Busca pelo título da proposta, pelo título do lead ou do negócio de origem e, quando o termo é numérico (com ou sem `#`), pelo código da proposta.",
        "schema": {
          "type": "string"
        }
      },
      "ProposalDealId": {
        "name": "deal_id",
        "in": "query",
        "description": "Filtra pelo UUID do negócio vinculado à proposta.",
        "schema": {
          "type": "string",
          "format": "uuid"
        }
      },
      "ProposalLeadId": {
        "name": "lead_id",
        "in": "query",
        "description": "Filtra pelo UUID do lead vinculado à proposta.",
        "schema": {
          "type": "string",
          "format": "uuid"
        }
      },
      "ProposalCreatedBy": {
        "name": "created_by",
        "in": "query",
        "description": "Filtra pelo UUID do usuário criador da proposta.",
        "schema": {
          "type": "string",
          "format": "uuid"
        }
      },
      "ProposalStatus": {
        "name": "status",
        "in": "query",
        "description": "Filtra pelo status da proposta.",
        "schema": {
          "$ref": "#/components/schemas/ProposalStatusValue"
        }
      },
      "ProposalApproved": {
        "name": "approved",
        "in": "query",
        "description": "Quando `true`, retorna apenas propostas aprovadas; quando `false`, exclui propostas aprovadas.",
        "schema": {
          "type": "boolean"
        }
      },
      "ProposalArchived": {
        "name": "archived",
        "in": "query",
        "description": "Quando `true`, retorna apenas propostas arquivadas; quando `false`, retorna apenas não arquivadas.",
        "schema": {
          "type": "boolean"
        }
      },
      "ProposalCode": {
        "name": "code",
        "in": "query",
        "description": "Filtra pelo código sequencial interno da proposta.",
        "schema": {
          "type": "integer",
          "minimum": 0
        }
      },
      "ProposalCreatedFrom": {
        "name": "created_from",
        "in": "query",
        "description": "Início do período de criação. Aceita data (`YYYY-MM-DD`), interpretada no horário de Brasília, ou data e hora ISO 8601 com fuso, como `2026-10-05T12:00:00-03:00`. Sem horário, considera o início do dia.",
        "schema": {
          "type": "string"
        }
      },
      "ProposalCreatedTo": {
        "name": "created_to",
        "in": "query",
        "description": "Fim do período de criação. Aceita data (`YYYY-MM-DD`), interpretada no horário de Brasília, ou data e hora ISO 8601 com fuso, como `2026-10-05T12:00:00-03:00`. Sem horário, considera o fim do dia.",
        "schema": {
          "type": "string"
        }
      },
      "ProposalValidFrom": {
        "name": "valid_from",
        "in": "query",
        "description": "Início do período de validade da proposta. Aceita data (`YYYY-MM-DD`), interpretada no horário de Brasília, ou data e hora ISO 8601 com fuso, como `2026-10-05T12:00:00-03:00`. Sem horário, considera o início do dia.",
        "schema": {
          "type": "string"
        }
      },
      "ProposalValidTo": {
        "name": "valid_to",
        "in": "query",
        "description": "Fim do período de validade da proposta. Aceita data (`YYYY-MM-DD`), interpretada no horário de Brasília, ou data e hora ISO 8601 com fuso, como `2026-10-05T12:00:00-03:00`. Sem horário, considera o fim do dia.",
        "schema": {
          "type": "string"
        }
      },
      "ProposalRejectedFrom": {
        "name": "rejected_from",
        "in": "query",
        "description": "Início do período de rejeição. Aceita data (`YYYY-MM-DD`), interpretada no horário de Brasília, ou data e hora ISO 8601 com fuso, como `2026-10-05T12:00:00-03:00`. Sem horário, considera o início do dia.",
        "schema": {
          "type": "string"
        }
      },
      "ProposalRejectedTo": {
        "name": "rejected_to",
        "in": "query",
        "description": "Fim do período de rejeição. Aceita data (`YYYY-MM-DD`), interpretada no horário de Brasília, ou data e hora ISO 8601 com fuso, como `2026-10-05T12:00:00-03:00`. Sem horário, considera o fim do dia.",
        "schema": {
          "type": "string"
        }
      },
      "ProposalDealCode": {
        "name": "deal_code",
        "in": "query",
        "description": "Código numérico do negócio vinculado. A API resolve o código para o ID interno antes da consulta.",
        "schema": {
          "type": "string"
        }
      },
      "ProposalIncludeDeliverySchedule": {
        "name": "include_delivery_schedule",
        "in": "query",
        "description": "Quando `true`, inclui em cada proposta o cronograma calculado ou `null` quando ele não existir. O padrão `false` omite a propriedade `delivery_schedule`.",
        "schema": {
          "type": "boolean",
          "default": false
        }
      },
      "ProposalTake": {
        "name": "take",
        "in": "query",
        "description": "Quantidade de registros a retornar, de 1 a 100. Padrão 10.",
        "schema": {
          "type": "integer",
          "minimum": 1,
          "maximum": 100,
          "default": 10
        }
      },
      "ProposalIsPrimary": {
        "name": "is_primary",
        "in": "query",
        "description": "Quando `true`, retorna apenas a proposta principal de cada lead ou negócio; quando `false`, apenas as demais.",
        "schema": {
          "type": "boolean"
        }
      },
      "ProposalDealStatus": {
        "name": "deal_status",
        "in": "query",
        "description": "Filtra pelo status do negócio vinculado: 1 = aberto, 2 = ganho, 3 = perdido. Propostas vinculadas a leads ficam fora do resultado.",
        "schema": {
          "type": "integer",
          "enum": [
            1,
            2,
            3
          ]
        }
      },
      "ProposalMinValue": {
        "name": "min_value",
        "in": "query",
        "description": "Valor total mínimo da proposta, com até duas casas decimais.",
        "schema": {
          "type": "number",
          "minimum": 0
        }
      },
      "ProposalMaxValue": {
        "name": "max_value",
        "in": "query",
        "description": "Valor total máximo da proposta, com até duas casas decimais. Não pode ser menor que `min_value`.",
        "schema": {
          "type": "number",
          "minimum": 0
        }
      },
      "ProposalOrderBy": {
        "name": "order_by",
        "in": "query",
        "description": "Campo de ordenação. Padrão `created_at`.",
        "schema": {
          "type": "string",
          "enum": [
            "created_at",
            "updated_at",
            "code",
            "total",
            "title"
          ],
          "default": "created_at"
        }
      },
      "ProposalOrderDirection": {
        "name": "order_direction",
        "in": "query",
        "description": "Direção da ordenação. Padrão `desc`.",
        "schema": {
          "type": "string",
          "enum": [
            "asc",
            "desc"
          ],
          "default": "desc"
        }
      },
      "TaskSearch": {
        "name": "search",
        "in": "query",
        "description": "Busca textual pelo título da tarefa.",
        "schema": {
          "type": "string"
        }
      },
      "TaskSkip": {
        "name": "skip",
        "in": "query",
        "description": "Quantidade de registros a pular. Envie junto com `take`: sem `take`, a listagem padrão retorna todos os registros e ignora `skip`.",
        "schema": {
          "type": "integer",
          "minimum": 0,
          "default": 0
        }
      },
      "TaskLeadId": {
        "name": "crm_lead_id",
        "in": "query",
        "description": "UUID do lead vinculado à tarefa.",
        "schema": {
          "type": "string",
          "format": "uuid"
        }
      },
      "TaskDealId": {
        "name": "crm_deal_id",
        "in": "query",
        "description": "UUID da oportunidade vinculada à tarefa.",
        "schema": {
          "type": "string",
          "format": "uuid"
        }
      },
      "TaskDeliveryId": {
        "name": "crm_delivery_id",
        "in": "query",
        "description": "UUID da entrega vinculada à tarefa.",
        "schema": {
          "type": "string",
          "format": "uuid"
        }
      },
      "TaskPersonId": {
        "name": "crm_person_id",
        "in": "query",
        "description": "UUID da pessoa vinculada à tarefa.",
        "schema": {
          "type": "string",
          "format": "uuid"
        }
      },
      "TaskOrganizationId": {
        "name": "crm_organization_id",
        "in": "query",
        "description": "UUID da organização vinculada à tarefa.",
        "schema": {
          "type": "string",
          "format": "uuid"
        }
      },
      "TaskCustomerId": {
        "name": "crm_customer_id",
        "in": "query",
        "description": "UUID do cliente vinculado à tarefa.",
        "schema": {
          "type": "string",
          "format": "uuid"
        }
      },
      "TaskResponsibleId": {
        "name": "responsible_id",
        "in": "query",
        "description": "UUID do usuário responsável pela tarefa.",
        "schema": {
          "type": "string",
          "format": "uuid"
        }
      },
      "TaskTypeId": {
        "name": "crm_task_type_id",
        "in": "query",
        "description": "UUID do tipo da tarefa.",
        "schema": {
          "type": "string",
          "format": "uuid"
        }
      },
      "TaskStageId": {
        "name": "crm_task_stage_id",
        "in": "query",
        "description": "UUID da etapa da tarefa.",
        "schema": {
          "type": "string",
          "format": "uuid"
        }
      },
      "TaskPriority": {
        "name": "priority",
        "in": "query",
        "description": "Prioridade da tarefa: 0 baixa, 1 normal, 2 alta, 3 urgente.",
        "schema": {
          "type": "integer",
          "enum": [
            0,
            1,
            2,
            3
          ]
        }
      },
      "TaskOnlyPending": {
        "name": "only_pending",
        "in": "query",
        "description": "Quando true, retorna apenas tarefas não concluídas.",
        "schema": {
          "type": "boolean"
        }
      },
      "TaskExecutionPeriod": {
        "name": "execution_period",
        "in": "query",
        "description": "Filtra tarefas pendentes por período de execução.",
        "schema": {
          "type": "string",
          "enum": [
            "overdue",
            "today",
            "future"
          ]
        }
      },
      "TaskIsPersonal": {
        "name": "is_personal",
        "in": "query",
        "description": "Filtra tarefas pessoais ou não pessoais.",
        "schema": {
          "type": "boolean"
        }
      },
      "TaskIsMeeting": {
        "name": "is_meeting",
        "in": "query",
        "description": "Filtra tarefas cujo tipo é reunião.",
        "schema": {
          "type": "boolean"
        }
      },
      "TaskIsRecurring": {
        "name": "is_recurring",
        "in": "query",
        "description": "Filtra tarefas vinculadas a uma série recorrente.",
        "schema": {
          "type": "boolean"
        }
      },
      "TaskWithoutDateTime": {
        "name": "without_date_time",
        "in": "query",
        "description": "Quando true, retorna apenas tarefas sem data/hora definida.",
        "schema": {
          "type": "boolean"
        }
      },
      "TaskMeetingResult": {
        "name": "meeting_result",
        "in": "query",
        "description": "Filtra reuniões pelo resultado registrado.",
        "schema": {
          "type": "string",
          "enum": [
            "realized",
            "no_show",
            "cancelled",
            "rescheduled",
            "no_result"
          ]
        }
      },
      "TaskStartDateFrom": {
        "name": "start_date_from",
        "in": "query",
        "description": "Data inicial mínima da tarefa. Trabalha no horário de Brasília e aceita datas entre 1980 e 2100. Considera sempre o início do dia informado; envie `YYYY-MM-DD`. Evite `Z` ou offset: o valor não é convertido para o horário de Brasília e o limite fica deslocado.",
        "schema": {
          "type": "string"
        }
      },
      "TaskStartDateTo": {
        "name": "start_date_to",
        "in": "query",
        "description": "Data inicial máxima da tarefa. Trabalha no horário de Brasília e aceita datas entre 1980 e 2100. Com `YYYY-MM-DD`, considera o fim do dia. Também aceita data e hora no horário de Brasília, sem sufixo de fuso (`YYYY-MM-DDTHH:mm:ss`). Evite `Z` ou offset: o valor não é convertido para o horário de Brasília e o limite fica deslocado.",
        "schema": {
          "type": "string"
        }
      },
      "TaskCompletedAtFrom": {
        "name": "completed_at_from",
        "in": "query",
        "description": "Data mínima de conclusão. Trabalha no horário de Brasília e aceita datas entre 1980 e 2100. Considera sempre o início do dia informado; envie `YYYY-MM-DD`. Evite `Z` ou offset: o valor não é convertido para o horário de Brasília e o limite fica deslocado.",
        "schema": {
          "type": "string"
        }
      },
      "TaskCompletedAtTo": {
        "name": "completed_at_to",
        "in": "query",
        "description": "Data máxima de conclusão. Trabalha no horário de Brasília e aceita datas entre 1980 e 2100. Com `YYYY-MM-DD`, considera o fim do dia. Também aceita data e hora no horário de Brasília, sem sufixo de fuso (`YYYY-MM-DDTHH:mm:ss`). Evite `Z` ou offset: o valor não é convertido para o horário de Brasília e o limite fica deslocado.",
        "schema": {
          "type": "string"
        }
      },
      "TaskCreatedAtFrom": {
        "name": "created_at_from",
        "in": "query",
        "description": "Data mínima de criação. Trabalha no horário de Brasília e aceita datas entre 1980 e 2100. Considera sempre o início do dia informado; envie `YYYY-MM-DD`. Evite `Z` ou offset: o valor não é convertido para o horário de Brasília e o limite fica deslocado.",
        "schema": {
          "type": "string"
        }
      },
      "TaskCreatedAtTo": {
        "name": "created_at_to",
        "in": "query",
        "description": "Data máxima de criação. Trabalha no horário de Brasília e aceita datas entre 1980 e 2100. Com `YYYY-MM-DD`, considera o fim do dia. Também aceita data e hora no horário de Brasília, sem sufixo de fuso (`YYYY-MM-DDTHH:mm:ss`). Evite `Z` ou offset: o valor não é convertido para o horário de Brasília e o limite fica deslocado.",
        "schema": {
          "type": "string"
        }
      },
      "TaskOrderPriority": {
        "name": "order_priority",
        "in": "query",
        "description": "Ordenação por prioridade. Quando mais de um `order_*` é enviado, a precedência é prioridade, data inicial, criação e atualização.",
        "schema": {
          "type": "string",
          "enum": [
            "asc",
            "desc"
          ]
        }
      },
      "TaskOrderStartDate": {
        "name": "order_start_date",
        "in": "query",
        "description": "Ordenação por data inicial. Quando mais de um `order_*` é enviado, a precedência é prioridade, data inicial, criação e atualização.",
        "schema": {
          "type": "string",
          "enum": [
            "asc",
            "desc"
          ]
        }
      },
      "TaskOrderCreatedAt": {
        "name": "order_created_at",
        "in": "query",
        "description": "Ordenação por data de criação. Quando mais de um `order_*` é enviado, a precedência é prioridade, data inicial, criação e atualização.",
        "schema": {
          "type": "string",
          "enum": [
            "asc",
            "desc"
          ]
        }
      },
      "TaskOrderUpdatedAt": {
        "name": "order_updated_at",
        "in": "query",
        "description": "Ordenação por data de atualização. Quando mais de um `order_*` é enviado, a precedência é prioridade, data inicial, criação e atualização.",
        "schema": {
          "type": "string",
          "enum": [
            "asc",
            "desc"
          ]
        }
      }
    },
    "schemas": {
      "CustomFieldEntityType": {
        "type": "integer",
        "enum": [
          1,
          2,
          3,
          4
        ],
        "description": "1 = lead, 2 = oportunidade, 3 = entrega, 4 = proposta.\n"
      },
      "CustomFieldStatus": {
        "type": "integer",
        "enum": [
          0,
          1
        ],
        "description": "0 = inativo, 1 = ativo."
      },
      "CustomFieldType": {
        "type": "integer",
        "enum": [
          0,
          1,
          2,
          3,
          4,
          5,
          6,
          7,
          8,
          9,
          10
        ],
        "description": "0 = texto curto, 1 = texto longo, 2 = número, 3 = rádio (uma opção, em option_id), 4 = seleção (option_id quando max_checkbox_selections = 1; nos demais casos, option_ids), 5 = caixas de seleção (option_ids), 6 = arquivo, 7 = data (YYYY-MM-DD), 8 = hora (HH:mm), 9 = data e hora local (YYYY-MM-DDTHH:mm), 10 = booleano. O tipo arquivo (6) não é suportado para a entidade proposta (4) e não pode ser preenchido pelas rotas externas de lead e oportunidade; o tipo booleano (10) é exclusivo da entidade proposta."
      },
      "ExternalCustomFieldOption": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "value": {
            "type": "string"
          },
          "position": {
            "type": "integer"
          }
        }
      },
      "ExternalCustomField": {
        "type": "object",
        "description": "Campo personalizado retornado pela API pública de integrações externas.",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "entity_type": {
            "$ref": "#/components/schemas/CustomFieldEntityType"
          },
          "section_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "section": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "name": {
                "type": "string"
              },
              "position": {
                "type": "integer"
              }
            }
          },
          "type": {
            "$ref": "#/components/schemas/CustomFieldType"
          },
          "status": {
            "$ref": "#/components/schemas/CustomFieldStatus"
          },
          "name": {
            "type": "string"
          },
          "position": {
            "type": "integer"
          },
          "is_required": {
            "type": "boolean"
          },
          "is_visible_on_create": {
            "type": "boolean"
          },
          "min_checkbox_selections": {
            "type": "integer",
            "nullable": true
          },
          "max_checkbox_selections": {
            "type": "integer",
            "nullable": true
          },
          "options": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ExternalCustomFieldOption"
            }
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "LeadVisibility": {
        "type": "integer",
        "enum": [
          0,
          1
        ],
        "description": "0 = privado; 1 = visível ao time, conforme as regras de acesso do CRM."
      },
      "LeadStatus": {
        "type": "integer",
        "enum": [
          1,
          2,
          3
        ],
        "description": "1 = aberto, 2 = ganho, 3 = perdido."
      },
      "LeadArchivedFilter": {
        "type": "string",
        "enum": [
          "include",
          "only"
        ]
      },
      "LeadResultFilter": {
        "type": "string",
        "enum": [
          "include",
          "only"
        ]
      },
      "LeadOrderBy": {
        "type": "string",
        "enum": [
          "name",
          "created_at",
          "last_activity_at",
          "quality_rating",
          "score"
        ]
      },
      "LeadOrderDirection": {
        "type": "string",
        "enum": [
          "asc",
          "desc"
        ]
      },
      "PersonContactType": {
        "type": "integer",
        "enum": [
          0,
          1,
          2,
          3,
          4,
          5,
          6,
          7
        ],
        "description": "0=WhatsApp, 1=Email, 2=Celular, 3=Telefone, 4=Instagram, 5=Facebook, 6=LinkedIn, 7=Outros.\n"
      },
      "MeasurementConsent": {
        "type": "string",
        "enum": [
          "GRANTED",
          "DENIED",
          "UNSPECIFIED"
        ],
        "description": "Consentimento para mensuração: GRANTED autoriza, DENIED recusa e UNSPECIFIED registra que não houve decisão informada. Em respostas de registros históricos sem valor canônico oficial, a API usa a decisão oficial do snapshot ativo mais recente; snapshots sem decisão não a sombreiam e a ausência de ambos resulta em UNSPECIFIED, sem backfill.\n"
      },
      "MarketingTracking": {
        "type": "object",
        "description": "Rastreio de marketing. Todos os valores são sanitizados (trim) e campos vazios são ignorados. `utm_*` são normalizados para `wegly_*` equivalentes quando estes não forem enviados. `utm_term` vira `utm_search_term` se o campo específico não for enviado. `url_conversion` tem seus parâmetros extraídos automaticamente (wegly_code, wegly_source, wegly_campaign, wegly_ad_set, wegly_content, wegly_displayed_on, wegly_conversion_tool, utm_*, gclid, fbclid). Em POST e PUT, `measurement_consent` na URL também é extraído. Valor desconhecido, duplicado divergente ou presente em URL malformada vira `UNSPECIFIED`; divergência com o body retorna 400. Sem `GRANTED`, `obref` é removido da query e o fragmento inteiro da URL completa é descartado; a URL integral nunca é registrada em logs. O alias isolado, um objeto vazio ou somente campos nulos/em branco não constituem aquisição e não criam snapshot/log. Quando `wegly_code` referencia um tracker válido e não há `crm_lead_source_id`, a origem do registro é a do tracker. No PUT, os campos enviados corrigem a aquisição atual: omitidos são preservados e `null` limpa o valor. Quando não há tracker nem origem explícita, `wegly_source` ou `utm_source` busca/cria a origem automaticamente.\n",
        "properties": {
          "measurement_consent": {
            "allOf": [
              {
                "$ref": "#/components/schemas/MeasurementConsent"
              }
            ],
            "description": "Alias legado. Prefira o campo top-level `measurement_consent`; se ambos forem enviados, os valores devem ser iguais.\n"
          },
          "wegly_code": {
            "type": "string",
            "description": "Código de rastreio Wegly. Vincula o tracker à aquisição e define a origem do registro quando `crm_lead_source_id` não é enviado."
          },
          "wegly_source": {
            "type": "string",
            "description": "Origem textual Wegly. Tem prioridade sobre `utm_source` quando for necessário buscar/criar origem automaticamente. `IG`, em qualquer caixa, é tratado como a origem `Instagram`."
          },
          "wegly_campaign": {
            "type": "string"
          },
          "wegly_ad_set": {
            "type": "string"
          },
          "wegly_content": {
            "type": "string"
          },
          "wegly_displayed_on": {
            "type": "string"
          },
          "wegly_conversion_tool": {
            "type": "string",
            "description": "ID, código ou nome da ferramenta de conversão. Se não existir, é criada automaticamente com código gerado.\n"
          },
          "wegly_creative": {
            "type": "string"
          },
          "gclid": {
            "type": "string",
            "description": "Prioritário sobre fbclid quando ambos enviados."
          },
          "fbclid": {
            "type": "string"
          },
          "url_conversion": {
            "type": "string",
            "description": "URL completa da conversão. Se não contiver protocolo, será normalizada para https://. É armazenada a base e a URL completa.\n"
          },
          "utm_search_term": {
            "type": "string"
          },
          "utm_source": {
            "type": "string",
            "description": "Fonte textual de marketing. Busca/cria origem automaticamente quando não houver `wegly_code`, `wegly_source` nem `crm_lead_source_id`. `IG`, em qualquer caixa, é tratado como a origem `Instagram`."
          },
          "utm_medium": {
            "type": "string",
            "description": "Meio/canal da campanha de marketing."
          },
          "utm_campaign": {
            "type": "string"
          },
          "utm_ad_set": {
            "type": "string"
          },
          "utm_content": {
            "type": "string"
          },
          "utm_term": {
            "type": "string"
          },
          "utm_display_on": {
            "type": "string"
          },
          "fbc": {
            "type": "string"
          },
          "fbp": {
            "type": "string"
          },
          "client_ip_address": {
            "type": "string"
          },
          "client_user_agent": {
            "type": "string"
          },
          "ga_client_id": {
            "type": "string"
          },
          "oppref": {
            "type": "string",
            "description": "Referência de rastreio; também pode ser extraída de url_conversion."
          },
          "obref": {
            "type": "string",
            "description": "Referência de mensuração preservada somente com consentimento efetivo GRANTED; também é removida da query da URL quando não autorizado."
          }
        }
      },
      "LeadPersonContact": {
        "type": "object",
        "properties": {
          "type": {
            "$ref": "#/components/schemas/PersonContactType"
          },
          "value": {
            "type": "string",
            "description": "Valor do contato. Telefones (tipos 0, 2 e 3) têm caracteres não numéricos removidos e devem ficar com 10 ou 11 dígitos (DDD + número, sem o DDI 55). O tipo 1 deve ser um e-mail válido.\n",
            "minLength": 1
          },
          "primary": {
            "type": "boolean",
            "description": "Indica contato principal ao cadastrar uma pessoa nova."
          }
        },
        "required": [
          "type",
          "value"
        ]
      },
      "LeadPerson": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string",
            "minLength": 1
          },
          "birth_date": {
            "type": "string",
            "format": "date"
          },
          "gender": {
            "type": "integer"
          },
          "notes": {
            "type": "string"
          },
          "contacts": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/LeadPersonContact"
            }
          },
          "avoid_duplicate": {
            "type": "boolean",
            "description": "Na criação (POST), true e duplicate_check_types preenchido habilitam a busca por qualquer contato dos tipos informados. Reutiliza a primeira pessoa encontrada na empresa e adiciona contatos faltantes; os demais dados de pessoa enviados não substituem o cadastro existente."
          },
          "duplicate_check_types": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/PersonContactType"
            },
            "description": "Tipos de contato usados na deduplicação durante POST. Telefones consideram variações brasileiras com e sem DDI 55."
          },
          "documents": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ExternalCrmPersonDocumentInput"
            }
          },
          "address": {
            "$ref": "#/components/schemas/ExternalCrmAddressInput"
          },
          "addresses": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ExternalCrmAddressInput"
            }
          }
        },
        "required": [
          "name"
        ]
      },
      "LeadOrganization": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string",
            "minLength": 1
          },
          "legal_name": {
            "type": "string"
          },
          "document": {
            "type": "string"
          },
          "industry": {
            "type": "string"
          },
          "description": {
            "type": "string"
          },
          "phone": {
            "type": "string"
          },
          "email": {
            "type": "string"
          },
          "site": {
            "type": "string"
          },
          "status": {
            "type": "integer",
            "enum": [
              0,
              1
            ]
          },
          "addresses": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ExternalCrmAddressInput"
            }
          },
          "address_name": {
            "type": "string"
          },
          "address_street": {
            "type": "string"
          },
          "address_number": {
            "type": "string"
          },
          "address_complement": {
            "type": "string"
          },
          "address_district": {
            "type": "string"
          },
          "address_city": {
            "type": "string"
          },
          "address_state": {
            "type": "string"
          },
          "address_postal_code": {
            "type": "string"
          },
          "address_status": {
            "type": "integer",
            "enum": [
              0,
              1
            ]
          },
          "address_type": {
            "type": "integer",
            "enum": [
              0,
              1,
              2,
              3
            ],
            "description": "0 = comercial; 1 = residencial; 2 = entrega; 3 = faturamento."
          }
        },
        "required": [
          "name"
        ]
      },
      "LeadCustomFieldValue": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "description": "ID do campo customizado.",
            "minLength": 1
          },
          "value": {
            "type": "string",
            "description": "Valor textual. Para tipos temporais, use YYYY-MM-DD (DATE), HH:mm (TIME) ou YYYY-MM-DDTHH:mm (DATETIME), sem Z ou offset.\n"
          },
          "option_id": {
            "type": "string"
          },
          "option_ids": {
            "type": "array",
            "items": {
              "type": "string"
            }
          }
        },
        "required": [
          "id"
        ]
      },
      "LeadFollowerInput": {
        "type": "object",
        "properties": {
          "user_id": {
            "type": "string",
            "format": "uuid",
            "description": "Usuário existente na empresa. Duplicatas são ignoradas na mesma requisição."
          },
          "role_id": {
            "type": "string",
            "format": "uuid",
            "description": "Função de seguidor (deve existir e estar ativa)."
          },
          "notes": {
            "type": "string",
            "maxLength": 1000
          }
        },
        "required": [
          "user_id",
          "role_id"
        ],
        "additionalProperties": false
      },
      "LeadNoteInput": {
        "type": "object",
        "properties": {
          "content": {
            "type": "string",
            "minLength": 1,
            "description": "Texto simples ou HTML. O HTML é higienizado; se nada restar após a higienização, a API retorna 400."
          },
          "is_pinned": {
            "type": "boolean"
          }
        },
        "required": [
          "content"
        ]
      },
      "CreateExternalLead": {
        "type": "object",
        "required": [
          "title"
        ],
        "properties": {
          "stage_id": {
            "type": "string",
            "format": "uuid",
            "description": "Estágio alvo. Caso omitido, usa a primeira etapa do funil primário."
          },
          "responsible_id": {
            "type": "string",
            "format": "uuid",
            "description": "Responsável pelo lead. Padrão: criador da chave. Se o usuário informado estiver inativo ou arquivado, o registro é atribuído ao usuário master da conta, com nota automática; usuário inexistente ou de outra empresa retorna 400."
          },
          "quality_rating": {
            "type": "integer",
            "enum": [
              1,
              2,
              3,
              4,
              5
            ]
          },
          "quality_reason": {
            "type": "string",
            "description": "Motivo da qualificação; obrigatório se o funil exigir."
          },
          "title": {
            "type": "string",
            "maxLength": 150,
            "minLength": 1
          },
          "visibility": {
            "$ref": "#/components/schemas/LeadVisibility"
          },
          "tags": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "Lista de IDs de tags existentes. IDs inexistentes resultam em erro."
          },
          "persons_id": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "person_id": {
                  "type": "string",
                  "format": "uuid"
                }
              },
              "required": [
                "person_id"
              ]
            },
            "description": "IDs de pessoas já cadastradas que serão associadas."
          },
          "person": {
            "$ref": "#/components/schemas/LeadPerson"
          },
          "organization_id": {
            "type": "string",
            "format": "uuid",
            "description": "Organização existente. Conflita com `organization`."
          },
          "organization": {
            "$ref": "#/components/schemas/LeadOrganization"
          },
          "custom_fields": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/LeadCustomFieldValue"
            },
            "description": "Respostas dos campos personalizados. Todos os campos obrigatórios da entidade precisam ser enviados; campos do tipo arquivo não são aceitos nesta rota."
          },
          "measurement_consent": {
            "allOf": [
              {
                "$ref": "#/components/schemas/MeasurementConsent"
              }
            ],
            "description": "Padrão GRANTED quando omitido na criação."
          },
          "marketing": {
            "$ref": "#/components/schemas/MarketingTracking"
          },
          "crm_lead_source_id": {
            "type": "string",
            "format": "uuid",
            "description": "Origem existente. Única forma aceita para informar origem manual nesta API."
          },
          "followers": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/LeadFollowerInput"
            },
            "description": "Seguidores adicionados após a criação do lead. Usuários duplicados na lista são ignorados. Se a gravação falhar, a API retorna erro, mas o registro permanece criado."
          },
          "note": {
            "$ref": "#/components/schemas/LeadNoteInput"
          },
          "idempotency_key": {
            "type": "string",
            "maxLength": 255,
            "description": "Chave da tentativa lógica de criação. O header x-idempotency-key, quando preenchido, tem prioridade. Reutilize a mesma chave para repetir uma chamada sem resposta; depois de uma criação que falhou após iniciada, use uma nova chave."
          }
        }
      },
      "UpdateExternalLead": {
        "type": "object",
        "required": [
          "title"
        ],
        "properties": {
          "stage_id": {
            "type": "string",
            "format": "uuid"
          },
          "responsible_id": {
            "type": "string",
            "format": "uuid",
            "description": "Usuário ativo da empresa. Um responsável inativo retorna 400; a substituição pelo master vale apenas na criação."
          },
          "quality_rating": {
            "type": "integer",
            "enum": [
              1,
              2,
              3,
              4,
              5
            ]
          },
          "quality_reason": {
            "type": "string"
          },
          "title": {
            "type": "string",
            "maxLength": 150,
            "minLength": 1
          },
          "visibility": {
            "$ref": "#/components/schemas/LeadVisibility"
          },
          "persons_id": {
            "type": "array",
            "description": "Lista de operações de associação ou remoção de participantes. `delete: true` remove a pessoa do lead; omita ou envie false para adicionar.\n",
            "items": {
              "type": "object",
              "properties": {
                "person_id": {
                  "type": "string",
                  "format": "uuid"
                },
                "delete": {
                  "type": "boolean"
                }
              },
              "required": [
                "person_id"
              ]
            }
          },
          "person": {
            "$ref": "#/components/schemas/LeadPerson"
          },
          "organization_id": {
            "type": "string",
            "nullable": true,
            "description": "Organização existente. Envie `null` para remover a organização atual. Conflita com `organization`.\n"
          },
          "organization": {
            "$ref": "#/components/schemas/LeadOrganization"
          },
          "custom_fields": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/LeadCustomFieldValue"
            },
            "description": "Quando enviado com itens, substitui todas as respostas do registro; reenvie o conjunto completo."
          },
          "measurement_consent": {
            "allOf": [
              {
                "$ref": "#/components/schemas/MeasurementConsent"
              }
            ],
            "description": "Quando omitido, preserva o valor efetivo atual."
          },
          "marketing": {
            "$ref": "#/components/schemas/MarketingTracking"
          },
          "crm_lead_source_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true,
            "description": "Origem existente. `null` remove a origem do registro e da aquisição atual."
          }
        },
        "description": "O PUT exige title. Os demais campos são opcionais; campos omitidos são preservados. Use as rotas de seguidores para alterar seguidores."
      },
      "LeadSummary": {
        "type": "object",
        "description": "Resumo retornado na listagem.",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "code": {
            "type": "integer"
          },
          "title": {
            "type": "string"
          },
          "measurement_consent": {
            "$ref": "#/components/schemas/MeasurementConsent"
          },
          "status": {
            "$ref": "#/components/schemas/LeadStatus"
          },
          "visibility": {
            "$ref": "#/components/schemas/LeadVisibility"
          },
          "quality_rating": {
            "type": "integer",
            "nullable": true
          },
          "archived_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "won_date": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "lost_date": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          },
          "last_activity_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "views_count": {
            "type": "integer"
          },
          "negotiation_mode": {
            "type": "integer",
            "description": "Modo de negociação (código interno)."
          },
          "stage": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string"
              },
              "name": {
                "type": "string"
              },
              "pipeline": {
                "type": "object",
                "properties": {
                  "id": {
                    "type": "string"
                  },
                  "name": {
                    "type": "string"
                  }
                }
              }
            }
          },
          "lead_source": {
            "type": "object",
            "nullable": true,
            "description": "Origem efetiva do registro: a da aquisição mais recente e, na falta dela, a gravada no registro. O histórico de aquisição é retornado separadamente em marketing_lead_source no detalhe.",
            "properties": {
              "id": {
                "type": "string"
              },
              "name": {
                "type": "string"
              },
              "logo": {
                "type": "string",
                "description": "URL assinada."
              }
            }
          },
          "person": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string"
              },
              "name": {
                "type": "string"
              }
            },
            "description": "Principal participante (prioriza participante marcado como `main`)."
          },
          "crm_organization_lead": {
            "type": "array",
            "description": "Relações de organização retornadas como no modelo interno.",
            "items": {
              "type": "object",
              "properties": {
                "crm_organization": {
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "name": {
                      "type": "string"
                    }
                  }
                }
              }
            }
          },
          "tags": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "name": {
                  "type": "string"
                },
                "color": {
                  "type": "object",
                  "nullable": true,
                  "description": "Cores da tag.",
                  "properties": {
                    "background": {
                      "type": "string",
                      "nullable": true
                    },
                    "foreground": {
                      "type": "string",
                      "nullable": true
                    }
                  }
                }
              }
            }
          },
          "pending_tasks_status": {
            "type": "string",
            "enum": [
              "NONE",
              "TODAY",
              "FUTURE",
              "OVERDUE"
            ],
            "description": "Consolidado das tarefas pendentes (NONE/TODAY/FUTURE/OVERDUE)."
          },
          "crm_task": {
            "type": "array",
            "description": "Tarefas pendentes retornadas com a listagem.",
            "items": {
              "type": "object",
              "properties": {
                "id": {
                  "type": "string"
                },
                "title": {
                  "type": "string"
                },
                "priority": {
                  "type": "integer"
                },
                "description": {
                  "type": "string",
                  "nullable": true
                },
                "start_date": {
                  "type": "string",
                  "format": "date-time",
                  "nullable": true
                },
                "crm_task_type": {
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "name": {
                      "type": "string"
                    },
                    "icon": {
                      "type": "string"
                    }
                  }
                },
                "end_date": {
                  "type": "string",
                  "format": "date-time",
                  "nullable": true
                },
                "has_time": {
                  "type": "boolean"
                },
                "archived_at": {
                  "type": "string",
                  "format": "date-time",
                  "nullable": true
                },
                "completed_at": {
                  "type": "string",
                  "format": "date-time",
                  "nullable": true
                },
                "deleted_at": {
                  "type": "string",
                  "format": "date-time",
                  "nullable": true
                }
              }
            }
          },
          "created_by_user": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string"
              },
              "name": {
                "type": "string"
              },
              "avatar": {
                "type": "string",
                "description": "URL assinada."
              }
            }
          },
          "responsible": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string"
              },
              "name": {
                "type": "string"
              },
              "avatar": {
                "type": "string",
                "description": "URL assinada."
              }
            }
          },
          "value": {
            "type": "number",
            "nullable": true
          },
          "icp": {
            "allOf": [
              {
                "$ref": "#/components/schemas/CrmIcpSummary"
              }
            ],
            "nullable": true
          },
          "icps": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CrmIcpAssignment"
            }
          },
          "partners": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CrmPartnerSummary"
            }
          },
          "has_channel_chat": {
            "type": "boolean",
            "description": "false quando a chave não tem crm/chats.read."
          },
          "channel_chats": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CrmChannelChatSummary"
            },
            "description": "Resumos de WhatsApp e Instagram; vazio sem crm/chats.read na própria chave."
          },
          "has_whatsapp_chat": {
            "type": "boolean",
            "description": "Alias de compatibilidade de has_channel_chat nas leituras externas."
          },
          "whatsapp_chats": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CrmChannelChatSummary"
            },
            "description": "Alias de compatibilidade de channel_chats nas leituras externas; pode incluir Instagram."
          },
          "score": {
            "type": "integer",
            "nullable": true
          },
          "score_criteria_count": {
            "type": "integer"
          },
          "score_updated_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "valuation": {
            "$ref": "#/components/schemas/CrmValuation"
          },
          "score_knowledge": {
            "$ref": "#/components/schemas/CrmScoreKnowledge"
          },
          "last_score_movement": {
            "allOf": [
              {
                "$ref": "#/components/schemas/CrmScoreMovement"
              }
            ],
            "nullable": true
          },
          "stagnation_status": {
            "type": "string",
            "enum": [
              "not_stagnant",
              "stagnant",
              "stagnant_with_future_task"
            ]
          },
          "stage_total_duration_seconds": {
            "type": "number"
          },
          "stage_total_duration_days": {
            "type": "number"
          },
          "has_future_task": {
            "type": "boolean"
          },
          "stagnates_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "stage_entered_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          }
        }
      },
      "LeadDetails": {
        "type": "object",
        "description": "Detalhamento completo retornado no GET /integrations/external/leads/{id}.",
        "properties": {
          "id": {
            "type": "string"
          },
          "code": {
            "type": "integer"
          },
          "title": {
            "type": "string"
          },
          "measurement_consent": {
            "$ref": "#/components/schemas/MeasurementConsent"
          },
          "created_by": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string"
              },
              "name": {
                "type": "string"
              },
              "avatar": {
                "type": "string"
              }
            }
          },
          "stage": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string"
              },
              "name": {
                "type": "string"
              },
              "pipeline": {
                "type": "object",
                "nullable": true,
                "properties": {
                  "id": {
                    "type": "string"
                  },
                  "name": {
                    "type": "string"
                  }
                }
              }
            }
          },
          "pipeline_stages": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "id": {
                  "type": "string"
                },
                "name": {
                  "type": "string"
                },
                "position": {
                  "type": "integer"
                }
              }
            }
          },
          "responsible": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string"
              },
              "name": {
                "type": "string"
              },
              "avatar": {
                "type": "string"
              }
            }
          },
          "lead_source": {
            "type": "object",
            "nullable": true,
            "description": "Origem efetiva do registro: a da aquisição mais recente e, na falta dela, a gravada no registro. O histórico de aquisição é retornado separadamente em marketing_lead_source no detalhe.",
            "properties": {
              "id": {
                "type": "string"
              },
              "name": {
                "type": "string"
              },
              "logo": {
                "type": "string"
              }
            }
          },
          "marketing_lead_source": {
            "type": "object",
            "nullable": true,
            "description": "Snapshot ativo de aquisição mais recente. campaing_name mantém a grafia do contrato. O consentimento efetivo é resolvido separadamente do snapshot de aquisição.",
            "properties": {
              "id": {
                "type": "string"
              },
              "utm_search_term": {
                "type": "string",
                "nullable": true
              },
              "utm_medium": {
                "type": "string",
                "nullable": true
              },
              "lead_source": {
                "type": "object",
                "nullable": true,
                "properties": {
                  "id": {
                    "type": "string"
                  },
                  "name": {
                    "type": "string"
                  },
                  "logo": {
                    "type": "string"
                  }
                }
              },
              "url_conversion": {
                "type": "string",
                "nullable": true
              },
              "campaing_name": {
                "type": "string",
                "nullable": true
              },
              "ad_set_name": {
                "type": "string",
                "nullable": true
              },
              "content_name": {
                "type": "string",
                "nullable": true
              },
              "displayed_on_name": {
                "type": "string",
                "nullable": true
              },
              "conversion_tool_name": {
                "type": "string",
                "nullable": true
              },
              "creative": {
                "type": "object",
                "nullable": true,
                "properties": {
                  "id": {
                    "type": "string"
                  },
                  "value": {
                    "type": "string"
                  },
                  "creative_uri": {
                    "type": "string"
                  }
                }
              },
              "source_url": {
                "type": "string",
                "nullable": true
              },
              "headline": {
                "type": "string",
                "nullable": true
              },
              "ad_body": {
                "type": "string",
                "nullable": true
              },
              "media_type": {
                "type": "string",
                "nullable": true
              },
              "ads_clid_id": {
                "type": "string",
                "nullable": true
              },
              "gclid": {
                "type": "string",
                "nullable": true
              },
              "fbclid": {
                "type": "string",
                "nullable": true
              },
              "fbc": {
                "type": "string",
                "nullable": true
              },
              "fbp": {
                "type": "string",
                "nullable": true
              },
              "conversion_url_full": {
                "type": "string",
                "nullable": true
              },
              "measurement_consent": {
                "$ref": "#/components/schemas/MeasurementConsent"
              }
            }
          },
          "quality_rating": {
            "type": "integer",
            "nullable": true
          },
          "quality_reason": {
            "type": "string",
            "nullable": true
          },
          "won_date": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "lost_date": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "crm_loss_reason": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string"
              },
              "name": {
                "type": "string"
              }
            }
          },
          "lost_reason_description": {
            "type": "string",
            "nullable": true
          },
          "visibility": {
            "$ref": "#/components/schemas/LeadVisibility"
          },
          "negotiation_mode": {
            "type": "integer"
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "archived_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "last_activity_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "participants": {
            "type": "array",
            "description": "Participantes do lead com informações de contato.",
            "items": {
              "type": "object",
              "properties": {
                "id": {
                  "type": "string"
                },
                "main": {
                  "type": "boolean",
                  "description": "Indica o participante principal."
                },
                "role": {
                  "type": "string",
                  "nullable": true,
                  "description": "Papel do participante no registro, em texto livre."
                },
                "notes": {
                  "type": "string",
                  "nullable": true
                },
                "person": {
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "name": {
                      "type": "string"
                    },
                    "contacts": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "id": {
                            "type": "string"
                          },
                          "type": {
                            "$ref": "#/components/schemas/PersonContactType"
                          },
                          "value": {
                            "type": "string"
                          },
                          "primary": {
                            "type": "boolean"
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "organization": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string"
              },
              "name": {
                "type": "string"
              },
              "logo": {
                "type": "string"
              }
            }
          },
          "custom_fields": {
            "type": "array",
            "description": "Respostas de campos customizados agrupadas por campo.",
            "items": {
              "type": "object",
              "properties": {
                "field_id": {
                  "type": "string"
                },
                "field_name": {
                  "type": "string"
                },
                "field_type": {
                  "type": "integer"
                },
                "answers": {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "properties": {
                      "id": {
                        "type": "string"
                      },
                      "option_id": {
                        "type": "string",
                        "nullable": true
                      },
                      "option_value": {
                        "type": "string",
                        "nullable": true
                      },
                      "value": {
                        "type": "string"
                      }
                    }
                  }
                }
              }
            }
          },
          "tags": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "id": {
                  "type": "string"
                },
                "name": {
                  "type": "string"
                },
                "color": {
                  "type": "object",
                  "nullable": true,
                  "description": "Cores da tag.",
                  "properties": {
                    "background": {
                      "type": "string",
                      "nullable": true
                    },
                    "foreground": {
                      "type": "string",
                      "nullable": true
                    }
                  }
                }
              }
            }
          },
          "stage_durations": {
            "type": "array",
            "description": "Tempo acumulado por etapa (segundos e texto legível).",
            "items": {
              "type": "object",
              "properties": {
                "stage_id": {
                  "type": "string"
                },
                "stage_name": {
                  "type": "string",
                  "nullable": true
                },
                "total_seconds": {
                  "type": "integer"
                },
                "human_readable": {
                  "type": "string"
                }
              }
            }
          },
          "value": {
            "type": "number",
            "nullable": true
          },
          "views_count": {
            "type": "integer"
          },
          "associations_count": {
            "type": "object",
            "properties": {
              "items": {
                "type": "integer"
              },
              "tasks": {
                "type": "integer"
              },
              "qualifications": {
                "type": "integer"
              },
              "notes": {
                "type": "integer"
              },
              "files": {
                "type": "integer"
              },
              "activities": {
                "type": "integer"
              },
              "proposals": {
                "type": "integer"
              },
              "deals": {
                "type": "integer"
              }
            }
          },
          "proposals": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "id": {
                  "type": "string"
                },
                "code": {
                  "type": "integer"
                },
                "version": {
                  "type": "integer"
                },
                "title": {
                  "type": "string"
                },
                "status": {
                  "type": "integer"
                },
                "is_primary": {
                  "type": "boolean"
                },
                "discount_type": {
                  "type": "integer",
                  "nullable": true
                },
                "discount_value": {
                  "type": "number",
                  "nullable": true
                },
                "subtotal": {
                  "type": "number",
                  "nullable": true
                },
                "total": {
                  "type": "number",
                  "nullable": true
                },
                "valid_until": {
                  "type": "string",
                  "format": "date-time",
                  "nullable": true
                },
                "created_at": {
                  "type": "string",
                  "format": "date-time"
                },
                "updated_at": {
                  "type": "string",
                  "format": "date-time"
                },
                "approved_at": {
                  "type": "string",
                  "format": "date-time",
                  "nullable": true
                },
                "archived_at": {
                  "type": "string",
                  "format": "date-time",
                  "nullable": true
                },
                "rejected_at": {
                  "type": "string",
                  "format": "date-time",
                  "nullable": true
                },
                "created_by": {
                  "type": "object",
                  "nullable": true,
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "name": {
                      "type": "string"
                    },
                    "avatar": {
                      "type": "string"
                    }
                  }
                },
                "approved_by": {
                  "type": "object",
                  "nullable": true,
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "name": {
                      "type": "string"
                    }
                  }
                }
              }
            }
          },
          "followers": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "role": {
                  "type": "object",
                  "nullable": true,
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "name": {
                      "type": "string"
                    }
                  }
                },
                "user": {
                  "type": "object",
                  "nullable": true,
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "name": {
                      "type": "string"
                    },
                    "avatar": {
                      "type": "string"
                    }
                  }
                },
                "notes": {
                  "type": "string",
                  "nullable": true
                }
              }
            }
          },
          "icp": {
            "allOf": [
              {
                "$ref": "#/components/schemas/CrmIcpSummary"
              }
            ],
            "nullable": true
          },
          "icps": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CrmIcpAssignment"
            }
          },
          "partners": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CrmPartnerSummary"
            }
          },
          "has_channel_chat": {
            "type": "boolean",
            "description": "false quando a chave não tem crm/chats.read."
          },
          "channel_chats": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CrmChannelChatSummary"
            },
            "description": "Resumos de WhatsApp e Instagram; vazio sem crm/chats.read na própria chave."
          },
          "has_whatsapp_chat": {
            "type": "boolean",
            "description": "Alias de compatibilidade de has_channel_chat nas leituras externas."
          },
          "whatsapp_chats": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CrmChannelChatSummary"
            },
            "description": "Alias de compatibilidade de channel_chats nas leituras externas; pode incluir Instagram."
          },
          "score": {
            "type": "integer",
            "nullable": true
          },
          "score_criteria_count": {
            "type": "integer"
          },
          "score_updated_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "valuation": {
            "$ref": "#/components/schemas/CrmValuation"
          },
          "qualification_metric": {
            "type": "string",
            "enum": [
              "quality_rating",
              "lead_score"
            ]
          },
          "projection_context": {
            "$ref": "#/components/schemas/CrmProjectionContext"
          },
          "crm_loss_reasons": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "id": {
                  "type": "string",
                  "format": "uuid"
                },
                "name": {
                  "type": "string"
                }
              }
            }
          },
          "deals": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "id": {
                  "type": "string",
                  "format": "uuid"
                },
                "code": {
                  "type": "integer"
                },
                "title": {
                  "type": "string"
                },
                "status": {
                  "$ref": "#/components/schemas/OpportunityStatusEnum"
                },
                "archived_at": {
                  "type": "string",
                  "format": "date-time",
                  "nullable": true
                },
                "won_date": {
                  "type": "string",
                  "format": "date-time",
                  "nullable": true
                },
                "lost_date": {
                  "type": "string",
                  "format": "date-time",
                  "nullable": true
                },
                "created_at": {
                  "type": "string",
                  "format": "date-time"
                },
                "updated_at": {
                  "type": "string",
                  "format": "date-time"
                },
                "stage": {
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "name": {
                      "type": "string"
                    },
                    "pipeline": {
                      "type": "object",
                      "properties": {
                        "id": {
                          "type": "string"
                        },
                        "name": {
                          "type": "string"
                        }
                      }
                    }
                  }
                },
                "value": {
                  "type": "number",
                  "nullable": true
                },
                "responsible": {
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string",
                      "format": "uuid"
                    },
                    "name": {
                      "type": "string"
                    },
                    "avatar": {
                      "type": "string",
                      "nullable": true
                    }
                  },
                  "nullable": true
                }
              }
            },
            "description": "Oportunidades associadas ao lead e visíveis no escopo da chave."
          }
        }
      },
      "LeadUpdateResult": {
        "type": "object",
        "description": "Retorno enxuto da atualização.",
        "properties": {
          "id": {
            "type": "string"
          },
          "code": {
            "type": "integer"
          },
          "title": {
            "type": "string"
          },
          "measurement_consent": {
            "$ref": "#/components/schemas/MeasurementConsent"
          },
          "quality_rating": {
            "type": "integer",
            "nullable": true
          },
          "quality_reason": {
            "type": "string",
            "nullable": true
          },
          "status": {
            "$ref": "#/components/schemas/LeadStatus"
          },
          "lost_reason_description": {
            "type": "string",
            "nullable": true
          },
          "value": {
            "type": "number",
            "nullable": true
          }
        }
      },
      "OpportunityStatusEnum": {
        "type": "integer",
        "enum": [
          1,
          2,
          3
        ],
        "description": "1 = aberta, 2 = ganha, 3 = perdida."
      },
      "OpportunityArchivedFilter": {
        "type": "string",
        "enum": [
          "include",
          "only"
        ]
      },
      "OpportunitySummary": {
        "type": "object",
        "description": "Resumo retornado na listagem de oportunidades.",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "code": {
            "type": "integer"
          },
          "title": {
            "type": "string"
          },
          "measurement_consent": {
            "$ref": "#/components/schemas/MeasurementConsent"
          },
          "status": {
            "$ref": "#/components/schemas/OpportunityStatusEnum"
          },
          "visibility": {
            "$ref": "#/components/schemas/OpportunityVisibility"
          },
          "quality_rating": {
            "type": "integer",
            "nullable": true
          },
          "archived_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "won_date": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "lost_date": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "expected_close_date": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "temperature": {
            "$ref": "#/components/schemas/OpportunityTemperature"
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          },
          "last_activity_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "views_count": {
            "type": "integer"
          },
          "stage": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string"
              },
              "name": {
                "type": "string"
              },
              "pipeline": {
                "type": "object",
                "properties": {
                  "id": {
                    "type": "string"
                  },
                  "name": {
                    "type": "string"
                  }
                }
              }
            }
          },
          "deal_source": {
            "type": "object",
            "nullable": true,
            "description": "Origem efetiva do registro: a da aquisição mais recente e, na falta dela, a gravada no registro. O histórico de aquisição é retornado separadamente em marketing_lead_source no detalhe.",
            "properties": {
              "id": {
                "type": "string"
              },
              "name": {
                "type": "string"
              },
              "logo": {
                "type": "string"
              }
            }
          },
          "person": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string"
              },
              "name": {
                "type": "string"
              }
            }
          },
          "organization": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string"
              },
              "name": {
                "type": "string"
              }
            }
          },
          "lead": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string"
              },
              "title": {
                "type": "string"
              }
            }
          },
          "tags": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "name": {
                  "type": "string"
                },
                "color": {
                  "type": "object",
                  "nullable": true,
                  "description": "Cores da tag.",
                  "properties": {
                    "background": {
                      "type": "string",
                      "nullable": true
                    },
                    "foreground": {
                      "type": "string",
                      "nullable": true
                    }
                  }
                }
              }
            }
          },
          "pending_tasks_status": {
            "type": "string",
            "enum": [
              "NONE",
              "TODAY",
              "FUTURE",
              "OVERDUE"
            ]
          },
          "value": {
            "type": "number",
            "nullable": true
          },
          "crm_task": {
            "type": "array",
            "description": "Tarefas pendentes retornadas com a listagem.",
            "items": {
              "type": "object",
              "properties": {
                "id": {
                  "type": "string"
                },
                "title": {
                  "type": "string"
                },
                "priority": {
                  "type": "integer"
                },
                "description": {
                  "type": "string",
                  "nullable": true
                },
                "start_date": {
                  "type": "string",
                  "format": "date-time",
                  "nullable": true
                },
                "crm_task_type": {
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "name": {
                      "type": "string"
                    },
                    "icon": {
                      "type": "string"
                    }
                  }
                },
                "end_date": {
                  "type": "string",
                  "format": "date-time",
                  "nullable": true
                },
                "has_time": {
                  "type": "boolean"
                },
                "archived_at": {
                  "type": "string",
                  "format": "date-time",
                  "nullable": true
                },
                "completed_at": {
                  "type": "string",
                  "format": "date-time",
                  "nullable": true
                },
                "deleted_at": {
                  "type": "string",
                  "format": "date-time",
                  "nullable": true
                }
              }
            }
          },
          "icp": {
            "allOf": [
              {
                "$ref": "#/components/schemas/CrmIcpSummary"
              }
            ],
            "nullable": true
          },
          "icps": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CrmIcpAssignment"
            }
          },
          "partners": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CrmPartnerSummary"
            }
          },
          "has_channel_chat": {
            "type": "boolean",
            "description": "false quando a chave não tem crm/chats.read."
          },
          "channel_chats": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CrmChannelChatSummary"
            },
            "description": "Resumos de WhatsApp e Instagram; vazio sem crm/chats.read na própria chave."
          },
          "has_whatsapp_chat": {
            "type": "boolean",
            "description": "Alias de compatibilidade de has_channel_chat nas leituras externas."
          },
          "whatsapp_chats": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CrmChannelChatSummary"
            },
            "description": "Alias de compatibilidade de channel_chats nas leituras externas; pode incluir Instagram."
          },
          "score": {
            "type": "integer",
            "nullable": true
          },
          "score_criteria_count": {
            "type": "integer"
          },
          "score_updated_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "valuation": {
            "$ref": "#/components/schemas/CrmValuation"
          },
          "score_knowledge": {
            "$ref": "#/components/schemas/CrmScoreKnowledge"
          },
          "last_score_movement": {
            "allOf": [
              {
                "$ref": "#/components/schemas/CrmScoreMovement"
              }
            ],
            "nullable": true
          },
          "stagnation_status": {
            "type": "string",
            "enum": [
              "not_stagnant",
              "stagnant",
              "stagnant_with_future_task"
            ]
          },
          "stage_total_duration_seconds": {
            "type": "number"
          },
          "stage_total_duration_days": {
            "type": "number"
          },
          "has_future_task": {
            "type": "boolean"
          },
          "stagnates_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "stage_entered_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "created_by_user": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "name": {
                "type": "string"
              },
              "avatar": {
                "type": "string",
                "nullable": true
              }
            },
            "nullable": true
          },
          "responsible": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "name": {
                "type": "string"
              },
              "avatar": {
                "type": "string",
                "nullable": true
              }
            },
            "nullable": true
          },
          "negotiation_mode": {
            "type": "integer",
            "nullable": true
          }
        }
      },
      "OpportunityDetails": {
        "type": "object",
        "description": "Detalhamento completo retornado no GET /integrations/external/deals/{id}.",
        "properties": {
          "id": {
            "type": "string"
          },
          "code": {
            "type": "integer"
          },
          "title": {
            "type": "string"
          },
          "measurement_consent": {
            "$ref": "#/components/schemas/MeasurementConsent"
          },
          "status": {
            "$ref": "#/components/schemas/OpportunityStatusEnum"
          },
          "created_by": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string"
              },
              "name": {
                "type": "string"
              },
              "avatar": {
                "type": "string"
              }
            }
          },
          "stage": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string"
              },
              "name": {
                "type": "string"
              },
              "pipeline": {
                "type": "object",
                "nullable": true,
                "properties": {
                  "id": {
                    "type": "string"
                  },
                  "name": {
                    "type": "string"
                  }
                }
              }
            }
          },
          "pipeline_stages": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "id": {
                  "type": "string"
                },
                "name": {
                  "type": "string"
                },
                "position": {
                  "type": "integer"
                }
              }
            }
          },
          "responsible": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string"
              },
              "name": {
                "type": "string"
              },
              "avatar": {
                "type": "string"
              }
            }
          },
          "deal_source": {
            "type": "object",
            "nullable": true,
            "description": "Origem efetiva do registro: a da aquisição mais recente e, na falta dela, a gravada no registro. O histórico de aquisição é retornado separadamente em marketing_lead_source no detalhe.",
            "properties": {
              "id": {
                "type": "string"
              },
              "name": {
                "type": "string"
              },
              "logo": {
                "type": "string"
              }
            }
          },
          "marketing_lead_source": {
            "type": "object",
            "nullable": true,
            "description": "Snapshot ativo de aquisição mais recente. campaing_name mantém a grafia do contrato. O consentimento efetivo é resolvido separadamente do snapshot de aquisição.",
            "properties": {
              "id": {
                "type": "string"
              },
              "utm_search_term": {
                "type": "string",
                "nullable": true
              },
              "utm_medium": {
                "type": "string",
                "nullable": true
              },
              "lead_source": {
                "type": "object",
                "nullable": true,
                "properties": {
                  "id": {
                    "type": "string"
                  },
                  "name": {
                    "type": "string"
                  },
                  "logo": {
                    "type": "string"
                  }
                }
              },
              "url_conversion": {
                "type": "string",
                "nullable": true
              },
              "campaing_name": {
                "type": "string",
                "nullable": true
              },
              "ad_set_name": {
                "type": "string",
                "nullable": true
              },
              "content_name": {
                "type": "string",
                "nullable": true
              },
              "displayed_on_name": {
                "type": "string",
                "nullable": true
              },
              "conversion_tool_name": {
                "type": "string",
                "nullable": true
              },
              "creative": {
                "type": "object",
                "nullable": true,
                "properties": {
                  "id": {
                    "type": "string"
                  },
                  "value": {
                    "type": "string"
                  },
                  "creative_uri": {
                    "type": "string"
                  }
                }
              },
              "source_url": {
                "type": "string",
                "nullable": true
              },
              "headline": {
                "type": "string",
                "nullable": true
              },
              "ad_body": {
                "type": "string",
                "nullable": true
              },
              "media_type": {
                "type": "string",
                "nullable": true
              },
              "ads_clid_id": {
                "type": "string",
                "nullable": true
              },
              "gclid": {
                "type": "string",
                "nullable": true
              },
              "fbclid": {
                "type": "string",
                "nullable": true
              },
              "fbc": {
                "type": "string",
                "nullable": true
              },
              "fbp": {
                "type": "string",
                "nullable": true
              },
              "conversion_url_full": {
                "type": "string",
                "nullable": true
              },
              "measurement_consent": {
                "$ref": "#/components/schemas/MeasurementConsent"
              }
            }
          },
          "quality_rating": {
            "type": "integer",
            "nullable": true
          },
          "quality_reason": {
            "type": "string",
            "nullable": true
          },
          "won_date": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "lost_date": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "crm_loss_reason": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string"
              },
              "name": {
                "type": "string"
              }
            }
          },
          "lost_reason_description": {
            "type": "string",
            "nullable": true
          },
          "visibility": {
            "$ref": "#/components/schemas/OpportunityVisibility"
          },
          "negotiation_mode": {
            "type": "integer",
            "nullable": true,
            "description": "Modo de negociacao da oportunidade. `0` indica produtos/pedido e `1` indica proposta."
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          },
          "archived_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "last_activity_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "expected_close_date": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "temperature": {
            "$ref": "#/components/schemas/OpportunityTemperature"
          },
          "participants": {
            "type": "array",
            "description": "Participantes da oportunidade com informações de contato.",
            "items": {
              "type": "object",
              "properties": {
                "id": {
                  "type": "string"
                },
                "main": {
                  "type": "boolean",
                  "description": "Indica o participante principal."
                },
                "role": {
                  "type": "string",
                  "nullable": true,
                  "description": "Papel do participante no registro, em texto livre."
                },
                "notes": {
                  "type": "string",
                  "nullable": true
                },
                "person": {
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "name": {
                      "type": "string"
                    },
                    "contacts": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "id": {
                            "type": "string"
                          },
                          "type": {
                            "$ref": "#/components/schemas/PersonContactType"
                          },
                          "value": {
                            "type": "string"
                          },
                          "primary": {
                            "type": "boolean"
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "organization": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string"
              },
              "name": {
                "type": "string"
              },
              "logo": {
                "type": "string"
              }
            }
          },
          "lead": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string"
              },
              "title": {
                "type": "string"
              }
            }
          },
          "custom_fields": {
            "type": "array",
            "description": "Respostas de campos customizados agrupadas por campo.",
            "items": {
              "type": "object",
              "properties": {
                "field_id": {
                  "type": "string"
                },
                "field_name": {
                  "type": "string"
                },
                "field_type": {
                  "type": "integer"
                },
                "answers": {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "properties": {
                      "id": {
                        "type": "string"
                      },
                      "option_id": {
                        "type": "string",
                        "nullable": true
                      },
                      "option_value": {
                        "type": "string",
                        "nullable": true
                      },
                      "value": {
                        "type": "string"
                      }
                    }
                  }
                }
              }
            }
          },
          "tags": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "id": {
                  "type": "string"
                },
                "name": {
                  "type": "string"
                },
                "color": {
                  "type": "object",
                  "nullable": true,
                  "description": "Cores da tag.",
                  "properties": {
                    "background": {
                      "type": "string",
                      "nullable": true
                    },
                    "foreground": {
                      "type": "string",
                      "nullable": true
                    }
                  }
                }
              }
            }
          },
          "stage_durations": {
            "type": "array",
            "description": "Tempo acumulado por etapa (segundos e texto legível).",
            "items": {
              "type": "object",
              "properties": {
                "stage_id": {
                  "type": "string"
                },
                "stage_name": {
                  "type": "string",
                  "nullable": true
                },
                "total_seconds": {
                  "type": "integer"
                },
                "human_readable": {
                  "type": "string"
                }
              }
            }
          },
          "value": {
            "type": "number",
            "nullable": true
          },
          "views_count": {
            "type": "integer"
          },
          "associations_count": {
            "type": "object",
            "properties": {
              "items": {
                "type": "integer"
              },
              "tasks": {
                "type": "integer"
              },
              "qualifications": {
                "type": "integer"
              },
              "notes": {
                "type": "integer"
              },
              "files": {
                "type": "integer"
              },
              "activities": {
                "type": "integer"
              },
              "proposals": {
                "type": "integer"
              }
            }
          },
          "proposals": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "id": {
                  "type": "string"
                },
                "code": {
                  "type": "integer"
                },
                "version": {
                  "type": "integer"
                },
                "title": {
                  "type": "string"
                },
                "status": {
                  "type": "integer"
                },
                "is_primary": {
                  "type": "boolean"
                },
                "discount_type": {
                  "type": "integer",
                  "nullable": true
                },
                "discount_value": {
                  "type": "number",
                  "nullable": true
                },
                "subtotal": {
                  "type": "number",
                  "nullable": true
                },
                "total": {
                  "type": "number",
                  "nullable": true
                },
                "valid_until": {
                  "type": "string",
                  "format": "date-time",
                  "nullable": true
                },
                "created_at": {
                  "type": "string",
                  "format": "date-time"
                },
                "updated_at": {
                  "type": "string",
                  "format": "date-time"
                },
                "approved_at": {
                  "type": "string",
                  "format": "date-time",
                  "nullable": true
                },
                "archived_at": {
                  "type": "string",
                  "format": "date-time",
                  "nullable": true
                },
                "rejected_at": {
                  "type": "string",
                  "format": "date-time",
                  "nullable": true
                },
                "created_by": {
                  "type": "object",
                  "nullable": true,
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "name": {
                      "type": "string"
                    },
                    "avatar": {
                      "type": "string"
                    }
                  }
                },
                "approved_by": {
                  "type": "object",
                  "nullable": true,
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "name": {
                      "type": "string"
                    }
                  }
                },
                "delivery_schedule": {
                  "type": "object",
                  "nullable": true,
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/ProposalDeliveryScheduleResponse"
                    }
                  ]
                }
              }
            }
          },
          "products": {
            "type": "array",
            "description": "Produtos diretamente associados a oportunidade em `crm_deal_product`.",
            "items": {
              "type": "object",
              "properties": {
                "id": {
                  "type": "string"
                },
                "product_id": {
                  "type": "string"
                },
                "product": {
                  "type": "object",
                  "nullable": true,
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "name": {
                      "type": "string"
                    },
                    "code": {
                      "type": "string",
                      "nullable": true
                    },
                    "unit": {
                      "type": "integer",
                      "nullable": true
                    },
                    "sale_price": {
                      "type": "number",
                      "nullable": true
                    }
                  }
                },
                "unit": {
                  "type": "integer",
                  "nullable": true
                },
                "quantity": {
                  "type": "number",
                  "nullable": true
                },
                "unit_price": {
                  "type": "number",
                  "nullable": true
                },
                "discount_type": {
                  "type": "integer",
                  "nullable": true
                },
                "discount_value": {
                  "type": "number",
                  "nullable": true
                },
                "subtotal": {
                  "type": "number",
                  "nullable": true
                },
                "total": {
                  "type": "number",
                  "nullable": true
                },
                "notes": {
                  "type": "string",
                  "nullable": true
                },
                "is_recurring_default": {
                  "type": "boolean"
                },
                "billing_interval_default": {
                  "type": "integer",
                  "nullable": true
                },
                "contract_term_months": {
                  "type": "integer",
                  "nullable": true
                },
                "start_date": {
                  "type": "string",
                  "format": "date-time",
                  "nullable": true
                },
                "end_date": {
                  "type": "string",
                  "format": "date-time",
                  "nullable": true
                },
                "billing_cycles": {
                  "type": "integer",
                  "nullable": true
                },
                "created_at": {
                  "type": "string",
                  "format": "date-time"
                },
                "updated_at": {
                  "type": "string",
                  "format": "date-time"
                },
                "billing_interval_count": {
                  "type": "integer",
                  "nullable": true
                }
              }
            }
          },
          "followers": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "role": {
                  "type": "object",
                  "nullable": true,
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "name": {
                      "type": "string"
                    }
                  }
                },
                "user": {
                  "type": "object",
                  "nullable": true,
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "name": {
                      "type": "string"
                    },
                    "avatar": {
                      "type": "string"
                    }
                  }
                },
                "notes": {
                  "type": "string",
                  "nullable": true
                }
              }
            }
          },
          "icp": {
            "allOf": [
              {
                "$ref": "#/components/schemas/CrmIcpSummary"
              }
            ],
            "nullable": true
          },
          "icps": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CrmIcpAssignment"
            }
          },
          "partners": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CrmPartnerSummary"
            }
          },
          "has_channel_chat": {
            "type": "boolean",
            "description": "false quando a chave não tem crm/chats.read."
          },
          "channel_chats": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CrmChannelChatSummary"
            },
            "description": "Resumos de WhatsApp e Instagram; vazio sem crm/chats.read na própria chave."
          },
          "has_whatsapp_chat": {
            "type": "boolean",
            "description": "Alias de compatibilidade de has_channel_chat nas leituras externas."
          },
          "whatsapp_chats": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/CrmChannelChatSummary"
            },
            "description": "Alias de compatibilidade de channel_chats nas leituras externas; pode incluir Instagram."
          },
          "score": {
            "type": "integer",
            "nullable": true
          },
          "score_criteria_count": {
            "type": "integer"
          },
          "score_updated_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "valuation": {
            "$ref": "#/components/schemas/CrmValuation"
          },
          "qualification_metric": {
            "type": "string",
            "enum": [
              "quality_rating",
              "lead_score"
            ]
          },
          "projection_context": {
            "$ref": "#/components/schemas/CrmProjectionContext"
          },
          "crm_loss_reasons": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "id": {
                  "type": "string",
                  "format": "uuid"
                },
                "name": {
                  "type": "string"
                }
              }
            }
          },
          "crm_gain_reason": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "name": {
                "type": "string"
              }
            },
            "nullable": true
          },
          "crm_gain_reasons": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "id": {
                  "type": "string",
                  "format": "uuid"
                },
                "name": {
                  "type": "string"
                }
              }
            }
          },
          "won_reason_description": {
            "type": "string",
            "nullable": true
          }
        }
      },
      "UpdateExternalOpportunity": {
        "type": "object",
        "required": [
          "title"
        ],
        "properties": {
          "stage_id": {
            "type": "string",
            "format": "uuid"
          },
          "responsible_id": {
            "type": "string",
            "format": "uuid",
            "description": "Usuário ativo da empresa. Um responsável inativo retorna 400; a substituição pelo master vale apenas na criação."
          },
          "quality_rating": {
            "type": "integer",
            "enum": [
              1,
              2,
              3,
              4,
              5
            ]
          },
          "quality_reason": {
            "type": "string"
          },
          "title": {
            "type": "string",
            "maxLength": 150,
            "minLength": 1
          },
          "value": {
            "type": "number",
            "description": "Valor monetário. Ignorado quando a oportunidade negocia por produtos ou por proposta."
          },
          "expected_close_date": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "visibility": {
            "$ref": "#/components/schemas/OpportunityVisibility"
          },
          "temperature": {
            "$ref": "#/components/schemas/OpportunityTemperature"
          },
          "persons_id": {
            "type": "array",
            "description": "Lista de operações de associação ou remoção de participantes. `delete: true` remove a pessoa da oportunidade; omita ou envie false para adicionar.\n",
            "items": {
              "type": "object",
              "properties": {
                "person_id": {
                  "type": "string",
                  "format": "uuid"
                },
                "delete": {
                  "type": "boolean"
                }
              },
              "required": [
                "person_id"
              ]
            }
          },
          "person": {
            "$ref": "#/components/schemas/OpportunityPersonUpdate"
          },
          "primary_person_id": {
            "type": "string",
            "format": "uuid"
          },
          "organization_id": {
            "type": "string",
            "nullable": true
          },
          "organization": {
            "$ref": "#/components/schemas/OpportunityOrganization"
          },
          "custom_fields": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/OpportunityCustomFieldValue"
            },
            "description": "Quando enviado com itens, substitui todas as respostas do registro; reenvie o conjunto completo."
          },
          "measurement_consent": {
            "allOf": [
              {
                "$ref": "#/components/schemas/MeasurementConsent"
              }
            ],
            "description": "Quando omitido, preserva o valor efetivo atual."
          },
          "marketing": {
            "$ref": "#/components/schemas/MarketingTracking"
          },
          "crm_lead_source_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true,
            "description": "Origem existente. `null` remove a origem do registro e da aquisição atual."
          },
          "crm_loss_reason_id": {
            "type": "string"
          },
          "lost_reason_description": {
            "type": "string"
          },
          "status": {
            "$ref": "#/components/schemas/OpportunityStatusEnum"
          },
          "won_date": {
            "type": "string",
            "format": "date-time"
          },
          "proposal_deadline_starts_on": {
            "type": "string",
            "format": "date",
            "description": "Data-base opcional entre 1980-01-01 e 2100-12-31, aceita somente na requisição que muda o status para ganho (`status = 2` em uma oportunidade ainda não ganha). Se omitida, a API fixa a data civil do ganho para a proposta principal que possuir prazos."
          },
          "lost_date": {
            "type": "string",
            "format": "date-time"
          },
          "tags": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "IDs de tags existentes. São acrescentadas às tags atuais."
          }
        },
        "description": "O PUT exige title. Os demais campos são opcionais; campos omitidos são preservados. Use as rotas de seguidores para alterar seguidores."
      },
      "OpportunityUpdateResult": {
        "type": "object",
        "description": "Retorno enxuto da atualização de oportunidade.",
        "properties": {
          "id": {
            "type": "string"
          },
          "code": {
            "type": "integer"
          },
          "title": {
            "type": "string"
          },
          "measurement_consent": {
            "$ref": "#/components/schemas/MeasurementConsent"
          },
          "quality_rating": {
            "type": "integer",
            "nullable": true
          },
          "quality_reason": {
            "type": "string",
            "nullable": true
          },
          "status": {
            "$ref": "#/components/schemas/OpportunityStatusEnum"
          },
          "lost_reason_description": {
            "type": "string",
            "nullable": true
          },
          "won_reason_description": {
            "type": "string",
            "nullable": true
          }
        }
      },
      "OpportunityVisibility": {
        "type": "integer",
        "enum": [
          0,
          1,
          2
        ],
        "description": "0 = privado (responsável e supervisores), 1 = equipe/responsável, 2 = público.\n"
      },
      "OpportunityTemperature": {
        "type": "integer",
        "enum": [
          1,
          2,
          3
        ],
        "description": "1 = frio, 2 = morno, 3 = quente."
      },
      "OpportunityPersonContact": {
        "type": "object",
        "properties": {
          "type": {
            "$ref": "#/components/schemas/PersonContactType"
          },
          "value": {
            "type": "string",
            "description": "Valor do contato. Telefones (tipos 0, 2 e 3) têm caracteres não numéricos removidos e devem ficar com 10 ou 11 dígitos (DDD + número, sem o DDI 55). O tipo 1 deve ser um e-mail válido.\n",
            "minLength": 1
          },
          "primary": {
            "type": "boolean",
            "description": "Indica contato principal ao cadastrar uma pessoa nova."
          }
        },
        "required": [
          "type",
          "value"
        ]
      },
      "OpportunityPerson": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string",
            "minLength": 1
          },
          "birth_date": {
            "type": "string",
            "format": "date"
          },
          "gender": {
            "type": "integer"
          },
          "notes": {
            "type": "string"
          },
          "contacts": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/OpportunityPersonContact"
            }
          },
          "avoid_duplicate": {
            "type": "boolean",
            "description": "Na criação (POST), true e duplicate_check_types preenchido habilitam a busca por qualquer contato dos tipos informados. Reutiliza a primeira pessoa encontrada na empresa e adiciona contatos faltantes; os demais dados de pessoa enviados não substituem o cadastro existente."
          },
          "duplicate_check_types": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/PersonContactType"
            },
            "description": "Tipos de contato usados na deduplicação durante POST. Telefones consideram variações brasileiras com e sem DDI 55."
          },
          "documents": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ExternalCrmPersonDocumentInput"
            }
          },
          "address": {
            "$ref": "#/components/schemas/ExternalCrmAddressInput"
          },
          "addresses": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ExternalCrmAddressInput"
            }
          }
        },
        "required": [
          "name"
        ]
      },
      "OpportunityOrganization": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string",
            "minLength": 1
          },
          "legal_name": {
            "type": "string"
          },
          "document": {
            "type": "string"
          },
          "industry": {
            "type": "string"
          },
          "description": {
            "type": "string"
          },
          "phone": {
            "type": "string"
          },
          "email": {
            "type": "string"
          },
          "site": {
            "type": "string"
          },
          "status": {
            "type": "integer",
            "enum": [
              0,
              1
            ]
          },
          "addresses": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ExternalCrmAddressInput"
            }
          },
          "address_name": {
            "type": "string"
          },
          "address_street": {
            "type": "string"
          },
          "address_number": {
            "type": "string"
          },
          "address_complement": {
            "type": "string"
          },
          "address_district": {
            "type": "string"
          },
          "address_city": {
            "type": "string"
          },
          "address_state": {
            "type": "string"
          },
          "address_postal_code": {
            "type": "string"
          },
          "address_status": {
            "type": "integer",
            "enum": [
              0,
              1
            ]
          },
          "address_type": {
            "type": "integer",
            "enum": [
              0,
              1,
              2,
              3
            ],
            "description": "0 = comercial; 1 = residencial; 2 = entrega; 3 = faturamento."
          }
        },
        "required": [
          "name"
        ]
      },
      "OpportunityCustomFieldValue": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "description": "ID do campo customizado.",
            "minLength": 1
          },
          "value": {
            "type": "string",
            "description": "Valor textual. Para tipos temporais, use YYYY-MM-DD (DATE), HH:mm (TIME) ou YYYY-MM-DDTHH:mm (DATETIME), sem Z ou offset.\n"
          },
          "option_id": {
            "type": "string"
          },
          "option_ids": {
            "type": "array",
            "items": {
              "type": "string"
            }
          }
        },
        "required": [
          "id"
        ]
      },
      "OpportunityFollowerInput": {
        "type": "object",
        "properties": {
          "user_id": {
            "type": "string",
            "format": "uuid",
            "description": "Usuário existente na empresa. Duplicatas são ignoradas na mesma requisição."
          },
          "role_id": {
            "type": "string",
            "format": "uuid",
            "description": "Função de seguidor (deve existir e estar ativa)."
          },
          "notes": {
            "type": "string",
            "maxLength": 1000
          }
        },
        "required": [
          "user_id",
          "role_id"
        ],
        "additionalProperties": false
      },
      "OpportunityNoteInput": {
        "type": "object",
        "properties": {
          "content": {
            "type": "string",
            "minLength": 1,
            "description": "Texto simples ou HTML. O HTML é higienizado; se nada restar após a higienização, a API retorna 400."
          },
          "is_pinned": {
            "type": "boolean"
          }
        },
        "required": [
          "content"
        ]
      },
      "CreateExternalOpportunity": {
        "type": "object",
        "required": [
          "title"
        ],
        "properties": {
          "stage_id": {
            "type": "string",
            "format": "uuid",
            "description": "Etapa do funil de oportunidades. Caso omitido, usa a primeira etapa do funil primário."
          },
          "responsible_id": {
            "type": "string",
            "format": "uuid",
            "description": "Responsável pela oportunidade. Padrão: criador da chave. Se o usuário informado estiver inativo ou arquivado, o registro é atribuído ao usuário master da conta, com nota automática; usuário inexistente ou de outra empresa retorna 400."
          },
          "quality_rating": {
            "type": "integer",
            "enum": [
              1,
              2,
              3,
              4,
              5
            ]
          },
          "quality_reason": {
            "type": "string",
            "description": "Motivo da qualificação; obrigatório se o funil exigir."
          },
          "title": {
            "type": "string",
            "maxLength": 150,
            "minLength": 1
          },
          "value": {
            "type": "number",
            "description": "Valor monetário com até 2 casas decimais."
          },
          "expected_close_date": {
            "type": "string",
            "format": "date-time",
            "description": "Data prevista de fechamento."
          },
          "visibility": {
            "$ref": "#/components/schemas/OpportunityVisibility"
          },
          "temperature": {
            "$ref": "#/components/schemas/OpportunityTemperature"
          },
          "tags": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "description": "Lista de IDs de tags existentes. IDs inexistentes resultam em erro."
          },
          "persons_id": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "person_id": {
                  "type": "string",
                  "format": "uuid"
                }
              },
              "required": [
                "person_id"
              ]
            },
            "description": "IDs de pessoas já cadastradas que serão associadas."
          },
          "person": {
            "$ref": "#/components/schemas/OpportunityPerson"
          },
          "primary_person_id": {
            "type": "string",
            "format": "uuid",
            "description": "Define o participante principal quando múltiplas pessoas são associadas."
          },
          "organization_id": {
            "type": "string",
            "format": "uuid",
            "description": "Organização existente. Conflita com `organization`."
          },
          "organization": {
            "$ref": "#/components/schemas/OpportunityOrganization"
          },
          "custom_fields": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/OpportunityCustomFieldValue"
            },
            "description": "Respostas dos campos personalizados. Todos os campos obrigatórios da entidade precisam ser enviados; campos do tipo arquivo não são aceitos nesta rota."
          },
          "measurement_consent": {
            "allOf": [
              {
                "$ref": "#/components/schemas/MeasurementConsent"
              }
            ],
            "description": "Padrão GRANTED quando omitido na criação."
          },
          "marketing": {
            "$ref": "#/components/schemas/MarketingTracking"
          },
          "crm_lead_source_id": {
            "type": "string",
            "format": "uuid",
            "description": "Origem existente. Única forma aceita para informar origem manual nesta API."
          },
          "followers": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/OpportunityFollowerInput"
            },
            "description": "Seguidores adicionados após a criação da oportunidade. Usuários duplicados na lista são ignorados. Se a gravação falhar, a API retorna erro, mas o registro permanece criado."
          },
          "note": {
            "$ref": "#/components/schemas/OpportunityNoteInput"
          },
          "idempotency_key": {
            "type": "string",
            "maxLength": 255,
            "description": "Chave da tentativa lógica de criação. O header x-idempotency-key, quando preenchido, tem prioridade. Reutilize a mesma chave para repetir uma chamada sem resposta; depois de uma criação que falhou após iniciada, use uma nova chave."
          }
        }
      },
      "OpportunityCreateResult": {
        "type": "object",
        "description": "Retorno da criação de oportunidade.",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "code": {
            "type": "integer",
            "description": "Código sequencial interno da oportunidade."
          },
          "title": {
            "type": "string"
          },
          "measurement_consent": {
            "$ref": "#/components/schemas/MeasurementConsent"
          }
        }
      },
      "ProposalStatusValue": {
        "type": "integer",
        "enum": [
          1,
          2,
          3,
          4,
          5
        ],
        "description": "1 = negociação, 2 = aprovada, 3 = rejeitada, 4 = arquivada, 5 = dispensada.\n"
      },
      "ProposalDiscountType": {
        "type": "integer",
        "enum": [
          0,
          1
        ],
        "description": "0 = percentual, 1 = valor fixo."
      },
      "ExternalUserSummary": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "name": {
            "type": "string"
          },
          "avatar": {
            "type": "string",
            "nullable": true
          }
        }
      },
      "ExternalPersonSummary": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "name": {
            "type": "string"
          }
        }
      },
      "ProposalContextSummary": {
        "type": "object",
        "description": "Lead ou negócio de origem da proposta.",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "title": {
            "type": "string",
            "nullable": true
          },
          "status": {
            "type": "integer",
            "enum": [
              1,
              2,
              3
            ],
            "description": "1 = aberto, 2 = ganho, 3 = perdido."
          },
          "archived_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "negotiation_mode": {
            "type": "integer",
            "nullable": true,
            "description": "Modo de negociação do registro. `0` indica produtos/pedido e `1` indica proposta."
          }
        }
      },
      "ProposalProductSummary": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "code": {
            "type": "string",
            "nullable": true
          },
          "name": {
            "type": "string"
          },
          "image": {
            "type": "string",
            "nullable": true
          }
        }
      },
      "ProposalCustomFieldValueInput": {
        "type": "object",
        "required": [
          "id"
        ],
        "description": "Resposta de um campo personalizado. Envie somente a propriedade compatível com o tipo do campo: `value`, `option_id`, `option_ids` ou `boolean_value`.\n",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid",
            "description": "ID da definição do campo personalizado de proposta."
          },
          "value": {
            "type": "string"
          },
          "option_id": {
            "type": "string",
            "format": "uuid"
          },
          "option_ids": {
            "type": "array",
            "uniqueItems": true,
            "items": {
              "type": "string",
              "format": "uuid"
            }
          },
          "boolean_value": {
            "type": "boolean"
          }
        }
      },
      "ProposalCustomFieldOptionResponse": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "value": {
            "type": "string"
          },
          "position": {
            "type": "integer"
          }
        }
      },
      "ProposalCustomFieldAnswerResponse": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "value": {
            "type": "string",
            "nullable": true
          },
          "option_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "option_value": {
            "type": "string",
            "nullable": true
          },
          "boolean_value": {
            "type": "boolean",
            "nullable": true
          }
        }
      },
      "ProposalCustomFieldResponse": {
        "type": "object",
        "properties": {
          "field_id": {
            "type": "string",
            "format": "uuid"
          },
          "field_name": {
            "type": "string"
          },
          "field_type": {
            "$ref": "#/components/schemas/CustomFieldType"
          },
          "position": {
            "type": "integer"
          },
          "is_required": {
            "type": "boolean"
          },
          "min_checkbox_selections": {
            "type": "integer",
            "nullable": true
          },
          "max_checkbox_selections": {
            "type": "integer",
            "nullable": true
          },
          "section_id": {
            "type": "string",
            "format": "uuid"
          },
          "section": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "name": {
                "type": "string"
              },
              "position": {
                "type": "integer"
              }
            }
          },
          "options": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ProposalCustomFieldOptionResponse"
            }
          },
          "answers": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ProposalCustomFieldAnswerResponse"
            }
          }
        }
      },
      "ProposalItemInput": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "nullable": true
          },
          "delete": {
            "type": "boolean",
            "description": "Marca o item para remoção durante uma atualização."
          },
          "product_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "sku": {
            "type": "string",
            "maxLength": 50,
            "nullable": true,
            "description": "Código interno do produto usado para resolver `product_id` quando ele não é enviado."
          },
          "name": {
            "type": "string",
            "maxLength": 150,
            "nullable": true
          },
          "description": {
            "type": "string",
            "nullable": true
          },
          "quantity": {
            "type": "number",
            "minimum": 0.001,
            "multipleOf": 0.001,
            "description": "Obrigatória em cada item enviado sem delete=true, inclusive quando id é informado."
          },
          "unit_price": {
            "type": "number",
            "minimum": 0,
            "multipleOf": 0.01,
            "description": "Quando omitido, usa o preço já salvo no item ou sale_price do produto. Informe explicitamente para itens livres."
          },
          "unit": {
            "type": "integer",
            "enum": [
              0,
              1,
              2,
              3,
              4,
              5,
              6,
              7
            ],
            "nullable": true
          },
          "discount_type": {
            "type": "integer",
            "enum": [
              0,
              1
            ],
            "nullable": true
          },
          "discount_value": {
            "type": "number",
            "minimum": 0,
            "nullable": true,
            "multipleOf": 0.001
          },
          "notes": {
            "type": "string",
            "nullable": true
          },
          "internal_notes": {
            "type": "string",
            "maxLength": 5000,
            "nullable": true,
            "description": "Observação interna do item, visível no CRM e omitida da exportação em PDF."
          },
          "is_recurring_default": {
            "type": "boolean"
          },
          "billing_interval_default": {
            "type": "integer",
            "enum": [
              0,
              1,
              2,
              3,
              4,
              5,
              6
            ],
            "nullable": true,
            "description": "0 = diário; 1 = semanal; 2 = mensal; 3 = bimestral; 4 = trimestral; 5 = semestral; 6 = anual. Obrigatório no estado final de um item recorrente."
          },
          "contract_term_months": {
            "type": "integer",
            "minimum": 1,
            "nullable": true
          },
          "start_date": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "end_date": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "billing_cycles": {
            "type": "integer",
            "minimum": 1,
            "nullable": true
          },
          "position": {
            "type": "integer",
            "minimum": 0,
            "nullable": true
          },
          "new_product": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ProposalNewProductInput"
              }
            ],
            "nullable": true
          },
          "new_product_client_id": {
            "type": "string",
            "nullable": true,
            "minLength": 1,
            "maxLength": 100,
            "description": "Referência a produto temporário do fluxo interno. A coleção new_products não integra o DTO externo; prefira new_product, product_id ou sku nesta integração."
          },
          "custom_fields": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ProposalItemCustomFieldValueInput"
            },
            "description": "Respostas dos campos do produto por field_id. Itens livres não aceitam campos de produto. Quando enviado para um item existente, substitui seus valores e valida campos obrigatórios."
          },
          "category_values": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ProposalItemCategoryValueInput"
            },
            "description": "Valores das categorias de itens comerciais da empresa. Quando enviado, substitui os valores do item."
          },
          "billing_interval_count": {
            "type": "integer",
            "minimum": 1,
            "nullable": true
          },
          "recurring_payment_method": {
            "type": "integer",
            "enum": [
              1,
              2,
              3
            ],
            "nullable": true,
            "description": "1 = Pix; 2 = cartão de crédito; 3 = boleto. É normalizado para null em itens não recorrentes."
          }
        },
        "description": "No POST, cria itens. No PUT, sem id adiciona, com id atualiza e com id + delete=true remove; itens omitidos são preservados. Ao menos um item deve permanecer. quantity é obrigatória nos itens enviados que não sejam remoções.",
        "allOf": [
          {
            "anyOf": [
              {
                "required": [
                  "quantity"
                ]
              },
              {
                "required": [
                  "delete"
                ],
                "properties": {
                  "delete": {
                    "type": "boolean",
                    "enum": [
                      true
                    ]
                  }
                }
              }
            ]
          }
        ]
      },
      "ProposalItemResponse": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "product_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "product": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ProposalProductSummary"
              }
            ],
            "nullable": true
          },
          "name": {
            "type": "string",
            "nullable": true
          },
          "description": {
            "type": "string",
            "nullable": true
          },
          "unit": {
            "type": "integer",
            "nullable": true
          },
          "quantity": {
            "type": "number"
          },
          "unit_price": {
            "type": "number"
          },
          "discount_type": {
            "type": "integer",
            "allOf": [
              {
                "$ref": "#/components/schemas/ProposalDiscountType"
              }
            ],
            "nullable": true
          },
          "discount_value": {
            "type": "number",
            "nullable": true
          },
          "subtotal": {
            "type": "number"
          },
          "total": {
            "type": "number"
          },
          "notes": {
            "type": "string",
            "nullable": true
          },
          "internal_notes": {
            "type": "string",
            "nullable": true,
            "description": "Observação interna do item, nunca incluída na exportação em PDF."
          },
          "is_recurring_default": {
            "type": "boolean"
          },
          "billing_interval_default": {
            "type": "integer",
            "nullable": true
          },
          "contract_term_months": {
            "type": "integer",
            "nullable": true
          },
          "start_date": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "end_date": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "billing_cycles": {
            "type": "integer",
            "nullable": true
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          },
          "position": {
            "type": "integer"
          },
          "billing_interval_count": {
            "type": "integer",
            "nullable": true
          },
          "recurring_payment_method": {
            "type": "integer",
            "enum": [
              1,
              2,
              3
            ],
            "nullable": true
          },
          "custom_fields": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ProposalItemCustomFieldResponse"
            }
          },
          "category_values": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ProposalItemCategoryResponse"
            }
          }
        }
      },
      "ProposalSummary": {
        "allOf": [
          {
            "$ref": "#/components/schemas/ProposalBaseResponse"
          },
          {
            "type": "object",
            "properties": {
              "items_count": {
                "type": "integer"
              },
              "payment_options_count": {
                "type": "integer"
              }
            }
          }
        ],
        "description": "Registro resumido da listagem. Contém contagens; arrays de itens e condições ficam no detalhe."
      },
      "ProposalDeadlineInput": {
        "type": "object",
        "required": [
          "stage",
          "qualifier",
          "quantity",
          "unit",
          "counting_mode"
        ],
        "properties": {
          "stage": {
            "type": "string",
            "minLength": 1,
            "maxLength": 150
          },
          "qualifier": {
            "type": "string",
            "enum": [
              "EXACT",
              "UP_TO"
            ]
          },
          "quantity": {
            "type": "integer",
            "minimum": 1,
            "description": "Limite condicional por unidade — DAYS 36525, WEEKS 5217, MONTHS 1200 e YEARS 100."
          },
          "unit": {
            "type": "string",
            "enum": [
              "DAYS",
              "WEEKS",
              "MONTHS",
              "YEARS"
            ],
            "description": "MONTHS e YEARS aceitam somente contagem CALENDAR."
          },
          "counting_mode": {
            "type": "string",
            "enum": [
              "CALENDAR",
              "BUSINESS"
            ],
            "description": "BUSINESS é aceito somente com DAYS ou WEEKS; considera segunda a sexta sem feriados. Uma semana útil equivale a 5 dias úteis."
          },
          "notes": {
            "type": "string",
            "maxLength": 2000,
            "nullable": true
          }
        },
        "allOf": [
          {
            "oneOf": [
              {
                "properties": {
                  "unit": {
                    "type": "string",
                    "enum": [
                      "DAYS"
                    ]
                  },
                  "quantity": {
                    "type": "integer",
                    "maximum": 36525
                  },
                  "counting_mode": {
                    "type": "string",
                    "enum": [
                      "CALENDAR",
                      "BUSINESS"
                    ]
                  }
                }
              },
              {
                "properties": {
                  "unit": {
                    "type": "string",
                    "enum": [
                      "WEEKS"
                    ]
                  },
                  "quantity": {
                    "type": "integer",
                    "maximum": 5217
                  },
                  "counting_mode": {
                    "type": "string",
                    "enum": [
                      "CALENDAR",
                      "BUSINESS"
                    ]
                  }
                }
              },
              {
                "properties": {
                  "unit": {
                    "type": "string",
                    "enum": [
                      "MONTHS"
                    ]
                  },
                  "quantity": {
                    "type": "integer",
                    "maximum": 1200
                  },
                  "counting_mode": {
                    "type": "string",
                    "enum": [
                      "CALENDAR"
                    ]
                  }
                }
              },
              {
                "properties": {
                  "unit": {
                    "type": "string",
                    "enum": [
                      "YEARS"
                    ]
                  },
                  "quantity": {
                    "type": "integer",
                    "maximum": 100
                  },
                  "counting_mode": {
                    "type": "string",
                    "enum": [
                      "CALENDAR"
                    ]
                  }
                }
              }
            ]
          }
        ]
      },
      "ProposalDeliveryScheduleInput": {
        "type": "object",
        "required": [
          "deadlines"
        ],
        "properties": {
          "starts_on": {
            "type": "string",
            "format": "date",
            "nullable": true,
            "description": "Data civil entre 1980-01-01 e 2100-12-31. Quando ausente, a previsão usa a data atual dinamicamente até a confirmação no ganho."
          },
          "deadlines": {
            "type": "array",
            "minItems": 1,
            "maxItems": 100,
            "items": {
              "$ref": "#/components/schemas/ProposalDeadlineInput"
            }
          }
        },
        "description": "Cronograma integral, com etapas sequenciais na ordem do array. Dias úteis são segunda a sexta, sem feriados; o horizonte total não pode ultrapassar 100 anos."
      },
      "ProposalDeadlineResponse": {
        "allOf": [
          {
            "$ref": "#/components/schemas/ProposalDeadlineInput"
          },
          {
            "type": "object",
            "required": [
              "position",
              "stage",
              "qualifier",
              "cumulative_qualifier",
              "quantity",
              "unit",
              "counting_mode",
              "notes",
              "estimated_start_date",
              "estimated_end_date",
              "estimated_end_is_business_day",
              "suggested_next_business_date"
            ],
            "properties": {
              "position": {
                "type": "integer"
              },
              "cumulative_qualifier": {
                "type": "string",
                "enum": [
                  "EXACT",
                  "UP_TO"
                ]
              },
              "estimated_start_date": {
                "type": "string",
                "format": "date"
              },
              "estimated_end_date": {
                "type": "string",
                "format": "date"
              },
              "estimated_end_is_business_day": {
                "type": "boolean"
              },
              "suggested_next_business_date": {
                "type": "string",
                "format": "date",
                "nullable": true
              }
            }
          }
        ]
      },
      "ProposalDeliveryScheduleResponse": {
        "type": "object",
        "required": [
          "starts_on",
          "effective_starts_on",
          "is_dynamic",
          "timezone",
          "calculation_version",
          "final_qualifier",
          "declared_total",
          "declared_totals",
          "estimated_delivery_date",
          "estimated_delivery_is_business_day",
          "suggested_next_business_date",
          "elapsed_calendar_days",
          "business_days_notice",
          "deadlines"
        ],
        "properties": {
          "starts_on": {
            "type": "string",
            "format": "date",
            "nullable": true
          },
          "effective_starts_on": {
            "type": "string",
            "format": "date"
          },
          "is_dynamic": {
            "type": "boolean"
          },
          "timezone": {
            "type": "string"
          },
          "calculation_version": {
            "type": "integer"
          },
          "final_qualifier": {
            "type": "string",
            "enum": [
              "EXACT",
              "UP_TO"
            ]
          },
          "declared_total": {
            "type": "string"
          },
          "declared_totals": {
            "type": "array",
            "items": {
              "type": "object",
              "required": [
                "quantity",
                "unit",
                "counting_mode"
              ],
              "properties": {
                "quantity": {
                  "type": "integer"
                },
                "unit": {
                  "type": "string",
                  "enum": [
                    "DAYS",
                    "WEEKS",
                    "MONTHS",
                    "YEARS"
                  ]
                },
                "counting_mode": {
                  "type": "string",
                  "enum": [
                    "CALENDAR",
                    "BUSINESS"
                  ]
                }
              }
            }
          },
          "estimated_delivery_date": {
            "type": "string",
            "format": "date"
          },
          "estimated_delivery_is_business_day": {
            "type": "boolean"
          },
          "suggested_next_business_date": {
            "type": "string",
            "format": "date",
            "nullable": true
          },
          "elapsed_calendar_days": {
            "type": "integer"
          },
          "business_days_notice": {
            "type": "string",
            "example": "Dias úteis consideram somente segunda a sexta-feira; feriados não são considerados."
          },
          "deadlines": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ProposalDeadlineResponse"
            }
          }
        }
      },
      "ProposalDetails": {
        "allOf": [
          {
            "$ref": "#/components/schemas/ProposalBaseResponse"
          },
          {
            "type": "object",
            "properties": {
              "items": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/ProposalItemResponse"
                }
              },
              "payment_options": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/ProposalPaymentOptionResponse"
                }
              },
              "custom_fields": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/ProposalCustomFieldResponse"
                },
                "description": "Todas as definições ativas de proposta, mesmo quando answers está vazio."
              },
              "delivery_schedule": {
                "type": "object",
                "allOf": [
                  {
                    "$ref": "#/components/schemas/ProposalDeliveryScheduleResponse"
                  }
                ],
                "nullable": true
              }
            }
          }
        ],
        "description": "Retorno de POST, PUT e GET por ID. Inclui itens, condições de pagamento, campos personalizados e cronograma; não inclui items_count nem payment_options_count."
      },
      "ProposalSummaryWithoutDeliverySchedule": {
        "allOf": [
          {
            "$ref": "#/components/schemas/ProposalSummary"
          },
          {
            "not": {
              "required": [
                "delivery_schedule"
              ]
            }
          }
        ],
        "description": "Resumo retornado quando `include_delivery_schedule` está ausente ou é `false`; a propriedade `delivery_schedule` não é enviada."
      },
      "ProposalSummaryWithDeliverySchedule": {
        "allOf": [
          {
            "$ref": "#/components/schemas/ProposalSummary"
          },
          {
            "type": "object",
            "required": [
              "delivery_schedule"
            ],
            "properties": {
              "delivery_schedule": {
                "type": "object",
                "allOf": [
                  {
                    "$ref": "#/components/schemas/ProposalDeliveryScheduleResponse"
                  }
                ],
                "nullable": true,
                "description": "Cronograma calculado na referência atual ou `null` quando a proposta não possui cronograma."
              }
            }
          }
        ]
      },
      "ProposalListResponse": {
        "type": "object",
        "required": [
          "total",
          "records"
        ],
        "description": "Variante padrão da listagem, sem `delivery_schedule` nos registros.",
        "properties": {
          "total": {
            "type": "integer"
          },
          "records": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ProposalSummaryWithoutDeliverySchedule"
            }
          }
        }
      },
      "ProposalListResponseWithDeliverySchedule": {
        "type": "object",
        "required": [
          "total",
          "records"
        ],
        "description": "Variante usada com `include_delivery_schedule=true`; todos os registros incluem `delivery_schedule`, inclusive quando o valor é `null`.",
        "properties": {
          "total": {
            "type": "integer"
          },
          "records": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ProposalSummaryWithDeliverySchedule"
            }
          }
        }
      },
      "ProposalDeleteResult": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          }
        }
      },
      "CreateExternalProposal": {
        "type": "object",
        "required": [
          "items"
        ],
        "properties": {
          "lead_id": {
            "type": "string",
            "format": "uuid"
          },
          "deal_id": {
            "type": "string",
            "format": "uuid"
          },
          "deal_code": {
            "type": "string",
            "maxLength": 50,
            "description": "Código público numérico do negócio, enviado como string. Evite enviar junto com deal_id: no POST o ID prevalece; no PUT o código prevalece."
          },
          "title": {
            "type": "string",
            "maxLength": 150,
            "nullable": true
          },
          "notes": {
            "type": "string",
            "nullable": true
          },
          "status": {
            "$ref": "#/components/schemas/ProposalStatusValue"
          },
          "discount_type": {
            "type": "integer",
            "allOf": [
              {
                "$ref": "#/components/schemas/ProposalDiscountType"
              }
            ],
            "nullable": true
          },
          "discount_value": {
            "type": "number",
            "minimum": 0,
            "nullable": true,
            "multipleOf": 0.01
          },
          "valid_until": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "approved_by": {
            "type": "string",
            "format": "uuid",
            "nullable": true,
            "description": "UUID da pessoa aprovadora vinculada à empresa; não é o ID de usuário do CRM."
          },
          "approved_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "archived_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "rejected_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "custom_fields": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ProposalCustomFieldValueInput"
            },
            "description": "Conjunto completo de respostas de proposta, validado contra campos ativos e obrigatórios. No PUT, omitir preserva; enviar substitui o conjunto e [] só é válido se não houver obrigatórios pendentes."
          },
          "delivery_schedule": {
            "$ref": "#/components/schemas/ProposalDeliveryScheduleInput"
          },
          "items": {
            "type": "array",
            "minItems": 1,
            "items": {
              "$ref": "#/components/schemas/ProposalItemInput"
            }
          }
        },
        "description": "Exige items e exatamente um contexto: lead_id OU negócio (deal_id/deal_code). Contextos ganhos, perdidos, arquivados ou em modo de negociação incompatível bloqueiam criação.",
        "anyOf": [
          {
            "required": [
              "lead_id"
            ]
          },
          {
            "required": [
              "deal_id"
            ]
          },
          {
            "required": [
              "deal_code"
            ]
          }
        ]
      },
      "UpdateExternalProposal": {
        "type": "object",
        "properties": {
          "lead_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "deal_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true,
            "description": "ID do negócio. Na implementação externa atual, null é convertido em ausência e preserva o negócio existente; não use null para desvincular uma proposta de negócio."
          },
          "deal_code": {
            "type": "string",
            "maxLength": 50,
            "description": "Código público numérico do negócio, enviado como string. Evite enviar junto com deal_id: no POST o ID prevalece; no PUT o código prevalece."
          },
          "title": {
            "type": "string",
            "maxLength": 150,
            "nullable": true
          },
          "notes": {
            "type": "string",
            "nullable": true
          },
          "status": {
            "$ref": "#/components/schemas/ProposalStatusValue"
          },
          "discount_type": {
            "type": "integer",
            "allOf": [
              {
                "$ref": "#/components/schemas/ProposalDiscountType"
              }
            ],
            "nullable": true
          },
          "discount_value": {
            "type": "number",
            "minimum": 0,
            "nullable": true,
            "multipleOf": 0.01
          },
          "valid_until": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "approved_by": {
            "type": "string",
            "format": "uuid",
            "nullable": true,
            "description": "UUID da pessoa aprovadora vinculada à empresa; não é o ID de usuário do CRM."
          },
          "approved_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "archived_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "rejected_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "custom_fields": {
            "type": "array",
            "description": "Conjunto completo de respostas de proposta, validado contra campos ativos e obrigatórios. No PUT, omitir preserva; enviar substitui o conjunto e [] só é válido se não houver obrigatórios pendentes.",
            "items": {
              "$ref": "#/components/schemas/ProposalCustomFieldValueInput"
            }
          },
          "delivery_schedule": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ProposalDeliveryScheduleInput"
              }
            ],
            "nullable": true,
            "description": "Quando omitido, preserva o cronograma; quando `null`, remove todos os prazos."
          },
          "items": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ProposalItemInput"
            },
            "description": "Mutações incrementais: id atualiza, id com delete=true remove, sem id cria. Itens omitidos e items=[] preservam os itens existentes. quantity é exigida em cada item enviado que não seja remoção."
          }
        },
        "description": "Atualização parcial com PUT. Campos omitidos são preservados. Contextos fechados bloqueiam a edição. Se o total mudar e houver condições de pagamento, o serviço exige revisão dessas condições no CRM."
      },
      "ChatStatusEnum": {
        "type": "string",
        "enum": [
          "OPEN",
          "RESOLVED",
          "SNOOZED"
        ]
      },
      "ChatPriorityValue": {
        "type": "integer",
        "enum": [
          0,
          1,
          2,
          3
        ],
        "description": "0 = baixa, 1 = normal, 2 = alta, 3 = urgente."
      },
      "ChatTypeEnum": {
        "type": "string",
        "enum": [
          "INDIVIDUAL",
          "GROUP"
        ]
      },
      "ChatMessageTypeEnum": {
        "type": "string",
        "enum": [
          "text",
          "reaction",
          "image",
          "video",
          "audio",
          "document",
          "template",
          "interactive",
          "location",
          "call",
          "contacts",
          "unsupported",
          "sticker",
          "button"
        ],
        "description": "Tipos mais comuns. Mensagens recebidas guardam o tipo informado pelo provedor, de modo que outros valores podem aparecer."
      },
      "ChatMessageOriginEnum": {
        "type": "string",
        "enum": [
          "INBOUND",
          "API_OUTBOUND",
          "MOBILE_APP_ECHO",
          "SYSTEM"
        ]
      },
      "ChatMessageSentViaEnum": {
        "type": "string",
        "enum": [
          "CONTACT",
          "API",
          "MOBILE_DEVICE",
          "SYSTEM"
        ]
      },
      "ChatMessageDeliveryStatusEnum": {
        "type": "string",
        "enum": [
          "processing",
          "sent",
          "delivered",
          "read",
          "failed",
          "received",
          "deleted",
          "delivery_unknown"
        ],
        "description": "Status persistido da mensagem; delivery_unknown indica que o resultado do envio ainda não foi confirmado."
      },
      "ChatTemplateInfo": {
        "type": "object",
        "required": [
          "name",
          "language"
        ],
        "properties": {
          "name": {
            "type": "string"
          },
          "language": {
            "type": "string"
          }
        }
      },
      "ChatTemplateField": {
        "type": "object",
        "required": [
          "component",
          "type",
          "value"
        ],
        "properties": {
          "component": {
            "type": "string",
            "enum": [
              "HEADER",
              "BODY",
              "BUTTONS"
            ]
          },
          "type": {
            "type": "string",
            "enum": [
              "TEXT",
              "IMAGE",
              "VIDEO",
              "DOCUMENT",
              "LOCATION"
            ]
          },
          "value": {
            "type": "string",
            "description": "Valor do campo. Em campos IMAGE, VIDEO ou DOCUMENT, aceita uma URL http(s) ou `file:<n>`, em que n é a posição (a partir de 0) do arquivo enviado no mesmo formulário, contando primeiro os de `files` e depois os de `file`."
          },
          "index": {
            "type": "number"
          },
          "button_index": {
            "type": "number"
          },
          "card_index": {
            "type": "number"
          }
        }
      },
      "ChatReaction": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "emoji": {
            "type": "string"
          },
          "actor": {
            "type": "string",
            "enum": [
              "CONTACT",
              "BUSINESS",
              "SYSTEM"
            ],
            "description": "`SYSTEM` pode aparecer em reações do Instagram."
          },
          "reactor_wa_id": {
            "type": "string"
          },
          "reactor_user_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "ChatAgentSummary": {
        "type": "object",
        "properties": {
          "agent_id": {
            "type": "string",
            "format": "uuid"
          },
          "user": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ExternalUserSummary"
              }
            ],
            "nullable": true
          }
        }
      },
      "ChatAssignableAgentSummary": {
        "type": "object",
        "properties": {
          "agent_id": {
            "type": "string",
            "format": "uuid"
          },
          "status": {
            "type": "string"
          },
          "user": {
            "$ref": "#/components/schemas/ExternalUserSummary"
          }
        }
      },
      "ChatPhoneSummary": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "display_number": {
            "type": "string",
            "nullable": true
          }
        }
      },
      "ChatPhoneDetails": {
        "allOf": [
          {
            "$ref": "#/components/schemas/ChatPhoneSummary"
          },
          {
            "type": "object",
            "properties": {
              "raw_number": {
                "type": "string"
              },
              "phone_number_id": {
                "type": "string"
              }
            }
          }
        ]
      },
      "ChatCrmPersonSummary": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "name": {
            "type": "string"
          }
        }
      },
      "ChatPersonContact": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "type": {
            "type": "integer"
          },
          "value": {
            "type": "string"
          },
          "primary": {
            "type": "boolean"
          }
        }
      },
      "ChatPersonDocument": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "type": {
            "type": "integer"
          },
          "label": {
            "type": "string",
            "nullable": true
          },
          "value": {
            "type": "string"
          }
        }
      },
      "ChatPersonAddress": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "status": {
            "type": "integer"
          },
          "type": {
            "type": "integer"
          },
          "name": {
            "type": "string",
            "nullable": true
          },
          "street": {
            "type": "string",
            "nullable": true
          },
          "number": {
            "type": "string",
            "nullable": true
          },
          "complement": {
            "type": "string",
            "nullable": true
          },
          "district": {
            "type": "string",
            "nullable": true
          },
          "city": {
            "type": "string",
            "nullable": true
          },
          "state": {
            "type": "string",
            "nullable": true
          },
          "postal_code": {
            "type": "string",
            "nullable": true
          }
        }
      },
      "ChatPersonDetails": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "name": {
            "type": "string"
          },
          "birth_date": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "gender": {
            "type": "integer",
            "nullable": true
          },
          "notes": {
            "type": "string",
            "nullable": true
          },
          "contacts": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatPersonContact"
            }
          },
          "documents": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatPersonDocument"
            }
          },
          "address": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ChatPersonAddress"
              }
            ],
            "nullable": true
          }
        }
      },
      "ChatMessageSummary": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "type": {
            "$ref": "#/components/schemas/ChatMessageTypeEnum"
          },
          "origin": {
            "$ref": "#/components/schemas/ChatMessageOriginEnum"
          },
          "from_me": {
            "type": "boolean"
          },
          "sent_via": {
            "$ref": "#/components/schemas/ChatMessageSentViaEnum"
          },
          "status": {
            "$ref": "#/components/schemas/ChatMessageDeliveryStatusEnum"
          },
          "body_text": {
            "type": "string",
            "nullable": true
          },
          "content_payload": {
            "type": "object",
            "nullable": true,
            "additionalProperties": true
          },
          "reactions": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatReaction"
            }
          },
          "meta_timestamp": {
            "type": "string",
            "format": "date-time"
          },
          "is_history": {
            "type": "boolean"
          },
          "history_phase": {
            "type": "integer",
            "nullable": true
          },
          "history_chunk_order": {
            "type": "integer",
            "nullable": true
          },
          "history_progress": {
            "type": "integer",
            "nullable": true
          },
          "is_media_placeholder": {
            "type": "boolean"
          },
          "agent": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "user": {
                "type": "object",
                "allOf": [
                  {
                    "$ref": "#/components/schemas/ExternalUserSummary"
                  }
                ],
                "nullable": true
              }
            }
          },
          "user": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ExternalUserSummary"
              }
            ],
            "nullable": true
          },
          "crm_marketing_lead_source": {
            "type": "array",
            "nullable": true,
            "items": {
              "type": "object",
              "additionalProperties": true
            }
          },
          "transcription": {
            "type": "string",
            "nullable": true
          },
          "is_forwarded": {
            "type": "boolean"
          },
          "whatsapp_ai_agent_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true,
            "description": "Agente de IA que enviou a mensagem; null para pessoas e automações. Em `last_message`, é preenchido apenas na listagem de chats."
          }
        }
      },
      "ChatSummary": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "wa_contact_id": {
            "type": "string"
          },
          "contact_name": {
            "type": "string"
          },
          "contact_number": {
            "type": "string"
          },
          "status": {
            "$ref": "#/components/schemas/ChatStatusEnum"
          },
          "chat_type": {
            "$ref": "#/components/schemas/ChatTypeEnum"
          },
          "unread_count": {
            "type": "integer"
          },
          "is_manually_unread": {
            "type": "boolean"
          },
          "priority": {
            "$ref": "#/components/schemas/ChatPriorityValue"
          },
          "archived_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "assigned_agent_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "phone_number": {
            "$ref": "#/components/schemas/ChatPhoneSummary"
          },
          "assigned_agent": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ChatAgentSummary"
              }
            ],
            "nullable": true
          },
          "last_message_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "last_message": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ChatMessageSummary"
              }
            ],
            "nullable": true
          },
          "crm_person": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ChatCrmPersonSummary"
              }
            ],
            "nullable": true
          },
          "last_customer_msg_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "session_expires_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "can_send_open_message": {
            "type": "boolean",
            "description": "Indica se a janela atual permite mensagem aberta."
          },
          "has_pending_copilot_actions": {
            "type": "boolean"
          },
          "pending_copilot_actions_count": {
            "type": "integer"
          },
          "has_active_whatsapp_flow_session": {
            "type": "boolean"
          },
          "active_whatsapp_flow_sessions": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatActiveFlowSession"
            }
          },
          "has_upcoming_scheduled_message": {
            "type": "boolean",
            "description": "Presente na listagem; indica agendamento futuro."
          },
          "channel_type": {
            "type": "string",
            "enum": [
              "WHATSAPP"
            ]
          },
          "channel_account_id": {
            "type": "string",
            "format": "uuid"
          },
          "channel_account": {
            "$ref": "#/components/schemas/ChatChannelAccount"
          },
          "external_contact": {
            "$ref": "#/components/schemas/ChatExternalContact"
          },
          "legacy": {
            "type": "object",
            "properties": {
              "whatsapp_chat_id": {
                "type": "string",
                "format": "uuid"
              },
              "whatsapp_phone_id": {
                "type": "string",
                "format": "uuid"
              },
              "wa_contact_id": {
                "type": "string"
              }
            }
          },
          "ai_attendance": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ChatAiAttendance"
              }
            ],
            "nullable": true,
            "description": "Presente nos registros de WhatsApp da listagem; null quando a conversa nunca teve agente de IA ou o recurso está desativado. Não faz parte da criação nem dos detalhes."
          }
        },
        "required": [
          "id",
          "wa_contact_id",
          "contact_name",
          "contact_number",
          "status",
          "priority",
          "chat_type",
          "unread_count",
          "is_manually_unread",
          "channel_type",
          "channel_account_id",
          "can_send_open_message"
        ]
      },
      "ChatListResponse": {
        "type": "object",
        "properties": {
          "total": {
            "type": "integer",
            "description": "Total de registros que correspondem à consulta."
          },
          "records": {
            "type": "array",
            "items": {
              "anyOf": [
                {
                  "$ref": "#/components/schemas/ChatSummary"
                },
                {
                  "$ref": "#/components/schemas/ChatInstagramSummary"
                }
              ]
            }
          },
          "next_cursor": {
            "type": "string",
            "nullable": true,
            "description": "Cursor opaco da próxima página; null quando não há continuação."
          }
        },
        "required": [
          "total",
          "records",
          "next_cursor"
        ]
      },
      "ChatUnreadSummary": {
        "type": "object",
        "properties": {
          "unread_messages_total": {
            "type": "integer"
          },
          "unread_chats_total": {
            "type": "integer"
          }
        }
      },
      "ChatDetails": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "wa_contact_id": {
            "type": "string"
          },
          "contact_name": {
            "type": "string"
          },
          "contact_number": {
            "type": "string"
          },
          "status": {
            "$ref": "#/components/schemas/ChatStatusEnum"
          },
          "chat_type": {
            "$ref": "#/components/schemas/ChatTypeEnum"
          },
          "unread_count": {
            "type": "integer"
          },
          "is_manually_unread": {
            "type": "boolean"
          },
          "priority": {
            "$ref": "#/components/schemas/ChatPriorityValue"
          },
          "archived_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "phone_number": {
            "$ref": "#/components/schemas/ChatPhoneDetails"
          },
          "assigned_agent": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ChatAgentSummary"
              }
            ],
            "nullable": true
          },
          "last_message": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ChatMessageSummary"
              }
            ],
            "nullable": true
          },
          "crm_person": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ChatPersonDetails"
              }
            ],
            "nullable": true
          },
          "last_customer_msg_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "session_expires_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "can_send_open_message": {
            "type": "boolean",
            "description": "Indica se a janela atual permite mensagem aberta."
          },
          "has_pending_copilot_actions": {
            "type": "boolean"
          },
          "pending_copilot_actions_count": {
            "type": "integer"
          },
          "channel_type": {
            "type": "string",
            "enum": [
              "WHATSAPP"
            ]
          },
          "channel_account_id": {
            "type": "string",
            "format": "uuid"
          },
          "channel_account": {
            "$ref": "#/components/schemas/ChatChannelAccount"
          },
          "external_contact": {
            "$ref": "#/components/schemas/ChatExternalContact"
          },
          "legacy": {
            "type": "object",
            "properties": {
              "whatsapp_chat_id": {
                "type": "string",
                "format": "uuid"
              },
              "whatsapp_phone_id": {
                "type": "string",
                "format": "uuid"
              },
              "wa_contact_id": {
                "type": "string"
              }
            }
          },
          "remote_profile_name": {
            "type": "string",
            "nullable": true
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          },
          "participants": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatAgentSummary"
            }
          },
          "crm_marketing_lead_source": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {},
              "additionalProperties": true
            }
          },
          "assignable_agents": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatAssignableAgentSummary"
            },
            "description": "Incluído ao consultar os detalhes; pode ser omitido nos retornos das mutações."
          },
          "whatsapp_flow_sessions": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatFlowSession"
            }
          },
          "pending_copilot_actions": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatPendingCopilotAction"
            }
          }
        },
        "required": [
          "id",
          "status",
          "priority",
          "channel_type",
          "participants",
          "created_at",
          "updated_at",
          "phone_number",
          "crm_person",
          "pending_copilot_actions",
          "whatsapp_flow_sessions"
        ]
      },
      "CreateExternalChat": {
        "type": "object",
        "required": [
          "whatsapp_phone_id",
          "template"
        ],
        "anyOf": [
          {
            "required": [
              "wa_contact_id"
            ]
          },
          {
            "required": [
              "person_contact_id"
            ]
          }
        ],
        "properties": {
          "whatsapp_phone_id": {
            "type": "string",
            "format": "uuid"
          },
          "wa_contact_id": {
            "type": "string",
            "maxLength": 50
          },
          "person_contact_id": {
            "type": "string",
            "format": "uuid"
          },
          "remote_profile_name": {
            "type": "string",
            "maxLength": 255,
            "nullable": true
          },
          "crm_person_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "assigned_agent_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "status": {
            "$ref": "#/components/schemas/ChatStatusEnum"
          },
          "template": {
            "$ref": "#/components/schemas/ChatTemplateInfo"
          },
          "template_fields": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatTemplateField"
            }
          }
        }
      },
      "SendExternalChatMessageTypeEnum": {
        "type": "string",
        "enum": [
          "text",
          "reaction",
          "image",
          "video",
          "audio",
          "document",
          "location",
          "template",
          "interactive",
          "call"
        ],
        "description": "Valores aceitos pelo DTO. Quando omitido, assume text; o template não é inferido pelo conteúdo e exige type=template. interactive e location são recusados nesta rota com 400; use as rotas dedicadas."
      },
      "SendExternalChatMessage": {
        "type": "object",
        "description": "Payload para envio de mensagem textual, template ou mídia em um chat existente.",
        "properties": {
          "type": {
            "$ref": "#/components/schemas/SendExternalChatMessageTypeEnum"
          },
          "body": {
            "type": "string",
            "description": "Texto da mensagem. Se houver anexos, o texto é enviado como mensagem separada e também como legenda de cada imagem, vídeo ou documento. Com type=template, não envie body: o texto seria enviado no lugar do template. Texto aberto admite até 4096 caracteres."
          },
          "reference_wamid": {
            "type": "string",
            "maxLength": 200,
            "description": "WAMID ou UUID local de uma mensagem de referência pertencente ao chat; a API resolve o WAMID antes do envio."
          },
          "template": {
            "$ref": "#/components/schemas/ChatTemplateInfo"
          },
          "template_fields": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatTemplateField"
            }
          }
        },
        "example": {
          "type": "text",
          "body": "Olá, tudo bem?"
        }
      },
      "SendExternalChatMessageMultipart": {
        "allOf": [
          {
            "$ref": "#/components/schemas/SendExternalChatMessage"
          },
          {
            "type": "object",
            "description": "Payload multipart para envio de mídia. Os campos `template` e `template_fields`, quando enviados por formulário, podem ser serializados como JSON.",
            "properties": {
              "files": {
                "type": "array",
                "description": "Arquivos enviados no campo `files`.",
                "items": {
                  "type": "string",
                  "format": "binary"
                },
                "maxItems": 10
              },
              "file": {
                "type": "array",
                "description": "Arquivos enviados no campo alternativo `file`.",
                "items": {
                  "type": "string",
                  "format": "binary"
                },
                "maxItems": 10
              }
            }
          }
        ]
      },
      "ChatMessagesResponse": {
        "type": "object",
        "properties": {
          "total": {
            "type": "integer",
            "description": "Quantidade de mensagens enviadas nesta operação; pode superar 1 quando houver texto e anexos."
          },
          "records": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatMessage"
            }
          }
        },
        "required": [
          "total",
          "records"
        ]
      },
      "ExternalFilesCreateBatchRequest": {
        "type": "object",
        "description": "Envie pelo menos um arquivo e exatamente um destino (crm_lead_id, crm_deal_id, lead_code ou deal_code). O controller limita cada campo multipart (file ou files) a 20 arquivos.",
        "properties": {
          "crm_lead_id": {
            "type": "string",
            "format": "uuid",
            "description": "UUID do lead que receberá os arquivos."
          },
          "crm_deal_id": {
            "type": "string",
            "format": "uuid",
            "description": "UUID do negócio que receberá os arquivos."
          },
          "lead_code": {
            "type": "string",
            "description": "Código numérico interno do lead que receberá os arquivos.",
            "pattern": "^\\d+$"
          },
          "deal_code": {
            "type": "string",
            "description": "Código numérico interno do negócio que receberá os arquivos.",
            "pattern": "^\\d+$"
          },
          "title": {
            "type": "string",
            "maxLength": 150,
            "description": "Título opcional do lote."
          },
          "note": {
            "type": "string",
            "description": "Observação opcional do lote."
          },
          "file": {
            "type": "string",
            "format": "binary",
            "description": "Campo alternativo de arquivo; pode ser repetido até 20 vezes. Use files para múltiplos arquivos em clientes gerados."
          },
          "files": {
            "type": "array",
            "description": "Campo principal para envio de um ou vários arquivos.",
            "items": {
              "type": "string",
              "format": "binary"
            },
            "maxItems": 20
          }
        }
      },
      "ExternalFileBatchUserSummary": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "name": {
            "type": "string"
          },
          "avatar": {
            "type": "string",
            "nullable": true
          }
        }
      },
      "ExternalFileBatchTargetSummary": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "title": {
            "type": "string"
          }
        }
      },
      "ExternalFileSummary": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "created_by": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ExternalFileBatchUserSummary"
              }
            ],
            "nullable": true
          },
          "file_url": {
            "type": "string",
            "nullable": true,
            "description": "URL temporária assinada; consulte novamente pelo ID para obter uma URL atualizada."
          },
          "file_name": {
            "type": "string",
            "nullable": true
          },
          "mime_type": {
            "type": "string",
            "nullable": true
          },
          "size": {
            "type": "integer"
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "ExternalFileBatchResponse": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "source": {
            "type": "integer",
            "enum": [
              1
            ],
            "description": "Fonte do lote fixa em API."
          },
          "title": {
            "type": "string",
            "nullable": true
          },
          "note": {
            "type": "string",
            "nullable": true
          },
          "files_count": {
            "type": "integer"
          },
          "total_size": {
            "type": "integer"
          },
          "created_by": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ExternalFileBatchUserSummary"
              }
            ],
            "nullable": true
          },
          "crm_lead": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ExternalFileBatchTargetSummary"
              }
            ],
            "nullable": true
          },
          "crm_deal": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ExternalFileBatchTargetSummary"
              }
            ],
            "nullable": true
          },
          "crm_delivery": {
            "type": "object",
            "nullable": true,
            "description": "Sempre `null` nesta rota pública."
          },
          "files": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ExternalFileSummary"
            }
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "ExternalFileResponse": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "created_by": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ExternalFileBatchUserSummary"
              }
            ],
            "nullable": true
          },
          "crm_lead": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ExternalFileBatchTargetSummary"
              }
            ],
            "nullable": true
          },
          "crm_deal": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ExternalFileBatchTargetSummary"
              }
            ],
            "nullable": true
          },
          "crm_delivery": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "title": {
                "type": "string"
              },
              "code": {
                "type": "integer"
              },
              "status": {
                "type": "integer"
              }
            }
          },
          "batch": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "title": {
                "type": "string",
                "nullable": true
              }
            }
          },
          "file_url": {
            "type": "string",
            "nullable": true,
            "description": "URL temporária assinada; consulte novamente pelo ID para obter uma URL atualizada."
          },
          "file_name": {
            "type": "string",
            "nullable": true
          },
          "mime_type": {
            "type": "string",
            "nullable": true
          },
          "size": {
            "type": "integer"
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "ExternalFilesListResponse": {
        "type": "object",
        "properties": {
          "total": {
            "type": "integer"
          },
          "records": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ExternalFileResponse"
            }
          }
        }
      },
      "ExternalTaskPriority": {
        "type": "integer",
        "enum": [
          0,
          1,
          2,
          3
        ],
        "description": "Prioridade da tarefa: 0 baixa, 1 normal, 2 alta, 3 urgente."
      },
      "ExternalTaskMeetingProvider": {
        "type": "string",
        "enum": [
          "teams_integration",
          "google_calendar_integration"
        ],
        "description": "Provedor de reunião online usado pela tarefa."
      },
      "ExternalTaskRecurrenceScope": {
        "type": "string",
        "enum": [
          "only_this",
          "this_and_future",
          "open_only",
          "all"
        ],
        "description": "Escopo aplicado em edições ou remoções de tarefas recorrentes. Padrão `only_this`."
      },
      "ExternalTaskRecurrenceRequest": {
        "type": "object",
        "properties": {
          "pattern": {
            "type": "string",
            "enum": [
              "every_n_days",
              "weekly"
            ]
          },
          "interval": {
            "type": "integer",
            "minimum": 1,
            "maximum": 365
          },
          "week_days": {
            "type": "array",
            "items": {
              "type": "string",
              "enum": [
                "sunday",
                "monday",
                "tuesday",
                "wednesday",
                "thursday",
                "friday",
                "saturday"
              ]
            },
            "minItems": 1,
            "maxItems": 7,
            "uniqueItems": true,
            "description": "Obrigatório para pattern=weekly."
          },
          "end_type": {
            "type": "string",
            "enum": [
              "none",
              "until_date"
            ]
          },
          "until_date": {
            "type": "string",
            "format": "date-time",
            "description": "Obrigatório quando end_type=until_date; não pode anteceder o início da tarefa."
          }
        },
        "required": [
          "pattern",
          "interval"
        ]
      },
      "ExternalTaskRecurrenceResponse": {
        "type": "object",
        "nullable": true,
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "pattern": {
            "type": "string",
            "enum": [
              "every_n_days",
              "weekly"
            ]
          },
          "interval": {
            "type": "integer"
          },
          "week_days": {
            "type": "array",
            "items": {
              "type": "string",
              "enum": [
                "sunday",
                "monday",
                "tuesday",
                "wednesday",
                "thursday",
                "friday",
                "saturday"
              ]
            }
          },
          "end_type": {
            "type": "string",
            "enum": [
              "none",
              "until_date"
            ]
          },
          "start_date": {
            "type": "string",
            "format": "date-time"
          },
          "end_date": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "until_date": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "index": {
            "type": "integer",
            "nullable": true
          },
          "is_exception": {
            "type": "boolean"
          }
        }
      },
      "ExternalTaskMentionRequest": {
        "type": "object",
        "required": [
          "mentioned_id"
        ],
        "properties": {
          "mentioned_id": {
            "type": "string",
            "format": "uuid"
          }
        }
      },
      "ExternalTaskMentionResponse": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "mentioned": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ExternalUserSummary"
              }
            ],
            "nullable": true
          },
          "mentioned_by": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ExternalUserSummary"
              }
            ],
            "nullable": true
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "CreateExternalTask": {
        "type": "object",
        "required": [
          "crm_task_type_id",
          "title"
        ],
        "properties": {
          "crm_task_type_id": {
            "type": "string",
            "format": "uuid"
          },
          "crm_task_stage_id": {
            "type": "string",
            "format": "uuid",
            "description": "Etapa da tarefa. Quando omitida, assume a primeira etapa ativa que não seja de conclusão; uma etapa de conclusão cria a tarefa já concluída."
          },
          "responsible_id": {
            "type": "string",
            "format": "uuid",
            "description": "Usuário responsável. Quando omitido, assume o usuário criador da chave."
          },
          "crm_lead_id": {
            "type": "string",
            "format": "uuid",
            "description": "Vincula a tarefa a um lead."
          },
          "crm_deal_id": {
            "type": "string",
            "format": "uuid",
            "description": "Vincula a tarefa a uma oportunidade."
          },
          "crm_delivery_id": {
            "type": "string",
            "format": "uuid",
            "description": "Vincula a tarefa a uma entrega."
          },
          "crm_person_id": {
            "type": "string",
            "format": "uuid",
            "description": "Vincula a tarefa a uma pessoa."
          },
          "crm_organization_id": {
            "type": "string",
            "format": "uuid",
            "description": "Vincula a tarefa a uma organização."
          },
          "crm_customer_id": {
            "type": "string",
            "format": "uuid",
            "description": "Vincula a tarefa a um cliente."
          },
          "priority": {
            "$ref": "#/components/schemas/ExternalTaskPriority"
          },
          "title": {
            "type": "string",
            "maxLength": 100,
            "minLength": 1
          },
          "description": {
            "type": "string",
            "description": "Texto simples ou HTML. O HTML é higienizado: são mantidos formatação básica, listas, tabelas e links; scripts, imagens e conteúdo incorporado são removidos."
          },
          "mentions": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ExternalTaskMentionRequest"
            }
          },
          "start_date": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "end_date": {
            "type": "string",
            "format": "date-time",
            "nullable": true,
            "description": "Exige `start_date`. Quando omitido, é calculado pela duração padrão do tipo de tarefa."
          },
          "has_time": {
            "type": "boolean",
            "description": "Com `false`, a tarefa vale para o dia inteiro e não aceita `end_date`."
          },
          "recurrence": {
            "$ref": "#/components/schemas/ExternalTaskRecurrenceRequest"
          },
          "meeting_outcome": {
            "type": "integer",
            "enum": [
              1,
              2,
              3,
              4
            ],
            "description": "Resultado da reunião: 1 = realizada, 2 = não compareceu, 3 = cancelada, 4 = reagendada. Aceito apenas em tarefas cujo tipo é reunião."
          },
          "meeting_outcome_notes": {
            "type": "string"
          },
          "is_personal": {
            "type": "boolean"
          },
          "create_meeting": {
            "type": "boolean"
          },
          "create_event": {
            "type": "boolean"
          },
          "create_online_meeting_link": {
            "type": "boolean"
          },
          "meeting_provider": {
            "$ref": "#/components/schemas/ExternalTaskMeetingProvider"
          },
          "meeting_participants": {
            "type": "array",
            "items": {
              "type": "string",
              "format": "email",
              "maxLength": 320
            },
            "maxItems": 100,
            "uniqueItems": true,
            "description": "E-mails são normalizados com trim e letras minúsculas."
          },
          "reminders_minutes": {
            "type": "array",
            "items": {
              "type": "integer",
              "minimum": 1
            },
            "uniqueItems": true,
            "description": "Minutos de antecedência dos lembretes. Exige tarefa com data e hora."
          },
          "parent_task_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true,
            "description": "Tarefa pai. Subtarefas não podem ter recorrência própria."
          },
          "tag_ids": {
            "type": "array",
            "items": {
              "type": "string",
              "format": "uuid"
            },
            "uniqueItems": true,
            "description": "IDs das tags da tarefa."
          },
          "meeting_mode": {
            "type": "string",
            "enum": [
              "online",
              "in_person"
            ]
          },
          "meeting_location": {
            "type": "string",
            "nullable": true,
            "minLength": 1,
            "maxLength": 500,
            "description": "Obrigatório para meeting_mode=in_person. Local não permitido para modo online."
          },
          "meeting_description": {
            "type": "string",
            "maxLength": 20000,
            "description": "Descrição HTML com formatação básica; máximo de 5.000 caracteres de texto normalizado."
          }
        },
        "description": "`crm_task_type_id` e `title` são obrigatórios. Envie no máximo um vínculo entre `crm_lead_id`, `crm_deal_id`, `crm_delivery_id`, `crm_person_id`, `crm_organization_id` e `crm_customer_id`."
      },
      "UpdateExternalTask": {
        "type": "object",
        "description": "Payload parcial de atualização. Todos os campos são opcionais; `recurrence_scope` controla o alcance em tarefas recorrentes e `is_completed` conclui a tarefa. expected_updated_at permite detectar conflitos concorrentes e é opcional na API externa.",
        "properties": {
          "crm_task_type_id": {
            "type": "string",
            "format": "uuid"
          },
          "crm_task_stage_id": {
            "type": "string",
            "format": "uuid"
          },
          "responsible_id": {
            "type": "string",
            "format": "uuid"
          },
          "crm_lead_id": {
            "type": "string",
            "format": "uuid",
            "description": "Vincula a tarefa a um lead. Substitui o vínculo atual; envie apenas um campo de vínculo."
          },
          "crm_deal_id": {
            "type": "string",
            "format": "uuid",
            "description": "Vincula a tarefa a uma oportunidade. Substitui o vínculo atual; envie apenas um campo de vínculo."
          },
          "crm_delivery_id": {
            "type": "string",
            "format": "uuid",
            "description": "Vincula a tarefa a uma entrega. Substitui o vínculo atual; envie apenas um campo de vínculo."
          },
          "crm_person_id": {
            "type": "string",
            "format": "uuid",
            "description": "Vincula a tarefa a uma pessoa. Substitui o vínculo atual; envie apenas um campo de vínculo."
          },
          "crm_organization_id": {
            "type": "string",
            "format": "uuid",
            "description": "Vincula a tarefa a uma organização. Substitui o vínculo atual; envie apenas um campo de vínculo."
          },
          "crm_customer_id": {
            "type": "string",
            "format": "uuid",
            "description": "Vincula a tarefa a um cliente. Substitui o vínculo atual; envie apenas um campo de vínculo."
          },
          "priority": {
            "$ref": "#/components/schemas/ExternalTaskPriority"
          },
          "title": {
            "type": "string",
            "maxLength": 100,
            "minLength": 1
          },
          "description": {
            "type": "string",
            "description": "Texto simples ou HTML. O HTML é higienizado: são mantidos formatação básica, listas, tabelas e links; scripts, imagens e conteúdo incorporado são removidos."
          },
          "mentions": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ExternalTaskUpdateMentionRequest"
            }
          },
          "start_date": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "end_date": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "has_time": {
            "type": "boolean"
          },
          "recurrence": {
            "$ref": "#/components/schemas/ExternalTaskRecurrenceRequest"
          },
          "meeting_outcome": {
            "type": "integer",
            "enum": [
              1,
              2,
              3,
              4
            ],
            "description": "Resultado da reunião: 1 = realizada, 2 = não compareceu, 3 = cancelada, 4 = reagendada. Aceito apenas em tarefas cujo tipo é reunião. No PUT, informar um resultado conclui a tarefa; com 4 e nova data, a API cria e retorna a tarefa reagendada."
          },
          "meeting_outcome_notes": {
            "type": "string"
          },
          "is_personal": {
            "type": "boolean"
          },
          "create_meeting": {
            "type": "boolean"
          },
          "create_event": {
            "type": "boolean"
          },
          "create_online_meeting_link": {
            "type": "boolean"
          },
          "meeting_provider": {
            "$ref": "#/components/schemas/ExternalTaskMeetingProvider"
          },
          "meeting_participants": {
            "type": "array",
            "items": {
              "type": "string",
              "format": "email",
              "maxLength": 320
            },
            "maxItems": 100,
            "uniqueItems": true,
            "description": "E-mails são normalizados com trim e letras minúsculas."
          },
          "reminders_minutes": {
            "type": "array",
            "items": {
              "type": "integer",
              "minimum": 1
            },
            "uniqueItems": true
          },
          "recurrence_scope": {
            "$ref": "#/components/schemas/ExternalTaskRecurrenceScope"
          },
          "completed_at": {
            "type": "string",
            "format": "date-time",
            "description": "Aceito por compatibilidade e ignorado: a conclusão usa sempre o horário do servidor."
          },
          "is_completed": {
            "type": "boolean",
            "description": "`true` conclui a tarefa. `false` não reabre: para reabrir, envie em `crm_task_stage_id` uma etapa que não seja de conclusão."
          },
          "parent_task_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true,
            "description": "Tarefa pai. Subtarefas não podem ter recorrência própria."
          },
          "tag_ids": {
            "type": "array",
            "items": {
              "type": "string",
              "format": "uuid"
            },
            "uniqueItems": true,
            "description": "IDs das tags da tarefa."
          },
          "meeting_mode": {
            "type": "string",
            "enum": [
              "online",
              "in_person"
            ]
          },
          "meeting_location": {
            "type": "string",
            "nullable": true,
            "minLength": 1,
            "maxLength": 500,
            "description": "Obrigatório para meeting_mode=in_person. Local não permitido para modo online."
          },
          "meeting_description": {
            "type": "string",
            "maxLength": 20000,
            "description": "Descrição HTML com formatação básica; máximo de 5.000 caracteres de texto normalizado."
          },
          "expected_updated_at": {
            "type": "string",
            "format": "date-time",
            "description": "Opcional na API externa. Envie updated_at da versão consultada. Uma versão desatualizada retorna 409."
          }
        }
      },
      "RemoveExternalTask": {
        "type": "object",
        "properties": {
          "recurrence_scope": {
            "$ref": "#/components/schemas/ExternalTaskRecurrenceScope"
          }
        }
      },
      "ExternalTask": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "title": {
            "type": "string"
          },
          "description": {
            "type": "string",
            "nullable": true
          },
          "is_personal": {
            "type": "boolean"
          },
          "priority": {
            "$ref": "#/components/schemas/ExternalTaskPriority"
          },
          "start_date": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "end_date": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "has_time": {
            "type": "boolean"
          },
          "completed_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "meeting_outcome": {
            "type": "integer",
            "enum": [
              1,
              2,
              3,
              4
            ],
            "nullable": true,
            "description": "Resultado da reunião: 1 = realizada, 2 = não compareceu, 3 = cancelada, 4 = reagendada."
          },
          "meeting_outcome_notes": {
            "type": "string",
            "nullable": true
          },
          "ai_processed": {
            "type": "boolean"
          },
          "ai_status": {
            "type": "integer",
            "nullable": true
          },
          "ai_error_log": {
            "type": "string",
            "nullable": true
          },
          "ai_last_action": {
            "type": "integer",
            "nullable": true
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          },
          "crm_task_type_id": {
            "type": "string",
            "format": "uuid"
          },
          "crm_task_stage_id": {
            "type": "string",
            "format": "uuid"
          },
          "crm_lead_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "crm_deal_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "crm_delivery_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "crm_person_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "crm_organization_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "crm_customer_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "recurrence_series_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "recurrence_index": {
            "type": "integer",
            "nullable": true
          },
          "recurrence_is_exception": {
            "type": "boolean"
          },
          "is_recurring": {
            "type": "boolean"
          },
          "recurrence": {
            "$ref": "#/components/schemas/ExternalTaskRecurrenceResponse"
          },
          "responsible_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "created_by": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ExternalUserSummary"
              }
            ],
            "nullable": true
          },
          "completed_by": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ExternalUserSummary"
              }
            ],
            "nullable": true
          },
          "responsible": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ExternalUserSummary"
              }
            ],
            "nullable": true
          },
          "crm_task_type": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "name": {
                "type": "string"
              },
              "icon": {
                "type": "string"
              },
              "is_meeting": {
                "type": "boolean"
              }
            }
          },
          "crm_task_stage": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "name": {
                "type": "string"
              },
              "color": {
                "type": "string"
              },
              "is_completion": {
                "type": "boolean"
              },
              "position": {
                "type": "integer"
              }
            }
          },
          "crm_lead": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "title": {
                "type": "string"
              },
              "code": {
                "oneOf": [
                  {
                    "type": "string"
                  },
                  {
                    "type": "integer"
                  }
                ]
              }
            }
          },
          "crm_deal": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "title": {
                "type": "string"
              },
              "code": {
                "oneOf": [
                  {
                    "type": "string"
                  },
                  {
                    "type": "integer"
                  }
                ]
              }
            }
          },
          "crm_delivery": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "title": {
                "type": "string"
              },
              "code": {
                "oneOf": [
                  {
                    "type": "string"
                  },
                  {
                    "type": "integer"
                  }
                ]
              },
              "status": {
                "type": "integer"
              }
            }
          },
          "crm_person": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "name": {
                "type": "string"
              }
            }
          },
          "crm_organization": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "name": {
                "type": "string"
              },
              "legal_name": {
                "type": "string",
                "nullable": true
              }
            }
          },
          "crm_customer": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "code": {
                "type": "integer"
              },
              "type": {
                "type": "integer"
              },
              "status": {
                "type": "integer"
              },
              "person": {
                "type": "object",
                "nullable": true,
                "properties": {
                  "id": {
                    "type": "string",
                    "format": "uuid"
                  },
                  "name": {
                    "type": "string"
                  }
                }
              },
              "organization": {
                "type": "object",
                "nullable": true,
                "properties": {
                  "id": {
                    "type": "string",
                    "format": "uuid"
                  },
                  "name": {
                    "type": "string"
                  },
                  "legal_name": {
                    "type": "string",
                    "nullable": true
                  }
                }
              }
            }
          },
          "mentions": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ExternalTaskMentionResponse"
            }
          },
          "recordings": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "recording_url": {
                  "type": "string",
                  "nullable": true
                },
                "transcription_url": {
                  "type": "string",
                  "nullable": true
                },
                "duration": {
                  "type": "integer"
                },
                "transcription_vtt_url": {
                  "type": "string",
                  "nullable": true
                },
                "transcription_txt_url": {
                  "type": "string",
                  "nullable": true
                }
              }
            }
          },
          "reminders_minutes": {
            "type": "array",
            "items": {
              "type": "integer"
            }
          },
          "meeting_link": {
            "type": "string"
          },
          "meeting_participants": {
            "type": "array",
            "items": {
              "type": "string",
              "format": "email"
            }
          },
          "meeting_provider": {
            "type": "string",
            "allOf": [
              {
                "$ref": "#/components/schemas/ExternalTaskMeetingProvider"
              }
            ],
            "nullable": true
          },
          "provider": {
            "type": "string",
            "allOf": [
              {
                "$ref": "#/components/schemas/ExternalTaskMeetingProvider"
              }
            ],
            "nullable": true
          },
          "sync_warning": {
            "type": "string"
          },
          "origin": {
            "type": "string",
            "enum": [
              "WEGLY",
              "GOOGLE_CALENDAR_IMPORT",
              "MICROSOFT_TEAMS_IMPORT"
            ]
          },
          "is_actionable": {
            "type": "boolean"
          },
          "ai_generated": {
            "type": "boolean"
          },
          "parent_task_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "hierarchy_level": {
            "type": "integer"
          },
          "is_subtask": {
            "type": "boolean"
          },
          "parent_task": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "title": {
                "type": "string"
              },
              "parent_task_id": {
                "type": "string",
                "format": "uuid",
                "nullable": true
              },
              "hierarchy_level": {
                "type": "integer"
              }
            },
            "nullable": true
          },
          "subtasks": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ExternalTask"
            },
            "description": "Presente na listagem hierarchy_mode=grouped."
          },
          "tags": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ExternalTaskTag"
            }
          },
          "calendar_lifecycle_status": {
            "type": "string",
            "nullable": true,
            "enum": [
              "upcoming",
              "in_progress",
              "ended",
              "cancelled",
              "unknown"
            ],
            "description": "Estado temporal de evento importado; null para tarefas nativas."
          },
          "meeting_mode": {
            "type": "string",
            "nullable": true,
            "enum": [
              "online",
              "in_person"
            ]
          },
          "meeting_location": {
            "type": "string",
            "nullable": true
          },
          "meeting_description": {
            "type": "string",
            "nullable": true
          },
          "meeting_event": {
            "$ref": "#/components/schemas/ExternalTaskMeetingEvent"
          },
          "meeting_sync": {
            "$ref": "#/components/schemas/ExternalTaskMeetingSync"
          },
          "meeting_attendees": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ExternalTaskMeetingAttendee"
            }
          },
          "meeting_can_manage_participants": {
            "type": "boolean"
          },
          "calendar_event_url": {
            "type": "string"
          },
          "meeting_response": {
            "type": "object",
            "properties": {
              "can_respond": {
                "type": "boolean"
              },
              "attendee_email": {
                "type": "string",
                "nullable": true
              },
              "response_status": {
                "type": "string",
                "nullable": true
              }
            },
            "description": "Elegibilidade do ator para responder ao convite, retornada na consulta por ID."
          },
          "meeting_can_respond": {
            "type": "boolean"
          },
          "meeting_self_attendee_email": {
            "type": "string",
            "nullable": true
          },
          "meeting_self_response_status": {
            "type": "string",
            "nullable": true
          },
          "meeting_recorder_sessions": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {},
              "additionalProperties": true
            },
            "description": "Sessões de gravação e seus artefatos disponíveis."
          },
          "comments": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {},
              "additionalProperties": true
            },
            "description": "Comentários incluídos na consulta de detalhes e nos retornos de escrita."
          }
        }
      },
      "ExternalTaskListResponse": {
        "type": "object",
        "properties": {
          "total": {
            "type": "integer"
          },
          "records": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ExternalTask"
            }
          }
        }
      },
      "ExternalTaskDeleteResult": {
        "type": "object",
        "properties": {
          "success": {
            "type": "boolean",
            "enum": [
              true
            ]
          }
        }
      },
      "CreateExternalSatisfactionShareLink": {
        "type": "object",
        "required": [
          "crm_person_id"
        ],
        "properties": {
          "crm_person_id": {
            "type": "string",
            "format": "uuid",
            "description": "UUID da pessoa que responderá o formulário."
          },
          "crm_deal_id": {
            "type": "string",
            "format": "uuid",
            "description": "UUID da oportunidade vinculada ao link. Não pode ser enviado junto de `crm_delivery_id`."
          },
          "crm_delivery_id": {
            "type": "string",
            "format": "uuid",
            "description": "UUID da entrega vinculada ao link. Não pode ser enviado junto de `crm_deal_id`."
          },
          "expires_at": {
            "type": "string",
            "format": "date-time",
            "description": "Data e hora de expiração do link. Quando omitido, o link não expira por data. Uma data no passado é aceita, mas o link já nasce expirado."
          },
          "max_uses": {
            "type": "integer",
            "minimum": 1,
            "maximum": 1000,
            "description": "Quantidade máxima de submissões públicas permitidas para o link. Quando omitido, não há limite explícito."
          }
        },
        "additionalProperties": false
      },
      "ExternalSatisfactionShareLinkResponse": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid",
            "description": "UUID do link público criado."
          },
          "token": {
            "type": "string",
            "format": "uuid",
            "description": "Token usado na rota pública do formulário."
          },
          "expires_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true,
            "description": "Data de expiração configurada para o link, quando houver."
          },
          "max_uses": {
            "type": "integer",
            "nullable": true,
            "description": "Limite de usos configurado para o link, quando houver."
          },
          "url": {
            "type": "string",
            "description": "Caminho público da API mantido por compatibilidade.",
            "example": "/crm/satisfaction/public/forms/8dd8779b-a2c1-4d61-92b1-b5d964e2a466"
          },
          "form_url": {
            "type": "string",
            "format": "uri",
            "description": "URL final do formulário no front-end para o respondente avaliar.",
            "example": "https://app.wegly.com.br/forms/8dd8779b-a2c1-4d61-92b1-b5d964e2a466"
          }
        }
      },
      "ExternalFollowerItem": {
        "type": "object",
        "properties": {
          "role": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "name": {
                "type": "string"
              }
            }
          },
          "user": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "name": {
                "type": "string"
              },
              "avatar": {
                "type": "string",
                "nullable": true
              }
            }
          },
          "notes": {
            "type": "string",
            "nullable": true
          }
        }
      },
      "LeadFollowersResponse": {
        "type": "object",
        "properties": {
          "followers": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ExternalFollowerItem"
            }
          }
        }
      },
      "OpportunityFollowersResponse": {
        "type": "object",
        "properties": {
          "followers": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ExternalFollowerItem"
            }
          }
        }
      },
      "FollowerRemoveResponse": {
        "type": "object",
        "properties": {
          "status": {
            "type": "string",
            "enum": [
              "success"
            ]
          }
        }
      },
      "ExternalApiError": {
        "type": "object",
        "properties": {
          "statusCode": {
            "type": "integer"
          },
          "message": {
            "oneOf": [
              {
                "type": "string"
              },
              {
                "type": "array",
                "items": {
                  "type": "string"
                }
              }
            ]
          },
          "error": {
            "type": "string"
          }
        },
        "description": "Formato de erro do HTTP/NestJS; os campos presentes variam conforme a exceção."
      },
      "ExternalTaskUpdateMentionRequest": {
        "type": "object",
        "properties": {
          "mentioned_id": {
            "type": "string",
            "format": "uuid"
          },
          "delete": {
            "type": "boolean",
            "description": "Remove a menção quando true."
          }
        },
        "required": [
          "mentioned_id"
        ]
      },
      "ExternalTaskTag": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "name": {
            "type": "string"
          },
          "color": {
            "type": "string",
            "nullable": true
          }
        }
      },
      "ExternalTaskMeetingAttendee": {
        "type": "object",
        "properties": {
          "email": {
            "type": "string",
            "format": "email"
          },
          "name": {
            "type": "string",
            "nullable": true
          },
          "response_status": {
            "type": "string",
            "enum": [
              "needs_action",
              "accepted",
              "declined",
              "tentative"
            ]
          },
          "response_updated_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "is_organizer": {
            "type": "boolean"
          },
          "is_self": {
            "type": "boolean"
          }
        }
      },
      "ExternalTaskMeetingSync": {
        "type": "object",
        "properties": {
          "operation_id": {
            "type": "string",
            "format": "uuid"
          },
          "status": {
            "type": "string",
            "nullable": true,
            "enum": [
              "synced",
              "pending",
              "retrying",
              "failed"
            ]
          },
          "attempts": {
            "type": "integer"
          },
          "max_attempts": {
            "type": "integer"
          },
          "next_retry_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "retry_after_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "can_retry": {
            "type": "boolean"
          },
          "error": {
            "type": "string",
            "nullable": true
          }
        },
        "nullable": true
      },
      "ExternalTaskMeetingEvent": {
        "type": "object",
        "properties": {
          "provider": {
            "type": "string",
            "nullable": true
          },
          "kind": {
            "type": "string",
            "nullable": true,
            "enum": [
              "instant_link",
              "calendar_event"
            ]
          },
          "mode": {
            "type": "string",
            "nullable": true,
            "enum": [
              "online",
              "in_person"
            ]
          },
          "location": {
            "type": "string",
            "nullable": true
          },
          "description": {
            "type": "string",
            "nullable": true
          },
          "status": {
            "type": "string",
            "nullable": true
          },
          "sync_status": {
            "type": "string",
            "nullable": true
          },
          "sync_operation_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "sync": {
            "$ref": "#/components/schemas/ExternalTaskMeetingSync"
          },
          "cancelled_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "online_url": {
            "type": "string",
            "nullable": true
          },
          "calendar_url": {
            "type": "string",
            "nullable": true
          },
          "attendees": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ExternalTaskMeetingAttendee"
            }
          },
          "is_external_invitation": {
            "type": "boolean"
          },
          "can_manage_event": {
            "type": "boolean"
          },
          "can_edit_participants": {
            "type": "boolean"
          },
          "provider_updated_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "last_synced_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          }
        },
        "nullable": true
      },
      "ProposalItemCustomFieldValueInput": {
        "type": "object",
        "properties": {
          "field_id": {
            "type": "string",
            "format": "uuid"
          },
          "value": {
            "oneOf": [
              {
                "type": "string",
                "nullable": true
              },
              {
                "type": "number"
              },
              {
                "type": "boolean"
              }
            ],
            "description": "Valor escalar compatível com o tipo da definição; null limpa o valor quando permitido."
          }
        },
        "required": [
          "field_id",
          "value"
        ]
      },
      "ProposalItemCustomFieldResponse": {
        "type": "object",
        "properties": {
          "field_id": {
            "type": "string",
            "format": "uuid"
          },
          "name": {
            "type": "string"
          },
          "type": {
            "type": "string",
            "enum": [
              "TEXT",
              "LONG_TEXT",
              "NUMBER",
              "DATE",
              "BOOLEAN",
              "SELECT"
            ]
          },
          "position": {
            "type": "integer"
          },
          "is_required": {
            "type": "boolean"
          },
          "is_visible_in_documents": {
            "type": "boolean"
          },
          "options": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "value": {
            "oneOf": [
              {
                "type": "string",
                "nullable": true
              },
              {
                "type": "number"
              },
              {
                "type": "boolean"
              }
            ],
            "description": "Valor escalar compatível com o tipo da definição; null limpa o valor quando permitido."
          }
        }
      },
      "ProposalItemCategoryValueInput": {
        "type": "object",
        "properties": {
          "category_id": {
            "type": "string",
            "format": "uuid"
          },
          "value": {
            "type": "string",
            "nullable": true,
            "maxLength": 500
          }
        },
        "required": [
          "category_id"
        ]
      },
      "ProposalItemCategoryResponse": {
        "type": "object",
        "properties": {
          "category_id": {
            "type": "string",
            "format": "uuid"
          },
          "category_name": {
            "type": "string"
          },
          "category_type": {
            "type": "string",
            "enum": [
              "TEXT",
              "SELECT"
            ]
          },
          "position": {
            "type": "integer"
          },
          "options": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "value": {
            "type": "string",
            "nullable": true
          }
        }
      },
      "ProposalProductCustomFieldDefinitionInput": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 150
          },
          "type": {
            "type": "string",
            "enum": [
              "TEXT",
              "LONG_TEXT",
              "NUMBER",
              "DATE",
              "BOOLEAN",
              "SELECT"
            ]
          },
          "position": {
            "type": "integer",
            "minimum": 0
          },
          "is_required": {
            "type": "boolean"
          },
          "is_visible_in_documents": {
            "type": "boolean"
          },
          "options": {
            "type": "array",
            "items": {
              "type": "string",
              "maxLength": 255
            },
            "maxItems": 100
          }
        },
        "required": [
          "name",
          "type",
          "position",
          "is_required",
          "is_visible_in_documents",
          "options"
        ]
      },
      "ProposalNewProductInput": {
        "type": "object",
        "description": "Cria um produto do catálogo na mesma transação da proposta; exige permissão de criação de produtos para o usuário responsável pela chave. Não combine com product_id, sku ou new_product_client_id. Imagem é enviada pela rota multipart do catálogo.",
        "properties": {
          "type": {
            "type": "integer",
            "enum": [
              0,
              1
            ],
            "description": "0 = produto; 1 = serviço."
          },
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 75
          },
          "active": {
            "type": "boolean"
          },
          "code": {
            "type": "string",
            "maxLength": 50
          },
          "description": {
            "type": "string"
          },
          "unit": {
            "type": "integer",
            "enum": [
              0,
              1,
              2,
              3,
              4,
              5,
              6,
              7
            ]
          },
          "cost_price": {
            "type": "number",
            "multipleOf": 0.01
          },
          "sale_price": {
            "type": "number",
            "multipleOf": 0.01
          },
          "is_recurring_default": {
            "type": "boolean"
          },
          "billing_interval_default": {
            "type": "integer",
            "enum": [
              0,
              1,
              2,
              3,
              4,
              5,
              6
            ],
            "nullable": true
          },
          "billing_interval_count_def": {
            "type": "integer",
            "minimum": 1,
            "nullable": true
          },
          "contract_term_months_def": {
            "type": "integer",
            "minimum": 1,
            "nullable": true
          },
          "custom_fields": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ProposalProductCustomFieldDefinitionInput"
            }
          }
        },
        "required": [
          "type",
          "name"
        ]
      },
      "ProposalPaymentInstallmentResponse": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "label": {
            "type": "string",
            "nullable": true
          },
          "position": {
            "type": "integer"
          },
          "amount": {
            "type": "number"
          },
          "percentage": {
            "type": "number",
            "nullable": true
          },
          "due_date": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "due_in_days": {
            "type": "integer",
            "nullable": true
          },
          "notes": {
            "type": "string",
            "nullable": true
          },
          "payment_method": {
            "type": "integer",
            "enum": [
              1,
              2,
              3,
              4,
              5,
              6,
              99
            ],
            "nullable": true,
            "description": "1 = Pix; 2 = crédito; 3 = boleto; 4 = transferência; 5 = dinheiro; 6 = débito; 99 = outro."
          },
          "payment_method_installments": {
            "type": "integer",
            "nullable": true
          },
          "card_receipt_mode": {
            "type": "integer",
            "enum": [
              1,
              2
            ],
            "nullable": true,
            "description": "1 = parcelado; 2 = antecipado."
          },
          "payment_method_notes": {
            "type": "string",
            "nullable": true
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "ProposalPaymentOptionResponse": {
        "type": "object",
        "description": "Condição de pagamento existente na proposta, com suas parcelas. Consulta disponível no detalhe; escrita de payment_options não está declarada nos DTOs externos.",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "name": {
            "type": "string"
          },
          "description": {
            "type": "string",
            "nullable": true
          },
          "position": {
            "type": "integer"
          },
          "discount_type": {
            "type": "integer",
            "enum": [
              0,
              1
            ],
            "nullable": true
          },
          "discount_value": {
            "type": "number",
            "nullable": true
          },
          "subtotal": {
            "type": "number"
          },
          "total": {
            "type": "number"
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          },
          "installments": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ProposalPaymentInstallmentResponse"
            }
          }
        }
      },
      "ProposalBaseResponse": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "lead": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ProposalContextSummary"
              }
            ],
            "nullable": true
          },
          "deal": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ProposalContextSummary"
              }
            ],
            "nullable": true
          },
          "code": {
            "type": "integer"
          },
          "version": {
            "type": "integer"
          },
          "title": {
            "type": "string",
            "nullable": true
          },
          "status": {
            "$ref": "#/components/schemas/ProposalStatusValue"
          },
          "notes": {
            "type": "string",
            "nullable": true
          },
          "is_primary": {
            "type": "boolean"
          },
          "discount_type": {
            "type": "integer",
            "allOf": [
              {
                "$ref": "#/components/schemas/ProposalDiscountType"
              }
            ],
            "nullable": true
          },
          "discount_value": {
            "type": "number",
            "nullable": true
          },
          "subtotal": {
            "type": "number"
          },
          "total": {
            "type": "number"
          },
          "valid_until": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "created_by": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ExternalUserSummary"
              }
            ],
            "nullable": true
          },
          "approved_by": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ExternalPersonSummary"
              }
            ],
            "nullable": true
          },
          "approved_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "archived_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "rejected_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          },
          "notes_format": {
            "type": "string",
            "enum": [
              "MARKDOWN",
              "HTML"
            ],
            "description": "Formato resolvido das observações. Ao enviar notes pela API externa, o serviço detecta HTML; caso contrário usa MARKDOWN."
          },
          "projected_values": {
            "type": "object",
            "description": "Projeções para horizontes de 6, 12, 18 e 24 meses. Registros de cálculo legado usam total como fallback.",
            "properties": {
              "6": {
                "type": "number",
                "nullable": true
              },
              "12": {
                "type": "number",
                "nullable": true
              },
              "18": {
                "type": "number",
                "nullable": true
              },
              "24": {
                "type": "number",
                "nullable": true
              }
            },
            "required": [
              "6",
              "12",
              "18",
              "24"
            ]
          },
          "has_recurring_value": {
            "type": "boolean"
          },
          "has_indefinite_recurring_value": {
            "type": "boolean"
          },
          "has_rolling_projection": {
            "type": "boolean"
          },
          "projection_calculated_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "projection_calculation_version": {
            "type": "integer",
            "nullable": true
          },
          "projection_source": {
            "type": "string",
            "description": "Origem do cálculo, por exemplo DIRECT_ITEMS ou LEGACY_CURRENT_VALUE."
          }
        }
      },
      "OpportunityOrderBy": {
        "type": "string",
        "enum": [
          "title",
          "created_at",
          "last_activity_at",
          "quality_rating",
          "score",
          "value",
          "expected_close_date",
          "temperature"
        ]
      },
      "ExternalCrmAddressInput": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string"
          },
          "street": {
            "type": "string"
          },
          "number": {
            "type": "string"
          },
          "complement": {
            "type": "string"
          },
          "district": {
            "type": "string"
          },
          "city": {
            "type": "string"
          },
          "state": {
            "type": "string"
          },
          "postal_code": {
            "type": "string"
          },
          "status": {
            "type": "integer",
            "enum": [
              0,
              1
            ]
          },
          "type": {
            "type": "integer",
            "enum": [
              0,
              1,
              2,
              3
            ],
            "description": "0 = comercial; 1 = residencial; 2 = entrega; 3 = faturamento."
          }
        }
      },
      "ExternalCrmPersonDocumentInput": {
        "type": "object",
        "properties": {
          "type": {
            "type": "integer",
            "enum": [
              0,
              1,
              2,
              3,
              4
            ],
            "description": "0 = CNH; 1 = RG; 2 = passaporte; 3 = CPF; 4 = outros."
          },
          "value": {
            "type": "string",
            "minLength": 1
          },
          "label": {
            "type": "string",
            "minLength": 1,
            "description": "Obrigatório quando type = 4 (outros)."
          }
        },
        "required": [
          "type",
          "value"
        ]
      },
      "OpportunityPersonUpdate": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string",
            "minLength": 1
          },
          "birth_date": {
            "type": "string",
            "format": "date"
          },
          "gender": {
            "type": "integer"
          },
          "notes": {
            "type": "string"
          },
          "contacts": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/OpportunityPersonContact"
            }
          },
          "documents": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ExternalCrmPersonDocumentInput"
            }
          },
          "address": {
            "$ref": "#/components/schemas/ExternalCrmAddressInput"
          },
          "addresses": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ExternalCrmAddressInput"
            }
          }
        },
        "required": [
          "name"
        ]
      },
      "CrmProjectionContext": {
        "type": "object",
        "properties": {
          "indefinite_horizon_months": {
            "type": "integer",
            "enum": [
              6,
              12,
              18,
              24
            ]
          },
          "display_mode": {
            "type": "string",
            "enum": [
              "CURRENT",
              "PROJECTED_CONTRACT_TOTAL"
            ]
          }
        }
      },
      "CrmValuation": {
        "type": "object",
        "properties": {
          "mode": {
            "type": "string",
            "enum": [
              "CURRENT",
              "PROJECTED_CONTRACT_TOTAL"
            ]
          },
          "source": {
            "type": "string",
            "enum": [
              "LEGACY_CURRENT_VALUE",
              "MANUAL",
              "DIRECT_ITEMS",
              "PRIMARY_PROPOSAL",
              "APPROVED_PROPOSAL"
            ]
          },
          "current_value": {
            "type": "number",
            "nullable": true
          },
          "projected_value": {
            "type": "number",
            "nullable": true
          },
          "display_value": {
            "type": "number",
            "nullable": true
          },
          "has_recurring_value": {
            "type": "boolean"
          },
          "has_indefinite_recurring_value": {
            "type": "boolean"
          },
          "has_rolling_projection": {
            "type": "boolean"
          },
          "indefinite_horizon_months": {
            "type": "integer",
            "enum": [
              6,
              12,
              18,
              24
            ]
          },
          "calculation_version": {
            "type": "integer",
            "nullable": true
          }
        },
        "description": "Valores calculados conforme o modo de exibição e horizonte da empresa. value continua representando o valor atual; display_value é o valor apropriado para a exibição configurada."
      },
      "CrmIcpSummary": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "name": {
            "type": "string"
          },
          "banner_type": {
            "type": "string"
          },
          "banner_image_url": {
            "type": "string",
            "nullable": true
          },
          "banner_color": {
            "type": "string",
            "nullable": true
          },
          "gradient_start_color": {
            "type": "string",
            "nullable": true
          },
          "gradient_end_color": {
            "type": "string",
            "nullable": true
          },
          "gradient_angle": {
            "type": "number",
            "nullable": true
          }
        }
      },
      "CrmIcpAssignment": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "name": {
            "type": "string"
          },
          "banner_type": {
            "type": "string"
          },
          "banner_image_url": {
            "type": "string",
            "nullable": true
          },
          "banner_color": {
            "type": "string",
            "nullable": true
          },
          "gradient_start_color": {
            "type": "string",
            "nullable": true
          },
          "gradient_end_color": {
            "type": "string",
            "nullable": true
          },
          "gradient_angle": {
            "type": "number",
            "nullable": true
          },
          "is_primary": {
            "type": "boolean"
          }
        }
      },
      "CrmChannelChatSummary": {
        "type": "object",
        "properties": {
          "chat_id": {
            "type": "string"
          },
          "title": {
            "type": "string"
          },
          "person_id": {
            "type": "string"
          },
          "person_name": {
            "type": "string"
          },
          "channel_account_id": {
            "type": "string"
          },
          "type": {
            "type": "string",
            "enum": [
              "WhatsApp",
              "Instagram"
            ]
          },
          "channel_type": {
            "type": "string",
            "enum": [
              "WHATSAPP",
              "INSTAGRAM"
            ]
          },
          "unread_count": {
            "type": "integer",
            "description": "Opcional; depende da autorização de leitura do contador."
          },
          "channel_account_name": {
            "type": "string",
            "nullable": true
          },
          "whatsapp_number_verified_name": {
            "type": "string",
            "nullable": true
          },
          "external_contact_id": {
            "type": "string",
            "nullable": true
          },
          "external_contact_handle": {
            "type": "string",
            "nullable": true
          },
          "chat_responsible": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "name": {
                "type": "string"
              },
              "avatar": {
                "type": "string",
                "nullable": true
              }
            },
            "nullable": true
          }
        }
      },
      "CrmPartnerSummary": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "type": {
            "type": "integer"
          },
          "name": {
            "type": "string"
          },
          "trade_name": {
            "type": "string",
            "nullable": true
          },
          "logo": {
            "type": "string",
            "nullable": true
          },
          "documents": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "id": {
                  "type": "string",
                  "format": "uuid"
                },
                "type": {
                  "type": "integer"
                },
                "value": {
                  "type": "string"
                },
                "label": {
                  "type": "string",
                  "nullable": true
                },
                "is_primary": {
                  "type": "boolean"
                }
              }
            }
          },
          "address": {
            "type": "object",
            "properties": {
              "city": {
                "type": "string",
                "nullable": true
              },
              "state": {
                "type": "string",
                "nullable": true
              },
              "country": {
                "type": "string",
                "nullable": true
              },
              "zip_code": {
                "type": "string",
                "nullable": true
              },
              "street": {
                "type": "string",
                "nullable": true
              },
              "number": {
                "type": "string",
                "nullable": true
              },
              "complement": {
                "type": "string",
                "nullable": true
              },
              "neighborhood": {
                "type": "string",
                "nullable": true
              },
              "formatted_address": {
                "type": "string",
                "nullable": true
              },
              "latitude": {
                "type": "number",
                "nullable": true
              },
              "longitude": {
                "type": "number",
                "nullable": true
              }
            },
            "nullable": true
          }
        }
      },
      "CrmScoreKnowledge": {
        "type": "object",
        "properties": {
          "total_criteria": {
            "type": "integer"
          },
          "filled_criteria": {
            "type": "integer"
          },
          "missing_criteria": {
            "type": "integer"
          },
          "percentage": {
            "type": "number",
            "nullable": true
          }
        }
      },
      "CrmScoreMovement": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "action": {
            "type": "string"
          },
          "direction": {
            "type": "string",
            "enum": [
              "positive",
              "negative",
              "neutral"
            ]
          },
          "delta": {
            "type": "number"
          },
          "previous_score": {
            "type": "number"
          },
          "new_score": {
            "type": "number"
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "ChatMedia": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "mime_type": {
            "type": "string"
          },
          "file_name": {
            "type": "string",
            "nullable": true
          },
          "is_downloaded": {
            "type": "boolean"
          },
          "url": {
            "type": "string",
            "nullable": true
          }
        },
        "required": [
          "id",
          "mime_type",
          "file_name",
          "is_downloaded",
          "url"
        ]
      },
      "ChatMessageCall": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "status": {
            "type": "string",
            "enum": [
              "RINGING",
              "IN_PROGRESS",
              "COMPLETED",
              "MISSED",
              "REJECTED",
              "FAILED",
              "CANCELED"
            ]
          },
          "direction": {
            "type": "string",
            "enum": [
              "INBOUND",
              "OUTBOUND"
            ]
          },
          "started_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "ended_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "duration_ms": {
            "type": "integer"
          },
          "recording_processed": {
            "type": "boolean"
          },
          "recording_available": {
            "type": "boolean"
          },
          "has_recording": {
            "type": "boolean"
          }
        }
      },
      "ChatQuotedMessage": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "type": {
            "$ref": "#/components/schemas/ChatMessageTypeEnum"
          },
          "origin": {
            "$ref": "#/components/schemas/ChatMessageOriginEnum"
          },
          "from_me": {
            "type": "boolean"
          },
          "sent_via": {
            "$ref": "#/components/schemas/ChatMessageSentViaEnum"
          },
          "status": {
            "$ref": "#/components/schemas/ChatMessageDeliveryStatusEnum"
          },
          "body_text": {
            "type": "string",
            "nullable": true
          },
          "content_payload": {
            "type": "object",
            "nullable": true,
            "additionalProperties": true
          },
          "reactions": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatReaction"
            }
          },
          "meta_timestamp": {
            "type": "string",
            "format": "date-time"
          },
          "is_history": {
            "type": "boolean"
          },
          "history_phase": {
            "type": "integer",
            "nullable": true
          },
          "history_chunk_order": {
            "type": "integer",
            "nullable": true
          },
          "history_progress": {
            "type": "integer",
            "nullable": true
          },
          "is_media_placeholder": {
            "type": "boolean"
          },
          "agent": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "user": {
                "type": "object",
                "allOf": [
                  {
                    "$ref": "#/components/schemas/ExternalUserSummary"
                  }
                ],
                "nullable": true
              }
            }
          },
          "user": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ExternalUserSummary"
              }
            ],
            "nullable": true
          },
          "transcription": {
            "type": "string",
            "nullable": true
          },
          "is_forwarded": {
            "type": "boolean"
          },
          "error_code": {
            "type": "integer",
            "nullable": true
          },
          "error_message": {
            "type": "string",
            "nullable": true
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "media": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ChatMedia"
              }
            ],
            "nullable": true
          },
          "page": {
            "type": "integer",
            "description": "Página da mensagem citada na mesma ordenação/paginação."
          },
          "whatsapp_ai_agent_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true,
            "description": "Agente de IA que enviou a mensagem; null para pessoas e automações."
          }
        },
        "required": [
          "id",
          "type",
          "origin",
          "status",
          "page"
        ]
      },
      "ChatMessage": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "type": {
            "$ref": "#/components/schemas/ChatMessageTypeEnum"
          },
          "origin": {
            "$ref": "#/components/schemas/ChatMessageOriginEnum"
          },
          "from_me": {
            "type": "boolean"
          },
          "sent_via": {
            "$ref": "#/components/schemas/ChatMessageSentViaEnum"
          },
          "status": {
            "$ref": "#/components/schemas/ChatMessageDeliveryStatusEnum"
          },
          "body_text": {
            "type": "string",
            "nullable": true
          },
          "content_payload": {
            "type": "object",
            "nullable": true,
            "additionalProperties": true
          },
          "reactions": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatReaction"
            }
          },
          "meta_timestamp": {
            "type": "string",
            "format": "date-time"
          },
          "is_history": {
            "type": "boolean"
          },
          "history_phase": {
            "type": "integer",
            "nullable": true
          },
          "history_chunk_order": {
            "type": "integer",
            "nullable": true
          },
          "history_progress": {
            "type": "integer",
            "nullable": true
          },
          "is_media_placeholder": {
            "type": "boolean"
          },
          "agent": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "user": {
                "type": "object",
                "allOf": [
                  {
                    "$ref": "#/components/schemas/ExternalUserSummary"
                  }
                ],
                "nullable": true
              }
            }
          },
          "user": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ExternalUserSummary"
              }
            ],
            "nullable": true
          },
          "transcription": {
            "type": "string",
            "nullable": true
          },
          "is_forwarded": {
            "type": "boolean"
          },
          "error_code": {
            "type": "integer",
            "nullable": true
          },
          "error_message": {
            "type": "string",
            "nullable": true
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "media": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ChatMedia"
              }
            ],
            "nullable": true
          },
          "call": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ChatMessageCall"
              }
            ],
            "nullable": true
          },
          "quoted_message": {
            "$ref": "#/components/schemas/ChatQuotedMessage"
          },
          "whatsapp_ai_agent_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true,
            "description": "Agente de IA que enviou a mensagem; null para pessoas e automações."
          }
        },
        "required": [
          "id",
          "type",
          "origin",
          "from_me",
          "sent_via",
          "status",
          "body_text",
          "transcription",
          "meta_timestamp",
          "created_at",
          "media",
          "call"
        ]
      },
      "ChatInstagramAttachment": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "media_id": {
            "type": "string",
            "nullable": true
          },
          "provider_media_id": {
            "type": "string",
            "nullable": true
          },
          "provider_type": {
            "type": "string",
            "nullable": true
          },
          "content_kind": {
            "type": "string"
          },
          "mime_type": {
            "type": "string",
            "nullable": true
          },
          "file_name": {
            "type": "string",
            "nullable": true
          },
          "file_size": {
            "type": "number",
            "nullable": true
          },
          "storage_path": {
            "type": "string",
            "nullable": true
          },
          "public_url": {
            "type": "string",
            "nullable": true
          },
          "source_url": {
            "type": "string",
            "nullable": true
          },
          "url": {
            "type": "string",
            "nullable": true
          },
          "is_downloaded": {
            "type": "boolean"
          },
          "download_status": {
            "type": "string"
          },
          "metadata": {
            "type": "object",
            "properties": {},
            "nullable": true,
            "additionalProperties": true
          }
        }
      },
      "ChatInstagramMessage": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "type": {
            "type": "string",
            "description": "Tipo normalizado da mensagem do canal."
          },
          "origin": {
            "type": "string",
            "enum": [
              "INBOUND",
              "API_OUTBOUND",
              "APP_ECHO",
              "SYSTEM"
            ]
          },
          "from_me": {
            "type": "boolean"
          },
          "sent_via": {
            "$ref": "#/components/schemas/ChatMessageSentViaEnum"
          },
          "status": {
            "type": "string",
            "enum": [
              "PROCESSING",
              "SENT",
              "DELIVERED",
              "READ",
              "FAILED",
              "DELETED"
            ],
            "description": "Status da mensagem no Instagram, em maiúsculas."
          },
          "body_text": {
            "type": "string",
            "nullable": true
          },
          "content_payload": {
            "type": "object",
            "nullable": true,
            "additionalProperties": true
          },
          "reactions": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatReaction"
            }
          },
          "meta_timestamp": {
            "type": "string",
            "format": "date-time"
          },
          "is_history": {
            "type": "boolean"
          },
          "history_phase": {
            "type": "integer",
            "nullable": true
          },
          "history_chunk_order": {
            "type": "integer",
            "nullable": true
          },
          "history_progress": {
            "type": "integer",
            "nullable": true
          },
          "is_media_placeholder": {
            "type": "boolean"
          },
          "agent": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "user": {
                "type": "object",
                "allOf": [
                  {
                    "$ref": "#/components/schemas/ExternalUserSummary"
                  }
                ],
                "nullable": true
              }
            }
          },
          "user": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ExternalUserSummary"
              }
            ],
            "nullable": true
          },
          "crm_marketing_lead_source": {
            "type": "array",
            "nullable": true,
            "items": {
              "type": "object",
              "additionalProperties": true
            }
          },
          "is_forwarded": {
            "type": "boolean"
          },
          "wamid": {
            "type": "string",
            "nullable": true
          },
          "provider_message_id": {
            "type": "string",
            "nullable": true
          },
          "ref_wamid": {
            "type": "string",
            "nullable": true
          },
          "ref_provider_message_id": {
            "type": "string",
            "nullable": true
          },
          "error_code": {
            "type": "string",
            "nullable": true,
            "description": "Código textual do erro, por exemplo `DELIVERY_UNKNOWN`."
          },
          "error_message": {
            "type": "string",
            "nullable": true
          },
          "shared_content": {
            "type": "object",
            "properties": {},
            "nullable": true,
            "additionalProperties": true
          },
          "media": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatInstagramAttachment"
            }
          },
          "attachments": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatInstagramAttachment"
            }
          },
          "provider_timestamp": {
            "type": "string",
            "format": "date-time"
          },
          "channel_type": {
            "type": "string",
            "enum": [
              "INSTAGRAM"
            ]
          },
          "quoted_message": {
            "allOf": [
              {
                "$ref": "#/components/schemas/ChatInstagramMessage"
              },
              {
                "type": "object",
                "properties": {
                  "page": {
                    "type": "integer"
                  }
                }
              }
            ]
          }
        },
        "required": [
          "id",
          "type",
          "origin",
          "from_me",
          "sent_via",
          "status",
          "body_text",
          "meta_timestamp",
          "media",
          "attachments",
          "channel_type"
        ]
      },
      "ChatFlowStep": {
        "type": "object",
        "properties": {
          "node_id": {
            "type": "string"
          },
          "node_key": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "status": {
            "type": "string",
            "nullable": true
          },
          "status_label": {
            "type": "string",
            "nullable": true
          },
          "branch_key": {
            "type": "string",
            "nullable": true
          },
          "branch_label": {
            "type": "string",
            "nullable": true
          },
          "started_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "finished_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          }
        }
      },
      "ChatFlowSession": {
        "type": "object",
        "properties": {
          "session_id": {
            "type": "string",
            "format": "uuid"
          },
          "flow_id": {
            "type": "string",
            "format": "uuid"
          },
          "flow_name": {
            "type": "string"
          },
          "status": {
            "type": "string",
            "enum": [
              "ACTIVE",
              "WAITING_INPUT",
              "WAITING_TIME",
              "PAUSED_BY_HUMAN",
              "TRANSFERRED",
              "COMPLETED",
              "FAILED",
              "CANCELED"
            ]
          },
          "status_label": {
            "type": "string"
          },
          "is_active": {
            "type": "boolean"
          },
          "started_at": {
            "type": "string",
            "format": "date-time"
          },
          "last_activity_at": {
            "type": "string",
            "format": "date-time"
          },
          "finished_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "current_step": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ChatFlowStep"
              }
            ],
            "nullable": true
          }
        }
      },
      "ChatActiveFlowSession": {
        "allOf": [
          {
            "$ref": "#/components/schemas/ChatFlowSession"
          },
          {
            "type": "object",
            "properties": {
              "journey": {
                "type": "object",
                "properties": {
                  "completed_steps": {
                    "type": "array",
                    "items": {
                      "$ref": "#/components/schemas/ChatFlowStep"
                    }
                  },
                  "current_step": {
                    "type": "object",
                    "allOf": [
                      {
                        "$ref": "#/components/schemas/ChatFlowStep"
                      }
                    ],
                    "nullable": true
                  },
                  "upcoming_steps": {
                    "type": "array",
                    "items": {
                      "$ref": "#/components/schemas/ChatFlowStep"
                    }
                  }
                }
              }
            }
          }
        ]
      },
      "ChatPendingCopilotAction": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "company_id": {
            "type": "string",
            "format": "uuid"
          },
          "execution_id": {
            "type": "string",
            "format": "uuid"
          },
          "agent_id": {
            "type": "string",
            "format": "uuid"
          },
          "agent_name": {
            "type": "string",
            "nullable": true
          },
          "chat_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "action_key": {
            "type": "string"
          },
          "status": {
            "type": "string"
          },
          "confidence": {
            "type": "string",
            "nullable": true
          },
          "requires_review": {
            "type": "boolean"
          },
          "input_payload": {},
          "output_payload": {
            "nullable": true
          },
          "failure_reason": {
            "type": "string",
            "nullable": true
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          },
          "executed_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          }
        }
      },
      "ChatChannelAccount": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "type": {
            "type": "string",
            "description": "WHATSAPP_PHONE para WhatsApp; tipo da conta para Instagram."
          },
          "display_name": {
            "type": "string",
            "nullable": true
          },
          "provider_status": {
            "type": "string"
          }
        }
      },
      "ChatExternalContact": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string"
          },
          "handle": {
            "type": "string",
            "nullable": true
          },
          "display_name": {
            "type": "string",
            "nullable": true
          },
          "avatar_url": {
            "type": "string",
            "nullable": true
          }
        }
      },
      "ChatInstagramSummary": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "wa_contact_id": {
            "type": "string",
            "nullable": true,
            "description": "Sempre null nas conversas Instagram."
          },
          "contact_name": {
            "type": "string"
          },
          "contact_number": {
            "type": "string"
          },
          "status": {
            "$ref": "#/components/schemas/ChatStatusEnum"
          },
          "chat_type": {
            "$ref": "#/components/schemas/ChatTypeEnum"
          },
          "unread_count": {
            "type": "integer"
          },
          "is_manually_unread": {
            "type": "boolean"
          },
          "priority": {
            "$ref": "#/components/schemas/ChatPriorityValue"
          },
          "archived_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "assigned_agent_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "phone_number": {
            "$ref": "#/components/schemas/ChatPhoneSummary"
          },
          "assigned_agent": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ChatAgentSummary"
              }
            ],
            "nullable": true
          },
          "last_message_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "last_message": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ChatInstagramMessage"
              }
            ],
            "nullable": true
          },
          "crm_person": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ChatPersonDetails"
              }
            ],
            "nullable": true
          },
          "last_customer_msg_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "session_expires_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "can_send_open_message": {
            "type": "boolean",
            "description": "Indica se a janela atual permite mensagem aberta."
          },
          "has_pending_copilot_actions": {
            "type": "boolean"
          },
          "pending_copilot_actions_count": {
            "type": "integer"
          },
          "has_active_whatsapp_flow_session": {
            "type": "boolean"
          },
          "active_whatsapp_flow_sessions": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatActiveFlowSession"
            }
          },
          "has_upcoming_scheduled_message": {
            "type": "boolean",
            "description": "Presente na listagem; indica agendamento futuro."
          },
          "channel_type": {
            "type": "string",
            "enum": [
              "INSTAGRAM"
            ]
          },
          "channel_account_id": {
            "type": "string",
            "format": "uuid"
          },
          "channel_account": {
            "$ref": "#/components/schemas/ChatChannelAccount"
          },
          "external_contact": {
            "$ref": "#/components/schemas/ChatExternalContact"
          },
          "legacy": {
            "type": "object",
            "properties": {},
            "description": "Objeto vazio para Instagram."
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          }
        },
        "required": [
          "id",
          "wa_contact_id",
          "contact_name",
          "contact_number",
          "status",
          "priority",
          "chat_type",
          "unread_count",
          "is_manually_unread",
          "channel_type",
          "channel_account_id",
          "can_send_open_message"
        ]
      },
      "ChatInstagramDetails": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "wa_contact_id": {
            "type": "string",
            "nullable": true,
            "description": "Sempre null nas conversas Instagram."
          },
          "contact_name": {
            "type": "string"
          },
          "contact_number": {
            "type": "string"
          },
          "status": {
            "$ref": "#/components/schemas/ChatStatusEnum"
          },
          "chat_type": {
            "$ref": "#/components/schemas/ChatTypeEnum"
          },
          "unread_count": {
            "type": "integer"
          },
          "is_manually_unread": {
            "type": "boolean"
          },
          "priority": {
            "$ref": "#/components/schemas/ChatPriorityValue"
          },
          "archived_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "assigned_agent_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "phone_number": {
            "$ref": "#/components/schemas/ChatPhoneSummary"
          },
          "assigned_agent": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ChatAgentSummary"
              }
            ],
            "nullable": true
          },
          "last_message_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "last_message": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ChatInstagramMessage"
              }
            ],
            "nullable": true
          },
          "crm_person": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ChatPersonDetails"
              }
            ],
            "nullable": true
          },
          "last_customer_msg_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "session_expires_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "can_send_open_message": {
            "type": "boolean",
            "description": "Indica se a janela atual permite mensagem aberta."
          },
          "has_pending_copilot_actions": {
            "type": "boolean"
          },
          "pending_copilot_actions_count": {
            "type": "integer"
          },
          "has_active_whatsapp_flow_session": {
            "type": "boolean"
          },
          "active_whatsapp_flow_sessions": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatActiveFlowSession"
            }
          },
          "has_upcoming_scheduled_message": {
            "type": "boolean",
            "description": "Presente na listagem; indica agendamento futuro."
          },
          "channel_type": {
            "type": "string",
            "enum": [
              "INSTAGRAM"
            ]
          },
          "channel_account_id": {
            "type": "string",
            "format": "uuid"
          },
          "channel_account": {
            "$ref": "#/components/schemas/ChatChannelAccount"
          },
          "external_contact": {
            "$ref": "#/components/schemas/ChatExternalContact"
          },
          "legacy": {
            "type": "object",
            "properties": {},
            "description": "Objeto vazio para Instagram."
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          },
          "participants": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatAgentSummary"
            }
          },
          "assignable_agents": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatAssignableAgentSummary"
            }
          },
          "crm_marketing_lead_sources": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {},
              "additionalProperties": true
            }
          },
          "pending_copilot_actions": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatPendingCopilotAction"
            }
          }
        },
        "required": [
          "id",
          "status",
          "channel_type",
          "participants",
          "assignable_agents",
          "pending_copilot_actions"
        ]
      },
      "ChatMessageListResponse": {
        "type": "object",
        "properties": {
          "total": {
            "type": "integer",
            "description": "Total de registros que correspondem à consulta."
          },
          "records": {
            "type": "array",
            "items": {
              "anyOf": [
                {
                  "$ref": "#/components/schemas/ChatMessage"
                },
                {
                  "$ref": "#/components/schemas/ChatInstagramMessage"
                }
              ]
            }
          }
        },
        "required": [
          "total",
          "records"
        ]
      },
      "ChatHistoryEntry": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "event_type": {
            "type": "string",
            "description": "Evento operacional, como CREATED, STATUS_CHANGED, RESOLVED, REOPENED, SNOOZED, ARCHIVED, UNARCHIVED, DELETED ou REACTIVATED."
          },
          "event_label": {
            "type": "string"
          },
          "source": {
            "type": "string"
          },
          "source_label": {
            "type": "string"
          },
          "from_status": {
            "type": "string",
            "enum": [
              "OPEN",
              "RESOLVED",
              "SNOOZED"
            ],
            "nullable": true
          },
          "from_status_label": {
            "type": "string",
            "nullable": true
          },
          "to_status": {
            "type": "string",
            "enum": [
              "OPEN",
              "RESOLVED",
              "SNOOZED"
            ],
            "nullable": true
          },
          "to_status_label": {
            "type": "string",
            "nullable": true
          },
          "reason": {
            "type": "string",
            "nullable": true
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "actor": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ExternalUserSummary"
              }
            ],
            "nullable": true
          }
        }
      },
      "ChatHistoryResponse": {
        "type": "object",
        "properties": {
          "total": {
            "type": "integer",
            "description": "Total de registros que correspondem à consulta."
          },
          "records": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatHistoryEntry"
            }
          }
        },
        "required": [
          "total",
          "records"
        ]
      },
      "ChatAssignableAgentsResponse": {
        "type": "object",
        "properties": {
          "total": {
            "type": "integer",
            "description": "Total de registros que correspondem à consulta."
          },
          "records": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatAssignableAgentSummary"
            }
          }
        },
        "required": [
          "total",
          "records"
        ]
      },
      "ChatTimelineCall": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "meta_call_id": {
            "type": "string"
          },
          "status": {
            "type": "string",
            "enum": [
              "RINGING",
              "IN_PROGRESS",
              "COMPLETED",
              "MISSED",
              "REJECTED",
              "FAILED",
              "CANCELED"
            ]
          },
          "status_label": {
            "type": "string",
            "enum": [
              "atendida",
              "perdida",
              "recusada",
              "falhou",
              "cancelada",
              "tocando",
              "em_andamento"
            ]
          },
          "direction": {
            "type": "string",
            "enum": [
              "INBOUND",
              "OUTBOUND"
            ]
          },
          "duration_ms": {
            "type": "number"
          },
          "duration_seconds": {
            "type": "number"
          },
          "started_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "ended_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          },
          "contact_display": {
            "type": "string",
            "nullable": true
          },
          "contact_name": {
            "type": "string",
            "nullable": true
          }
        }
      },
      "ChatTimelineMessage": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "type": {
            "$ref": "#/components/schemas/ChatMessageTypeEnum"
          },
          "origin": {
            "$ref": "#/components/schemas/ChatMessageOriginEnum"
          },
          "from_me": {
            "type": "boolean"
          },
          "sent_via": {
            "$ref": "#/components/schemas/ChatMessageSentViaEnum"
          },
          "status": {
            "$ref": "#/components/schemas/ChatMessageDeliveryStatusEnum"
          },
          "body_text": {
            "type": "string",
            "nullable": true
          },
          "content_payload": {
            "type": "object",
            "nullable": true,
            "additionalProperties": true
          },
          "reactions": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatReaction"
            }
          },
          "meta_timestamp": {
            "type": "string",
            "format": "date-time"
          },
          "is_history": {
            "type": "boolean"
          },
          "history_phase": {
            "type": "integer",
            "nullable": true
          },
          "history_chunk_order": {
            "type": "integer",
            "nullable": true
          },
          "history_progress": {
            "type": "integer",
            "nullable": true
          },
          "is_media_placeholder": {
            "type": "boolean"
          },
          "agent": {
            "type": "object",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "user": {
                "type": "object",
                "allOf": [
                  {
                    "$ref": "#/components/schemas/ExternalUserSummary"
                  }
                ],
                "nullable": true
              }
            }
          },
          "user": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ExternalUserSummary"
              }
            ],
            "nullable": true
          },
          "transcription": {
            "type": "string",
            "nullable": true
          },
          "is_forwarded": {
            "type": "boolean"
          },
          "error_code": {
            "type": "integer",
            "nullable": true
          },
          "error_message": {
            "type": "string",
            "nullable": true
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "media": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ChatMedia"
              }
            ],
            "nullable": true
          },
          "quoted_message": {
            "allOf": [
              {
                "$ref": "#/components/schemas/ChatTimelineMessage"
              },
              {
                "type": "object",
                "properties": {
                  "page": {
                    "type": "integer"
                  }
                }
              }
            ]
          }
        }
      },
      "ChatTimelineResponse": {
        "type": "object",
        "properties": {
          "total": {
            "type": "integer",
            "description": "Total de registros que correspondem à consulta."
          },
          "records": {
            "type": "array",
            "items": {
              "oneOf": [
                {
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "event_type": {
                      "type": "string",
                      "enum": [
                        "MESSAGE"
                      ]
                    },
                    "event_at": {
                      "type": "string",
                      "format": "date-time"
                    },
                    "message": {
                      "$ref": "#/components/schemas/ChatTimelineMessage"
                    }
                  },
                  "required": [
                    "id",
                    "event_type",
                    "event_at",
                    "message"
                  ]
                },
                {
                  "type": "object",
                  "properties": {
                    "id": {
                      "type": "string"
                    },
                    "event_type": {
                      "type": "string",
                      "enum": [
                        "CALL"
                      ]
                    },
                    "event_at": {
                      "type": "string",
                      "format": "date-time"
                    },
                    "call": {
                      "$ref": "#/components/schemas/ChatTimelineCall"
                    }
                  },
                  "required": [
                    "id",
                    "event_type",
                    "event_at",
                    "call"
                  ]
                }
              ]
            }
          }
        },
        "required": [
          "total",
          "records"
        ]
      },
      "ChatTemplateComponent": {
        "type": "object",
        "properties": {
          "type": {
            "type": "string"
          },
          "format": {
            "type": "string"
          },
          "text": {
            "type": "string"
          },
          "buttons": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {},
              "additionalProperties": true
            }
          },
          "cards": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "components": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/ChatTemplateComponent"
                  }
                }
              }
            }
          },
          "example": {}
        }
      },
      "ChatTemplateRequiredField": {
        "type": "object",
        "properties": {
          "component": {
            "type": "string",
            "enum": [
              "HEADER",
              "BODY",
              "BUTTONS",
              "CAROUSEL"
            ]
          },
          "type": {
            "type": "string",
            "enum": [
              "TEXT",
              "IMAGE",
              "VIDEO",
              "DOCUMENT",
              "LOCATION"
            ]
          },
          "index": {
            "type": "number"
          },
          "button_index": {
            "type": "number"
          },
          "card_index": {
            "type": "number"
          },
          "variable_name": {
            "type": "string"
          },
          "label": {
            "type": "string"
          }
        },
        "required": [
          "component",
          "type",
          "label"
        ]
      },
      "ChatTemplate": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "language": {
            "type": "string"
          },
          "status": {
            "type": "string"
          },
          "category": {
            "type": "string"
          },
          "components": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatTemplateComponent"
            }
          },
          "created_at": {
            "type": "string"
          },
          "created_time": {
            "type": "string"
          },
          "required_fields": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatTemplateRequiredField"
            }
          }
        },
        "required": [
          "id",
          "name",
          "language",
          "status",
          "category",
          "components",
          "required_fields"
        ]
      },
      "UpdateExternalChatStatus": {
        "type": "object",
        "properties": {
          "status": {
            "$ref": "#/components/schemas/ChatStatusEnum"
          },
          "reason": {
            "type": "string",
            "maxLength": 500
          }
        },
        "required": [
          "status"
        ]
      },
      "UpdateExternalChatPriority": {
        "type": "object",
        "properties": {
          "priority": {
            "$ref": "#/components/schemas/ChatPriorityValue"
          }
        },
        "required": [
          "priority"
        ]
      },
      "AddExternalChatParticipant": {
        "type": "object",
        "properties": {
          "user_id": {
            "type": "string",
            "format": "uuid"
          }
        },
        "required": [
          "user_id"
        ]
      },
      "UpdateExternalChatResponsible": {
        "type": "object",
        "properties": {
          "user_id": {
            "type": "string",
            "format": "uuid"
          },
          "update_chat": {
            "type": "boolean",
            "default": true
          },
          "update_leads": {
            "type": "boolean",
            "default": false
          },
          "update_deals": {
            "type": "boolean",
            "default": false
          }
        },
        "required": [
          "user_id"
        ]
      },
      "ChatPersonContactInput": {
        "type": "object",
        "properties": {
          "type": {
            "type": "integer",
            "enum": [
              0,
              1,
              2,
              3,
              4,
              5,
              6,
              7
            ],
            "description": "0 WhatsApp, 1 e-mail, 2 celular, 3 telefone, 4 Instagram, 5 Facebook, 6 LinkedIn, 7 outros."
          },
          "value": {
            "type": "string",
            "minLength": 1
          },
          "primary": {
            "type": "boolean"
          }
        },
        "required": [
          "type",
          "value"
        ]
      },
      "ChatPersonDocumentInput": {
        "type": "object",
        "properties": {
          "type": {
            "type": "integer",
            "enum": [
              0,
              1,
              2,
              3,
              4
            ],
            "description": "0 CNH, 1 RG, 2 passaporte, 3 CPF, 4 outros."
          },
          "value": {
            "type": "string",
            "minLength": 1
          },
          "label": {
            "type": "string",
            "minLength": 1,
            "description": "Obrigatório quando type=4."
          }
        },
        "required": [
          "type",
          "value"
        ],
        "anyOf": [
          {
            "properties": {
              "type": {
                "type": "integer",
                "enum": [
                  0,
                  1,
                  2,
                  3
                ]
              }
            }
          },
          {
            "properties": {
              "type": {
                "type": "integer",
                "enum": [
                  4
                ]
              }
            },
            "required": [
              "label"
            ]
          }
        ]
      },
      "ChatPersonAddressInput": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string"
          },
          "street": {
            "type": "string"
          },
          "number": {
            "type": "string"
          },
          "complement": {
            "type": "string"
          },
          "district": {
            "type": "string"
          },
          "city": {
            "type": "string"
          },
          "state": {
            "type": "string"
          },
          "postal_code": {
            "type": "string"
          },
          "status": {
            "type": "integer",
            "enum": [
              0,
              1
            ]
          },
          "type": {
            "type": "integer",
            "enum": [
              0,
              1,
              2,
              3
            ]
          }
        }
      },
      "CreateExternalChatPerson": {
        "type": "object",
        "properties": {
          "person_id": {
            "type": "string",
            "format": "uuid",
            "description": "Vincula uma pessoa existente; sem este campo, informe name para criar."
          },
          "name": {
            "type": "string",
            "minLength": 1
          },
          "birth_date": {
            "anyOf": [
              {
                "type": "string",
                "format": "date"
              },
              {
                "type": "string",
                "format": "date-time"
              }
            ]
          },
          "gender": {
            "type": "integer"
          },
          "notes": {
            "type": "string"
          },
          "contacts": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatPersonContactInput"
            }
          },
          "address": {
            "$ref": "#/components/schemas/ChatPersonAddressInput"
          },
          "addresses": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatPersonAddressInput"
            }
          },
          "documents": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatPersonDocumentInput"
            }
          }
        },
        "anyOf": [
          {
            "required": [
              "person_id"
            ]
          },
          {
            "required": [
              "name"
            ]
          }
        ]
      },
      "ReactExternalChatMessage": {
        "type": "object",
        "properties": {
          "emoji": {
            "type": "string",
            "minLength": 1,
            "maxLength": 10
          }
        },
        "required": [
          "emoji"
        ]
      },
      "EditExternalChatMessage": {
        "type": "object",
        "properties": {
          "body": {
            "type": "string",
            "minLength": 1,
            "maxLength": 4096
          }
        },
        "required": [
          "body"
        ]
      },
      "SendExternalChatLocation": {
        "type": "object",
        "properties": {
          "latitude": {
            "type": "number",
            "minimum": -90,
            "maximum": 90
          },
          "longitude": {
            "type": "number",
            "minimum": -180,
            "maximum": 180
          },
          "name": {
            "type": "string",
            "maxLength": 100
          },
          "address": {
            "type": "string",
            "maxLength": 200
          },
          "reference_wamid": {
            "type": "string",
            "maxLength": 200
          }
        },
        "required": [
          "latitude",
          "longitude"
        ]
      },
      "SendExternalChatTyping": {
        "type": "object",
        "properties": {
          "is_typing": {
            "type": "boolean"
          },
          "reference_wamid": {
            "type": "string",
            "maxLength": 200
          }
        },
        "required": [
          "is_typing"
        ]
      },
      "ChatTypingResponse": {
        "type": "object",
        "properties": {
          "chat_id": {
            "type": "string",
            "format": "uuid"
          },
          "is_typing": {
            "type": "boolean"
          },
          "reference_wamid": {
            "type": "string",
            "nullable": true
          },
          "dispatched_at": {
            "type": "string",
            "format": "date-time"
          }
        },
        "required": [
          "chat_id",
          "is_typing",
          "reference_wamid",
          "dispatched_at"
        ]
      },
      "ChatInteractiveReplyButton": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "title": {
            "type": "string",
            "minLength": 1,
            "maxLength": 20
          }
        },
        "required": [
          "id",
          "title"
        ]
      },
      "ChatInteractiveRow": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "minLength": 1,
            "maxLength": 200
          },
          "title": {
            "type": "string",
            "minLength": 1,
            "maxLength": 24
          },
          "description": {
            "type": "string",
            "maxLength": 72
          }
        },
        "required": [
          "id",
          "title"
        ]
      },
      "ChatInteractiveSection": {
        "type": "object",
        "properties": {
          "title": {
            "type": "string",
            "maxLength": 24
          },
          "rows": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatInteractiveRow"
            },
            "minItems": 1,
            "maxItems": 10
          }
        },
        "required": [
          "rows"
        ]
      },
      "SendExternalChatInteractive": {
        "type": "object",
        "properties": {
          "interactive_type": {
            "type": "string",
            "enum": [
              "button",
              "list"
            ]
          },
          "body": {
            "type": "object",
            "properties": {
              "text": {
                "type": "string",
                "minLength": 1,
                "maxLength": 1024
              }
            },
            "required": [
              "text"
            ]
          },
          "header": {
            "type": "object",
            "properties": {
              "text": {
                "type": "string",
                "maxLength": 60
              }
            },
            "required": [
              "text"
            ]
          },
          "footer": {
            "type": "object",
            "properties": {
              "text": {
                "type": "string",
                "maxLength": 60
              }
            },
            "required": [
              "text"
            ]
          },
          "action": {
            "type": "object",
            "properties": {
              "buttons": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/ChatInteractiveReplyButton"
                },
                "minItems": 1,
                "maxItems": 3
              },
              "button": {
                "type": "string",
                "maxLength": 20
              },
              "sections": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/ChatInteractiveSection"
                },
                "minItems": 1,
                "maxItems": 10
              }
            },
            "description": "button exige buttons e não aceita button/sections; list exige button e sections e não aceita buttons. São permitidas até 10 linhas no total da lista, com IDs únicos."
          },
          "reference_wamid": {
            "type": "string",
            "maxLength": 200
          }
        },
        "required": [
          "interactive_type",
          "body",
          "action"
        ],
        "oneOf": [
          {
            "properties": {
              "interactive_type": {
                "type": "string",
                "enum": [
                  "button"
                ]
              },
              "action": {
                "required": [
                  "buttons"
                ]
              }
            }
          },
          {
            "properties": {
              "interactive_type": {
                "type": "string",
                "enum": [
                  "list"
                ]
              },
              "action": {
                "required": [
                  "button",
                  "sections"
                ]
              }
            }
          }
        ]
      },
      "CreateExternalChatScheduledMessage": {
        "type": "object",
        "properties": {
          "scheduled_at": {
            "type": "string",
            "format": "date-time",
            "description": "Data/hora futura com fuso, em ISO 8601."
          },
          "cancel_on_inbound": {
            "type": "boolean",
            "default": false
          },
          "type": {
            "type": "string",
            "enum": [
              "text",
              "template"
            ],
            "description": "Quando omitido, template se houver template; caso contrário, text."
          },
          "body": {
            "type": "string"
          },
          "template": {
            "$ref": "#/components/schemas/ChatTemplateInfo"
          },
          "template_fields": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatTemplateField"
            }
          },
          "reference_wamid": {
            "type": "string",
            "maxLength": 200
          }
        },
        "required": [
          "scheduled_at"
        ]
      },
      "UpdateExternalChatScheduledMessage": {
        "type": "object",
        "properties": {
          "scheduled_at": {
            "type": "string",
            "format": "date-time",
            "description": "Data/hora futura com fuso, em ISO 8601."
          },
          "cancel_on_inbound": {
            "type": "boolean"
          },
          "type": {
            "type": "string",
            "enum": [
              "text",
              "template"
            ],
            "description": "Quando omitido, passa a template se `template` for enviado; caso contrário, mantém o tipo atual do agendamento."
          },
          "body": {
            "type": "string"
          },
          "template": {
            "$ref": "#/components/schemas/ChatTemplateInfo"
          },
          "template_fields": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatTemplateField"
            }
          },
          "reference_wamid": {
            "type": "string",
            "maxLength": 200
          },
          "replace_files": {
            "type": "boolean",
            "description": "true remove/substitui anexos anteriores. Enviar novos arquivos também substitui todos os anexos anteriores."
          }
        }
      },
      "CreateExternalChatScheduledMessageMultipart": {
        "type": "object",
        "properties": {
          "scheduled_at": {
            "type": "string",
            "format": "date-time",
            "description": "Data/hora futura com fuso, em ISO 8601."
          },
          "cancel_on_inbound": {
            "type": "boolean",
            "default": false
          },
          "type": {
            "type": "string",
            "enum": [
              "text",
              "template"
            ],
            "description": "Quando omitido, template se houver template; caso contrário, text."
          },
          "body": {
            "type": "string"
          },
          "template": {
            "$ref": "#/components/schemas/ChatTemplateInfo"
          },
          "template_fields": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatTemplateField"
            }
          },
          "reference_wamid": {
            "type": "string",
            "maxLength": 200
          },
          "files": {
            "type": "array",
            "items": {
              "type": "string",
              "format": "binary"
            },
            "maxItems": 10
          },
          "file": {
            "type": "array",
            "items": {
              "type": "string",
              "format": "binary"
            },
            "maxItems": 10
          }
        },
        "required": [
          "scheduled_at"
        ],
        "description": "No multipart, template e template_fields aceitam JSON serializado. Use files ou file para os anexos."
      },
      "UpdateExternalChatScheduledMessageMultipart": {
        "type": "object",
        "properties": {
          "scheduled_at": {
            "type": "string",
            "format": "date-time",
            "description": "Data/hora futura com fuso, em ISO 8601."
          },
          "cancel_on_inbound": {
            "type": "boolean"
          },
          "type": {
            "type": "string",
            "enum": [
              "text",
              "template"
            ],
            "description": "Quando omitido, passa a template se `template` for enviado; caso contrário, mantém o tipo atual do agendamento."
          },
          "body": {
            "type": "string"
          },
          "template": {
            "$ref": "#/components/schemas/ChatTemplateInfo"
          },
          "template_fields": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatTemplateField"
            }
          },
          "reference_wamid": {
            "type": "string",
            "maxLength": 200
          },
          "replace_files": {
            "type": "boolean",
            "description": "true remove/substitui anexos anteriores. Enviar novos arquivos também substitui todos os anexos anteriores."
          },
          "files": {
            "type": "array",
            "items": {
              "type": "string",
              "format": "binary"
            },
            "maxItems": 10
          },
          "file": {
            "type": "array",
            "items": {
              "type": "string",
              "format": "binary"
            },
            "maxItems": 10
          }
        },
        "description": "No multipart, template e template_fields aceitam JSON serializado. Use files ou file para os anexos."
      },
      "CancelExternalChatScheduledMessage": {
        "type": "object",
        "properties": {
          "reason": {
            "type": "string",
            "maxLength": 500
          }
        }
      },
      "ChatScheduledMessage": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "chat_id": {
            "type": "string",
            "format": "uuid"
          },
          "company_id": {
            "type": "string",
            "format": "uuid"
          },
          "is_scheduled": {
            "type": "boolean",
            "enum": [
              true
            ]
          },
          "status": {
            "type": "string",
            "enum": [
              "PENDING",
              "PROCESSING",
              "SENT",
              "CANCELED",
              "FAILED"
            ]
          },
          "message_kind": {
            "type": "string",
            "enum": [
              "OPEN_MESSAGE",
              "TEMPLATE"
            ]
          },
          "cancel_reason": {
            "type": "string",
            "enum": [
              "USER_REQUEST",
              "CHAT_INTERACTION",
              "TEMPLATE_INVALID_OR_UNAVAILABLE"
            ],
            "nullable": true
          },
          "cancel_reason_description": {
            "type": "string",
            "nullable": true
          },
          "failure_reason": {
            "type": "string",
            "nullable": true
          },
          "cancel_on_inbound": {
            "type": "boolean"
          },
          "scheduled_at": {
            "type": "string",
            "format": "date-time"
          },
          "processed_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "sent_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "canceled_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          },
          "created_by_user_id": {
            "type": "string",
            "format": "uuid"
          },
          "sender_agent_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "canceled_by_user_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "payload": {
            "type": "object",
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "text",
                  "template"
                ]
              },
              "body": {
                "type": "string"
              },
              "template": {
                "$ref": "#/components/schemas/ChatTemplateInfo"
              },
              "template_fields": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/ChatTemplateField"
                }
              },
              "reference_wamid": {
                "type": "string"
              }
            },
            "required": [
              "type"
            ]
          },
          "attachments": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "id": {
                  "type": "string",
                  "format": "uuid"
                },
                "file_name": {
                  "type": "string"
                },
                "mime_type": {
                  "type": "string"
                },
                "file_size": {
                  "type": "number"
                }
              }
            }
          },
          "sent_message_ids": {
            "type": "array",
            "items": {
              "type": "string",
              "format": "uuid"
            }
          },
          "whatsapp_ai_agent_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true,
            "description": "Agente de IA que criou o agendamento; null para agendamentos criados por pessoas ou pela integração."
          }
        }
      },
      "ChatScheduledMessageResponse": {
        "type": "object",
        "properties": {
          "total": {
            "type": "integer",
            "description": "Total de registros que correspondem à consulta."
          },
          "records": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ChatScheduledMessage"
            }
          }
        },
        "required": [
          "total",
          "records"
        ]
      },
      "ProposalAttachmentUserSummary": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "name": {
            "type": "string"
          },
          "avatar": {
            "type": "string",
            "nullable": true
          }
        }
      },
      "ProposalAttachmentFile": {
        "type": "object",
        "description": "Dados do arquivo; presente somente quando `kind = FILE`.",
        "properties": {
          "name": {
            "type": "string"
          },
          "extension": {
            "type": "string",
            "nullable": true,
            "description": "Extensão em minúsculas, sem o ponto."
          },
          "mime_type": {
            "type": "string",
            "nullable": true
          },
          "size_bytes": {
            "type": "integer"
          },
          "can_preview": {
            "type": "boolean",
            "description": "Arquivo pronto, em formato com visualização rápida no CRM e com até 50 MB."
          },
          "can_play_inline": {
            "type": "boolean",
            "description": "Arquivo pronto em MP3 ou MP4, reproduzível pelo player do CRM."
          }
        }
      },
      "ProposalAttachmentDocumentSummary": {
        "type": "object",
        "description": "Dados do documento da biblioteca; presente somente quando `kind = DOCUMENT`.",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "title": {
            "type": "string"
          },
          "summary": {
            "type": "string",
            "nullable": true
          },
          "workflow_status": {
            "type": "string",
            "enum": [
              "DRAFT",
              "PUBLISHED"
            ]
          },
          "has_unpublished_changes": {
            "type": "boolean"
          },
          "published_version": {
            "type": "integer",
            "nullable": true
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          },
          "last_edited_by_user": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ProposalAttachmentUserSummary"
              }
            ],
            "nullable": true
          },
          "is_available": {
            "type": "boolean",
            "description": "`false` quando o documento está na lixeira da biblioteca."
          },
          "access": {
            "type": "object",
            "description": "O que o usuário criador da chave pode fazer com o documento na biblioteca.",
            "properties": {
              "can_open": {
                "type": "boolean"
              },
              "can_edit": {
                "type": "boolean"
              }
            }
          }
        }
      },
      "ProposalAttachment": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "proposal_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "draft_token": {
            "type": "string",
            "format": "uuid",
            "nullable": true,
            "description": "Sempre `null` na API externa."
          },
          "kind": {
            "type": "string",
            "enum": [
              "FILE",
              "DOCUMENT"
            ]
          },
          "status": {
            "type": "string",
            "enum": [
              "UPLOADING",
              "READY"
            ],
            "description": "Anexos criados pela API externa já nascem `READY`."
          },
          "position": {
            "type": "integer"
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          },
          "created_by_user": {
            "$ref": "#/components/schemas/ProposalAttachmentUserSummary"
          },
          "file": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ProposalAttachmentFile"
              }
            ],
            "nullable": true
          },
          "document": {
            "type": "object",
            "allOf": [
              {
                "$ref": "#/components/schemas/ProposalAttachmentDocumentSummary"
              }
            ],
            "nullable": true
          }
        }
      },
      "ProposalAttachmentListResponse": {
        "type": "object",
        "properties": {
          "total": {
            "type": "integer"
          },
          "records": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ProposalAttachment"
            }
          }
        }
      },
      "ProposalAttachmentFilesUploadRequest": {
        "type": "object",
        "description": "Payload multipart para anexar arquivos à proposta. Envie ao menos um arquivo em `files` ou `file`, com até 10 arquivos no total e até 20 MB por arquivo.",
        "properties": {
          "files": {
            "type": "array",
            "description": "Campo principal para envio de um ou vários arquivos.",
            "maxItems": 10,
            "items": {
              "type": "string",
              "format": "binary"
            }
          },
          "file": {
            "type": "string",
            "format": "binary",
            "description": "Campo alternativo para envio de arquivos; conta para o mesmo limite de 10."
          }
        }
      },
      "CreateProposalAttachmentDocument": {
        "type": "object",
        "properties": {
          "title": {
            "type": "string",
            "maxLength": 180,
            "description": "Título do documento. Quando omitido ou vazio, o documento nasce como \"Documento sem título\"."
          },
          "folder_id": {
            "type": "string",
            "format": "uuid",
            "description": "Pasta da biblioteca que vai receber o documento. Omita para criar na raiz."
          },
          "visibility": {
            "type": "string",
            "enum": [
              "PRIVATE",
              "RESTRICTED",
              "COMPANY"
            ],
            "default": "PRIVATE",
            "description": "Visibilidade do documento na biblioteca."
          },
          "content_markdown": {
            "type": "string",
            "maxLength": 200000,
            "description": "Conteúdo inicial da página principal, em Markdown. Não pode referenciar imagens de outro documento."
          }
        }
      },
      "AttachProposalLibraryItems": {
        "type": "object",
        "description": "Informe ao menos um item em `document_ids` ou `file_ids`, com até 20 itens por requisição somando as duas listas.",
        "properties": {
          "document_ids": {
            "type": "array",
            "maxItems": 20,
            "uniqueItems": true,
            "description": "Documentos da biblioteca que serão vinculados à proposta.",
            "items": {
              "type": "string",
              "format": "uuid"
            }
          },
          "file_ids": {
            "type": "array",
            "maxItems": 20,
            "uniqueItems": true,
            "description": "Arquivos do Drive da biblioteca que serão copiados para a proposta.",
            "items": {
              "type": "string",
              "format": "uuid"
            }
          }
        }
      },
      "UpdateProposalAttachmentDocument": {
        "type": "object",
        "properties": {
          "title": {
            "type": "string",
            "maxLength": 180,
            "description": "Novo título do documento; não pode ficar vazio."
          },
          "content_markdown": {
            "type": "string",
            "maxLength": 200000,
            "description": "Novo conteúdo da página principal, em Markdown. Substitui o conteúdo atual."
          }
        }
      },
      "ProposalAttachmentDocumentPage": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "parent_page_id": {
            "type": "string",
            "format": "uuid",
            "nullable": true
          },
          "title": {
            "type": "string"
          },
          "level": {
            "type": "integer",
            "minimum": 1,
            "description": "`1` para páginas raiz, `2` para filhas e assim por diante."
          },
          "content_format": {
            "type": "string",
            "enum": [
              "MARKDOWN",
              "HTML"
            ]
          },
          "content_markdown": {
            "type": "string",
            "nullable": true,
            "description": "Conteúdo em Markdown, preenchido quando `content_format = MARKDOWN`."
          },
          "plain_text": {
            "type": "string",
            "nullable": true,
            "description": "Texto puro, preenchido quando `content_format = HTML`."
          }
        }
      },
      "ProposalAttachmentDocumentContent": {
        "type": "object",
        "properties": {
          "attachment_id": {
            "type": "string",
            "format": "uuid"
          },
          "version_scope": {
            "type": "string",
            "enum": [
              "DRAFT",
              "PUBLISHED"
            ],
            "description": "Versão efetivamente lida."
          },
          "document": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "title": {
                "type": "string"
              },
              "summary": {
                "type": "string",
                "nullable": true
              },
              "workflow_status": {
                "type": "string",
                "enum": [
                  "DRAFT",
                  "PUBLISHED"
                ]
              },
              "published_version": {
                "type": "integer",
                "nullable": true
              },
              "has_unpublished_changes": {
                "type": "boolean"
              },
              "updated_at": {
                "type": "string",
                "format": "date-time"
              }
            }
          },
          "pages": {
            "type": "array",
            "description": "Páginas na ordem de leitura: cada página é seguida das suas subpáginas.",
            "items": {
              "$ref": "#/components/schemas/ProposalAttachmentDocumentPage"
            }
          }
        }
      },
      "ProposalAttachmentDownloadUrl": {
        "type": "object",
        "properties": {
          "url": {
            "type": "string",
            "format": "uri",
            "description": "URL assinada, válida por 15 minutos."
          },
          "expires_at": {
            "type": "string",
            "format": "date-time"
          },
          "file_name": {
            "type": "string"
          },
          "disposition": {
            "type": "string",
            "enum": [
              "attachment",
              "inline"
            ],
            "description": "Sempre `attachment` nesta rota."
          }
        }
      },
      "ProposalAttachmentRemoveResult": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "message": {
            "type": "string",
            "example": "Anexo removido com sucesso."
          }
        }
      },
      "ChatAiAttendance": {
        "type": "object",
        "description": "Resumo do atendimento por agente de IA em uma conversa WhatsApp da listagem.",
        "properties": {
          "state": {
            "type": "string",
            "enum": [
              "AI",
              "TRANSFERRED",
              "TEAM"
            ],
            "description": "AI: o agente conduz a conversa. TRANSFERRED: transferida pelo agente e ainda sem resposta de uma pessoa. TEAM: com a equipe."
          },
          "agent": {
            "type": "object",
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "name": {
                "type": "string"
              },
              "profile_name": {
                "type": "string",
                "nullable": true
              }
            }
          },
          "since": {
            "type": "string",
            "format": "date-time",
            "nullable": true,
            "description": "Com o agente atendendo, início do atendimento; depois, momento em que o agente saiu da conversa."
          },
          "end_reason": {
            "type": "string",
            "nullable": true,
            "enum": [
              "TRANSFER_RULE",
              "FALLBACK",
              "RESPONSE_LIMIT",
              "HUMAN_REPLY",
              "MANUAL_ASSIGNMENT",
              "CHAT_RESOLVED",
              "AI_COINS_EXHAUSTED",
              "OUTSIDE_ACTIVE_HOURS"
            ],
            "description": "Motivo do encerramento do atendimento pelo agente; null enquanto ele conduz a conversa."
          },
          "transferred_to": {
            "type": "object",
            "nullable": true,
            "description": "Pessoa que recebeu a conversa na transferência.",
            "properties": {
              "id": {
                "type": "string",
                "format": "uuid"
              },
              "name": {
                "type": "string"
              }
            }
          }
        }
      }
    }
  }
}
