{"openapi":"3.1.0","info":{"title":"My Clinic API","version":"1.0.0","description":"API REST multi-tenant do **My Clinic**: cadastro da clínica, agenda, pacientes, CRM, comunicação, time de agentes de IA, automações e cobrança.\n\n### Autenticação\n1. O aplicativo autentica o usuário no provedor de identidade da plataforma e recebe um **token de acesso (JWT)** de curta duração (15 min — renove antes de expirar).\n2. Envie `Authorization: Bearer <TOKEN>` em toda chamada `/v1`.\n3. Se o usuário tiver acesso a mais de uma clínica, envie `X-Clinic-Id: <clinic_id>` (lista em `GET /v1/me/memberships`). O servidor **valida o vínculo** — o `clinic_id` nunca é aceito no corpo.\n4. Integrações servidor-a-servidor (automações/agentes): `Authorization: Bearer <SERVICE_TOKEN>` + `X-Clinic-Id` + `X-Agent-Key` (o agente precisa estar habilitado na clínica).\n\n### Convenções\n- Respostas: `{ \"data\": ... }`; listas: `{ \"data\": [...], \"meta\": { hasNext, nextCursor, total, limit } }` com paginação por **cursor** (`?limit=&cursor=`).\n- Ordenação: `?sort=-campo,outro`. Filtros múltiplos: valores separados por vírgula (`?status=agendado,confirmado`). Busca: `?q=`.\n- Erros: `{ \"error\": { code, message, details?, requestId } }` — 400, 401, 402, 403, 404, 409, 422, 429, 500, 502, 503.\n- Datas locais da clínica em `YYYY-MM-DD` e horas em `HH:MM`; instantes em ISO 8601 UTC. Valores monetários em reais (número).\n- Toda escrita gera registro no histórico de ações (auditoria) com antes/depois mascarado e origem humano/agente.\n- Ações que disparam fluxos devolvem `meta.webhooks[]` com o status do envio do evento ao motor de automação (`sent` | `failed` | `disabled`).\n- Teste grátis do plano encerrado sem ativação: o painel fica em **somente leitura** — escritas respondem 402 `trial_expired` (cobrança em `/v1/billing*` e dados pessoais em `/v1/me*` continuam liberados; leituras seguem normais).\n- Rate limit: padrão 120 req/min por token (cabeçalhos `X-RateLimit-*`; 429 com `Retry-After`). Exportações e convites têm limites menores.\n- Cada operação traz um **exemplo cURL** pronto para copiar; troque `{baseUrl}` pela URL do ambiente e os marcadores `<...>` pelos seus valores."},"components":{"securitySchemes":{"platformJwt":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Token de acesso (JWT) emitido pelo provedor de identidade da plataforma para o usuário logado."},"serviceToken":{"type":"http","scheme":"bearer","description":"Token de serviço para integrações servidor-a-servidor (automações/agentes). Exige os cabeçalhos X-Clinic-Id e X-Agent-Key."},"providerWebhook":{"type":"http","scheme":"bearer","description":"Segredo combinado com o provedor de emissão fiscal, enviado por ele no cabeçalho Authorization dos avisos (webhooks). Não é token de usuário."}},"schemas":{"Error":{"type":"object","required":["error"],"properties":{"error":{"type":"object","required":["code","message","requestId"],"properties":{"code":{"type":"string","description":"Código estável para tratamento programático.","example":"validation_error"},"message":{"type":"string","description":"Mensagem em pt-BR para exibição."},"details":{"type":"array","items":{"$ref":"#/components/schemas/FieldError"}},"requestId":{"type":"string","description":"Id da requisição (também no cabeçalho X-Request-Id). Informe ao suporte."}}}},"title":"Error"},"LeadForecastResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/LeadForecast"}},"title":"LeadForecastResponse"},"AutomationSubscribedActionResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/AutomationSubscribed"},"meta":{"$ref":"#/components/schemas/ActionMeta"}},"title":"AutomationSubscribedActionResponse"},"FiscalSettingsResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/FiscalSettings"}},"title":"FiscalSettingsResponse"},"BillingResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Billing"}},"title":"BillingResponse"},"LeadBoardColumn":{"type":"object","required":["stage","label","total","items","nextCursor"],"properties":{"stage":{"type":"string","enum":["NEW","DISCOVERY","QUALIFIED","READY_TO_SCHEDULE","SCHEDULED","COMPLETED","NURTURE","NOT_A_FIT","HUMAN_HANDOFF"]},"label":{"type":"string"},"total":{"type":"integer","description":"Leads na etapa com os filtros aplicados."},"items":{"type":"array","items":{"$ref":"#/components/schemas/Lead"}},"nextCursor":{"anyOf":[{"type":"string","description":"Para \"ver mais\": GET /leads?stage=<etapa>&cursor=<nextCursor> com os mesmos filtros e ordenação."},{"type":"null"}]},"valueTotal":{"type":"number","description":"Soma de estimatedValue (R$) dos leads da etapa com os filtros aplicados. Só leads com valor."},"withValue":{"type":"integer","description":"Quantos leads da etapa têm valor estimado (de `total`)."}},"title":"LeadBoardColumn"},"LeadActionResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Lead"},"meta":{"$ref":"#/components/schemas/ActionMeta"}},"title":"LeadActionResponse"},"LeadList":{"type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/Lead"}},"meta":{"$ref":"#/components/schemas/PageMeta"}},"title":"LeadList"},"FiscalCandidateList":{"type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/FiscalCandidate"}},"meta":{"$ref":"#/components/schemas/PageMeta"}},"title":"FiscalCandidateList"},"FiscalServiceRules":{"type":"object","required":["serviceKey","serviceName","active","price","current","rules"],"properties":{"serviceKey":{"type":"string"},"serviceName":{"type":"string"},"active":{"type":"boolean"},"price":{"anyOf":[{"type":"number"},{"type":"null"}]},"current":{"anyOf":[{"$ref":"#/components/schemas/FiscalServiceRule"},{"type":"null"}]},"rules":{"type":"array","items":{"$ref":"#/components/schemas/FiscalServiceRule"},"description":"Todas as versões (mais recente primeiro)."}},"title":"FiscalServiceRules"},"AppointmentActionResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Appointment"},"meta":{"$ref":"#/components/schemas/ActionMeta"}},"title":"AppointmentActionResponse"},"InboundMessageResponse":{"type":"object","required":["data","meta"],"properties":{"data":{"$ref":"#/components/schemas/InboundMessageResult"},"meta":{"type":"object","required":["idempotent","webhooks"],"properties":{"idempotent":{"type":"boolean","description":"true = repetição: nada novo foi gravado nem disparado."},"webhooks":{"type":"array","items":{"$ref":"#/components/schemas/WebhookMeta"}}}}},"title":"InboundMessageResponse"},"AppointmentList":{"type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/Appointment"}},"meta":{"$ref":"#/components/schemas/PageMeta"}},"title":"AppointmentList"},"LeadResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Lead"}},"title":"LeadResponse"},"FiscalCandidateResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/FiscalCandidate"}},"title":"FiscalCandidateResponse"},"IntegrationDetailActionResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/IntegrationDetail"},"meta":{"$ref":"#/components/schemas/ActionMeta"}},"title":"IntegrationDetailActionResponse"},"AppointmentResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Appointment"}},"title":"AppointmentResponse"},"FinanceSummaryResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/FinanceSummary"}},"title":"FinanceSummaryResponse"},"FiscalDocumentDetailResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/FiscalDocumentDetail"}},"title":"FiscalDocumentDetailResponse"},"FiscalDocumentList":{"type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/FiscalDocument"}},"meta":{"$ref":"#/components/schemas/PageMeta"}},"title":"FiscalDocumentList"},"LeadSummaryResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/LeadSummary"}},"title":"LeadSummaryResponse"},"IntegrationDetailResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/IntegrationDetail"}},"title":"IntegrationDetailResponse"},"AgentDetailResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/AgentDetail"}},"title":"AgentDetailResponse"},"KnowledgeArticleActionResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/KnowledgeArticle"},"meta":{"$ref":"#/components/schemas/ActionMeta"}},"title":"KnowledgeArticleActionResponse"},"PatientList":{"type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/Patient"}},"meta":{"$ref":"#/components/schemas/PageMeta"}},"title":"PatientList"},"SignupRequest":{"type":"object","required":["clinic","owner","plan","consent"],"properties":{"clinic":{"type":"object","required":["name","phone","email","street","specialty","teamSize"],"properties":{"name":{"type":"string","minLength":2,"maxLength":128,"example":"Clínica Exemplo"},"cnpj":{"type":"string","pattern":"^\\d{2}\\.?\\d{3}\\.?\\d{3}/?\\d{4}-?\\d{2}$","description":"Opcional. Os dígitos verificadores são conferidos (422 invalid_cnpj).","example":"11.222.333/0001-81"},"phone":{"type":"string","minLength":8,"maxLength":32,"pattern":"^[0-9+()\\s.-]+$","description":"Telefone de contato da clínica.","example":"(16) 99999-0000"},"email":{"type":"string","format":"email","maxLength":160,"description":"E-mail de contato da clínica (pode ser diferente do e-mail de login)."},"zip":{"type":"string","pattern":"^\\d{5}-?\\d{3}$","example":"14400-000"},"street":{"type":"string","minLength":5,"maxLength":160,"description":"Endereço (rua, número, bairro)."},"city":{"type":"string","maxLength":80},"state":{"type":"string","pattern":"^[A-Za-z]{2}$","example":"SP"},"specialty":{"type":"string","minLength":2,"maxLength":64,"description":"Área de atuação principal.","example":"Fisioterapia"},"teamSize":{"type":"string","enum":["solo","2-5","6-20","20+"],"description":"Tamanho da equipe: solo (só eu), 2-5, 6-20, 20+."}},"additionalProperties":false},"owner":{"type":"object","required":["phone","marketingOptIn"],"properties":{"phone":{"type":"string","minLength":8,"maxLength":32,"pattern":"^[0-9+()\\s.-]+$","description":"WhatsApp do dono da conta.","example":"(16) 99999-0000"},"jobTitle":{"type":"string","maxLength":80,"description":"Cargo ou função.","example":"Fisioterapeuta"},"marketingOptIn":{"type":"boolean","description":"Aceita receber novidades e dicas por e-mail/WhatsApp."}},"additionalProperties":false},"plan":{"type":"object","required":["id","cycle"],"properties":{"id":{"type":"string","pattern":"^[a-z0-9-]{1,32}$","description":"Plano com preço publicado (GET /v1/billing/plans com selfSignup = true). Sob consulta → 422 plan_requires_sales.","example":"profissional"},"cycle":{"type":"string","enum":["mensal","anual"],"description":"Ciclo de cobrança escolhido no site (vale depois do teste)."}},"additionalProperties":false},"consent":{"type":"object","required":["accepted","termsVersion","privacyVersion"],"properties":{"accepted":{"type":"boolean","description":"Aceite dos Termos de Uso e da Política de Privacidade (obrigatório).","enum":[true]},"termsVersion":{"type":"string","minLength":1,"maxLength":32,"pattern":"^[A-Za-z0-9._-]+$","description":"Versão dos Termos de Uso exibida no aceite.","example":"2026-09"},"privacyVersion":{"type":"string","minLength":1,"maxLength":32,"pattern":"^[A-Za-z0-9._-]+$","description":"Versão da Política de Privacidade exibida no aceite.","example":"2026-09"}},"additionalProperties":false},"website":{"type":"string","maxLength":200,"description":"Campo-isca anti-robô: o formulário deve mantê-lo oculto e vazio. Preenchido → 400."}},"title":"SignupRequest","additionalProperties":false},"FiscalDocumentResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/FiscalDocument"}},"title":"FiscalDocumentResponse"},"AutomationActionResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Automation"},"meta":{"$ref":"#/components/schemas/ActionMeta"}},"title":"AutomationActionResponse"},"TransactionActionResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Transaction"},"meta":{"$ref":"#/components/schemas/ActionMeta"}},"title":"TransactionActionResponse"},"TransactionList":{"type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/Transaction"}},"meta":{"$ref":"#/components/schemas/PageMeta"}},"title":"TransactionList"},"PatientResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Patient"}},"title":"PatientResponse"},"FiscalBatchList":{"type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/FiscalBatch"}},"meta":{"$ref":"#/components/schemas/PageMeta"}},"title":"FiscalBatchList"},"KnowledgeArticleResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/KnowledgeArticle"}},"title":"KnowledgeArticleResponse"},"AuditEventList":{"type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/AuditEvent"}},"meta":{"$ref":"#/components/schemas/PageMeta"}},"title":"AuditEventList"},"AutomationResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Automation"}},"title":"AutomationResponse"},"TransactionResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Transaction"}},"title":"TransactionResponse"},"ClinicResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Clinic"}},"title":"ClinicResponse"},"LeadPatch":{"type":"object","properties":{"name":{"type":"string","minLength":2,"maxLength":128},"phone":{"type":"string","minLength":8,"maxLength":32},"email":{"anyOf":[{"type":"string","format":"email","maxLength":160},{"type":"null"}]},"age":{"anyOf":[{"type":"integer","minimum":0,"maximum":130},{"type":"null"}]},"sex":{"anyOf":[{"type":"string","maxLength":16},{"type":"null"}]},"city":{"anyOf":[{"type":"string","maxLength":80},{"type":"null"}]},"source":{"type":"string","enum":["META_ADS","GOOGLE","INSTAGRAM","FECHADA","INFLUENCER","INDICACAO"]},"channel":{"type":"string","enum":["WhatsApp","Instagram","Site","E-mail","Telefone"]},"serviceKey":{"anyOf":[{"type":"string","maxLength":64},{"type":"null"}]},"professionalKey":{"anyOf":[{"type":"string","maxLength":64},{"type":"null"}]},"owner":{"anyOf":[{"type":"object","required":["type","id"],"properties":{"type":{"type":"string","enum":["human","agent"]},"id":{"type":"string","maxLength":64,"description":"membership id (humano) ou agent_key (agente)."}}},{"type":"null"}]},"nextAction":{"anyOf":[{"type":"object","required":["label","at"],"properties":{"label":{"type":"string","maxLength":128},"at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"actionable":{"type":"boolean"}}},{"type":"null"}]},"score":{"type":"integer","minimum":0,"maximum":100,"description":"Somente agentes (qualificação determinística MOVA-TECH-001)."},"qualified":{"type":"boolean","description":"Somente agentes."},"ready":{"type":"boolean","description":"Somente agentes."},"touch":{"type":"boolean","description":"true = atualiza lastInteractionAt para agora."},"estimatedValue":{"type":["number","null"],"minimum":0,"maximum":10000000,"description":"Valor estimado em R$ (no banco: centavos). null limpa."},"labelIds":{"$ref":"#/components/schemas/LeadPatchLabelIds"},"expectedCloseDate":{"anyOf":[{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","examples":["2026-09-18"],"description":"Data prevista de fechamento (YYYY-MM-DD). null limpa."},{"type":"null"}]}},"title":"LeadPatch","additionalProperties":false},"InvitationActionResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Invitation"},"meta":{"$ref":"#/components/schemas/ActionMeta"}},"title":"InvitationActionResponse"},"FiscalBatchResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/FiscalBatch"}},"title":"FiscalBatchResponse"},"MeResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Me"}},"title":"MeResponse"},"AgentActionResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Agent"},"meta":{"$ref":"#/components/schemas/ActionMeta"}},"title":"AgentActionResponse"},"IntegrationActionResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Integration"},"meta":{"$ref":"#/components/schemas/ActionMeta"}},"title":"IntegrationActionResponse"},"ConversationDetailResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/ConversationDetail"}},"title":"ConversationDetailResponse"},"FiscalServiceRuleResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/FiscalServiceRule"}},"title":"FiscalServiceRuleResponse"},"FiscalSettingsUpdate":{"type":"object","properties":{"documentType":{"type":"string","enum":["pendente","nfse_nacional","nfse_municipal"]},"taxRegime":{"type":"string","enum":["pendente","simples_nacional","mei","lucro_presumido","lucro_real","outro"]},"trigger":{"type":"string","enum":["atendimento_realizado","pagamento_recebido"]},"autoCandidates":{"type":"boolean"},"legalName":{"anyOf":[{"type":"string","maxLength":160},{"type":"null"}]},"tradeName":{"anyOf":[{"type":"string","maxLength":160},{"type":"null"}]},"cnpj":{"anyOf":[{"type":"string","pattern":"^\\d{2}\\.?\\d{3}\\.?\\d{3}/?\\d{4}-?\\d{2}$","examples":["11.222.333/0001-81"]},{"type":"null"}]},"municipalRegistration":{"anyOf":[{"type":"string","maxLength":32},{"type":"null"}]},"cityIbge":{"anyOf":[{"type":"string","pattern":"^\\d{7}$","description":"Código IBGE do município (7 dígitos)."},{"type":"null"}]},"cityName":{"anyOf":[{"type":"string","maxLength":80},{"type":"null"}]},"uf":{"anyOf":[{"type":"string","pattern":"^[A-Z]{2}$"},{"type":"null"}]},"addressStreet":{"anyOf":[{"type":"string","maxLength":160},{"type":"null"}]},"addressNumber":{"anyOf":[{"type":"string","maxLength":20},{"type":"null"}]},"addressDistrict":{"anyOf":[{"type":"string","maxLength":80},{"type":"null"}]},"addressZip":{"anyOf":[{"type":"string","pattern":"^\\d{5}-?\\d{3}$"},{"type":"null"}]},"rpsSeries":{"anyOf":[{"type":"string","pattern":"^[A-Za-z0-9]{1,5}$","description":"Série da DPS/RPS (Homologação e Produção). Simulação usa \"SIM\"."},{"type":"null"}]},"numberingStartHomologacao":{"anyOf":[{"type":"integer","minimum":1},{"type":"null"}]},"numberingStartProducao":{"anyOf":[{"type":"integer","minimum":1,"description":"Próximo número de Produção (último usado no sistema anterior + 1)."},{"type":"null"}]},"takerRequiresCpf":{"type":"boolean"},"takerRequiresAddress":{"type":"boolean"},"accountantName":{"anyOf":[{"type":"string","maxLength":128},{"type":"null"}]},"accountantEmail":{"anyOf":[{"type":"string","format":"email","maxLength":160},{"type":"null"}]}},"title":"FiscalSettingsUpdate","additionalProperties":false},"AuditEventResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/AuditEvent"}},"title":"AuditEventResponse"},"ServiceList":{"type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/Service"}},"meta":{"$ref":"#/components/schemas/PageMeta"}},"title":"ServiceList"},"OutboxEventActionResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/OutboxEvent"},"meta":{"$ref":"#/components/schemas/ActionMeta"}},"title":"OutboxEventActionResponse"},"ClinicUserActionResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/ClinicUser"},"meta":{"$ref":"#/components/schemas/ActionMeta"}},"title":"ClinicUserActionResponse"},"OutboxEventList":{"type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/OutboxEvent"}},"meta":{"$ref":"#/components/schemas/PageMeta"}},"title":"OutboxEventList"},"ClinicUserList":{"type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/ClinicUser"}},"meta":{"$ref":"#/components/schemas/PageMeta"}},"title":"ClinicUserList"},"TransactionCreate":{"type":"object","required":["type","description","amount","status"],"properties":{"type":{"type":"string","enum":["receita","despesa"]},"description":{"type":"string","minLength":2,"maxLength":160},"amount":{"type":"number","minimum":0,"maximum":10000000,"description":"Valor em reais (BRL). No banco: amount_minor (centavos).","exclusiveMinimum":0},"status":{"type":"string","enum":["recebido","pago","a-receber","a-pagar","atrasado"],"description":"receita: recebido | a-receber | atrasado · despesa: pago | a-pagar | atrasado"},"method":{"anyOf":[{"type":"string","enum":["Pix","Crédito","Débito","Dinheiro","Boleto","TED","Cheque"]},{"type":"null"}]},"occurredAt":{"type":"string","format":"date-time"},"dueDate":{"anyOf":[{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","examples":["2026-09-18"]},{"type":"null"}]},"party":{"anyOf":[{"type":"string","maxLength":128},{"type":"null"}]},"patientId":{"anyOf":[{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9._-]+$"},{"type":"null"}]},"appointmentId":{"anyOf":[{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9._-]+$"},{"type":"null"}]},"serviceKey":{"anyOf":[{"type":"string","maxLength":64},{"type":"null"}]},"professionalKey":{"anyOf":[{"type":"string","maxLength":64},{"type":"null"}]},"externalReference":{"anyOf":[{"type":"string","maxLength":128},{"type":"null"}]},"agentState":{"type":"string","enum":["executado","aguardando"],"description":"Somente agentes (Cecília)."},"agentAction":{"type":"string","maxLength":255,"description":"Somente agentes."},"category":{"anyOf":[{"type":"string","enum":["aluguel","internet","sistema","outro"],"description":"Tipo da despesa (só despesas). Padrão: outro."},{"type":"null"}]}},"title":"TransactionCreate","additionalProperties":false},"InboundMessage":{"type":"object","required":["channel","externalMessageId","externalChatRef","text","receivedAt"],"properties":{"channel":{"type":"string","enum":["whatsapp","email","sms","instagram","outros"],"description":"Canal da conversa. Conversas de prévia de agente (prefixo reservado) só com `outros`."},"externalMessageId":{"type":"string","minLength":1,"maxLength":255,"description":"Id da mensagem no provedor do canal. Chave natural de deduplicação."},"externalChatRef":{"type":"string","minLength":1,"maxLength":255,"description":"Id do chat no provedor do canal (ex.: `5516999990000@s.whatsapp.net`) ou o prefixo reservado de prévia de agente. Conversa = (clínica, canal, externalChatRef)."},"contactName":{"type":"string","minLength":1,"maxLength":128,"description":"Nome exibido no provedor (pushName). Paciente/lead já cadastrado tem prioridade."},"phone":{"type":"string","maxLength":32,"description":"Telefone do contato; se ausente, extraído de externalChatRef (dígitos antes do @)."},"text":{"type":"string","minLength":1,"maxLength":4000,"description":"Texto da mensagem (mídia sem legenda: descreva, ex.: \"[imagem]\")."},"receivedAt":{"type":"string","format":"date-time","description":"Quando o provedor recebeu a mensagem (horário no futuro é limitado ao agora)."},"media":{"$ref":"#/components/schemas/InboundMedia"}},"additionalProperties":false,"title":"InboundMessage"},"ConversationActionResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Conversation"},"meta":{"$ref":"#/components/schemas/ActionMeta"}},"title":"ConversationActionResponse"},"KnowledgeArticleInput":{"type":"object","required":["title","type","category"],"properties":{"title":{"type":"string","minLength":3,"maxLength":200},"excerpt":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}]},"type":{"type":"string","enum":["artigo","faq","protocolo","material"]},"category":{"type":"string","enum":["atendimento","procedimentos","tratamentos","pos-atendimento","financeiro","convenios","marketing","gestao","equipe","juridico","outros"]},"intro":{"anyOf":[{"type":"string","maxLength":2000},{"type":"null"}]},"steps":{"type":"array","items":{"$ref":"#/components/schemas/KnowledgeStep"},"maxItems":30},"tip":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}]},"keywords":{"type":"array","items":{"type":"string","maxLength":64},"maxItems":30},"aliases":{"type":"array","items":{"type":"string","maxLength":128},"maxItems":30},"serviceKey":{"anyOf":[{"type":"string","maxLength":64},{"type":"null"}]},"professionalKey":{"anyOf":[{"type":"string","maxLength":64},{"type":"null"}]},"source":{"anyOf":[{"type":"string","maxLength":255},{"type":"null"}]},"validUntil":{"anyOf":[{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"},{"type":"null"}]},"safeForAi":{"type":"boolean"},"requiresHuman":{"type":"boolean"},"requiresClinicalAssessment":{"type":"boolean"},"usedBy":{"type":"array","items":{"type":"string","maxLength":64},"maxItems":20,"description":"agent_keys que podem usar o artigo."},"status":{"type":"string","enum":["rascunho","em_revisao"],"description":"Publicação só via revisão (POST /review)."}},"title":"KnowledgeArticleInput","additionalProperties":false},"ConversationList":{"type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/Conversation"}},"meta":{"$ref":"#/components/schemas/PageMeta"}},"title":"ConversationList"},"AppointmentCreate":{"type":"object","required":["date","start"],"properties":{"kind":{"type":"string","enum":["consulta","interno"],"default":"consulta"},"patientId":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9._-]+$","description":"Paciente cadastrado (recomendado)."},"patientName":{"type":"string","minLength":2,"maxLength":128,"description":"Obrigatório sem patientId; em evento interno é o título."},"leadId":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9._-]+$"},"serviceKey":{"type":"string","maxLength":64,"description":"Obrigatório em consulta. Serviço ativo do cadastro."},"professionalKey":{"anyOf":[{"type":"string","maxLength":64},{"type":"null"}]},"date":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","example":"2026-09-18"},"start":{"type":"string","pattern":"^([01]\\d|2[0-3]):[0-5]\\d$","example":"14:00"},"end":{"type":"string","pattern":"^([01]\\d|2[0-3]):[0-5]\\d$","description":"Padrão: início + duração do serviço.","example":"14:00"},"modality":{"type":"string","enum":["presencial","online"]},"room":{"anyOf":[{"type":"string","maxLength":64},{"type":"null"}]},"status":{"type":"string","enum":["agendado","confirmado","pendente"]},"notes":{"type":"string","maxLength":5000,"description":"Observações operacionais (schedule:write)."},"tags":{"type":"array","items":{"type":"string","maxLength":40},"maxItems":10},"agentState":{"type":"string","enum":["agendado","confirmado","sugestao","aguardando_aprovacao","escalado"],"description":"Somente token de agente."},"agentNote":{"type":"string","maxLength":500,"description":"Somente token de agente."}},"title":"AppointmentCreate","additionalProperties":false},"ClinicPatch":{"type":"object","properties":{"name":{"type":"string","minLength":2,"maxLength":128},"tagline":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}]},"legalName":{"anyOf":[{"type":"string","maxLength":160},{"type":"null"}]},"cnpj":{"anyOf":[{"type":"string","pattern":"^\\d{2}\\.?\\d{3}\\.?\\d{3}/?\\d{4}-?\\d{2}$"},{"type":"null"}]},"email":{"anyOf":[{"type":"string","format":"email","maxLength":160},{"type":"null"}]},"phone":{"anyOf":[{"type":"string","maxLength":32},{"type":"null"}]},"site":{"anyOf":[{"type":"string","format":"uri","maxLength":255},{"type":"null"}]},"timezone":{"type":"string","maxLength":64,"example":"America/Sao_Paulo"},"locale":{"type":"string","enum":["pt-BR","en-US","es-ES"]},"dateFormat":{"type":"string","enum":["DD/MM/AAAA","MM/DD/AAAA","AAAA-MM-DD"]},"timeFormat":{"type":"string","enum":["24","12"]},"monthlyRevenueGoal":{"anyOf":[{"type":"number","minimum":0,"maximum":100000000,"multipleOf":0.01,"description":"Meta de receita mensal (reais). null remove a meta."},{"type":"null"}]},"currency":{"type":"string","enum":["BRL","USD","EUR"]},"address":{"type":"object","properties":{"street":{"anyOf":[{"type":"string","maxLength":160},{"type":"null"}]},"district":{"anyOf":[{"type":"string","maxLength":80},{"type":"null"}]},"zip":{"anyOf":[{"type":"string","maxLength":10,"examples":["14400-000"]},{"type":"null"}]},"city":{"anyOf":[{"type":"string","maxLength":80},{"type":"null"}]},"state":{"anyOf":[{"type":"string","maxLength":2,"examples":["SP"]},{"type":"null"}]},"country":{"anyOf":[{"type":"string","maxLength":2},{"type":"null"}]}}}},"title":"ClinicPatch","additionalProperties":false},"AgentResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Agent"}},"title":"AgentResponse"},"IntegrationResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Integration"}},"title":"IntegrationResponse"},"ProfessionalList":{"type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/Professional"}},"meta":{"$ref":"#/components/schemas/PageMeta"}},"title":"ProfessionalList"},"ApprovalActionResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Approval"},"meta":{"$ref":"#/components/schemas/ActionMeta"}},"title":"ApprovalActionResponse"},"MessageActionResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Message"},"meta":{"$ref":"#/components/schemas/ActionMeta"}},"title":"MessageActionResponse"},"PatientCreate":{"type":"object","required":["name"],"properties":{"name":{"type":"string","minLength":2,"maxLength":128},"birthDate":{"anyOf":[{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","examples":["2026-09-18"]},{"type":"null"}]},"sex":{"anyOf":[{"type":"string","enum":["Feminino","Masculino","Outro","Não informado"]},{"type":"null"}]},"cpf":{"anyOf":[{"type":"string","pattern":"^\\d{3}\\.?\\d{3}\\.?\\d{3}-?\\d{2}$","description":"Write-only: nunca é devolvido completo."},{"type":"null"}]},"phone":{"anyOf":[{"type":"string","maxLength":32},{"type":"null"}]},"email":{"anyOf":[{"type":"string","format":"email","maxLength":160},{"type":"null"}]},"city":{"anyOf":[{"type":"string","maxLength":80},{"type":"null"}]},"address":{"anyOf":[{"type":"string","maxLength":255},{"type":"null"}]},"status":{"type":"string","enum":["ativo","inativo"]},"tags":{"type":"array","items":{"type":"string","maxLength":40},"maxItems":20},"serviceKey":{"anyOf":[{"type":"string","maxLength":64},{"type":"null"}]},"plan":{"anyOf":[{"type":"string","enum":["Particular","Convênio"]},{"type":"null"}]},"origin":{"anyOf":[{"type":"string","maxLength":64},{"type":"null"}]},"professionalKey":{"anyOf":[{"type":"string","maxLength":64},{"type":"null"}]},"leadId":{"anyOf":[{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9._-]+$"},{"type":"null"}]},"lgpdConsent":{"type":"boolean","description":"true registra o consentimento LGPD agora."}},"title":"PatientCreate","additionalProperties":false},"AgentPreflightResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/AgentPreflight"}},"title":"AgentPreflightResponse"},"ServiceResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Service"}},"title":"ServiceResponse"},"SatisfactionReportResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/SatisfactionReport"}},"title":"SatisfactionReportResponse"},"ApprovalList":{"type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/Approval"}},"meta":{"$ref":"#/components/schemas/PageMeta"}},"title":"ApprovalList"},"MessageList":{"type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/Message"}},"meta":{"$ref":"#/components/schemas/PageMeta"}},"title":"MessageList"},"KnowledgeArticleListItemList":{"type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/KnowledgeArticleListItem"}},"meta":{"$ref":"#/components/schemas/PageMeta"}},"title":"KnowledgeArticleListItemList"},"LeadCreate":{"type":"object","required":["name","phone","source","channel","serviceKey"],"properties":{"name":{"type":"string","minLength":2,"maxLength":128},"phone":{"type":"string","minLength":8,"maxLength":32},"email":{"anyOf":[{"type":"string","format":"email","maxLength":160},{"type":"null"}]},"source":{"type":"string","enum":["META_ADS","GOOGLE","INSTAGRAM","FECHADA","INFLUENCER","INDICACAO"]},"channel":{"type":"string","enum":["WhatsApp","Instagram","Site","E-mail","Telefone"]},"serviceKey":{"type":"string","maxLength":64,"description":"Serviço de interesse (cadastro da clínica)."},"age":{"anyOf":[{"type":"integer","minimum":0,"maximum":130},{"type":"null"}]},"sex":{"anyOf":[{"type":"string","maxLength":16},{"type":"null"}]},"city":{"anyOf":[{"type":"string","maxLength":80},{"type":"null"}]},"estimatedValue":{"type":["number","null"],"minimum":0,"maximum":10000000,"description":"Valor estimado em R$ (no banco: centavos). null limpa."},"labelIds":{"$ref":"#/components/schemas/LeadPatchLabelIds"},"expectedCloseDate":{"anyOf":[{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","examples":["2026-09-18"],"description":"Data prevista de fechamento (YYYY-MM-DD). null limpa."},{"type":"null"}]}},"title":"LeadCreate","additionalProperties":false},"ClinicUserResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/ClinicUser"}},"title":"ClinicUserResponse"},"FiscalCandidateReview":{"type":"object","properties":{"taker":{"type":"object","properties":{"name":{"type":"string","minLength":2,"maxLength":128},"cpf":{"anyOf":[{"type":"string","pattern":"^\\d{3}\\.?\\d{3}\\.?\\d{3}-?\\d{2}$","description":"Write-only: nunca é devolvido completo."},{"type":"null"}]},"address":{"anyOf":[{"$ref":"#/components/schemas/FiscalTakerAddress"},{"type":"null"}]}},"additionalProperties":false},"amount":{"type":"number","exclusiveMinimum":0,"maximum":1000000,"description":"Valor da nota em reais (procedência: revisão)."},"confirmAmount":{"type":"boolean","description":"Confirma o valor vindo da tabela do serviço."},"acknowledgeReview":{"type":"boolean","description":"Confirma a revisão depois de nota rejeitada ou cancelada."}},"title":"FiscalCandidateReview","additionalProperties":false},"FiscalServiceRuleCreate":{"type":"object","required":["serviceKey"],"properties":{"serviceKey":{"type":"string","minLength":1,"maxLength":64},"description":{"anyOf":[{"type":"string","maxLength":1000,"description":"Discriminação do serviço na nota."},{"type":"null"}]},"nationalTaxCode":{"anyOf":[{"type":"string","pattern":"^\\d{6}$","description":"Código de tributação nacional (6 dígitos)."},{"type":"null"}]},"lc116Item":{"anyOf":[{"type":"string","pattern":"^\\d{1,2}\\.\\d{2}$","examples":["04.08"]},{"type":"null"}]},"nbsCode":{"anyOf":[{"type":"string","pattern":"^\\d{9}$"},{"type":"null"}]},"municipalTaxCode":{"anyOf":[{"type":"string","maxLength":20},{"type":"null"}]},"cnae":{"anyOf":[{"type":"string","pattern":"^\\d{7}$"},{"type":"null"}]},"issRate":{"anyOf":[{"type":"number","minimum":0,"maximum":100,"description":"Alíquota em %."},{"type":"null"}]},"issWithheld":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"issTaxation":{"anyOf":[{"type":"string","enum":["tributavel","imune","exportacao","nao_incidencia"]},{"type":"null"}]},"incidence":{"anyOf":[{"type":"string","enum":["prestador","tomador"]},{"type":"null"}]},"trigger":{"type":"string","enum":["padrao","atendimento_realizado","pagamento_recebido"]},"notes":{"anyOf":[{"type":"string","maxLength":1000},{"type":"null"}]}},"title":"FiscalServiceRuleCreate","additionalProperties":false},"BillingProfileActionResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/BillingProfile"},"meta":{"$ref":"#/components/schemas/ActionMeta"}},"title":"BillingProfileActionResponse"},"ClinicalEvolutionList":{"type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/ClinicalEvolution"}},"meta":{"$ref":"#/components/schemas/PageMeta"}},"title":"ClinicalEvolutionList"},"PatientTimelineEventList":{"type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/PatientTimelineEvent"}},"meta":{"$ref":"#/components/schemas/PageMeta"}},"title":"PatientTimelineEventList"},"FiscalServiceRulePatch":{"type":"object","properties":{"description":{"anyOf":[{"type":"string","maxLength":1000,"description":"Discriminação do serviço na nota."},{"type":"null"}]},"nationalTaxCode":{"anyOf":[{"type":"string","pattern":"^\\d{6}$","description":"Código de tributação nacional (6 dígitos)."},{"type":"null"}]},"lc116Item":{"anyOf":[{"type":"string","pattern":"^\\d{1,2}\\.\\d{2}$","examples":["04.08"]},{"type":"null"}]},"nbsCode":{"anyOf":[{"type":"string","pattern":"^\\d{9}$"},{"type":"null"}]},"municipalTaxCode":{"anyOf":[{"type":"string","maxLength":20},{"type":"null"}]},"cnae":{"anyOf":[{"type":"string","pattern":"^\\d{7}$"},{"type":"null"}]},"issRate":{"anyOf":[{"type":"number","minimum":0,"maximum":100,"description":"Alíquota em %."},{"type":"null"}]},"issWithheld":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"issTaxation":{"anyOf":[{"type":"string","enum":["tributavel","imune","exportacao","nao_incidencia"]},{"type":"null"}]},"incidence":{"anyOf":[{"type":"string","enum":["prestador","tomador"]},{"type":"null"}]},"trigger":{"type":"string","enum":["padrao","atendimento_realizado","pagamento_recebido"]},"notes":{"anyOf":[{"type":"string","maxLength":1000},{"type":"null"}]}},"title":"FiscalServiceRulePatch","additionalProperties":false},"SignupResultActionResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/SignupResult"},"meta":{"$ref":"#/components/schemas/ActionMeta"}},"title":"SignupResultActionResponse"},"ConversationResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Conversation"}},"title":"ConversationResponse"},"AgentRunActionResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/AgentRun"},"meta":{"$ref":"#/components/schemas/ActionMeta"}},"title":"AgentRunActionResponse"},"InvoiceList":{"type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/Invoice"}},"meta":{"$ref":"#/components/schemas/PageMeta"}},"title":"InvoiceList"},"SubscriptionActivatedActionResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/SubscriptionActivated"},"meta":{"$ref":"#/components/schemas/ActionMeta"}},"title":"SubscriptionActivatedActionResponse"},"ProfessionalResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Professional"}},"title":"ProfessionalResponse"},"AgentRunList":{"type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/AgentRun"}},"meta":{"$ref":"#/components/schemas/PageMeta"}},"title":"AgentRunList"},"AuditSummaryResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/AuditSummary"}},"title":"AuditSummaryResponse"},"Plan":{"type":"object","required":["id","name","description","price","priceAnnual","selfSignup","features","rows","limits","current","warnings"],"properties":{"id":{"type":"string"},"name":{"type":"string"},"description":{"anyOf":[{"type":"string"},{"type":"null"}]},"price":{"anyOf":[{"type":"number","description":"R$/mês no ciclo mensal; null = sob consulta."},{"type":"null"}]},"priceAnnual":{"anyOf":[{"type":"number","description":"R$/mês no ciclo anual (cobrado 12× de uma vez); null = sob consulta."},{"type":"null"}]},"selfSignup":{"type":"boolean","description":"true = pode ser escolhido no autocadastro (POST /v1/signup). Planos sob consulta = false."},"features":{"type":"array","items":{"type":"string"}},"rows":{"type":"object","additionalProperties":{"type":"string"}},"limits":{"type":"object","required":["patients","messages"],"properties":{"patients":{"anyOf":[{"type":"integer"},{"type":"null"}]},"messages":{"anyOf":[{"type":"integer"},{"type":"null"}]}}},"current":{"type":"boolean"},"warnings":{"type":"array","items":{"type":"string","description":"Ex.: a clínica já passa do limite de pacientes deste plano."}}},"title":"Plan"},"DataRequestList":{"type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/DataRequest"}},"meta":{"$ref":"#/components/schemas/PageMeta"}},"title":"DataRequestList"},"FinanceSeriesResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/FinanceSeries"}},"title":"FinanceSeriesResponse"},"ServiceCreate":{"type":"object","required":["name","category","duration"],"properties":{"key":{"type":"string","pattern":"^[a-z0-9-]{2,64}$","description":"Gerado a partir do nome se omitido. Imutável depois de criado."},"name":{"type":"string","minLength":2,"maxLength":128},"description":{"anyOf":[{"type":"string","maxLength":255},{"type":"null"}]},"category":{"type":"string","minLength":2,"maxLength":40,"example":"Fisioterapia"},"duration":{"type":"integer","minimum":5,"maximum":600},"price":{"anyOf":[{"type":"number","minimum":0,"maximum":10000000,"description":"Valor em reais (BRL). No banco: amount_minor (centavos)."},{"type":"null"}]},"active":{"type":"boolean","default":true},"requiresProfessional":{"type":"boolean","default":true},"aiDescription":{"anyOf":[{"type":"string","maxLength":1000},{"type":"null"}]},"rules":{"anyOf":[{"type":"string","maxLength":2000},{"type":"null"}]},"professionals":{"type":"array","items":{"type":"string","maxLength":64},"maxItems":50,"description":"professional_keys que atendem o serviço."}},"title":"ServiceCreate","additionalProperties":false},"ApprovalResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Approval"}},"title":"ApprovalResponse"},"AgentConfigActionResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/AgentConfig"},"meta":{"$ref":"#/components/schemas/ActionMeta"}},"title":"AgentConfigActionResponse"},"MessageResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Message"}},"title":"MessageResponse"},"IntegrationLogList":{"type":"object","required":["data","meta"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/IntegrationLog"}},"meta":{"$ref":"#/components/schemas/PageMeta"}},"title":"IntegrationLogList"},"AppointmentSummaryResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/AppointmentSummary"}},"title":"AppointmentSummaryResponse"},"TransactionPatch":{"type":"object","properties":{"description":{"type":"string","minLength":2,"maxLength":160},"amount":{"type":"number","minimum":0,"maximum":10000000,"description":"Valor em reais (BRL). No banco: amount_minor (centavos).","exclusiveMinimum":0},"status":{"type":"string","enum":["recebido","pago","a-receber","a-pagar","atrasado"]},"method":{"anyOf":[{"type":"string","enum":["Pix","Crédito","Débito","Dinheiro","Boleto","TED","Cheque"]},{"type":"null"}]},"dueDate":{"anyOf":[{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","examples":["2026-09-18"]},{"type":"null"}]},"party":{"anyOf":[{"type":"string","maxLength":128},{"type":"null"}]},"serviceKey":{"anyOf":[{"type":"string","maxLength":64},{"type":"null"}]},"category":{"anyOf":[{"type":"string","enum":["aluguel","internet","sistema","outro"]},{"type":"null"}]}},"title":"TransactionPatch","additionalProperties":false},"ClinicalEvolutionResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/ClinicalEvolution"}},"title":"ClinicalEvolutionResponse"},"BillingCancellationUndoActionResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/BillingCancellationUndo"},"meta":{"$ref":"#/components/schemas/ActionMeta"}},"title":"BillingCancellationUndoActionResponse"},"BillingPlanChangeUndoActionResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/BillingPlanChangeUndo"},"meta":{"$ref":"#/components/schemas/ActionMeta"}},"title":"BillingPlanChangeUndoActionResponse"},"KnowledgeCountsResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/KnowledgeCounts"}},"title":"KnowledgeCountsResponse"},"InvoiceResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/Invoice"}},"title":"InvoiceResponse"},"AgentRunResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/AgentRun"}},"title":"AgentRunResponse"},"ProfessionalCreate":{"type":"object","required":["name"],"properties":{"key":{"type":"string","pattern":"^[a-z0-9-]{2,64}$"},"name":{"type":"string","minLength":2,"maxLength":128},"specialty":{"anyOf":[{"type":"string","maxLength":128},{"type":"null"}]},"status":{"type":"string","enum":["ativo","inativo"]},"room":{"anyOf":[{"type":"string","maxLength":64},{"type":"null"}]},"calendarRef":{"anyOf":[{"type":"string","maxLength":255,"description":"Id do calendário (Google). Write-only: volta mascarado."},{"type":"null"}]},"timezone":{"anyOf":[{"type":"string","maxLength":64},{"type":"null"}]},"services":{"type":"array","items":{"type":"string","maxLength":64},"maxItems":100}},"title":"ProfessionalCreate","additionalProperties":false},"LeadCountsResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/LeadCounts"}},"title":"LeadCountsResponse"},"AppointmentPatch":{"type":"object","properties":{"room":{"anyOf":[{"type":"string","maxLength":64},{"type":"null"}]},"modality":{"type":"string","enum":["presencial","online"]},"tags":{"type":"array","items":{"type":"string","maxLength":40},"maxItems":10},"notes":{"anyOf":[{"type":"string","maxLength":5000},{"type":"null"}]},"reason":{"anyOf":[{"type":"string","maxLength":2000},{"type":"null"}]},"nextSteps":{"type":"array","items":{"type":"object","required":["label","done"],"properties":{"label":{"type":"string","maxLength":200},"done":{"type":"boolean"}}},"maxItems":20}},"title":"AppointmentPatch","additionalProperties":false},"PatientSummaryResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/PatientSummary"}},"title":"PatientSummaryResponse"},"FinanceTotalsResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/FinanceTotals"}},"title":"FinanceTotalsResponse"},"SignupStatusResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/SignupStatus"}},"title":"SignupStatusResponse"},"KnowledgeSummaryPrevious":{"type":"object","required":["month","published","categories","agentsUsing","ratingAvg"],"properties":{"month":{"type":"string","description":"Mês anterior (YYYY-MM) — valores no último dia dele.","example":"2026-08"},"published":{"type":"integer","description":"Itens publicados até o fim do mês anterior (published_at)."},"categories":{"type":"integer"},"agentsUsing":{"type":"integer"},"ratingAvg":{"anyOf":[{"type":"number","description":"Média das notas do mês anterior (rating_monthly_json)."},{"type":"null"}]}},"title":"KnowledgeSummaryPrevious"},"RecurringExpenseResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/RecurringExpense"}},"title":"RecurringExpenseResponse"},"FiscalSummaryResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/FiscalSummary"}},"title":"FiscalSummaryResponse"},"PatientCountsResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/PatientCounts"}},"title":"PatientCountsResponse"},"ClinicUserCountsResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/ClinicUserCounts"}},"title":"ClinicUserCountsResponse"},"MembershipSummary":{"type":"object","required":["clinicId","clinicName","city","clinicStatus","role","roleLabel","logoUrl"],"properties":{"clinicId":{"type":"string"},"clinicName":{"type":"string"},"city":{"anyOf":[{"type":"string"},{"type":"null"}]},"clinicStatus":{"type":"string"},"role":{"type":"string","enum":["admin","profissional","recepcao","financeiro","marketing","suporte","estagiario"]},"roleLabel":{"type":"string"},"logoUrl":{"anyOf":[{"type":"string"},{"type":"null"}]}},"title":"MembershipSummary"},"PatientTaskResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/PatientTask"}},"title":"PatientTaskResponse"},"ConversationCountsResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/ConversationCounts"}},"title":"ConversationCountsResponse"},"ClinicCreate":{"type":"object","required":["name"],"properties":{"id":{"type":"string","pattern":"^[a-z0-9-]{3,40}$","description":"clinic_id desejado (slug). Gerado a partir do nome se omitido."},"name":{"type":"string","minLength":2,"maxLength":128},"legalName":{"type":"string","maxLength":160},"timezone":{"type":"string","maxLength":64},"city":{"type":"string","maxLength":80},"state":{"type":"string","maxLength":2}},"title":"ClinicCreate","additionalProperties":false},"HealthReady":{"type":"object","required":["status","checks"],"properties":{"status":{"type":"string","enum":["ok","degraded"]},"checks":{"type":"object","required":["database","dataBackend","n8n"],"properties":{"database":{"type":"string","enum":["ok","unreachable","not_configured"]},"dataBackend":{"type":"string","enum":["appwrite","memory","none"]},"n8n":{"type":"string","enum":["configured","not_configured"]}}}},"title":"HealthReady"},"AgentPreflightRequest":{"type":"object","required":["trace_id","requested_operation"],"properties":{"trace_id":{"type":"string","minLength":1,"maxLength":128,"pattern":"^[A-Za-z0-9._:-]+$"},"requested_operation":{"type":"string","minLength":1,"maxLength":128,"pattern":"^[A-Za-z0-9._:-]+$"},"conversation_id":{"type":"string","minLength":1,"maxLength":128,"pattern":"^[A-Za-z0-9._:-]+$"}},"additionalProperties":false,"title":"AgentPreflightRequest"},"FiscalSyncResultResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/FiscalSyncResult"}},"title":"FiscalSyncResultResponse"},"LeadLabelResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/LeadLabel"}},"title":"LeadLabelResponse"},"LeadLabelCreate":{"type":"object","required":["name","color"],"properties":{"name":{"type":"string","minLength":1,"maxLength":24,"description":"Nome curto, único na clínica (sem diferenciar maiúsculas e acentos)."},"color":{"type":"string","enum":["blue","green","amber","red","violet","pink","teal","slate"]}},"title":"LeadLabelCreate","additionalProperties":false},"LeadLabelPatch":{"type":"object","properties":{"name":{"type":"string","minLength":1,"maxLength":24,"description":"Nome curto, único na clínica (sem diferenciar maiúsculas e acentos)."},"color":{"type":"string","enum":["blue","green","amber","red","violet","pink","teal","slate"]}},"title":"LeadLabelPatch","additionalProperties":false},"IntegrationCalendarInput":{"type":"object","required":["id","name","enabled"],"properties":{"id":{"type":"string","maxLength":128},"name":{"type":"string","maxLength":128},"description":{"type":"string","maxLength":255},"enabled":{"type":"boolean"},"isDefault":{"type":"boolean"}},"additionalProperties":false,"title":"IntegrationCalendarInput"},"AppointmentAttentionResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/AppointmentAttention"}},"title":"AppointmentAttentionResponse"},"FiscalWebhookResultResponse":{"type":"object","required":["data"],"properties":{"data":{"$ref":"#/components/schemas/FiscalWebhookResult"}},"title":"FiscalWebhookResultResponse"},"PatientTag":{"type":"object","required":["tag","count"],"properties":{"tag":{"type":"string"},"count":{"type":"integer","description":"Pacientes (não excluídos) com a tag."}},"title":"PatientTag"},"FieldError":{"type":"object","required":["field","message","code"],"properties":{"field":{"type":"string"},"message":{"type":"string"},"code":{"type":"string"}},"title":"FieldError"},"LeadForecast":{"type":"object","required":["months","totals","overdue","noDate","openStages"],"properties":{"months":{"type":"array","items":{"$ref":"#/components/schemas/LeadForecastMonth"}},"totals":{"$ref":"#/components/schemas/LeadValueTotals"},"overdue":{"type":"object","required":["count","valueTotal"],"properties":{"count":{"type":"integer"},"valueTotal":{"type":"number"}},"description":"Leads abertos com fechamento previsto antes do primeiro mês (vencido)."},"noDate":{"type":"object","required":["count","valueTotal"],"properties":{"count":{"type":"integer"},"valueTotal":{"type":"number"}},"description":"Leads abertos sem data prevista."},"openStages":{"type":"array","items":{"type":"string","enum":["NEW","DISCOVERY","QUALIFIED","READY_TO_SCHEDULE","SCHEDULED","COMPLETED","NURTURE","NOT_A_FIT","HUMAN_HANDOFF"]},"description":"Etapas consideradas abertas (todas menos Virou paciente e Fora do perfil)."}},"title":"LeadForecast"},"FiscalSettings":{"type":"object","required":["persisted","version","mode","modeLabel","provider","productionServerEnabled","documentType","taxRegime","trigger","autoCandidates","emitter","rpsSeries","numberingStart","takerRequiresCpf","takerRequiresAddress","accountant","approval","gate","suggestions","readiness","modes","phrases"],"properties":{"persisted":{"type":"boolean","description":"false = a clínica ainda não salvou a configuração (valores padrão, modo Simulação)."},"version":{"type":"integer"},"mode":{"type":"string","enum":["simulacao","homologacao","producao"]},"modeLabel":{"type":"string"},"provider":{"type":"object","required":["id","label","homologacaoConfigured","producaoConfigured","webhookConfigured"],"properties":{"id":{"anyOf":[{"type":"string","description":"Provedor real habilitado no servidor (null = só Simulação)."},{"type":"null"}]},"label":{"anyOf":[{"type":"string"},{"type":"null"}]},"homologacaoConfigured":{"type":"boolean","description":"Credencial de homologação desta clínica cadastrada no servidor (o valor nunca é exposto)."},"producaoConfigured":{"type":"boolean"},"webhookConfigured":{"type":"boolean"}}},"productionServerEnabled":{"type":"boolean","description":"Trava global de Produção liberada no servidor."},"documentType":{"type":"string","enum":["pendente","nfse_nacional","nfse_municipal"]},"taxRegime":{"type":"string","enum":["pendente","simples_nacional","mei","lucro_presumido","lucro_real","outro"]},"trigger":{"type":"string","enum":["atendimento_realizado","pagamento_recebido"]},"autoCandidates":{"type":"boolean","description":"Gerar candidato automaticamente quando o atendimento vira realizado."},"emitter":{"$ref":"#/components/schemas/FiscalEmitter"},"rpsSeries":{"anyOf":[{"type":"string"},{"type":"null"}]},"numberingStart":{"type":"object","required":["homologacao","producao"],"properties":{"homologacao":{"anyOf":[{"type":"integer"},{"type":"null"}]},"producao":{"anyOf":[{"type":"integer"},{"type":"null"}]}}},"takerRequiresCpf":{"type":"boolean"},"takerRequiresAddress":{"type":"boolean"},"accountant":{"type":"object","required":["name","email"],"properties":{"name":{"anyOf":[{"type":"string"},{"type":"null"}]},"email":{"anyOf":[{"type":"string"},{"type":"null"}]}}},"approval":{"$ref":"#/components/schemas/FiscalSettingsApproval"},"gate":{"type":"array","items":{"$ref":"#/components/schemas/FiscalGateEntry"}},"suggestions":{"type":"object","required":["legalName","cnpj","cityName","uf","addressStreet","addressZip","addressDistrict"],"properties":{"legalName":{"anyOf":[{"type":"string"},{"type":"null"}]},"cnpj":{"anyOf":[{"type":"string"},{"type":"null"}]},"cityName":{"anyOf":[{"type":"string"},{"type":"null"}]},"uf":{"anyOf":[{"type":"string"},{"type":"null"}]},"addressStreet":{"anyOf":[{"type":"string"},{"type":"null"}]},"addressZip":{"anyOf":[{"type":"string"},{"type":"null"}]},"addressDistrict":{"anyOf":[{"type":"string"},{"type":"null"}]}},"description":"Dados do cadastro da clínica (procedência: Dados da clínica) para pré-preencher — só valem depois de salvos aqui."},"readiness":{"type":"array","items":{"$ref":"#/components/schemas/FiscalReadinessArea"}},"modes":{"type":"array","items":{"$ref":"#/components/schemas/FiscalModeState"}},"phrases":{"type":"object","required":["activateProduction"],"properties":{"activateProduction":{"type":"string"}}}},"title":"FiscalSettings"},"Billing":{"type":"object","required":["plan","status","trialEndsAt","trialDaysLeft","trialExpired","cycle","nextChargeAt","paymentMethod","billingProfile","usage","addons","nextInvoice","pendingPlanId","quoteRequest","cancelRequestedAt","policies"],"properties":{"plan":{"type":"object","required":["id","name","description","price","priceAnnual","period","features"],"properties":{"id":{"type":"string"},"name":{"type":"string"},"description":{"anyOf":[{"type":"string"},{"type":"null"}]},"price":{"anyOf":[{"type":"number","description":"R$/mês no ciclo mensal."},{"type":"null"}]},"priceAnnual":{"anyOf":[{"type":"number","description":"R$/mês no ciclo anual."},{"type":"null"}]},"period":{"type":"string"},"features":{"type":"array","items":{"type":"string"}}}},"status":{"type":"string","enum":["ativa","teste","cancelamento_solicitado","cancelada","inadimplente"]},"trialEndsAt":{"anyOf":[{"type":"string","format":"date-time","description":"Fim do teste grátis do plano (status \"teste\"); null fora do teste."},{"type":"null"}]},"trialDaysLeft":{"anyOf":[{"type":"integer","description":"Dias restantes do teste (arredondado para cima; 0 = terminou)."},{"type":"null"}]},"trialExpired":{"type":"boolean","description":"true = teste terminou sem ativação: o painel está em somente leitura (escritas → 402 trial_expired), exceto cobrança e dados pessoais."},"cycle":{"type":"object","required":["label","start","end"],"properties":{"label":{"type":"string"},"start":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"end":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]}}},"nextChargeAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"paymentMethod":{"anyOf":[{"type":"object","required":["brand","last4","expires","primary"],"properties":{"brand":{"type":"string"},"last4":{"type":"string"},"expires":{"anyOf":[{"type":"string"},{"type":"null"}]},"primary":{"type":"boolean"}}},{"type":"null"}]},"billingProfile":{"$ref":"#/components/schemas/BillingProfile"},"usage":{"type":"array","items":{"$ref":"#/components/schemas/UsageRow"}},"addons":{"type":"object","required":["monthlyTotal","items"],"properties":{"monthlyTotal":{"type":"number","description":"Soma mensal das automações ativas (testes ainda não cobram)."},"items":{"type":"array","items":{"type":"object","required":["automationId","name","status","monthly","cycleCharge"],"properties":{"automationId":{"type":"string"},"name":{"type":"string"},"status":{"type":"string"},"monthly":{"type":"number"},"cycleCharge":{"type":"number"}}}}}},"nextInvoice":{"type":"object","required":["date","items","total"],"properties":{"date":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"items":{"type":"array","items":{"type":"object","required":["label","amount"],"properties":{"label":{"type":"string"},"amount":{"type":"number"}}}},"total":{"type":"number"}}},"pendingPlanId":{"anyOf":[{"type":"string","description":"Mudança de plano agendada para o fim do ciclo (desfazer: DELETE /billing/plan-changes). Plano sob consulta NÃO entra aqui — ver quoteRequest."},{"type":"null"}]},"quoteRequest":{"anyOf":[{"$ref":"#/components/schemas/BillingQuoteRequest"},{"type":"null"}]},"cancelRequestedAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"policies":{"type":"object","required":["priceTaxNote","fairUsePolicy","trialDays","planTrialDays","dataRetentionDays"],"properties":{"priceTaxNote":{"type":"string"},"fairUsePolicy":{"type":"string"},"trialDays":{"type":"integer","description":"Dias de teste grátis de cada automação."},"planTrialDays":{"type":"integer","description":"Dias de teste grátis do plano no autocadastro."},"dataRetentionDays":{"type":"integer","description":"Depois do fim do teste sem ativação, os dados ficam guardados por este número de dias."}}}},"title":"Billing"},"AutomationSubscribed":{"type":"object","required":["id","name","summary","about","category","categoryLabel","highlight","price","agent","benefits","potential","potentialLabel","settings","subscription","trialAvailable","pricing","automation"],"properties":{"id":{"type":"string"},"name":{"type":"string"},"summary":{"anyOf":[{"type":"string"},{"type":"null"}]},"about":{"anyOf":[{"type":"string"},{"type":"null"}]},"category":{"type":"string"},"categoryLabel":{"type":"string"},"highlight":{"anyOf":[{"type":"string","enum":["premium","recomendada"]},{"type":"null"}]},"price":{"type":"number","description":"R$/mês."},"agent":{"anyOf":[{"$ref":"#/components/schemas/AgentRef"},{"type":"null"}]},"benefits":{"type":"array","items":{"type":"string"}},"potential":{"anyOf":[{"type":"number"},{"type":"null"}]},"potentialLabel":{"anyOf":[{"type":"string"},{"type":"null"}]},"settings":{"type":"array","items":{"$ref":"#/components/schemas/AutomationSetting"}},"subscription":{"anyOf":[{"$ref":"#/components/schemas/AutomationSubscription"},{"type":"null"}]},"trialAvailable":{"type":"boolean"},"pricing":{"$ref":"#/components/schemas/PricingPreview"},"automation":{"$ref":"#/components/schemas/Automation"}},"title":"AutomationSubscribed","description":"Automation + pricing. `automation` (obsoleto) repete o mesmo objeto do formato antigo { automation, pricing }."},"FiscalCandidate":{"type":"object","required":["id","source","sourceId","appointmentId","transactionId","patientId","serviceKey","serviceName","serviceDate","amount","amountSource","amountConfirmed","taker","status","reviewStatus","issues","ignoredReason","reviewedAt","batchId","documentId","documentStatus","documents","capturedAt","rawHash"],"properties":{"id":{"type":"string"},"source":{"type":"string","enum":["atendimento","pagamento","planilha"]},"sourceId":{"type":"string"},"appointmentId":{"anyOf":[{"type":"string"},{"type":"null"}]},"transactionId":{"anyOf":[{"type":"string"},{"type":"null"}]},"patientId":{"anyOf":[{"type":"string"},{"type":"null"}]},"serviceKey":{"anyOf":[{"type":"string"},{"type":"null"}]},"serviceName":{"anyOf":[{"type":"string"},{"type":"null"}]},"serviceDate":{"type":"string"},"amount":{"anyOf":[{"type":"number"},{"type":"null"}]},"amountSource":{"anyOf":[{"type":"string","description":"lancamento | multiplos_lancamentos | tabela_servico | ausente | revisao"},{"type":"null"}]},"amountConfirmed":{"type":"boolean"},"taker":{"type":"object","required":["name","nameSource","cpfMasked","cpfSource","address","addressSource"],"properties":{"name":{"anyOf":[{"type":"string"},{"type":"null"}]},"nameSource":{"anyOf":[{"type":"string"},{"type":"null"}]},"cpfMasked":{"anyOf":[{"type":"string","description":"Sempre mascarado."},{"type":"null"}]},"cpfSource":{"anyOf":[{"type":"string"},{"type":"null"}]},"address":{"anyOf":[{"$ref":"#/components/schemas/FiscalTakerAddress"},{"type":"null"}]},"addressSource":{"anyOf":[{"type":"string","description":"revisao | revisao_anterior (copiado de outra revisão do mesmo paciente)."},{"type":"null"}]}}},"status":{"type":"string","enum":["pendente","pronta","em_lote","em_processamento","emitida","ignorada"],"description":"Situação no modo atual da clínica."},"reviewStatus":{"type":"string"},"issues":{"type":"array","items":{"$ref":"#/components/schemas/FiscalIssue"}},"ignoredReason":{"anyOf":[{"type":"string"},{"type":"null"}]},"reviewedAt":{"anyOf":[{"type":"string"},{"type":"null"}]},"batchId":{"anyOf":[{"type":"string"},{"type":"null"}]},"documentId":{"anyOf":[{"type":"string","description":"Nota do modo atual (quando existe)."},{"type":"null"}]},"documentStatus":{"anyOf":[{"type":"string","enum":["reservada","enviando","processando","autorizada","rejeitada","incerta","erro","cancelamento_solicitado","cancelada"]},{"type":"null"}]},"documents":{"type":"object","required":["simulacao","homologacao","producao"],"properties":{"simulacao":{"anyOf":[{"type":"string"},{"type":"null"}]},"homologacao":{"anyOf":[{"type":"string"},{"type":"null"}]},"producao":{"anyOf":[{"type":"string"},{"type":"null"}]}}},"capturedAt":{"anyOf":[{"type":"string"},{"type":"null"}]},"rawHash":{"anyOf":[{"type":"string","description":"sha256 do payload bruto da origem preservado na captura."},{"type":"null"}]}},"title":"FiscalCandidate"},"FinanceSummary":{"type":"object","required":["period","receita","recebido","emAberto","emAbertoQtd","despesas","resultado","inadimplencia","atrasado","previous","receitaPorServico","porDia","mensal","receitaPorProfissional","monthlyRevenueGoal","benchmarks"],"properties":{"period":{"$ref":"#/components/schemas/FinanceSummaryPeriod"},"receita":{"type":"number","description":"Receitas lançadas no período (exceto estornadas)."},"recebido":{"type":"number"},"emAberto":{"type":"number","description":"Receitas a receber + atrasadas."},"emAbertoQtd":{"type":"integer"},"despesas":{"type":"number"},"resultado":{"type":"number","description":"receita − despesas (não é lucro: custos não são modelados)."},"inadimplencia":{"anyOf":[{"type":"number","description":"% das receitas do período em atraso."},{"type":"null"}]},"atrasado":{"type":"number","description":"Receitas do período em atraso (R$)."},"previous":{"type":"object","required":["from","to","receita","recebido","despesas","resultado"],"properties":{"from":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","example":"2026-09-18"},"to":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","example":"2026-09-18"},"receita":{"type":"number"},"recebido":{"type":"number"},"despesas":{"type":"number"},"resultado":{"type":"number"}}},"receitaPorServico":{"type":"array","items":{"type":"object","required":["serviceKey","label","value","atendimentos"],"properties":{"serviceKey":{"anyOf":[{"type":"string"},{"type":"null"}]},"label":{"type":"string"},"value":{"type":"number"},"atendimentos":{"type":"integer"}}}},"porDia":{"type":"array","items":{"type":"object","required":["date","receitas","despesas"],"properties":{"date":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","example":"2026-09-18"},"receitas":{"type":"number"},"despesas":{"type":"number"}}}},"mensal":{"type":"array","items":{"type":"object","required":["month","receita","recebido","atrasado","inadimplencia","despesas"],"properties":{"month":{"type":"string","example":"2026-09"},"receita":{"type":"number"},"recebido":{"type":"number"},"atrasado":{"type":"number","description":"Receitas do mês hoje em atraso."},"inadimplencia":{"anyOf":[{"type":"number","description":"% das receitas do mês em atraso (null sem receita)."},{"type":"null"}]},"despesas":{"type":"number"}}},"description":"6 meses até o fim do período."},"receitaPorProfissional":{"type":"array","items":{"type":"object","required":["professionalKey","label","value","atendimentos","participacao"],"properties":{"professionalKey":{"anyOf":[{"type":"string"},{"type":"null"}]},"label":{"type":"string"},"value":{"type":"number"},"atendimentos":{"type":"integer","description":"Receitas lançadas (sessões/planos)."},"participacao":{"anyOf":[{"type":"number","description":"% da receita do período."},{"type":"null"}]}}},"description":"Receitas sem profissional (ex.: planos sem responsável) ficam em \"Sem profissional\"."},"monthlyRevenueGoal":{"anyOf":[{"type":"number","description":"Meta de receita mensal da clínica (reais). null = não definida."},{"type":"null"}]},"benchmarks":{"anyOf":[{"$ref":"#/components/schemas/Benchmarks"},{"type":"null"}]}},"title":"FinanceSummary"},"InboundMessageResult":{"type":"object","required":["conversation","message","conversationCreated","event"],"properties":{"conversation":{"$ref":"#/components/schemas/Conversation"},"message":{"$ref":"#/components/schemas/Message"},"conversationCreated":{"type":"boolean","description":"true = a conversa foi criada por este pedido."},"event":{"anyOf":[{"$ref":"#/components/schemas/OutboxEvent2"},{"type":"null"}]}},"title":"InboundMessageResult"},"FiscalDocumentDetail":{"type":"object","required":["id","candidateId","batchId","environment","environmentLabel","simulated","generation","provider","status","statusLabel","series","number","amount","serviceKey","serviceDate","rule","takerName","takerDocMasked","nfseNumber","verificationCode","accessKey","authorizedAt","providerStatus","error","cancel","attempts","lastAttemptAt","files","createdAt","history"],"properties":{"id":{"type":"string","description":"Também é a referência idempotente enviada ao provedor."},"candidateId":{"type":"string"},"batchId":{"anyOf":[{"type":"string"},{"type":"null"}]},"environment":{"type":"string","enum":["simulacao","homologacao","producao"]},"environmentLabel":{"type":"string"},"simulated":{"type":"boolean","description":"true = gerada no modo Simulação (sem valor fiscal)."},"generation":{"type":"integer"},"provider":{"type":"string"},"status":{"type":"string","enum":["reservada","enviando","processando","autorizada","rejeitada","incerta","erro","cancelamento_solicitado","cancelada"]},"statusLabel":{"type":"string"},"series":{"anyOf":[{"type":"string"},{"type":"null"}]},"number":{"anyOf":[{"type":"integer","description":"Número da DPS/RPS reservado."},{"type":"null"}]},"amount":{"type":"number"},"serviceKey":{"anyOf":[{"type":"string"},{"type":"null"}]},"serviceDate":{"anyOf":[{"type":"string"},{"type":"null"}]},"rule":{"$ref":"#/components/schemas/FiscalDocumentDetailRule"},"takerName":{"anyOf":[{"type":"string"},{"type":"null"}]},"takerDocMasked":{"anyOf":[{"type":"string"},{"type":"null"}]},"nfseNumber":{"anyOf":[{"type":"string"},{"type":"null"}]},"verificationCode":{"anyOf":[{"type":"string"},{"type":"null"}]},"accessKey":{"anyOf":[{"type":"string"},{"type":"null"}]},"authorizedAt":{"anyOf":[{"type":"string"},{"type":"null"}]},"providerStatus":{"anyOf":[{"type":"string"},{"type":"null"}]},"error":{"anyOf":[{"type":"object","required":["code","message"],"properties":{"code":{"anyOf":[{"type":"string"},{"type":"null"}]},"message":{"anyOf":[{"type":"string"},{"type":"null"}]}}},{"type":"null"}]},"cancel":{"$ref":"#/components/schemas/FiscalDocumentDetailCancel"},"attempts":{"type":"integer"},"lastAttemptAt":{"anyOf":[{"type":"string"},{"type":"null"}]},"files":{"$ref":"#/components/schemas/FiscalDocumentDetailFiles"},"createdAt":{"type":"string","format":"date-time"},"history":{"type":"array","items":{"$ref":"#/components/schemas/FiscalAttempt"}}},"title":"FiscalDocumentDetail"},"LeadSummary":{"type":"object","required":["total","byStage","qualified","ready","scheduled","converted","conversionRate","funnel","bySource","byChannel","byService","byAgent","weekly","trend"],"properties":{"total":{"type":"integer"},"byStage":{"type":"object","additionalProperties":{"type":"integer"}},"qualified":{"type":"integer"},"ready":{"type":"integer"},"scheduled":{"type":"integer"},"converted":{"type":"integer"},"conversionRate":{"anyOf":[{"type":"number","description":"% que virou paciente."},{"type":"null"}]},"funnel":{"type":"array","items":{"type":"object","required":["stage","label","reached","conversionFromPrevious"],"properties":{"stage":{"type":"string","enum":["NEW","DISCOVERY","QUALIFIED","READY_TO_SCHEDULE","SCHEDULED","COMPLETED","NURTURE","NOT_A_FIT","HUMAN_HANDOFF"]},"label":{"type":"string"},"reached":{"type":"integer"},"conversionFromPrevious":{"anyOf":[{"type":"number"},{"type":"null"}]}}}},"bySource":{"type":"array","items":{"type":"object","required":["source","label","count","scheduled"],"properties":{"source":{"type":"string","enum":["META_ADS","GOOGLE","INSTAGRAM","FECHADA","INFLUENCER","INDICACAO"]},"label":{"type":"string"},"count":{"type":"integer"},"scheduled":{"type":"integer","description":"Chegaram a Agendado ou além."}}}},"byChannel":{"type":"array","items":{"type":"object","required":["channel","count","scheduled"],"properties":{"channel":{"type":"string"},"count":{"type":"integer"},"scheduled":{"type":"integer","description":"Chegaram a Agendado ou além."}}}},"byService":{"type":"array","items":{"type":"object","required":["key","name","count","scheduled"],"properties":{"key":{"type":"string"},"name":{"type":"string"},"count":{"type":"integer"},"scheduled":{"type":"integer","description":"Chegaram a Agendado ou além."}}}},"byAgent":{"type":"array","items":{"type":"object","required":["agent","count","advanced"],"properties":{"agent":{"type":"string","description":"agent_key da última ação automática."},"count":{"type":"integer"},"advanced":{"type":"integer","description":"Chegaram a Qualificado ou além."}}}},"weekly":{"type":"array","items":{"type":"object","required":["weekStart","total","qualified","ready","scheduled"],"properties":{"weekStart":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","example":"2026-09-18"},"total":{"type":"integer"},"qualified":{"type":"integer"},"ready":{"type":"integer"},"scheduled":{"type":"integer"}}}},"trend":{"anyOf":[{"type":"object","required":["unit","points","bySource"],"properties":{"unit":{"type":"string","enum":["dia","semana"]},"points":{"type":"array","items":{"type":"object","required":["start","current","previous"],"properties":{"start":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","examples":["2026-09-18"]},"current":{"type":"integer"},"previous":{"type":"integer","description":"Mesmo balde no período anterior (N dias antes)."}}}},"bySource":{"type":"array","items":{"type":"object","required":["source","points"],"properties":{"source":{"type":"string","enum":["META_ADS","GOOGLE","INSTAGRAM","FECHADA","INFLUENCER","INDICACAO"]},"points":{"type":"array","items":{"type":"integer"}}}}}},"description":"Só com periodDays: novos leads por dia (até 30 dias) ou semana, atual × período anterior."},{"type":"null"}]}},"title":"LeadSummary"},"IntegrationDetail":{"type":"object","required":["id","name","summary","description","category","availability","auth","provider","benefits","status","connection","scopes","credentialRef","eventsSynced","config","webhooks"],"properties":{"id":{"type":"string"},"name":{"type":"string"},"summary":{"anyOf":[{"type":"string"},{"type":"null"}]},"description":{"anyOf":[{"type":"string"},{"type":"null"}]},"category":{"type":"string"},"availability":{"type":"string","enum":["disponivel","em-breve"]},"auth":{"type":"string","enum":["oauth","apikey","smtp","whatsapp"]},"provider":{"anyOf":[{"type":"string"},{"type":"null"}]},"benefits":{"type":"array","items":{"type":"string"}},"status":{"type":"string","enum":["ativa","disponivel","em-breve","pausada","erro","conectando"],"description":"Status exibido nos cards (derivado do catálogo + conexão da clínica)."},"connection":{"anyOf":[{"$ref":"#/components/schemas/IntegrationConnection"},{"type":"null"}]},"scopes":{"type":"array","items":{"$ref":"#/components/schemas/IntegrationScope"}},"credentialRef":{"anyOf":[{"type":"string","description":"Sempre mascarada (gcal_ref_••••7F2A)."},{"type":"null"}]},"eventsSynced":{"type":"integer"},"config":{"type":"object","required":["syncMode","grantedScopes","calendars","syncSettings"],"properties":{"syncMode":{"anyOf":[{"type":"string"},{"type":"null"}]},"grantedScopes":{"type":"array","items":{"type":"string"}},"calendars":{"type":"array","items":{"type":"object","required":["id","name","description","enabled"],"properties":{"id":{"type":"string"},"name":{"type":"string"},"description":{"anyOf":[{"type":"string"},{"type":"null"}]},"enabled":{"type":"boolean"},"isDefault":{"type":"boolean"}}}},"syncSettings":{"type":"array","items":{"type":"object","required":["id","label","value"],"properties":{"id":{"type":"string"},"label":{"type":"string"},"value":{"type":"boolean"}}}}}},"webhooks":{"type":"array","items":{"type":"object","required":["id","event","endpoint","active","lastDelivery"],"properties":{"id":{"type":"string"},"event":{"type":"string"},"endpoint":{"anyOf":[{"type":"string","description":"URL mascarada."},{"type":"null"}]},"active":{"type":"boolean"},"lastDelivery":{"anyOf":[{"type":"string","format":"date-time","description":"Última entrega (ISO 8601); o front formata (\"há 6 minutos\"). Valor legado não-ISO vira null."},{"type":"null"}]}}}}},"title":"IntegrationDetail"},"AgentDetail":{"type":"object","required":["id","name","role","channel","status","statusLabel","enabled","lastRunAt","handoffs","resolution","nextAction","activity","image","runtime","pausedReason","priority","technicalId","subtitle","objective","scope","sla","handoffTo","owner","automation","performance","recentActivity","config","history"],"properties":{"id":{"type":"string","description":"agent_key funcional e estável (knowledge, qualificacao, agendamento, pos-consulta, financeiro, reativacao…)."},"name":{"type":"string","description":"Persona exibida (Lívia, Flávia, Vitória, Sofia, Cecília, Letícia)."},"role":{"anyOf":[{"type":"string"},{"type":"null"}]},"channel":{"anyOf":[{"type":"string","enum":["WhatsApp","Site","Instagram","Interno"]},{"type":"null"}]},"status":{"type":"string","enum":["ativo","execucao","pausa","erro","handoff"]},"statusLabel":{"type":"string"},"enabled":{"type":"boolean"},"lastRunAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"handoffs":{"type":"integer","description":"Transferências para a equipe hoje."},"resolution":{"anyOf":[{"type":"number","description":"% resolvidos sem a equipe."},{"type":"null"}]},"nextAction":{"anyOf":[{"type":"string"},{"type":"null"}]},"activity":{"anyOf":[{"type":"string"},{"type":"null"}]},"image":{"anyOf":[{"type":"string"},{"type":"null"}]},"runtime":{"anyOf":[{"type":"string","description":"Runtime técnico (PRD §1.9) — só para agents:manage."},{"type":"null"}]},"pausedReason":{"anyOf":[{"type":"string"},{"type":"null"}]},"priority":{"anyOf":[{"type":"string","enum":["Alta","Média","Baixa"],"description":"Prioridade definida pela clínica (filtro da lista)."},{"type":"null"}]},"technicalId":{"anyOf":[{"type":"string","description":"agent_id técnico (mova-agent-…) — só para agents:manage."},{"type":"null"}]},"subtitle":{"anyOf":[{"type":"string"},{"type":"null"}]},"objective":{"anyOf":[{"type":"string"},{"type":"null"}]},"scope":{"anyOf":[{"type":"string"},{"type":"null"}]},"sla":{"anyOf":[{"type":"string"},{"type":"null"}]},"handoffTo":{"anyOf":[{"type":"string"},{"type":"null"}]},"owner":{"anyOf":[{"type":"string"},{"type":"null"}]},"automation":{"type":"boolean"},"performance":{"type":"array","items":{"type":"object","required":["value","label"],"properties":{"value":{"type":"string"},"label":{"type":"string"}}}},"recentActivity":{"type":"array","items":{"type":"object","required":["id","text","at","tone"],"properties":{"id":{"type":"string"},"text":{"type":"string"},"at":{"type":"string","format":"date-time"},"tone":{"type":"string"}}}},"config":{"$ref":"#/components/schemas/AgentConfig"},"history":{"type":"array","items":{"type":"object","required":["id","text","author","at"],"properties":{"id":{"type":"string"},"text":{"type":"string"},"author":{"type":"string"},"at":{"type":"string","format":"date-time"}}}}},"title":"AgentDetail"},"FiscalDocument":{"type":"object","required":["id","candidateId","batchId","environment","environmentLabel","simulated","generation","provider","status","statusLabel","series","number","amount","serviceKey","serviceDate","rule","takerName","takerDocMasked","nfseNumber","verificationCode","accessKey","authorizedAt","providerStatus","error","cancel","attempts","lastAttemptAt","files","createdAt"],"properties":{"id":{"type":"string","description":"Também é a referência idempotente enviada ao provedor."},"candidateId":{"type":"string"},"batchId":{"anyOf":[{"type":"string"},{"type":"null"}]},"environment":{"type":"string","enum":["simulacao","homologacao","producao"]},"environmentLabel":{"type":"string"},"simulated":{"type":"boolean","description":"true = gerada no modo Simulação (sem valor fiscal)."},"generation":{"type":"integer"},"provider":{"type":"string"},"status":{"type":"string","enum":["reservada","enviando","processando","autorizada","rejeitada","incerta","erro","cancelamento_solicitado","cancelada"]},"statusLabel":{"type":"string"},"series":{"anyOf":[{"type":"string"},{"type":"null"}]},"number":{"anyOf":[{"type":"integer","description":"Número da DPS/RPS reservado."},{"type":"null"}]},"amount":{"type":"number"},"serviceKey":{"anyOf":[{"type":"string"},{"type":"null"}]},"serviceDate":{"anyOf":[{"type":"string"},{"type":"null"}]},"rule":{"$ref":"#/components/schemas/FiscalDocumentDetailRule"},"takerName":{"anyOf":[{"type":"string"},{"type":"null"}]},"takerDocMasked":{"anyOf":[{"type":"string"},{"type":"null"}]},"nfseNumber":{"anyOf":[{"type":"string"},{"type":"null"}]},"verificationCode":{"anyOf":[{"type":"string"},{"type":"null"}]},"accessKey":{"anyOf":[{"type":"string"},{"type":"null"}]},"authorizedAt":{"anyOf":[{"type":"string"},{"type":"null"}]},"providerStatus":{"anyOf":[{"type":"string"},{"type":"null"}]},"error":{"anyOf":[{"type":"object","required":["code","message"],"properties":{"code":{"anyOf":[{"type":"string"},{"type":"null"}]},"message":{"anyOf":[{"type":"string"},{"type":"null"}]}}},{"type":"null"}]},"cancel":{"$ref":"#/components/schemas/FiscalDocumentDetailCancel"},"attempts":{"type":"integer"},"lastAttemptAt":{"anyOf":[{"type":"string"},{"type":"null"}]},"files":{"$ref":"#/components/schemas/FiscalDocumentDetailFiles"},"createdAt":{"type":"string","format":"date-time"}},"title":"FiscalDocument"},"Patient":{"type":"object","required":["id","name","age","sex","birthDate","cpf","phone","email","city","address","status","isNew","tags","service","plan","origin","professional","lastVisitAt","lastVisitDaysAgo","nextAppointment","leadId","lgpdConsentAt","createdAt","updatedAt"],"properties":{"id":{"type":"string"},"name":{"type":"string"},"age":{"anyOf":[{"type":"integer","description":"Calculada de birthDate."},{"type":"null"}]},"sex":{"anyOf":[{"type":"string","examples":["Feminino","Masculino"]},{"type":"null"}]},"birthDate":{"anyOf":[{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","examples":["2026-09-18"]},{"type":"null"}]},"cpf":{"anyOf":[{"type":"string","description":"SEMPRE mascarado (123.***.***-00)."},{"type":"null"}]},"phone":{"anyOf":[{"type":"string","description":"Completo com patients:write; mascarado para os demais perfis."},{"type":"null"}]},"email":{"anyOf":[{"type":"string"},{"type":"null"}]},"city":{"anyOf":[{"type":"string"},{"type":"null"}]},"address":{"anyOf":[{"type":"string"},{"type":"null"}]},"status":{"type":"string","enum":["ativo","inativo"]},"isNew":{"type":"boolean","description":"Cadastrado no mês corrente (timezone da clínica)."},"tags":{"type":"array","items":{"type":"string"}},"service":{"anyOf":[{"$ref":"#/components/schemas/KeyName"},{"type":"null"}]},"plan":{"anyOf":[{"type":"string","examples":["Particular","Convênio"]},{"type":"null"}]},"origin":{"anyOf":[{"type":"string","examples":["Lead (Instagram)","Indicação","Recepção"]},{"type":"null"}]},"professional":{"anyOf":[{"$ref":"#/components/schemas/KeyName"},{"type":"null"}]},"lastVisitAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"lastVisitDaysAgo":{"anyOf":[{"type":"integer","description":"null = nunca consultou."},{"type":"null"}]},"nextAppointment":{"anyOf":[{"type":"object","required":["id","date","time","professional","type"],"properties":{"id":{"type":"string"},"date":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","examples":["2026-09-18"]},"time":{"type":"string"},"professional":{"anyOf":[{"type":"string"},{"type":"null"}]},"type":{"anyOf":[{"type":"string"},{"type":"null"}]}}},{"type":"null"}]},"leadId":{"anyOf":[{"type":"string"},{"type":"null"}]},"lgpdConsentAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}},"title":"Patient"},"KnowledgeArticle":{"type":"object","required":["id","title","excerpt","type","typeLabel","category","categoryLabel","status","statusLabel","updatedAt","updatedBy","intro","steps","tip","keywords","aliases","service","professional","source","validUntil","ai"],"properties":{"id":{"type":"string"},"title":{"type":"string"},"excerpt":{"anyOf":[{"type":"string"},{"type":"null"}]},"type":{"type":"string","enum":["artigo","faq","protocolo","material"]},"typeLabel":{"type":"string"},"category":{"type":"string"},"categoryLabel":{"type":"string"},"status":{"type":"string","enum":["publicado","em_revisao","rascunho"]},"statusLabel":{"type":"string"},"updatedAt":{"type":"string","format":"date-time"},"updatedBy":{"anyOf":[{"type":"string"},{"type":"null"}]},"intro":{"anyOf":[{"type":"string"},{"type":"null"}]},"steps":{"type":"array","items":{"$ref":"#/components/schemas/KnowledgeStep"}},"tip":{"anyOf":[{"type":"string"},{"type":"null"}]},"keywords":{"type":"array","items":{"type":"string"}},"aliases":{"type":"array","items":{"type":"string"}},"service":{"anyOf":[{"$ref":"#/components/schemas/KeyName"},{"type":"null"}]},"professional":{"anyOf":[{"$ref":"#/components/schemas/KeyName"},{"type":"null"}]},"source":{"anyOf":[{"type":"string"},{"type":"null"}]},"validUntil":{"anyOf":[{"type":"string","description":"YYYY-MM-DD"},{"type":"null"}]},"ai":{"type":"object","required":["safeForAi","requiresHuman","requiresClinicalAssessment","review","usedBy","usableByAgents"],"properties":{"safeForAi":{"type":"boolean"},"requiresHuman":{"type":"boolean"},"requiresClinicalAssessment":{"type":"boolean"},"review":{"type":"object","required":["status","statusLabel","by","at","note"],"properties":{"status":{"type":"string","enum":["aprovado","pendente","reprovado"]},"statusLabel":{"type":"string"},"by":{"anyOf":[{"type":"string"},{"type":"null"}]},"at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"note":{"anyOf":[{"type":"string"},{"type":"null"}]}}},"usedBy":{"type":"array","items":{"type":"object","required":["key","name"],"properties":{"key":{"type":"string"},"name":{"type":"string"}}}},"usableByAgents":{"type":"boolean","description":"publicado + aprovado + safeForAi + dentro da validade."}}}},"title":"KnowledgeArticle"},"Transaction":{"type":"object","required":["id","date","time","occurredAt","description","party","patientId","type","amount","status","statusLabel","method","dueDate","paidAt","service","professional","appointmentId","agent","reversedFrom","category"],"properties":{"id":{"type":"string"},"date":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","description":"Data local (timezone da clínica).","example":"2026-09-18"},"time":{"type":"string","example":"14:30"},"occurredAt":{"type":"string","format":"date-time"},"description":{"type":"string"},"party":{"anyOf":[{"type":"string","description":"Paciente/fornecedor."},{"type":"null"}]},"patientId":{"anyOf":[{"type":"string"},{"type":"null"}]},"type":{"type":"string","enum":["receita","despesa"]},"amount":{"type":"number"},"status":{"type":"string","enum":["recebido","pago","a-receber","a-pagar","atrasado","estornado"]},"statusLabel":{"type":"string"},"method":{"anyOf":[{"type":"string"},{"type":"null"}]},"dueDate":{"anyOf":[{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","examples":["2026-09-18"]},{"type":"null"}]},"paidAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"service":{"anyOf":[{"$ref":"#/components/schemas/KeyName"},{"type":"null"}]},"professional":{"anyOf":[{"$ref":"#/components/schemas/KeyName"},{"type":"null"}]},"appointmentId":{"anyOf":[{"type":"string"},{"type":"null"}]},"agent":{"anyOf":[{"type":"object","required":["key","name","image","state","action","at"],"properties":{"key":{"type":"string"},"name":{"type":"string"},"image":{"anyOf":[{"type":"string"},{"type":"null"}]},"state":{"type":"string","enum":["executado","aguardando"]},"action":{"anyOf":[{"type":"string"},{"type":"null"}]},"at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]}}},{"type":"null"}]},"reversedFrom":{"anyOf":[{"type":"string"},{"type":"null"}]},"category":{"anyOf":[{"type":"string","enum":["aluguel","internet","sistema","outro"],"description":"Tipo da despesa (aluguel, internet, sistema, outro). null em receitas."},{"type":"null"}]}},"title":"Transaction"},"Clinic":{"type":"object","required":["id","name","tagline","legalName","cnpj","email","phone","site","timezone","locale","dateFormat","timeFormat","currency","address","city","status","logoUrl","logoLocked","monthlyRevenueGoal"],"properties":{"id":{"type":"string","example":"mowa"},"name":{"type":"string","example":"Clínica Mowa"},"tagline":{"anyOf":[{"type":"string"},{"type":"null"}]},"legalName":{"anyOf":[{"type":"string"},{"type":"null"}]},"cnpj":{"anyOf":[{"type":"string"},{"type":"null"}]},"email":{"anyOf":[{"type":"string"},{"type":"null"}]},"phone":{"anyOf":[{"type":"string"},{"type":"null"}]},"site":{"anyOf":[{"type":"string"},{"type":"null"}]},"timezone":{"type":"string","example":"America/Sao_Paulo"},"locale":{"type":"string","example":"pt-BR"},"dateFormat":{"anyOf":[{"type":"string"},{"type":"null"}]},"timeFormat":{"anyOf":[{"type":"string"},{"type":"null"}]},"currency":{"anyOf":[{"type":"string"},{"type":"null"}]},"address":{"$ref":"#/components/schemas/Address"},"city":{"anyOf":[{"type":"string","description":"Cidade formatada \"Franca - SP\" (cabeçalho do painel)."},{"type":"null"}]},"status":{"type":"string","enum":["DRAFT","ONBOARDING","READY_FOR_TEST","ACTIVE","SUSPENDED","ARCHIVED"]},"logoUrl":{"anyOf":[{"type":"string","description":"Logo da clínica. Só é liberado com o plano ativo; enquanto null o painel mostra \"My Clinic\"."},{"type":"null"}]},"logoLocked":{"type":"boolean","description":"true = existe logo, mas o plano ainda não foi ativado."},"monthlyRevenueGoal":{"anyOf":[{"type":"number","description":"Meta de receita mensal (reais), usada em Relatórios e Financeiro. null = sem meta."},{"type":"null"}]}},"title":"Clinic"},"Me":{"type":"object","required":["user","clinic","role","roleLabel","permissions","professionalKey","ownScheduleOnly","platformRole","emailVerified","subscriptionStatus","trialEndsAt","trialExpired"],"properties":{"user":{"type":"object","required":["id","name","email","initials"],"properties":{"id":{"type":"string"},"name":{"type":"string"},"email":{"type":"string"},"initials":{"type":"string"}}},"clinic":{"type":"object","required":["id","name","city","status","timezone","logoUrl"],"properties":{"id":{"type":"string"},"name":{"type":"string"},"city":{"anyOf":[{"type":"string"},{"type":"null"}]},"status":{"type":"string"},"timezone":{"type":"string"},"logoUrl":{"anyOf":[{"type":"string"},{"type":"null"}]}}},"role":{"anyOf":[{"type":"string","enum":["admin","profissional","recepcao","financeiro","marketing","suporte","estagiario"]},{"type":"null"}]},"roleLabel":{"type":"string","example":"Administrador"},"permissions":{"type":"array","items":{"type":"string"}},"professionalKey":{"anyOf":[{"type":"string"},{"type":"null"}]},"ownScheduleOnly":{"type":"boolean","description":"true = agenda filtrada pelos próprios atendimentos (Profissional de saúde)."},"platformRole":{"anyOf":[{"type":"string"},{"type":"null"}]},"emailVerified":{"type":"boolean","description":"E-mail da conta confirmado no provedor de identidade. Com a verificação ligada no ambiente, convidar, conectar integrações, contratar automações e enviar mensagens exigem true (403 email_not_verified)."},"subscriptionStatus":{"anyOf":[{"type":"string","enum":["ativa","teste","cancelamento_solicitado","cancelada","inadimplente"],"description":"Status da assinatura do plano da clínica ativa; null = clínica sem assinatura."},{"type":"null"}]},"trialEndsAt":{"anyOf":[{"type":"string","format":"date-time","description":"Fim do teste grátis do plano (só com subscriptionStatus = \"teste\")."},{"type":"null"}]},"trialExpired":{"type":"boolean","description":"true = teste grátis terminou sem ativação: painel em somente leitura (escritas → 402 trial_expired, exceto cobrança e dados pessoais). Os dados ficam guardados por 90 dias."}},"title":"Me"},"FiscalBatch":{"type":"object","required":["id","environment","environmentLabel","status","itemCount","total","items","blocked","results","nextNumber","confirmationPhrase","createdAt","confirmedAt","finishedAt"],"properties":{"id":{"type":"string"},"environment":{"type":"string","enum":["simulacao","homologacao","producao"]},"environmentLabel":{"type":"string"},"status":{"type":"string","enum":["rascunho","emitindo","concluido","concluido_com_falhas","interrompido","descartado"]},"itemCount":{"type":"integer"},"total":{"type":"number"},"items":{"type":"array","items":{"$ref":"#/components/schemas/FiscalBatchItem"}},"blocked":{"type":"array","items":{"type":"object","required":["candidateId","issues"],"properties":{"candidateId":{"type":"string"},"issues":{"type":"array","items":{"type":"object","required":["code","message"],"properties":{"code":{"type":"string"},"message":{"type":"string"}}}}}}},"results":{"anyOf":[{"type":"object","additionalProperties":{"anyOf":[{"type":"integer"},{"type":"string"},{"type":"null"}]}},{"type":"null"}]},"nextNumber":{"anyOf":[{"type":"object","required":["series","number"],"properties":{"series":{"type":"string"},"number":{"type":"integer"}},"description":"Próximo número livre agora (a reserva definitiva acontece na emissão)."},{"type":"null"}]},"confirmationPhrase":{"anyOf":[{"type":"string","description":"Frase exigida para emitir (só em Produção)."},{"type":"null"}]},"createdAt":{"type":"string","format":"date-time"},"confirmedAt":{"anyOf":[{"type":"string"},{"type":"null"}]},"finishedAt":{"anyOf":[{"type":"string"},{"type":"null"}]}},"title":"FiscalBatch"},"ConversationDetail":{"type":"object","required":["id","name","channel","preview","lastMessageAt","unread","mine","assignedTo","archived","activeAgent","patientId","leadId","tags","contact","appointments"],"properties":{"id":{"type":"string"},"name":{"type":"string"},"channel":{"type":"string","enum":["whatsapp","email","sms","instagram","outros"]},"preview":{"anyOf":[{"type":"string"},{"type":"null"}]},"lastMessageAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"unread":{"type":"integer"},"mine":{"type":"boolean","description":"Conversa atribuída ao usuário atual."},"assignedTo":{"anyOf":[{"type":"object","required":["id","name"],"properties":{"id":{"type":"string"},"name":{"type":"string"}}},{"type":"null"}]},"archived":{"type":"boolean"},"activeAgent":{"anyOf":[{"$ref":"#/components/schemas/AgentRef"},{"type":"null"}]},"patientId":{"anyOf":[{"type":"string"},{"type":"null"}]},"leadId":{"anyOf":[{"type":"string"},{"type":"null"}]},"tags":{"type":"array","items":{"type":"string"}},"contact":{"$ref":"#/components/schemas/Contact"},"appointments":{"type":"array","items":{"type":"object","required":["id","date","time","description","status","statusLabel"],"properties":{"id":{"type":"string"},"date":{"type":"string"},"time":{"type":"string"},"description":{"type":"string"},"status":{"type":"string"},"statusLabel":{"type":"string"}}}}},"title":"ConversationDetail"},"FiscalServiceRule":{"type":"object","required":["id","serviceKey","version","status","description","nationalTaxCode","lc116Item","nbsCode","municipalTaxCode","cnae","issRate","issWithheld","issTaxation","incidence","trigger","notes","validFrom","validTo","approval","missingFields","createdAt"],"properties":{"id":{"type":"string"},"serviceKey":{"type":"string"},"version":{"type":"integer"},"status":{"type":"string","enum":["rascunho","aprovada","substituida","descartada"]},"description":{"anyOf":[{"type":"string"},{"type":"null"}]},"nationalTaxCode":{"anyOf":[{"type":"string"},{"type":"null"}]},"lc116Item":{"anyOf":[{"type":"string"},{"type":"null"}]},"nbsCode":{"anyOf":[{"type":"string"},{"type":"null"}]},"municipalTaxCode":{"anyOf":[{"type":"string"},{"type":"null"}]},"cnae":{"anyOf":[{"type":"string"},{"type":"null"}]},"issRate":{"anyOf":[{"type":"number","description":"Alíquota do ISS em % (2 = 2,00 %). null = não informada."},{"type":"null"}]},"issWithheld":{"anyOf":[{"type":"boolean"},{"type":"null"}]},"issTaxation":{"anyOf":[{"type":"string","enum":["tributavel","imune","exportacao","nao_incidencia"]},{"type":"null"}]},"incidence":{"anyOf":[{"type":"string","enum":["prestador","tomador"]},{"type":"null"}]},"trigger":{"type":"string","enum":["padrao","atendimento_realizado","pagamento_recebido"]},"notes":{"anyOf":[{"type":"string"},{"type":"null"}]},"validFrom":{"anyOf":[{"type":"string"},{"type":"null"}]},"validTo":{"anyOf":[{"type":"string"},{"type":"null"}]},"approval":{"$ref":"#/components/schemas/FiscalSettingsApproval"},"missingFields":{"type":"array","items":{"type":"string"},"description":"O que falta para poder aprovar no tipo de documento atual."},"createdAt":{"type":"string","format":"date-time"}},"title":"FiscalServiceRule"},"AuditEvent":{"type":"object","required":["id","date","time","occurredAt","actor","action","actionLabel","resource","resourceLabel","resourceId","details","level","levelLabel","ip","origin","traceId","before","after","changes","agentState"],"properties":{"id":{"type":"string"},"date":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","description":"Data local da clínica.","example":"2026-09-18"},"time":{"type":"string","example":"13:42"},"occurredAt":{"type":"string","format":"date-time"},"actor":{"type":"object","required":["id","name","role","kind"],"properties":{"id":{"anyOf":[{"type":"string"},{"type":"null"}]},"name":{"type":"string"},"role":{"anyOf":[{"type":"string"},{"type":"null"}]},"kind":{"type":"string","enum":["humano","agente","sistema"]}}},"action":{"type":"string","enum":["login","update","create","invite","configure","delete","view","reconcile","send","record_preview","revoke_access","reverse","change_role","export","approve","reject"]},"actionLabel":{"type":"string","example":"Atualizar"},"resource":{"type":"string","example":"patient"},"resourceLabel":{"type":"string","example":"Paciente"},"resourceId":{"anyOf":[{"type":"string"},{"type":"null"}]},"details":{"type":"string"},"level":{"type":"string","enum":["info","medio","alto"]},"levelLabel":{"type":"string"},"ip":{"anyOf":[{"type":"string"},{"type":"null"}]},"origin":{"anyOf":[{"type":"string"},{"type":"null"}]},"traceId":{"anyOf":[{"type":"string"},{"type":"null"}]},"before":{"anyOf":[{"type":"string","description":"Resumo mascarado do estado anterior."},{"type":"null"}]},"after":{"anyOf":[{"type":"string","description":"Resumo mascarado do novo estado."},{"type":"null"}]},"changes":{"type":"array","items":{"type":"object","required":["field","before","after"],"properties":{"field":{"type":"string"},"before":{},"after":{}}}},"agentState":{"anyOf":[{"type":"string"},{"type":"null"}]}},"title":"AuditEvent"},"Invitation":{"type":"object","required":["invitationId","user","expiresAt"],"properties":{"invitationId":{"type":"string"},"user":{"$ref":"#/components/schemas/ClinicUser"},"expiresAt":{"type":"string","format":"date-time"},"devInviteToken":{"type":"string","description":"Somente no modo de desenvolvimento em memória. Em produção o token só vai no e-mail (enviado pelas automações)."}},"title":"Invitation"},"Agent":{"type":"object","required":["id","name","role","channel","status","statusLabel","enabled","lastRunAt","handoffs","resolution","nextAction","activity","image","runtime","pausedReason","priority"],"properties":{"id":{"type":"string","description":"agent_key funcional e estável (knowledge, qualificacao, agendamento, pos-consulta, financeiro, reativacao…)."},"name":{"type":"string","description":"Persona exibida (Lívia, Flávia, Vitória, Sofia, Cecília, Letícia)."},"role":{"anyOf":[{"type":"string"},{"type":"null"}]},"channel":{"anyOf":[{"type":"string","enum":["WhatsApp","Site","Instagram","Interno"]},{"type":"null"}]},"status":{"type":"string","enum":["ativo","execucao","pausa","erro","handoff"]},"statusLabel":{"type":"string"},"enabled":{"type":"boolean"},"lastRunAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"handoffs":{"type":"integer","description":"Transferências para a equipe hoje."},"resolution":{"anyOf":[{"type":"number","description":"% resolvidos sem a equipe."},{"type":"null"}]},"nextAction":{"anyOf":[{"type":"string"},{"type":"null"}]},"activity":{"anyOf":[{"type":"string"},{"type":"null"}]},"image":{"anyOf":[{"type":"string"},{"type":"null"}]},"runtime":{"anyOf":[{"type":"string","description":"Runtime técnico (PRD §1.9) — só para agents:manage."},{"type":"null"}]},"pausedReason":{"anyOf":[{"type":"string"},{"type":"null"}]},"priority":{"anyOf":[{"type":"string","enum":["Alta","Média","Baixa"],"description":"Prioridade definida pela clínica (filtro da lista)."},{"type":"null"}]}},"title":"Agent"},"Integration":{"type":"object","required":["id","name","summary","description","category","availability","auth","provider","benefits","status","connection"],"properties":{"id":{"type":"string"},"name":{"type":"string"},"summary":{"anyOf":[{"type":"string"},{"type":"null"}]},"description":{"anyOf":[{"type":"string"},{"type":"null"}]},"category":{"type":"string"},"availability":{"type":"string","enum":["disponivel","em-breve"]},"auth":{"type":"string","enum":["oauth","apikey","smtp","whatsapp"]},"provider":{"anyOf":[{"type":"string"},{"type":"null"}]},"benefits":{"type":"array","items":{"type":"string"}},"status":{"type":"string","enum":["ativa","disponivel","em-breve","pausada","erro","conectando"],"description":"Status exibido nos cards (derivado do catálogo + conexão da clínica)."},"connection":{"anyOf":[{"$ref":"#/components/schemas/IntegrationConnection"},{"type":"null"}]}},"title":"Integration"},"Service":{"type":"object","required":["id","key","name","description","category","duration","price","currency","active","requiresProfessional","aiDescription","rules","demand","professionals","createdAt","updatedAt"],"properties":{"id":{"type":"string"},"key":{"type":"string","description":"service_key — único dentro da clínica.","example":"sessao-fisioterapia"},"name":{"type":"string","example":"Sessão de Fisioterapia"},"description":{"anyOf":[{"type":"string"},{"type":"null"}]},"category":{"type":"string","example":"Fisioterapia"},"duration":{"type":"integer","description":"Minutos."},"price":{"anyOf":[{"type":"number","description":"Preço base em R$."},{"type":"null"}]},"currency":{"type":"string"},"active":{"type":"boolean"},"requiresProfessional":{"type":"boolean"},"aiDescription":{"anyOf":[{"type":"string","description":"Texto seguro para os agentes responderem pacientes."},{"type":"null"}]},"rules":{"anyOf":[{"type":"string"},{"type":"null"}]},"demand":{"anyOf":[{"type":"integer","minimum":0,"maximum":8,"description":"Nível 0–8 (calculado por rotina da plataforma)."},{"type":"null"}]},"professionals":{"type":"array","items":{"$ref":"#/components/schemas/KeyName"}},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}},"title":"Service"},"AgentPreflight":{"type":"object","required":["policy_version","request_id","trace_id","clinic_id","agent_key","observed_at","observation_only","decision","authorized","send","gates"],"properties":{"policy_version":{"type":"string","enum":["f02-observation-v1"]},"request_id":{"type":"string"},"trace_id":{"type":"string"},"clinic_id":{"type":"string"},"agent_key":{"type":"string"},"observed_at":{"type":"string","format":"date-time"},"observation_only":{"type":"boolean","enum":[true]},"decision":{"type":"string","enum":["HOLD","DENY"],"description":"HOLD = há gate sem comprovação (UNVERIFIED); DENY = algum gate FAIL. Nunca ALLOW."},"authorized":{"type":"boolean","enum":[false]},"send":{"type":"boolean","enum":[false]},"gates":{"type":"array","items":{"$ref":"#/components/schemas/PreflightGate"}}},"additionalProperties":false,"title":"AgentPreflight"},"SatisfactionReport":{"type":"object","required":["period","media","avaliacoes","respostaPct","distribuicao","comentarios","benchmark","benchmarkLabel"],"properties":{"period":{"$ref":"#/components/schemas/Period"},"media":{"anyOf":[{"type":"number"},{"type":"null"}]},"avaliacoes":{"type":"integer"},"respostaPct":{"anyOf":[{"type":"number","description":"% dos atendimentos realizados que receberam nota."},{"type":"null"}]},"distribuicao":{"type":"array","items":{"type":"object","required":["estrelas","label","total","value"],"properties":{"estrelas":{"type":"integer","minimum":1,"maximum":5},"label":{"type":"string"},"total":{"type":"integer"},"value":{"anyOf":[{"type":"number","description":"%"},{"type":"null"}]}}}},"comentarios":{"type":"array","items":{"type":"object","required":["nota","texto","data","profissional"],"properties":{"nota":{"type":"integer"},"texto":{"type":"string"},"data":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","example":"2026-09-18"},"profissional":{"anyOf":[{"type":"string"},{"type":"null"}]}}}},"benchmark":{"anyOf":[{"type":"number"},{"type":"null"}]},"benchmarkLabel":{"anyOf":[{"type":"string"},{"type":"null"}]}},"title":"SatisfactionReport"},"OutboxEvent":{"type":"object","required":["id","event","eventId","status","attempts","nextAttemptAt","lastError","lastHttpStatus","createdAt","sentAt","traceId","refType","refId"],"properties":{"id":{"type":"string"},"event":{"type":"string","example":"message.received"},"eventId":{"type":"string","description":"UUID do envelope — estável entre reenvios (o consumidor deduplica por ele)."},"status":{"$ref":"#/components/schemas/OutboxEventStatus"},"attempts":{"type":"integer"},"nextAttemptAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"lastError":{"anyOf":[{"type":"string"},{"type":"null"}]},"lastHttpStatus":{"anyOf":[{"type":"integer"},{"type":"null"}]},"createdAt":{"type":"string","format":"date-time"},"sentAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"traceId":{"anyOf":[{"type":"string"},{"type":"null"}]},"refType":{"anyOf":[{"type":"string"},{"type":"null"}]},"refId":{"anyOf":[{"type":"string"},{"type":"null"}]}},"title":"OutboxEvent"},"Professional":{"type":"object","required":["id","key","name","specialty","status","room","calendarRef","hasCalendar","timezone","userId","services","createdAt","updatedAt"],"properties":{"id":{"type":"string"},"key":{"type":"string","description":"professional_key — nunca correlacionar com agentes pelo nome (PRD §1.10).","example":"renata"},"name":{"type":"string"},"specialty":{"anyOf":[{"type":"string"},{"type":"null"}]},"status":{"type":"string","enum":["ativo","inativo"]},"room":{"anyOf":[{"type":"string"},{"type":"null"}]},"calendarRef":{"anyOf":[{"type":"string","description":"Referência mascarada do calendário externo."},{"type":"null"}]},"hasCalendar":{"type":"boolean"},"timezone":{"anyOf":[{"type":"string"},{"type":"null"}]},"userId":{"anyOf":[{"type":"string"},{"type":"null"}]},"services":{"type":"array","items":{"$ref":"#/components/schemas/KeyName"}},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}},"title":"Professional"},"AuditSummary":{"type":"object","required":["total","critical","people","last","actors","actions","resources"],"properties":{"total":{"type":"integer"},"critical":{"type":"integer","description":"Eventos de nível alto."},"people":{"type":"integer","description":"Pessoas (humanos) com atividade no período."},"last":{"anyOf":[{"type":"object","required":["date","time","actorName"],"properties":{"date":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","examples":["2026-09-18"]},"time":{"type":"string"},"actorName":{"type":"string"}}},{"type":"null"}]},"actors":{"type":"array","items":{"type":"string"},"description":"Autores com eventos no período (filtro \"Usuário\")."},"actions":{"type":"array","items":{"type":"string","enum":["login","update","create","invite","configure","delete","view","reconcile","send","record_preview","revoke_access","reverse","change_role","export","approve","reject"]}},"resources":{"type":"array","items":{"type":"object","required":["key","label"],"properties":{"key":{"type":"string"},"label":{"type":"string"}}}}},"title":"AuditSummary"},"FinanceSeries":{"type":"object","required":["period","days","atrasadasQtd"],"properties":{"period":{"$ref":"#/components/schemas/FinanceSummaryPeriod"},"days":{"type":"array","items":{"type":"object","required":["date","recebido","emAberto"],"properties":{"date":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","example":"2026-09-18"},"recebido":{"type":"number","description":"Receitas do período recebidas até o dia (acumulado, R$)."},"emAberto":{"type":"number","description":"Saldo a receber no fim do dia: lançadas até o dia e ainda não pagas naquele dia (R$)."}}},"description":"Um ponto por dia, do início do período até hoje (ou o fim do período, se já passou)."},"atrasadasQtd":{"type":"integer","description":"Receitas do período hoje em atraso (a lista sai de /finance/transactions?status=atrasado)."}},"title":"FinanceSeries"},"Approval":{"type":"object","required":["id","agent","action","context","resourceType","resourceId","status","decidedBy","decidedAt","decisionNote","createdAt"],"properties":{"id":{"type":"string"},"agent":{"$ref":"#/components/schemas/AgentRef"},"action":{"type":"string"},"context":{"anyOf":[{"type":"string"},{"type":"null"}]},"resourceType":{"anyOf":[{"type":"string"},{"type":"null"}]},"resourceId":{"anyOf":[{"type":"string"},{"type":"null"}]},"status":{"type":"string","enum":["pendente","aprovado","rejeitado","expirado"]},"decidedBy":{"anyOf":[{"type":"string"},{"type":"null"}]},"decidedAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"decisionNote":{"anyOf":[{"type":"string"},{"type":"null"}]},"createdAt":{"type":"string","format":"date-time"}},"title":"Approval"},"KnowledgeArticleListItem":{"type":"object","required":["id","title","excerpt","type","typeLabel","category","categoryLabel","status","statusLabel","updatedAt","updatedBy","reviewStatus","usableByAgents"],"properties":{"id":{"type":"string"},"title":{"type":"string"},"excerpt":{"anyOf":[{"type":"string"},{"type":"null"}]},"type":{"type":"string","enum":["artigo","faq","protocolo","material"]},"typeLabel":{"type":"string"},"category":{"type":"string"},"categoryLabel":{"type":"string"},"status":{"type":"string","enum":["publicado","em_revisao","rascunho"]},"statusLabel":{"type":"string"},"updatedAt":{"type":"string","format":"date-time"},"updatedBy":{"anyOf":[{"type":"string"},{"type":"null"}]},"reviewStatus":{"type":"string","enum":["aprovado","pendente","reprovado"]},"usableByAgents":{"type":"boolean","description":"publicado + aprovado + safeForAi + dentro da validade."}},"title":"KnowledgeArticleListItem"},"AppointmentSummary":{"type":"object","required":["from","to","sessions","uniquePatients","notCancelledRate","byStatus","byProfessional"],"properties":{"from":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","example":"2026-09-18"},"to":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","example":"2026-09-18"},"sessions":{"type":"integer","description":"Consultas (exclui eventos internos)."},"uniquePatients":{"type":"integer"},"notCancelledRate":{"anyOf":[{"type":"number","description":"% de sessões não canceladas."},{"type":"null"}]},"byStatus":{"type":"object","additionalProperties":{"type":"integer"}},"byProfessional":{"type":"array","items":{"type":"object","required":["key","name","sessions"],"properties":{"key":{"type":"string"},"name":{"type":"string"},"sessions":{"type":"integer"}}}}},"title":"AppointmentSummary"},"FinanceUpcoming":{"type":"object","required":["id","kind","name","description","dueDate","dueInDays","amount","status","expenseKind"],"properties":{"id":{"type":"string"},"kind":{"type":"string","enum":["transacao","recorrente"]},"name":{"type":"string"},"description":{"anyOf":[{"type":"string"},{"type":"null"}]},"dueDate":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","example":"2026-09-18"},"dueInDays":{"type":"integer","description":"Negativo = vencido."},"amount":{"type":"number"},"status":{"anyOf":[{"type":"string"},{"type":"null"}]},"expenseKind":{"anyOf":[{"type":"string","enum":["aluguel","internet","sistema","outro"],"description":"A pagar: tipo da despesa (recorrente: kind; lançamento: category). null em recebimentos."},{"type":"null"}]}},"title":"FinanceUpcoming"},"ClinicalEvolution":{"type":"object","required":["id","date","title","kind","content","professional","authorName","appointmentId","createdAt"],"properties":{"id":{"type":"string"},"date":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","example":"2026-09-18"},"title":{"type":"string"},"kind":{"type":"string","enum":["evolucao","anamnese","outro"]},"content":{"anyOf":[{"type":"string"},{"type":"null"}]},"professional":{"anyOf":[{"$ref":"#/components/schemas/KeyName"},{"type":"null"}]},"authorName":{"anyOf":[{"type":"string"},{"type":"null"}]},"appointmentId":{"anyOf":[{"type":"string"},{"type":"null"}]},"createdAt":{"type":"string","format":"date-time"}},"title":"ClinicalEvolution"},"PatientTimelineEvent":{"type":"object","required":["id","kind","title","description","occurredAt","author","actorType","agent"],"properties":{"id":{"type":"string"},"kind":{"type":"string","example":"consulta"},"title":{"type":"string"},"description":{"anyOf":[{"type":"string"},{"type":"null"}]},"occurredAt":{"type":"string","format":"date-time"},"author":{"anyOf":[{"type":"string"},{"type":"null"}]},"actorType":{"anyOf":[{"type":"string","enum":["human","agent","system"]},{"type":"null"}]},"agent":{"anyOf":[{"$ref":"#/components/schemas/AgentRef"},{"type":"null"}]}},"title":"PatientTimelineEvent"},"KnowledgeCounts":{"type":"object","required":["all","total","byCategory","byStatus"],"properties":{"all":{"type":"integer","description":"Itens da base inteira (sem filtros) — 0 = base vazia."},"total":{"type":"integer","description":"Itens do tipo pedido (todas as categorias e situações)."},"byCategory":{"type":"array","items":{"type":"object","required":["id","name","count"],"properties":{"id":{"type":"string"},"name":{"type":"string"},"count":{"type":"integer"}}}},"byStatus":{"type":"object","required":["publicado","em_revisao","rascunho"],"properties":{"publicado":{"type":"integer"},"em_revisao":{"type":"integer"},"rascunho":{"type":"integer"}}}},"title":"KnowledgeCounts"},"SignupResult":{"type":"object","required":["clinicId","planId","cycle","trialEndsAt","created"],"properties":{"clinicId":{"type":"string","description":"Clínica criada. Com mais de um vínculo, envie em X-Clinic-Id.","example":"clin_3f9a1c2b7d4e5f60a1b2"},"planId":{"type":"string","example":"profissional"},"cycle":{"type":"string","enum":["mensal","anual"]},"trialEndsAt":{"anyOf":[{"type":"string","format":"date-time","description":"Fim do teste grátis do plano (null se a assinatura já foi ativada)."},{"type":"null"}]},"created":{"type":"boolean","description":"true = esta chamada criou a clínica (201); false = repetição (200, mesmos dados)."}},"title":"SignupResult"},"Invoice":{"type":"object","required":["id","date","description","amount","status","statusLabel","invoiceNumber","items","hasPdf"],"properties":{"id":{"type":"string"},"date":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","example":"2026-09-18"},"description":{"anyOf":[{"type":"string"},{"type":"null"}]},"amount":{"type":"number"},"status":{"type":"string","enum":["pago","a-pagar","atrasado"]},"statusLabel":{"type":"string"},"invoiceNumber":{"type":"string"},"items":{"type":"array","items":{"type":"object","required":["label","amount"],"properties":{"label":{"type":"string"},"amount":{"type":"number"}}}},"hasPdf":{"type":"boolean"}},"title":"Invoice"},"AgentRun":{"type":"object","required":["id","agentKey","title","detail","status","statusLabel","startedAt","finishedAt","retryable","traceId"],"properties":{"id":{"type":"string"},"agentKey":{"type":"string"},"title":{"type":"string"},"detail":{"anyOf":[{"type":"string"},{"type":"null"}]},"status":{"type":"string","enum":["sucesso","falha","aprovacao","humano","execucao"]},"statusLabel":{"type":"string"},"startedAt":{"type":"string","format":"date-time"},"finishedAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"retryable":{"type":"boolean"},"traceId":{"anyOf":[{"type":"string"},{"type":"null"}]}},"title":"AgentRun"},"SubscriptionActivated":{"type":"object","required":["clinicId","subscriptionId","planId","status","cycle","cycleStart","cycleEnd","activatedAt"],"properties":{"clinicId":{"type":"string"},"subscriptionId":{"type":"string"},"planId":{"type":"string"},"status":{"type":"string","enum":["ativa"]},"cycle":{"type":"string","enum":["mensal","anual"]},"cycleStart":{"type":"string","format":"date-time"},"cycleEnd":{"type":"string","format":"date-time","description":"Fim do primeiro ciclo pago (próxima cobrança)."},"activatedAt":{"type":"string","format":"date-time"}},"title":"SubscriptionActivated"},"DataRequest":{"type":"object","required":["id","kind","kindLabel","status","statusLabel","reason","requestedAt","completedAt"],"properties":{"id":{"type":"string"},"kind":{"type":"string","enum":["export","deletion"]},"kindLabel":{"type":"string"},"status":{"type":"string","enum":["solicitado","em_andamento","concluido","recusado"]},"statusLabel":{"type":"string"},"reason":{"anyOf":[{"type":"string"},{"type":"null"}]},"requestedAt":{"type":"string","format":"date-time"},"completedAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]}},"title":"DataRequest"},"LeadCounts":{"type":"object","required":["todos","novos","qualificados","ready","handoff","marcada","realizada"],"properties":{"todos":{"type":"integer"},"novos":{"type":"integer","description":"Etapa NEW."},"qualificados":{"type":"integer"},"ready":{"type":"integer","description":"Prontos para agendar."},"handoff":{"type":"integer","description":"Etapa HUMAN_HANDOFF (com a equipe)."},"marcada":{"type":"integer","description":"Consulta futura marcada."},"realizada":{"type":"integer","description":"Consulta realizada."}},"title":"LeadCounts"},"PatientSummary":{"type":"object","required":["total","ativos","novos","consultasRealizadas","taxaRetorno"],"properties":{"total":{"type":"integer"},"ativos":{"type":"integer"},"novos":{"type":"integer","description":"Cadastrados no mês corrente."},"consultasRealizadas":{"type":"integer","description":"Atendimentos realizados no mês corrente."},"taxaRetorno":{"anyOf":[{"type":"number","description":"% de pacientes com 2+ atendimentos realizados entre os que tiveram 1+ nos últimos 180 dias."},{"type":"null"}]}},"title":"PatientSummary"},"FinanceTotals":{"type":"object","required":["count","amount","byStatus"],"properties":{"count":{"type":"integer","description":"Lançamentos que atendem aos filtros."},"amount":{"type":"number","description":"Soma (R$) dos lançamentos filtrados."},"byStatus":{"type":"array","items":{"type":"object","required":["status","count","amount"],"properties":{"status":{"type":"string","enum":["recebido","pago","a-receber","a-pagar","atrasado","estornado"]},"count":{"type":"integer"},"amount":{"type":"number"}}}}},"title":"FinanceTotals"},"SignupStatus":{"type":"object","required":["enabled"],"properties":{"enabled":{"type":"boolean","description":"true = o autocadastro está aberto neste ambiente (POST /v1/signup aceita cadastros)."},"termsVersion":{"type":"string","description":"Versão vigente dos Termos de Uso, quando configurada no ambiente.","example":"2026-09"},"privacyVersion":{"type":"string","description":"Versão vigente da Política de Privacidade, quando configurada no ambiente.","example":"2026-09"}},"title":"SignupStatus","additionalProperties":false},"ActionMeta":{"type":"object","required":["webhooks"],"properties":{"webhooks":{"type":"array","items":{"$ref":"#/components/schemas/WebhookMeta"}}},"title":"ActionMeta"},"RecurringExpense":{"type":"object","required":["id","name","frequency","nextDueDate","amount","kind","active"],"properties":{"id":{"type":"string"},"name":{"type":"string"},"frequency":{"type":"string"},"nextDueDate":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","example":"2026-09-18"},"amount":{"type":"number"},"kind":{"type":"string","enum":["aluguel","internet","sistema","outro"]},"active":{"type":"boolean"}},"title":"RecurringExpense"},"FiscalSummary":{"type":"object","required":["mode","queue","ignored","documents"],"properties":{"mode":{"type":"string","enum":["simulacao","homologacao","producao"]},"queue":{"type":"integer","description":"Candidatos sem nota no modo atual (não ignorados)."},"ignored":{"type":"integer"},"documents":{"type":"object","description":"Notas do modo atual por status.","additionalProperties":{"type":"integer"}}},"title":"FiscalSummary"},"PatientCounts":{"type":"object","required":["todos","ativos","inativos","novos","com","sem"],"properties":{"todos":{"type":"integer"},"ativos":{"type":"integer"},"inativos":{"type":"integer"},"novos":{"type":"integer","description":"Cadastrados no mês corrente."},"com":{"type":"integer","description":"Com próxima sessão marcada."},"sem":{"type":"integer","description":"Sem próxima sessão marcada."}},"title":"PatientCounts"},"InboundMedia":{"type":"object","required":["type"],"properties":{"type":{"type":"string","enum":["image","audio","video","document","sticker","location","other"]},"url":{"type":"string","format":"uri","maxLength":2048,"description":"URL temporária do provedor (nunca binário)."},"caption":{"type":"string","maxLength":1000},"mimeType":{"type":"string","maxLength":100}},"additionalProperties":false,"title":"InboundMedia"},"PageMeta":{"type":"object","required":["hasNext","nextCursor","total","limit"],"properties":{"hasNext":{"type":"boolean"},"nextCursor":{"anyOf":[{"type":"string","description":"Passe em ?cursor= para a próxima página."},{"type":"null"}]},"total":{"anyOf":[{"type":"integer","description":"Total de itens que atendem ao filtro (quando disponível)."},{"type":"null"}]},"limit":{"type":"integer"}},"title":"PageMeta"},"ClinicUserCounts":{"type":"object","required":["total","byStatus"],"properties":{"total":{"type":"integer","description":"Todos os vínculos (inclui convites e acessos revogados)."},"byStatus":{"type":"object","required":["ativo","pendente","inativo","revogado"],"properties":{"ativo":{"type":"integer"},"pendente":{"type":"integer"},"inativo":{"type":"integer"},"revogado":{"type":"integer"}}}},"title":"ClinicUserCounts"},"PatientTask":{"type":"object","required":["id","label","done","dueAt","completedAt","createdAt"],"properties":{"id":{"type":"string"},"label":{"type":"string"},"done":{"type":"boolean"},"dueAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"completedAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"createdAt":{"type":"string","format":"date-time"}},"title":"PatientTask"},"IntegrationLog":{"type":"object","required":["id","title","detail","kind","origin","occurredAt"],"properties":{"id":{"type":"string"},"title":{"type":"string"},"detail":{"anyOf":[{"type":"string"},{"type":"null"}]},"kind":{"type":"string","enum":["ok","info","erro"]},"origin":{"anyOf":[{"type":"string"},{"type":"null"}]},"occurredAt":{"type":"string","format":"date-time"}},"title":"IntegrationLog"},"ConversationCounts":{"type":"object","required":["all","unread","mine","archived","unreadByChannel"],"properties":{"all":{"type":"integer"},"unread":{"type":"integer"},"mine":{"type":"integer"},"archived":{"type":"integer"},"unreadByChannel":{"type":"object","description":"Canal → conversas não lidas; `total` = soma.","additionalProperties":{"type":"integer"}}},"title":"ConversationCounts"},"AvailabilityWindow":{"type":"object","required":["weekday","start","end"],"properties":{"weekday":{"type":"integer","minimum":0,"maximum":6,"description":"0 = domingo."},"start":{"type":"string","pattern":"^([01]\\d|2[0-3]):[0-5]\\d$","example":"14:00"},"end":{"type":"string","pattern":"^([01]\\d|2[0-3]):[0-5]\\d$","example":"14:00"}},"title":"AvailabilityWindow"},"FiscalSyncResult":{"type":"object","required":["created","existing","skipped"],"properties":{"created":{"type":"integer"},"existing":{"type":"integer"},"skipped":{"type":"array","items":{"type":"object","required":["reason","count"],"properties":{"reason":{"type":"string"},"count":{"type":"integer"}}}}},"title":"FiscalSyncResult"},"SeriesPoint":{"type":"object","required":["label","value"],"properties":{"label":{"type":"string","description":"YYYY-MM ou YYYY-MM-DD"},"value":{"anyOf":[{"type":"number"},{"type":"null"}]},"benchmark":{"anyOf":[{"type":"number"},{"type":"null"}]}},"title":"SeriesPoint"},"LeadPatchLabelIds":{"type":"array","items":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9._-]+$"},"maxItems":5,"description":"Ids do catálogo GET /leads/labels (até 5). Lista vazia limpa. Substitui a lista inteira."},"BillingCancellationUndo":{"type":"object","required":["status","nextChargeAt"],"properties":{"status":{"type":"string"},"nextChargeAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]}},"title":"BillingCancellationUndo"},"AppointmentAttention":{"type":"object","required":["from","total","awaitingApproval"],"properties":{"from":{"type":"string"},"total":{"type":"integer"},"awaitingApproval":{"type":"integer"}},"title":"AppointmentAttention"},"BillingPlanChangeUndo":{"type":"object","required":["planId","pendingPlanId"],"properties":{"planId":{"type":"string"},"pendingPlanId":{"anyOf":[{"type":"string"},{"type":"null"}]}},"title":"BillingPlanChangeUndo"},"FiscalWebhookResult":{"type":"object","required":["status"],"properties":{"status":{"type":"string","enum":["processado","duplicado","ignorado","erro"]}},"title":"FiscalWebhookResult"},"LabelValue":{"type":"object","required":["label","value"],"properties":{"label":{"type":"string"},"value":{"anyOf":[{"type":"number"},{"type":"null"}]}},"title":"LabelValue"},"LeadForecastMonth":{"type":"object","required":["month","label","total","valueTotal","withValue","byStage","items","nextCursor"],"properties":{"month":{"type":"string","pattern":"^\\d{4}-\\d{2}$","example":"2026-10"},"label":{"type":"string","description":"Mês por extenso (pt-BR), ex.: \"outubro de 2026\"."},"total":{"type":"integer","description":"Leads abertos com fechamento previsto no mês."},"valueTotal":{"type":"number","description":"Soma de estimatedValue (R$) do mês."},"withValue":{"type":"integer"},"byStage":{"type":"array","items":{"type":"object","required":["stage","label","count","valueTotal"],"properties":{"stage":{"type":"string","enum":["NEW","DISCOVERY","QUALIFIED","READY_TO_SCHEDULE","SCHEDULED","COMPLETED","NURTURE","NOT_A_FIT","HUMAN_HANDOFF"]},"label":{"type":"string"},"count":{"type":"integer"},"valueTotal":{"type":"number"}}}},"items":{"type":"array","items":{"$ref":"#/components/schemas/Lead"},"description":"Primeiros leads do mês (fechamento mais próximo primeiro)."},"nextCursor":{"anyOf":[{"type":"string","description":"Para \"ver mais\": GET /leads?stage=<abertas>&closeFrom=<1º dia>&closeTo=<último dia>&sort=expectedCloseDate&cursor=<nextCursor> com os mesmos filtros."},{"type":"null"}]}},"title":"LeadForecastMonth"},"Appointment":{"type":"object","required":["id","date","start","end","durationMin","startsAt","kind","patient","patientId","leadId","professional","service","status","statusLabel","outcome","origin","modality","room","agent","notes","reason","nextSteps","clinicalRedacted","tags","cancelReason","rescheduledFrom","rating","createdAt","updatedAt"],"properties":{"id":{"type":"string"},"date":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","description":"Data local da clínica.","example":"2026-09-18"},"start":{"type":"string","pattern":"^([01]\\d|2[0-3]):[0-5]\\d$","example":"14:00"},"end":{"type":"string","pattern":"^([01]\\d|2[0-3]):[0-5]\\d$","example":"14:00"},"durationMin":{"type":"integer"},"startsAt":{"anyOf":[{"type":"string","format":"date-time","description":"Instante UTC do início."},{"type":"null"}]},"kind":{"type":"string","enum":["consulta","interno"]},"patient":{"type":"string","description":"Nome do paciente (consulta) ou título (evento interno)."},"patientId":{"anyOf":[{"type":"string"},{"type":"null"}]},"leadId":{"anyOf":[{"type":"string"},{"type":"null"}]},"professional":{"anyOf":[{"$ref":"#/components/schemas/KeyName"},{"type":"null"}]},"service":{"anyOf":[{"$ref":"#/components/schemas/KeyName"},{"type":"null"}]},"status":{"type":"string","enum":["agendado","confirmado","pendente","em_andamento","realizado","cancelado","remarcacao","faltou"]},"statusLabel":{"type":"string"},"outcome":{"anyOf":[{"type":"string","enum":["ATTENDED","NO_SHOW","CANCELLED","RESCHEDULED"]},{"type":"null"}]},"origin":{"type":"string","enum":["agente","manual","google","site","instagram"]},"modality":{"type":"string","enum":["presencial","online"]},"room":{"anyOf":[{"type":"string"},{"type":"null"}]},"agent":{"anyOf":[{"type":"object","required":["agentKey","name","image","state","at","note"],"properties":{"agentKey":{"type":"string"},"name":{"type":"string"},"image":{"anyOf":[{"type":"string"},{"type":"null"}]},"state":{"type":"string","enum":["agendado","confirmado","sugestao","aguardando_aprovacao","escalado"]},"at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"note":{"anyOf":[{"type":"string"},{"type":"null"}]}}},{"type":"null"}]},"notes":{"anyOf":[{"type":"string","description":"Observações operacionais da sessão (recepção/equipe). Visíveis com schedule:read."},{"type":"null"}]},"reason":{"anyOf":[{"type":"string","description":"Clínico — null sem clinical:read."},{"type":"null"}]},"nextSteps":{"anyOf":[{"type":"array","items":{"type":"object","required":["label","done"],"properties":{"label":{"type":"string"},"done":{"type":"boolean"}}}},{"type":"null"}]},"clinicalRedacted":{"type":"boolean","description":"true = campos clínicos ocultados para o perfil atual."},"tags":{"type":"array","items":{"type":"string"}},"cancelReason":{"anyOf":[{"type":"string"},{"type":"null"}]},"rescheduledFrom":{"anyOf":[{"type":"object","required":["date","start","end"],"properties":{"date":{"type":"string"},"start":{"type":"string"},"end":{"type":"string"}}},{"type":"null"}]},"rating":{"anyOf":[{"$ref":"#/components/schemas/AppointmentRating"},{"type":"null"}]},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}},"title":"Appointment"},"Automation":{"type":"object","required":["id","name","summary","about","category","categoryLabel","highlight","price","agent","benefits","potential","potentialLabel","settings","subscription","trialAvailable"],"properties":{"id":{"type":"string"},"name":{"type":"string"},"summary":{"anyOf":[{"type":"string"},{"type":"null"}]},"about":{"anyOf":[{"type":"string"},{"type":"null"}]},"category":{"type":"string"},"categoryLabel":{"type":"string"},"highlight":{"anyOf":[{"type":"string","enum":["premium","recomendada"]},{"type":"null"}]},"price":{"type":"number","description":"R$/mês."},"agent":{"anyOf":[{"$ref":"#/components/schemas/AgentRef"},{"type":"null"}]},"benefits":{"type":"array","items":{"type":"string"}},"potential":{"anyOf":[{"type":"number"},{"type":"null"}]},"potentialLabel":{"anyOf":[{"type":"string"},{"type":"null"}]},"settings":{"type":"array","items":{"$ref":"#/components/schemas/AutomationSetting"}},"subscription":{"anyOf":[{"$ref":"#/components/schemas/AutomationSubscription"},{"type":"null"}]},"trialAvailable":{"type":"boolean"}},"title":"Automation"},"OutboxEvent2":{"type":"object","required":["id","event","eventId","status","attempts","nextAttemptAt","lastError","lastHttpStatus","createdAt","sentAt","traceId","refType","refId"],"properties":{"id":{"type":"string"},"event":{"type":"string","examples":["message.received"]},"eventId":{"type":"string","description":"UUID do envelope — estável entre reenvios (o consumidor deduplica por ele)."},"status":{"$ref":"#/components/schemas/OutboxEventStatus"},"attempts":{"type":"integer"},"nextAttemptAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"lastError":{"anyOf":[{"type":"string"},{"type":"null"}]},"lastHttpStatus":{"anyOf":[{"type":"integer"},{"type":"null"}]},"createdAt":{"type":"string","format":"date-time"},"sentAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"traceId":{"anyOf":[{"type":"string"},{"type":"null"}]},"refType":{"anyOf":[{"type":"string"},{"type":"null"}]},"refId":{"anyOf":[{"type":"string"},{"type":"null"}]}},"title":"OutboxEvent"},"ClinicUser":{"type":"object","required":["id","userId","name","email","role","roleLabel","status","joinedAt","lastAccessAt","isCurrent","professionalKey","extraPermissions","invitationId","invitationExpiresAt"],"properties":{"id":{"type":"string","description":"Id do vínculo (membership)."},"userId":{"anyOf":[{"type":"string","description":"Id do usuário no provedor de identidade (null enquanto o convite está pendente)."},{"type":"null"}]},"name":{"type":"string"},"email":{"type":"string"},"role":{"type":"string","enum":["admin","profissional","recepcao","financeiro","marketing","suporte","estagiario"]},"roleLabel":{"type":"string"},"status":{"type":"string","enum":["ativo","pendente","inativo","revogado"],"description":"ativo | pendente (convite) | inativo (suspenso) | revogado"},"joinedAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"lastAccessAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"isCurrent":{"type":"boolean"},"professionalKey":{"anyOf":[{"type":"string"},{"type":"null"}]},"extraPermissions":{"type":"array","items":{"type":"string"}},"invitationId":{"anyOf":[{"type":"string"},{"type":"null"}]},"invitationExpiresAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]}},"title":"ClinicUser"},"Conversation":{"type":"object","required":["id","name","channel","preview","lastMessageAt","unread","mine","assignedTo","archived","activeAgent","patientId","leadId","tags"],"properties":{"id":{"type":"string"},"name":{"type":"string"},"channel":{"type":"string","enum":["whatsapp","email","sms","instagram","outros"]},"preview":{"anyOf":[{"type":"string"},{"type":"null"}]},"lastMessageAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"unread":{"type":"integer"},"mine":{"type":"boolean","description":"Conversa atribuída ao usuário atual."},"assignedTo":{"anyOf":[{"type":"object","required":["id","name"],"properties":{"id":{"type":"string"},"name":{"type":"string"}}},{"type":"null"}]},"archived":{"type":"boolean"},"activeAgent":{"anyOf":[{"$ref":"#/components/schemas/AgentRef"},{"type":"null"}]},"patientId":{"anyOf":[{"type":"string"},{"type":"null"}]},"leadId":{"anyOf":[{"type":"string"},{"type":"null"}]},"tags":{"type":"array","items":{"type":"string"}}},"title":"Conversation"},"Message":{"type":"object","required":["id","from","text","sentAt","agent","authorName","read","delivery"],"properties":{"id":{"type":"string"},"from":{"type":"string","enum":["patient","clinic","system"]},"text":{"type":"string"},"sentAt":{"type":"string","format":"date-time"},"agent":{"anyOf":[{"$ref":"#/components/schemas/AgentRef"},{"type":"null"}]},"authorName":{"anyOf":[{"type":"string"},{"type":"null"}]},"read":{"type":"boolean"},"delivery":{"anyOf":[{"type":"string","enum":["enviando","entregue","lido","falhou","registrado"],"description":"enviando = entregue ao motor de automação, aguardando confirmação; registrado = gravada no histórico sem envio (envio automático desligado); falhou = o motor de automação não aceitou o envio."},{"type":"null"}]}},"title":"Message"},"FiscalEmitter":{"type":"object","required":["legalName","tradeName","cnpj","municipalRegistration","cityIbge","cityName","uf","addressStreet","addressNumber","addressDistrict","addressZip"],"properties":{"legalName":{"anyOf":[{"type":"string"},{"type":"null"}]},"tradeName":{"anyOf":[{"type":"string"},{"type":"null"}]},"cnpj":{"anyOf":[{"type":"string"},{"type":"null"}]},"municipalRegistration":{"anyOf":[{"type":"string"},{"type":"null"}]},"cityIbge":{"anyOf":[{"type":"string"},{"type":"null"}]},"cityName":{"anyOf":[{"type":"string"},{"type":"null"}]},"uf":{"anyOf":[{"type":"string"},{"type":"null"}]},"addressStreet":{"anyOf":[{"type":"string"},{"type":"null"}]},"addressNumber":{"anyOf":[{"type":"string"},{"type":"null"}]},"addressDistrict":{"anyOf":[{"type":"string"},{"type":"null"}]},"addressZip":{"anyOf":[{"type":"string"},{"type":"null"}]}},"title":"FiscalEmitter"},"BillingProfile":{"type":"object","required":["cycle","invoiceEmail","invoiceEmailEnabled","reminderDays","reminderEnabled","legalName","cnpj"],"properties":{"cycle":{"type":"string","description":"Frequência de cobrança do plano: Mensal | Anual (automações seguem mensais)."},"invoiceEmail":{"anyOf":[{"type":"string"},{"type":"null"}]},"invoiceEmailEnabled":{"type":"boolean","description":"Receber notas fiscais por e-mail (padrão true)."},"reminderDays":{"type":"integer"},"reminderEnabled":{"type":"boolean","description":"Lembrete de vencimento reminderDays dias antes da fatura (padrão true)."},"legalName":{"anyOf":[{"type":"string"},{"type":"null"}]},"cnpj":{"anyOf":[{"type":"string"},{"type":"null"}]}},"title":"BillingProfile"},"PreflightGate":{"type":"object","required":["gate","status","reason"],"properties":{"gate":{"type":"string","enum":["REQUEST_CONTRACT","CLINIC_IDENTITY","CLINIC_STATUS","AGENT_IDENTITY","AGENT_ENABLED","AGENT_STATUS","SERVICE_ALLOWED","AUTOMATION_ALLOWED","CONSENT","USAGE_LIMITS","HUMAN_TAKEOVER","PURPOSE_ALLOWED","CAPABILITIES_ALLOWED","CHANNEL_ALLOWED","IDEMPOTENCY_LOCK","CANONICAL_AUTHORIZATION"]},"status":{"type":"string","enum":["PASS","FAIL","UNVERIFIED"]},"reason":{"type":"string","description":"Código estável (sem dados pessoais)."}},"additionalProperties":false,"title":"PreflightGate"},"PricingPreview":{"type":"object","required":["monthly","nextInvoiceAmount","proRataDays","cycleDays","trialEndsAt","noticeAt","terms"],"properties":{"monthly":{"type":"number"},"nextInvoiceAmount":{"type":"number","description":"Valor que entra na próxima fatura."},"proRataDays":{"type":"integer"},"cycleDays":{"type":"integer"},"trialEndsAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"noticeAt":{"anyOf":[{"type":"string","format":"date-time","description":"Quando avisaremos antes do fim do teste."},{"type":"null"}]},"terms":{"type":"string"}},"title":"PricingPreview"},"FiscalAttempt":{"type":"object","required":["id","kind","outcome","startedAt","durationMs","httpStatus","providerStatus","errorCode","errorMessage"],"properties":{"id":{"type":"string"},"kind":{"type":"string"},"outcome":{"type":"string"},"startedAt":{"type":"string"},"durationMs":{"anyOf":[{"type":"integer"},{"type":"null"}]},"httpStatus":{"anyOf":[{"type":"integer"},{"type":"null"}]},"providerStatus":{"anyOf":[{"type":"string"},{"type":"null"}]},"errorCode":{"anyOf":[{"type":"string"},{"type":"null"}]},"errorMessage":{"anyOf":[{"type":"string"},{"type":"null"}]}},"title":"FiscalAttempt"},"Address":{"type":"object","required":["street","district","zip","city","state","country"],"properties":{"street":{"anyOf":[{"type":"string","maxLength":160},{"type":"null"}]},"district":{"anyOf":[{"type":"string","maxLength":80},{"type":"null"}]},"zip":{"anyOf":[{"type":"string","maxLength":10,"examples":["14400-000"]},{"type":"null"}]},"city":{"anyOf":[{"type":"string","maxLength":80},{"type":"null"}]},"state":{"anyOf":[{"type":"string","maxLength":2,"examples":["SP"]},{"type":"null"}]},"country":{"anyOf":[{"type":"string","maxLength":2},{"type":"null"}]}},"title":"Address"},"FiscalBatchItem":{"type":"object","required":["candidateId","serviceKey","serviceName","serviceDate","amount","takerName","takerCpfMasked","ruleVersion","ruleStatus"],"properties":{"candidateId":{"type":"string"},"serviceKey":{"anyOf":[{"type":"string"},{"type":"null"}]},"serviceName":{"anyOf":[{"type":"string"},{"type":"null"}]},"serviceDate":{"type":"string"},"amount":{"type":"number"},"takerName":{"type":"string"},"takerCpfMasked":{"anyOf":[{"type":"string"},{"type":"null"}]},"ruleVersion":{"type":"integer"},"ruleStatus":{"type":"string"}},"title":"FiscalBatchItem"},"Contact":{"type":"object","required":["phone","email","age","birthDate","address","active","isPatient"],"properties":{"phone":{"anyOf":[{"type":"string"},{"type":"null"}]},"email":{"anyOf":[{"type":"string"},{"type":"null"}]},"age":{"anyOf":[{"type":"integer"},{"type":"null"}]},"birthDate":{"anyOf":[{"type":"string"},{"type":"null"}]},"address":{"anyOf":[{"type":"string"},{"type":"null"}]},"active":{"type":"boolean","description":"Paciente ativo (false = lead ou paciente inativo)."},"isPatient":{"type":"boolean"}},"title":"Contact"},"FiscalIssue":{"type":"object","required":["code","message","field","blocks","blocksCurrentMode"],"properties":{"code":{"type":"string"},"message":{"type":"string"},"field":{"anyOf":[{"type":"string","description":"Campo a corrigir na revisão (null = regra, configuração ou origem)."},{"type":"null"}]},"blocks":{"type":"array","items":{"type":"string","enum":["simulacao","homologacao","producao"]},"description":"Modos em que a pendência impede a emissão."},"blocksCurrentMode":{"type":"boolean"}},"title":"FiscalIssue"},"FiscalModeState":{"type":"object","required":["mode","label","available","blockers"],"properties":{"mode":{"type":"string","enum":["simulacao","homologacao","producao"]},"label":{"type":"string"},"available":{"type":"boolean","description":"true = nada bloqueia este modo agora."},"blockers":{"type":"array","items":{"type":"object","required":["key","label","reason"],"properties":{"key":{"type":"string"},"label":{"type":"string"},"reason":{"type":"string"}}}}},"title":"FiscalModeState"},"UsageRow":{"type":"object","required":["key","label","used","unit","limit","percent","fairUse"],"properties":{"key":{"type":"string","enum":["patients","appointments","messages","storage"]},"label":{"type":"string"},"used":{"anyOf":[{"type":"number"},{"type":"null"}]},"unit":{"anyOf":[{"type":"string"},{"type":"null"}]},"limit":{"anyOf":[{"type":"number"},{"type":"null"}]},"percent":{"anyOf":[{"type":"integer"},{"type":"null"}]},"fairUse":{"type":"boolean"}},"title":"UsageRow"},"Benchmarks":{"type":"object","required":["label","retorno","inadimplencia","satisfacao"],"properties":{"label":{"type":"string","examples":["Clínicas do mesmo porte (plano Profissional)"]},"retorno":{"anyOf":[{"type":"number"},{"type":"null"}]},"inadimplencia":{"anyOf":[{"type":"number"},{"type":"null"}]},"satisfacao":{"anyOf":[{"type":"number"},{"type":"null"}]}},"title":"Benchmarks","description":"Referência da plataforma para clínicas do mesmo plano."},"FiscalGateEntry":{"type":"object","required":["item","label","attested","byName","at","evidence","validUntil"],"properties":{"item":{"type":"string"},"label":{"type":"string"},"attested":{"type":"boolean"},"byName":{"anyOf":[{"type":"string"},{"type":"null"}]},"at":{"anyOf":[{"type":"string"},{"type":"null"}]},"evidence":{"anyOf":[{"type":"string"},{"type":"null"}]},"validUntil":{"anyOf":[{"type":"string"},{"type":"null"}]}},"title":"FiscalGateEntry"},"AgentConfig":{"type":"object","required":["schedule","dailyLimit","approvalRequired","tone"],"properties":{"schedule":{"anyOf":[{"type":"string","examples":["Seg a sáb · 08:00–20:00"]},{"type":"null"}]},"dailyLimit":{"anyOf":[{"type":"string","examples":["400 mensagens/dia"]},{"type":"null"}]},"approvalRequired":{"type":"boolean"},"tone":{"anyOf":[{"type":"string","examples":["Acolhedor e objetivo"]},{"type":"null"}]}},"title":"AgentConfig"},"FiscalReadinessArea":{"type":"object","required":["key","label","state","blocks","reason","action"],"properties":{"key":{"type":"string"},"label":{"type":"string"},"state":{"type":"string","enum":["ok","pendente","atencao"]},"blocks":{"type":"array","items":{"type":"string","enum":["simulacao","homologacao","producao"]}},"reason":{"type":"string"},"action":{"type":"string"}},"title":"FiscalReadinessArea"},"LeadValueTotals":{"type":"object","required":["total","valueTotal","withValue"],"properties":{"total":{"type":"integer","description":"Leads com os filtros aplicados."},"valueTotal":{"type":"number","description":"Soma de estimatedValue (R$). Só leads com valor."},"withValue":{"type":"integer","description":"Quantos têm valor estimado."}},"title":"LeadValueTotals"},"FiscalDocumentDetailCancel":{"anyOf":[{"type":"object","required":["reason","requestedAt","cancelledAt"],"properties":{"reason":{"anyOf":[{"type":"string"},{"type":"null"}]},"requestedAt":{"anyOf":[{"type":"string"},{"type":"null"}]},"cancelledAt":{"anyOf":[{"type":"string"},{"type":"null"}]}}},{"type":"null"}]},"IntegrationScope":{"type":"object","required":["id","label","description","default"],"properties":{"id":{"type":"string"},"label":{"type":"string"},"description":{"type":"string"},"required":{"type":"boolean"},"sensitive":{"type":"boolean"},"default":{"type":"boolean"}},"title":"IntegrationScope"},"FiscalSettingsApproval":{"anyOf":[{"type":"object","required":["byName","evidence","at","recordedBy"],"properties":{"byName":{"type":"string"},"evidence":{"anyOf":[{"type":"string"},{"type":"null"}]},"at":{"type":"string"},"recordedBy":{"anyOf":[{"type":"string"},{"type":"null"}]}}},{"type":"null"}]},"Period":{"type":"object","required":["from","to"],"properties":{"from":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","example":"2026-09-18"},"to":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","example":"2026-09-18"}},"title":"Period"},"FiscalDocumentDetailRule":{"type":"object","required":["id","version","status"],"properties":{"id":{"anyOf":[{"type":"string"},{"type":"null"}]},"version":{"anyOf":[{"type":"integer"},{"type":"null"}]},"status":{"anyOf":[{"type":"string"},{"type":"null"}]}}},"FinanceSummaryPeriod":{"type":"object","required":["from","to"],"properties":{"from":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","example":"2026-09-18"},"to":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","example":"2026-09-18"}}},"FiscalDocumentDetailFiles":{"type":"array","items":{"type":"object","required":["kind","sha256","size"],"properties":{"kind":{"type":"string","enum":["xml","pdf"]},"sha256":{"type":"string"},"size":{"anyOf":[{"type":"integer"},{"type":"null"}]}}}},"KnowledgeStep":{"type":"object","required":["title","text"],"properties":{"title":{"type":"string","maxLength":160},"text":{"type":"string","maxLength":2000}},"title":"KnowledgeStep"},"Lead":{"type":"object","required":["id","name","age","sex","phone","email","city","source","sourceLabel","channel","service","stage","stageLabel","score","qualified","ready","appointment","appointmentAt","appointmentId","professional","lastInteractionAt","lastInteractionMin","nextAction","owner","agent","note","patientId","conversationId","estimatedValue","labels","expectedCloseDate","createdAt","createdDaysAgo"],"properties":{"id":{"type":"string"},"name":{"type":"string"},"age":{"anyOf":[{"type":"integer","description":"null = \"Idade a completar\"."},{"type":"null"}]},"sex":{"anyOf":[{"type":"string"},{"type":"null"}]},"phone":{"anyOf":[{"type":"string"},{"type":"null"}]},"email":{"anyOf":[{"type":"string"},{"type":"null"}]},"city":{"anyOf":[{"type":"string"},{"type":"null"}]},"source":{"anyOf":[{"type":"string","enum":["META_ADS","GOOGLE","INSTAGRAM","FECHADA","INFLUENCER","INDICACAO"]},{"type":"null"}]},"sourceLabel":{"anyOf":[{"type":"string"},{"type":"null"}]},"channel":{"anyOf":[{"type":"string","enum":["WhatsApp","Instagram","Site","E-mail","Telefone"]},{"type":"null"}]},"service":{"anyOf":[{"$ref":"#/components/schemas/KeyName"},{"type":"null"}]},"stage":{"type":"string","enum":["NEW","DISCOVERY","QUALIFIED","READY_TO_SCHEDULE","SCHEDULED","COMPLETED","NURTURE","NOT_A_FIT","HUMAN_HANDOFF"]},"stageLabel":{"type":"string"},"score":{"anyOf":[{"type":"integer","minimum":0,"maximum":100},{"type":"null"}]},"qualified":{"type":"boolean"},"ready":{"type":"boolean","description":"ready_to_schedule"},"appointment":{"anyOf":[{"type":"string","enum":["agendado","realizado"]},{"type":"null"}]},"appointmentAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"appointmentId":{"anyOf":[{"type":"string"},{"type":"null"}]},"professional":{"anyOf":[{"$ref":"#/components/schemas/KeyName"},{"type":"null"}]},"lastInteractionAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"lastInteractionMin":{"anyOf":[{"type":"integer","description":"Minutos desde a última interação."},{"type":"null"}]},"nextAction":{"anyOf":[{"type":"object","required":["label","at","actionable"],"properties":{"label":{"type":"string"},"at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"actionable":{"type":"boolean"}}},{"type":"null"}]},"owner":{"anyOf":[{"type":"object","required":["type","id","name"],"properties":{"type":{"type":"string","enum":["human","agent"]},"id":{"anyOf":[{"type":"string"},{"type":"null"}]},"name":{"type":"string"}}},{"type":"null"}]},"agent":{"anyOf":[{"$ref":"#/components/schemas/AgentRef"},{"type":"null"}]},"note":{"anyOf":[{"type":"string","description":"Motivo da etapa (ex.: \"Fora do perfil\", transferência)."},{"type":"null"}]},"patientId":{"anyOf":[{"type":"string"},{"type":"null"}]},"conversationId":{"anyOf":[{"type":"string"},{"type":"null"}]},"estimatedValue":{"anyOf":[{"type":"number","minimum":0,"description":"Valor estimado da oportunidade em R$ (no banco: centavos). null = sem valor."},{"type":"null"}]},"labels":{"type":"array","items":{"$ref":"#/components/schemas/LeadLabel"},"description":"Etiquetas do catálogo da clínica (até 5), na ordem escolhida."},"expectedCloseDate":{"anyOf":[{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","examples":["2026-09-18"],"description":"Data prevista de fechamento (sem hora)."},{"type":"null"}]},"createdAt":{"type":"string","format":"date-time"},"createdDaysAgo":{"type":"integer"}},"title":"Lead"},"IntegrationConnection":{"type":"object","required":["status","account","connectedAt","connectedBy","lastActivityAt","lastHealthcheckAt","lastErrorCode"],"properties":{"status":{"type":"string","enum":["conectando","ativa","pausada","erro","desconectada"]},"account":{"anyOf":[{"type":"string"},{"type":"null"}]},"connectedAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"connectedBy":{"anyOf":[{"type":"string"},{"type":"null"}]},"lastActivityAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"lastHealthcheckAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"lastErrorCode":{"anyOf":[{"type":"string"},{"type":"null"}]}},"title":"IntegrationConnection"},"FiscalTakerAddress":{"type":"object","required":["street","number","district","zip","cityIbge","uf"],"properties":{"street":{"type":"string","minLength":2,"maxLength":160},"number":{"type":"string","minLength":1,"maxLength":20},"complement":{"anyOf":[{"type":"string","maxLength":60},{"type":"null"}]},"district":{"type":"string","minLength":2,"maxLength":80},"zip":{"type":"string","pattern":"^\\d{5}-?\\d{3}$"},"cityIbge":{"type":"string","pattern":"^\\d{7}$"},"cityName":{"anyOf":[{"type":"string","maxLength":80},{"type":"null"}]},"uf":{"type":"string","pattern":"^[A-Z]{2}$"}},"title":"FiscalTakerAddress"},"BillingQuoteRequest":{"type":"object","required":["planId","planName","requestedAt","status"],"properties":{"planId":{"type":"string"},"planName":{"type":"string"},"requestedAt":{"type":"string","format":"date-time"},"status":{"type":"string","enum":["solicitada","em_contato","concluida","cancelada"]}},"title":"BillingQuoteRequest","description":"Pedido de proposta de plano sob consulta (ex.: Rede de clínicas). Não altera o plano."},"AppointmentRating":{"type":"object","required":["score","comment","at","channel"],"properties":{"score":{"type":"integer","minimum":1,"maximum":5},"comment":{"anyOf":[{"type":"string"},{"type":"null"}]},"at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"channel":{"anyOf":[{"type":"string"},{"type":"null"}]}},"title":"AppointmentRating","description":"Pesquisa de satisfação pós-atendimento (nota 1–5)."},"WebhookMeta":{"type":"object","required":["event","status"],"properties":{"event":{"type":"string","example":"appointment.cancelled"},"status":{"type":"string","enum":["sent","failed","disabled"],"description":"sent = o motor de automação respondeu 2xx; failed = erro/timeout (a operação no banco já foi feita); disabled = motor de automação não configurado."}},"title":"WebhookMeta"},"OutboxEventStatus":{"type":"string","enum":["pending","sent","failed","dead","disabled"],"description":"pending = aguardando 1º envio; sent = o motor de automação respondeu 2xx; failed = falhou, nova tentativa em nextAttemptAt; dead = desistiu após o máximo de tentativas; disabled = motor de automação não configurado (sandbox, sem reenvio automático)."},"AutomationSubscription":{"type":"object","required":["status","since","trialEndsAt","trialDaysLeft","activeUntil","settings","cycleCharge"],"properties":{"status":{"type":"string","enum":["ativa","teste","cancelada"]},"since":{"type":"string","format":"date-time"},"trialEndsAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]},"trialDaysLeft":{"anyOf":[{"type":"integer"},{"type":"null"}]},"activeUntil":{"anyOf":[{"type":"string","format":"date-time","description":"Cancelada: vale até esta data (fim do ciclo cobrado)."},{"type":"null"}]},"settings":{"type":"object","additionalProperties":{"anyOf":[{"type":"boolean"},{"type":"string"}]}},"cycleCharge":{"type":"number","description":"Valor que entra na próxima fatura (R$), proporcional quando aplicável."}},"title":"AutomationSubscription"},"AutomationSetting":{"type":"object","required":["id","kind","label","default"],"properties":{"id":{"type":"string"},"kind":{"type":"string","enum":["toggle","choice"]},"label":{"type":"string"},"description":{"type":"string"},"options":{"type":"array","items":{"type":"string"}},"default":{"anyOf":[{"type":"boolean"},{"type":"string"}]}},"title":"AutomationSetting"},"LeadLabel":{"type":"object","required":["id","name","color"],"properties":{"id":{"type":"string"},"name":{"type":"string"},"color":{"type":"string","enum":["blue","green","amber","red","violet","pink","teal","slate"],"description":"Cor da paleta fechada."}},"title":"LeadLabel"},"AgentRef":{"type":"object","required":["key","name","image"],"properties":{"key":{"type":"string"},"name":{"type":"string"},"image":{"anyOf":[{"type":"string"},{"type":"null"}]}},"title":"AgentRef"},"KeyName":{"type":"object","required":["key","name"],"properties":{"key":{"type":"string"},"name":{"type":"string"}},"title":"KeyName"}},"responses":{"ServiceUnavailable":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HealthReady"}}}},"TooManyRequests":{"description":"Limite de requisições excedido (veja Retry-After).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"InternalError":{"description":"Erro interno (sem detalhes expostos).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"BadRequest":{"description":"Requisição malformada (JSON inválido, cursor inválido ou clínica ativa não informada).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"Unauthorized":{"description":"Token ausente, inválido ou expirado.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"Forbidden":{"description":"Autenticado, mas sem permissão (perfil ou clínica).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"Conflict":{"description":"Conflito de estado (duplicidade, transição inválida, conflito de agenda).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"UnprocessableEntity":{"description":"Dados semanticamente inválidos (erros por campo em details).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"ServiceUnavailable2":{"description":"Banco de dados indisponível ou não configurado.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"PayloadTooLarge":{"description":"Erro","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"UnsupportedMediaType":{"description":"Erro","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"NotFound":{"description":"Recurso não encontrado na clínica ativa.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"BadRequest2":{"description":"Requisição malformada (JSON inválido, cursor inválido ou clínica ativa não informada).","content":{"application/xml":{"schema":{"$ref":"#/components/schemas/Error"}},"application/pdf":{"schema":{"$ref":"#/components/schemas/Error"}}}},"Unauthorized2":{"description":"Token ausente, inválido ou expirado.","content":{"application/xml":{"schema":{"$ref":"#/components/schemas/Error"}},"application/pdf":{"schema":{"$ref":"#/components/schemas/Error"}}}},"Forbidden2":{"description":"Autenticado, mas sem permissão (perfil ou clínica).","content":{"application/xml":{"schema":{"$ref":"#/components/schemas/Error"}},"application/pdf":{"schema":{"$ref":"#/components/schemas/Error"}}}},"NotFound2":{"description":"Recurso não encontrado na clínica ativa.","content":{"application/xml":{"schema":{"$ref":"#/components/schemas/Error"}},"application/pdf":{"schema":{"$ref":"#/components/schemas/Error"}}}},"UnprocessableEntity2":{"description":"Dados semanticamente inválidos (erros por campo em details).","content":{"application/xml":{"schema":{"$ref":"#/components/schemas/Error"}},"application/pdf":{"schema":{"$ref":"#/components/schemas/Error"}}}},"TooManyRequests2":{"description":"Limite de requisições excedido (veja Retry-After).","content":{"application/xml":{"schema":{"$ref":"#/components/schemas/Error"}},"application/pdf":{"schema":{"$ref":"#/components/schemas/Error"}}}},"InternalError2":{"description":"Erro interno (sem detalhes expostos).","content":{"application/xml":{"schema":{"$ref":"#/components/schemas/Error"}},"application/pdf":{"schema":{"$ref":"#/components/schemas/Error"}}}},"ServiceUnavailable3":{"description":"Banco de dados indisponível ou não configurado.","content":{"application/xml":{"schema":{"$ref":"#/components/schemas/Error"}},"application/pdf":{"schema":{"$ref":"#/components/schemas/Error"}}}},"BadRequest3":{"description":"Requisição malformada (JSON inválido, cursor inválido ou clínica ativa não informada).","content":{"text/csv":{"schema":{"$ref":"#/components/schemas/Error"}}}},"Unauthorized3":{"description":"Token ausente, inválido ou expirado.","content":{"text/csv":{"schema":{"$ref":"#/components/schemas/Error"}}}},"Forbidden3":{"description":"Autenticado, mas sem permissão (perfil ou clínica).","content":{"text/csv":{"schema":{"$ref":"#/components/schemas/Error"}}}},"UnprocessableEntity3":{"description":"Dados semanticamente inválidos (erros por campo em details).","content":{"text/csv":{"schema":{"$ref":"#/components/schemas/Error"}}}},"TooManyRequests3":{"description":"Limite de requisições excedido (veja Retry-After).","content":{"text/csv":{"schema":{"$ref":"#/components/schemas/Error"}}}},"InternalError3":{"description":"Erro interno (sem detalhes expostos).","content":{"text/csv":{"schema":{"$ref":"#/components/schemas/Error"}}}},"ServiceUnavailable4":{"description":"Banco de dados indisponível ou não configurado.","content":{"text/csv":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"parameters":{"HeaderXClinicId":{"schema":{"type":"string","pattern":"^[A-Za-z0-9._-]{1,64}$"},"in":"header","name":"x-clinic-id","required":false,"description":"Clínica ativa. Obrigatório só para quem tem acesso a mais de uma clínica (ou token de serviço). Validado contra o vínculo do usuário."},"QueryLimit":{"schema":{"type":"integer","minimum":1,"maximum":100,"default":25},"in":"query","name":"limit","required":false,"description":"Itens por página (1–100)."},"QueryCursor":{"schema":{"type":"string","maxLength":200},"in":"query","name":"cursor","required":false,"description":"Cursor opaco recebido em meta.nextCursor."},"QueryPage":{"schema":{"type":"integer","minimum":1,"maximum":200},"in":"query","name":"page","required":false,"description":"Paginação numerada (tabelas): página 1-based, offset = (page − 1) × limit. Ignorado quando há `cursor`. Listas longas/feeds devem usar `cursor`."},"PathId":{"schema":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9._-]+$"},"in":"path","name":"id","required":true,"description":"Id do recurso."},"QueryService":{"schema":{"type":"string"},"in":"query","name":"service","required":false,"description":"service_keys separados por vírgula."},"QueryProfessional":{"schema":{"type":"string"},"in":"query","name":"professional","required":false,"description":"professional_keys separados por vírgula."},"QueryCreatedFrom":{"schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"},"example":"2026-09-18","in":"query","name":"createdFrom","required":false},"QueryCreatedTo":{"schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"},"example":"2026-09-18","in":"query","name":"createdTo","required":false},"PathId2":{"schema":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9._-]+$"},"in":"path","name":"id","required":true},"PathTaskId":{"schema":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9._-]+$"},"in":"path","name":"taskId","required":true},"QueryCategory":{"schema":{"type":"string"},"in":"query","name":"category","required":false,"description":"Categorias separadas por vírgula."},"QuerySort":{"schema":{"type":"string","maxLength":120},"example":"date,start","in":"query","name":"sort","required":false,"description":"Ordenação: campos separados por vírgula, prefixo \"-\" = decrescente. Permitidos: date, start, startsAt, createdAt, status. Padrão: date,start."},"QueryStatus":{"schema":{"type":"string"},"in":"query","name":"status","required":false,"description":"Status separados por vírgula: agendado, confirmado, pendente, em_andamento, realizado, cancelado, remarcacao, faltou."},"QueryOrigin":{"schema":{"type":"string"},"in":"query","name":"origin","required":false,"description":"Origens separadas por vírgula: agente, manual, google, site, instagram."},"QueryPatientId":{"schema":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9._-]+$"},"in":"query","name":"patientId","required":false},"QueryAgentState":{"schema":{"type":"string","enum":["agendado","confirmado","sugestao","aguardando_aprovacao","escalado"]},"in":"query","name":"agentState","required":false},"QueryFrom":{"schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"},"example":"2026-09-18","in":"query","name":"from","required":false},"QueryTo":{"schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"},"example":"2026-09-18","in":"query","name":"to","required":false},"QuerySort2":{"schema":{"type":"string","maxLength":120},"example":"-lastInteractionAt","in":"query","name":"sort","required":false,"description":"Ordenação: campos separados por vírgula, prefixo \"-\" = decrescente. Permitidos: lastInteractionAt, score, createdAt, name, stage, estimatedValue, expectedCloseDate. Padrão: -lastInteractionAt."},"QueryQ":{"schema":{"type":"string","maxLength":100},"in":"query","name":"q","required":false,"description":"Nome, telefone, e-mail, cidade ou origem (código ou rótulo: \"insta\", \"Google\", \"indicação\")."},"QueryStage":{"schema":{"type":"string"},"in":"query","name":"stage","required":false,"description":"Etapas separadas por vírgula: NEW, DISCOVERY, QUALIFIED, READY_TO_SCHEDULE, SCHEDULED, COMPLETED, NURTURE, NOT_A_FIT, HUMAN_HANDOFF."},"QuerySource":{"schema":{"type":"string"},"in":"query","name":"source","required":false,"description":"Origens separadas por vírgula."},"QueryChannel":{"schema":{"type":"string"},"in":"query","name":"channel","required":false,"description":"Canais separados por vírgula."},"QueryAppointment":{"schema":{"type":"string","enum":["agendado","realizado","nenhum"]},"in":"query","name":"appointment","required":false},"QueryOwner":{"schema":{"type":"string","maxLength":64},"in":"query","name":"owner","required":false,"description":"membership id ou agent_key."},"QueryAgent":{"schema":{"type":"string","maxLength":64},"in":"query","name":"agent","required":false,"description":"agent_key da última ação automática."},"QueryPeriodDays":{"schema":{"type":"integer","minimum":1,"maximum":365},"in":"query","name":"periodDays","required":false,"description":"Atalho: leads criados nos últimos N dias."},"QueryLabels":{"schema":{"type":"string","maxLength":400},"in":"query","name":"labels","required":false,"description":"Ids de etiqueta separados por vírgula: leads com QUALQUER uma delas."},"QueryCloseFrom":{"schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"},"example":"2026-09-18","in":"query","name":"closeFrom","required":false,"description":"Fechamento previsto a partir desta data (inclusive)."},"QueryCloseTo":{"schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"},"example":"2026-09-18","in":"query","name":"closeTo","required":false,"description":"Fechamento previsto até esta data (inclusive)."},"QueryHasValue":{"schema":{"type":"boolean"},"in":"query","name":"hasValue","required":false,"description":"true = só leads com valor estimado; false = só sem valor."},"QueryChannel2":{"schema":{"type":"string"},"in":"query","name":"channel","required":false,"description":"Canais separados por vírgula: whatsapp, email, sms, instagram, outros."},"QueryAgent2":{"schema":{"type":"string","enum":["ia","equipe"]},"in":"query","name":"agent","required":false,"description":"ia = conduzida por assistente de IA agora; equipe = sem agente ativo."},"QueryQ2":{"schema":{"type":"string","maxLength":100},"in":"query","name":"q","required":false,"description":"Nome ou telefone do contato (mín. 2 caracteres)."},"QueryLeadId":{"schema":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9._-]+$"},"in":"query","name":"leadId","required":false},"PathKey":{"schema":{"type":"string","pattern":"^[a-z0-9-]{2,64}$"},"example":"agendamento","in":"path","name":"key","required":true,"description":"agent_key funcional (ex.: agendamento)."},"QueryStatus2":{"schema":{"type":"string"},"in":"query","name":"status","required":false,"description":"Status separados por vírgula: recebido, pago, a-receber, a-pagar, atrasado, estornado."},"QueryMethod":{"schema":{"type":"string"},"in":"query","name":"method","required":false,"description":"Formas de pagamento separadas por vírgula."},"QueryIncludeReversed":{"schema":{"type":"boolean","default":false},"in":"query","name":"includeReversed","required":false,"description":"Inclui estornadas. Padrão: não (a menos que status peça \"estornado\")."},"QueryQ3":{"schema":{"type":"string","maxLength":100},"in":"query","name":"q","required":false,"description":"Descrição ou paciente/fornecedor."},"QueryProfessional2":{"schema":{"type":"string","maxLength":200},"in":"query","name":"professional","required":false,"description":"professional_keys separados por vírgula."},"QueryLimit2":{"schema":{"type":"integer","minimum":1,"maximum":100},"in":"query","name":"limit","required":false,"description":"Só os N vencimentos mais próximos (painéis laterais). Padrão: todos."},"PathId3":{"schema":{"type":"string","pattern":"^[a-z0-9-]{2,64}$"},"in":"path","name":"id","required":true,"description":"integration_id do catálogo (whatsapp, google-calendar, smtp…)."},"QueryAction":{"schema":{"type":"string"},"in":"query","name":"action","required":false,"description":"Ações separadas por vírgula: login, update, create, invite, configure, delete, view, reconcile, send, record_preview, revoke_access, reverse, change_role, export, approve, reject."},"QueryResource":{"schema":{"type":"string"},"in":"query","name":"resource","required":false,"description":"Recursos separados por vírgula: clinic, user, invitation, patient, clinical_record, task, service, professional, appointment, lead, conversation, agent, approval, automation, billing, finance, knowledge, integration, audit, security, report, fiscal."},"QueryActorName":{"schema":{"type":"string","maxLength":128},"in":"query","name":"actorName","required":false,"description":"Nome exato do autor (filtro \"Usuário\" da tela)."},"QueryQ4":{"schema":{"type":"string","maxLength":100},"in":"query","name":"q","required":false,"description":"Busca em ator, detalhes, recurso e id."},"QueryFrom2":{"schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"},"example":"2026-09-18","in":"query","name":"from","required":false,"description":"Padrão: 1º dia do mês corrente."},"QueryTo2":{"schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"},"example":"2026-09-18","in":"query","name":"to","required":false,"description":"Padrão: hoje."}}},"paths":{"/health":{"get":{"summary":"Liveness (processo no ar)","tags":["Sistema"],"security":[],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["status","version","uptimeSeconds","time"],"properties":{"status":{"type":"string","enum":["ok","degraded"]},"version":{"type":"string"},"uptimeSeconds":{"type":"integer"},"time":{"type":"string","format":"date-time"}}}}}}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/health\""}],"description":"**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/health\"\n```"}},"/health/ready":{"get":{"summary":"Readiness (dependências configuradas)","tags":["Sistema"],"description":"Não expõe endpoints, chaves nem ids de projeto.\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/health/ready\"\n```","security":[],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HealthReady"}}}},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/health/ready\""}]}},"/v1/signup/status":{"get":{"operationId":"getSignupStatus","summary":"Status do autocadastro (público)","tags":["Cadastro"],"description":"Diz se o autocadastro está aberto neste ambiente e, quando configuradas (`SIGNUP_TERMS_VERSION`, `SIGNUP_PRIVACY_VERSION`), as versões vigentes dos Termos de Uso e da Política de Privacidade. **Não exige token.** O site consulta ao abrir o cadastro para não pedir dados nem criar conta com o cadastro fechado.\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/signup/status\"\n```","security":[],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SignupStatusResponse"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/signup/status\""}]}},"/v1/signup":{"post":{"operationId":"postSignup","summary":"Autocadastro: criar a clínica do usuário autenticado (teste grátis do plano)","tags":["Cadastro"],"description":"Primeiro o dono cria a conta (e-mail e senha) no provedor de identidade da plataforma; depois, com o token dessa conta, chama esta rota. Nome e e-mail do dono vêm do token — nunca do corpo.\n\nCria, numa chamada só: a clínica (status `ONBOARDING`), o vínculo do dono como **Administrador** e a assinatura do plano escolhido em **teste grátis de 7 dias** (`trialEndsAt`). Durante o teste nada é cobrado; ao fim, sem ativação, o painel fica em somente leitura (402 `trial_expired` nas escritas).\n\n**Idempotente:** repetir a chamada (mesmo usuário) devolve **200** com o mesmo `clinicId` e `created: false`, sem duplicar nada; a primeira criação devolve **201**. Duas chamadas simultâneas criam uma clínica só. Cada usuário cria no máximo uma clínica por esta rota.\n\nDepois do cadastro, `GET /v1/me` já responde com a clínica nova (envie `X-Clinic-Id` se a pessoa também tiver acesso a outras clínicas).\n\nErros: 503 `signup_disabled` (cadastro ainda não aberto no ambiente), 403 `signup_not_allowed` (token de serviço ou equipe da plataforma), 400 (campo-isca preenchido), 409 `signup_conflict` (estado inconsistente — fale com o suporte), 422 `unknown_plan` / `plan_requires_sales` / `invalid_cnpj` / `validation_error`.\n\n**Eventos de automação:** `clinic.created`\n\n**Rate limit:** 5 requisições / 3600 s por IP.\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/signup\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Agent-Key: <agent_key>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"clinic\": {\n      \"name\": \"Clínica Exemplo\",\n      \"phone\": \"(16) 99999-0000\",\n      \"email\": \"contato@exemplo.com\",\n      \"street\": \"<street>\",\n      \"specialty\": \"Fisioterapia\",\n      \"teamSize\": \"solo\"\n    },\n    \"owner\": {\n      \"phone\": \"(16) 99999-0000\",\n      \"marketingOptIn\": true,\n      \"jobTitle\": \"Fisioterapeuta\"\n    },\n    \"plan\": {\n      \"id\": \"profissional\",\n      \"cycle\": \"mensal\"\n    },\n    \"consent\": {\n      \"accepted\": true,\n      \"termsVersion\": \"2026-09\",\n      \"privacyVersion\": \"2026-09\"\n    },\n    \"website\": \"<website>\"\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SignupRequest"}}}},"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SignupResultActionResponse"}}}},"201":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SignupResultActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/signup\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Agent-Key: <agent_key>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"clinic\": {\n      \"name\": \"Clínica Exemplo\",\n      \"phone\": \"(16) 99999-0000\",\n      \"email\": \"contato@exemplo.com\",\n      \"street\": \"<street>\",\n      \"specialty\": \"Fisioterapia\",\n      \"teamSize\": \"solo\"\n    },\n    \"owner\": {\n      \"phone\": \"(16) 99999-0000\",\n      \"marketingOptIn\": true,\n      \"jobTitle\": \"Fisioterapeuta\"\n    },\n    \"plan\": {\n      \"id\": \"profissional\",\n      \"cycle\": \"mensal\"\n    },\n    \"consent\": {\n      \"accepted\": true,\n      \"termsVersion\": \"2026-09\",\n      \"privacyVersion\": \"2026-09\"\n    },\n    \"website\": \"<website>\"\n  }'"}]}},"/v1/me":{"get":{"operationId":"getMe","summary":"Usuário e contexto ativo (clínica, perfil, permissões)","tags":["Sessão"],"description":"Use para montar a navegação por perfil. Com mais de uma clínica, envie X-Clinic-Id.\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/me\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MeResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/me\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/me/memberships":{"get":{"operationId":"getMeMemberships","summary":"Clínicas acessíveis (seletor de clínica)","tags":["Sessão"],"description":"Lista só vínculos ativos do usuário autenticado. Trocar de clínica = enviar outro X-Clinic-Id e descartar os dados em cache do tenant anterior (PRD §7).\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/me/memberships\" \\\n  -H \"Authorization: Bearer <TOKEN>\"\n```","security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/MembershipSummary"}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/me/memberships\" \\\n  -H \"Authorization: Bearer <TOKEN>\""}]}},"/v1/clinic":{"get":{"operationId":"getClinic","summary":"Dados da clínica ativa","tags":["Clínica"],"description":"**Permissão:** `clinic:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/clinic\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ClinicResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/clinic\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"patch":{"operationId":"patchClinic","summary":"Atualizar dados da clínica","tags":["Clínica"],"description":"Status do tenant não é alterável aqui (somente plataforma).\n\n**Permissão:** `clinic:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X PATCH \"{baseUrl}/v1/clinic\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"<name>\",\n    \"tagline\": \"<tagline>\",\n    \"legalName\": \"<legalName>\",\n    \"cnpj\": \"<cnpj>\",\n    \"email\": \"contato@exemplo.com\",\n    \"phone\": \"<phone>\",\n    \"site\": \"https://exemplo.com\",\n    \"timezone\": \"America/Sao_Paulo\"\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ClinicPatch"}}}},"parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ClinicResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X PATCH \"{baseUrl}/v1/clinic\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"<name>\",\n    \"tagline\": \"<tagline>\",\n    \"legalName\": \"<legalName>\",\n    \"cnpj\": \"<cnpj>\",\n    \"email\": \"contato@exemplo.com\",\n    \"phone\": \"<phone>\",\n    \"site\": \"https://exemplo.com\",\n    \"timezone\": \"America/Sao_Paulo\"\n  }'"}]}},"/v1/clinic/logo":{"put":{"operationId":"putClinicLogo","summary":"Enviar logo da clínica (multipart/form-data, campo \"file\")","tags":["Clínica"],"description":"PNG, JPEG, WEBP ou SVG sem scripts, até 2 MB. Guardado no armazenamento de arquivos da plataforma com leitura pública (logo não é dado sensível). O logo só aparece no painel após a ativação do plano. PNG/JPEG/WEBP são redimensionados (máx. 512px de lado) e recomprimidos para WEBP no servidor, com metadados (EXIF/GPS) removidos — mesmo que o cliente já tenha otimizado a imagem antes de enviar. SVG passa intacto.\n\n**Permissão:** `clinic:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X PUT \"{baseUrl}/v1/clinic/logo\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -F \"file=@./arquivo.png\"\n```","parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ClinicResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"413":{"$ref":"#/components/responses/PayloadTooLarge"},"415":{"$ref":"#/components/responses/UnsupportedMediaType"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X PUT \"{baseUrl}/v1/clinic/logo\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -F \"file=@./arquivo.png\""}]},"delete":{"operationId":"deleteClinicLogo","summary":"Remover logo da clínica","tags":["Clínica"],"description":"**Permissão:** `clinic:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X DELETE \"{baseUrl}/v1/clinic/logo\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"204":{"description":"Default Response"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X DELETE \"{baseUrl}/v1/clinic/logo\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/clinics":{"get":{"operationId":"getClinics","summary":"Listar clínicas (somente equipe da plataforma)","tags":["Clínica"],"description":"Visão cross-tenant do PRD §2.1 / §30.1. Usuários de clínica recebem 403.\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/clinics\" \\\n  -H \"Authorization: Bearer <TOKEN>\"\n```","parameters":[{"schema":{"type":"string","enum":["DRAFT","ONBOARDING","READY_FOR_TEST","ACTIVE","SUSPENDED","ARCHIVED"]},"in":"query","name":"status","required":false},{"schema":{"type":"string","maxLength":100},"in":"query","name":"q","required":false}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"array","items":{"type":"object","required":["id","name","status","city"],"properties":{"id":{"type":"string"},"name":{"type":"string"},"status":{"type":"string"},"city":{"anyOf":[{"type":"string"},{"type":"null"}]}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/clinics\" \\\n  -H \"Authorization: Bearer <TOKEN>\""}]},"post":{"operationId":"postClinics","summary":"Cadastrar clínica (tenant) — somente platform_admin","tags":["Clínica"],"description":"Cria em status DRAFT (PRD §8: criar clínica inicia onboarding; não ativa atendimento automatizado).\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/clinics\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"name\":\"<name>\",\"id\":\"<id>\",\"legalName\":\"<legalName>\",\"timezone\":\"<timezone>\",\"city\":\"<city>\",\"state\":\"<s\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ClinicCreate"}}}},"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"201":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ClinicResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/clinics\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"name\":\"<name>\",\"id\":\"<id>\",\"legalName\":\"<legalName>\",\"timezone\":\"<timezone>\",\"city\":\"<city>\",\"state\":\"<s\"}'"}]}},"/v1/users/roles":{"get":{"operationId":"getUsersRoles","summary":"Perfis de acesso e permissões efetivas","tags":["Usuários"],"description":"Rótulos/descrições exibidos no front estão em web/src/data/usuarios.ts; aqui está a regra aplicada no servidor.\n\n**Permissão:** `users:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/users/roles\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"array","items":{"type":"object","required":["key","label","permissions","seesClinicalRecords","seesFinance","ownScheduleOnly"],"properties":{"key":{"type":"string","enum":["admin","profissional","recepcao","financeiro","marketing","suporte","estagiario"]},"label":{"type":"string"},"permissions":{"type":"array","items":{"type":"string"}},"seesClinicalRecords":{"type":"boolean"},"seesFinance":{"type":"boolean"},"ownScheduleOnly":{"type":"boolean"}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/users/roles\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/users":{"get":{"operationId":"getUsers","summary":"Listar usuários da clínica (inclui convites pendentes)","tags":["Usuários"],"description":"**Permissão:** `users:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/users?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryLimit"},{"$ref":"#/components/parameters/QueryCursor"},{"$ref":"#/components/parameters/QueryPage"},{"schema":{"type":"string","maxLength":120},"example":"name","in":"query","name":"sort","required":false,"description":"Ordenação: campos separados por vírgula, prefixo \"-\" = decrescente. Permitidos: name, joinedAt, lastAccessAt, role, status. Padrão: name."},{"schema":{"type":"string","maxLength":100},"in":"query","name":"q","required":false,"description":"Nome ou e-mail."},{"schema":{"type":"string"},"example":"admin,recepcao","in":"query","name":"role","required":false,"description":"Perfis separados por vírgula."},{"schema":{"type":"string"},"example":"ativo,pendente","in":"query","name":"status","required":false,"description":"Status separados por vírgula."},{"schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"},"in":"query","name":"joinedFrom","required":false},{"schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"},"in":"query","name":"joinedTo","required":false},{"schema":{"type":"string","maxLength":160},"in":"query","name":"email","required":false,"description":"E-mail exato (sem diferenciar maiúsculas) — checagem de duplicidade no convite."},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ClinicUserList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/users?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/users/counts":{"get":{"operationId":"getUsersCounts","summary":"Contagem de usuários por status (KPIs da tela)","tags":["Usuários"],"description":"**Permissão:** `users:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/users/counts\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ClinicUserCountsResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/users/counts\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/users/{id}":{"get":{"operationId":"getUsersById","summary":"Detalhe de um usuário","tags":["Usuários"],"description":"**Permissão:** `users:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/users/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ClinicUserResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/users/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"patch":{"operationId":"patchUsersById","summary":"Alterar perfil de acesso / vínculo com profissional","tags":["Usuários"],"description":"Mudança de perfil é auditada como \"Alterar perfil\" (nível alto). Não é possível rebaixar o último administrador nem alterar o próprio perfil.\n\n**Permissão:** `users:manage`\n\n**Eventos de automação:** `user.access_changed`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X PATCH \"{baseUrl}/v1/users/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"role\":\"admin\",\"professionalKey\":\"<professionalKey>\",\"extraPermissions\":[\"clinic:read\"]}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"role":{"type":"string","enum":["admin","profissional","recepcao","financeiro","marketing","suporte","estagiario"]},"professionalKey":{"anyOf":[{"type":"string","maxLength":64},{"type":"null"}]},"extraPermissions":{"type":"array","items":{"type":"string","enum":["clinic:read","clinic:write","users:read","users:manage","patients:read","patients:write","clinical:read","clinical:write","services:read","services:write","professionals:read","professionals:write","schedule:read","schedule:write","leads:read","leads:write","conversations:read","conversations:write","agents:read","agents:manage","approvals:decide","automations:read","automations:manage","billing:read","billing:manage","finance:read","finance:write","knowledge:read","knowledge:write","knowledge:review","integrations:read","integrations:manage","audit:read","audit:export","reports:read","reports:finance","fiscal:read","fiscal:configure","fiscal:emit","onboarding:read","onboarding:write","onboarding:approve"]},"maxItems":20,"description":"Permissões adicionais além do perfil (somente admin)."}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ClinicUserActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X PATCH \"{baseUrl}/v1/users/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"role\":\"admin\",\"professionalKey\":\"<professionalKey>\",\"extraPermissions\":[\"clinic:read\"]}'"}]}},"/v1/users/{id}/suspend":{"post":{"operationId":"postUsersByIdSuspend","summary":"Suspender acesso","tags":["Usuários"],"description":"**Permissão:** `users:manage`\n\n**Eventos de automação:** `user.access_changed`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/users/<id>/suspend\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ClinicUserActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/users/<id>/suspend\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/users/{id}/reactivate":{"post":{"operationId":"postUsersByIdReactivate","summary":"Reativar acesso","tags":["Usuários"],"description":"**Permissão:** `users:manage`\n\n**Eventos de automação:** `user.access_changed`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/users/<id>/reactivate\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ClinicUserActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/users/<id>/reactivate\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/users/{id}/revoke":{"post":{"operationId":"postUsersByIdRevoke","summary":"Revogar acesso (inclui convite pendente)","tags":["Usuários"],"description":"**Permissão:** `users:manage`\n\n**Eventos de automação:** `user.access_changed`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/users/<id>/revoke\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ClinicUserActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/users/<id>/revoke\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/invitations":{"post":{"operationId":"postInvitations","summary":"Convidar usuário (e-mail + perfil)","tags":["Usuários"],"description":"Cria o vínculo com status \"pendente\" e um convite válido por 7 dias. O token nunca é gravado em claro (só o hash) e nunca volta na resposta em produção — as automações enviam o e-mail com o link.\n\n**Permissão:** `users:manage`\n\n**Eventos de automação:** `user.invited`\n\n**Rate limit:** 20 requisições / 3600 s.\n\n**E-mail verificado:** quando a verificação de e-mail está ligada no ambiente, contas com e-mail ainda não confirmado recebem 403 `email_not_verified`.\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/invitations\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"email\": \"contato@exemplo.com\",\n    \"role\": \"admin\",\n    \"name\": \"<name>\",\n    \"message\": \"<message>\",\n    \"professionalKey\": \"<professionalKey>\"\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["email","role"],"properties":{"email":{"type":"string","format":"email","maxLength":160},"name":{"type":"string","maxLength":128},"role":{"type":"string","enum":["admin","profissional","recepcao","financeiro","marketing","suporte","estagiario"]},"message":{"type":"string","maxLength":500},"professionalKey":{"type":"string","maxLength":64}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"201":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InvitationActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/invitations\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"email\": \"contato@exemplo.com\",\n    \"role\": \"admin\",\n    \"name\": \"<name>\",\n    \"message\": \"<message>\",\n    \"professionalKey\": \"<professionalKey>\"\n  }'"}]}},"/v1/invitations/{id}/resend":{"post":{"operationId":"postInvitationsByIdResend","summary":"Reenviar convite (gera novo link e renova a validade)","tags":["Usuários"],"description":"Mantém o MESMO `invitationId` (o link anterior deixa de valer). Cancelar depois pelo mesmo id continua funcionando.\n\n**Permissão:** `users:manage`\n\n**Eventos de automação:** `user.invited`\n\n**Rate limit:** 20 requisições / 3600 s.\n\n**E-mail verificado:** quando a verificação de e-mail está ligada no ambiente, contas com e-mail ainda não confirmado recebem 403 `email_not_verified`.\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/invitations/<id>/resend\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InvitationActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/invitations/<id>/resend\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/invitations/{id}":{"delete":{"operationId":"deleteInvitationsById","summary":"Cancelar convite pendente","tags":["Usuários"],"description":"**Permissão:** `users:manage`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X DELETE \"{baseUrl}/v1/invitations/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"204":{"description":"Default Response"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X DELETE \"{baseUrl}/v1/invitations/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/invitations/accept":{"post":{"operationId":"postInvitationsAccept","summary":"Aceitar convite (usuário convidado, já autenticado na plataforma)","tags":["Usuários"],"description":"O e-mail da conta autenticada precisa ser o mesmo do convite. Não exige clínica ativa.\n\n**Rate limit:** 10 requisições / 600 s.\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/invitations/accept\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"token\":\"<token>\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["token"],"properties":{"token":{"type":"string","minLength":20,"maxLength":200}},"additionalProperties":false}}}},"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"object","required":["clinicId","membershipId","role"],"properties":{"clinicId":{"type":"string"},"membershipId":{"type":"string"},"role":{"type":"string","enum":["admin","profissional","recepcao","financeiro","marketing","suporte","estagiario"]}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/invitations/accept\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"token\":\"<token>\"}'"}]}},"/v1/patients":{"get":{"operationId":"getPatients","summary":"Listar pacientes","tags":["Pacientes"],"description":"**Permissão:** `patients:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/patients?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryLimit"},{"$ref":"#/components/parameters/QueryCursor"},{"$ref":"#/components/parameters/QueryPage"},{"schema":{"type":"string","maxLength":120},"example":"name","in":"query","name":"sort","required":false,"description":"Ordenação: campos separados por vírgula, prefixo \"-\" = decrescente. Permitidos: name, lastVisitAt, createdAt, nextAppointmentAt. Padrão: name."},{"schema":{"type":"string","maxLength":100},"in":"query","name":"q","required":false,"description":"Nome, telefone, e-mail ou tag."},{"schema":{"type":"string","enum":["ativo","inativo"]},"in":"query","name":"status","required":false},{"schema":{"type":"boolean"},"in":"query","name":"isNew","required":false},{"schema":{"type":"string","maxLength":40},"in":"query","name":"tag","required":false},{"$ref":"#/components/parameters/QueryService"},{"$ref":"#/components/parameters/QueryProfessional"},{"schema":{"type":"string","maxLength":64},"in":"query","name":"origin","required":false},{"schema":{"type":"string","enum":["Particular","Convênio"]},"in":"query","name":"plan","required":false},{"schema":{"type":"boolean"},"in":"query","name":"hasNextAppointment","required":false},{"schema":{"type":"integer","minimum":1,"maximum":3650},"in":"query","name":"noVisitSinceDays","required":false,"description":"Sem consulta há N dias ou mais (reativação)."},{"schema":{"type":"string","enum":["todos","30","90","mais","nunca"]},"in":"query","name":"lastVisit","required":false,"description":"Filtro \"Última sessão\": 30 = até 30 dias; 90 = de 31 a 90 dias; mais = há mais de 90 dias; nunca = sem sessão realizada."},{"$ref":"#/components/parameters/QueryCreatedFrom"},{"$ref":"#/components/parameters/QueryCreatedTo"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PatientList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/patients?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"post":{"operationId":"postPatients","summary":"Cadastrar paciente","tags":["Pacientes"],"description":"**Permissão:** `patients:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/patients\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"<name>\",\n    \"birthDate\": \"2026-09-18\",\n    \"sex\": \"Feminino\",\n    \"cpf\": \"<cpf>\",\n    \"phone\": \"<phone>\",\n    \"email\": \"contato@exemplo.com\",\n    \"city\": \"<city>\",\n    \"address\": \"<address>\"\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PatientCreate"}}}},"parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"201":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PatientResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/patients\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"<name>\",\n    \"birthDate\": \"2026-09-18\",\n    \"sex\": \"Feminino\",\n    \"cpf\": \"<cpf>\",\n    \"phone\": \"<phone>\",\n    \"email\": \"contato@exemplo.com\",\n    \"city\": \"<city>\",\n    \"address\": \"<address>\"\n  }'"}]}},"/v1/patients/counts":{"get":{"operationId":"getPatientsCounts","summary":"Contagens dos segmentos (chips) da tela Pacientes","tags":["Pacientes"],"description":"Consulta leve (só contagens, sem itens), independente da lista: os chips não mudam com a página nem com a busca.\n\n**Permissão:** `patients:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/patients/counts\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PatientCountsResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/patients/counts\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/patients/tags":{"get":{"operationId":"getPatientsTags","summary":"Tags distintas dos pacientes da clínica (com contagem)","tags":["Pacientes"],"description":"Opções do filtro \"Tag\" da tela Pacientes — a base inteira, não só a página carregada. Agregado no servidor com cache de 60 s por clínica (invalidado ao criar/editar/excluir paciente).\n\n**Permissão:** `patients:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/patients/tags\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/PatientTag"}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/patients/tags\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/patients/summary":{"get":{"operationId":"getPatientsSummary","summary":"KPIs da tela Pacientes (e da Home)","tags":["Pacientes"],"description":"**Permissão:** `patients:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/patients/summary\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PatientSummaryResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/patients/summary\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/patients/{id}":{"get":{"operationId":"getPatientsById","summary":"Ficha do paciente","tags":["Pacientes"],"description":"**Permissão:** `patients:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/patients/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PatientResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/patients/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"patch":{"operationId":"patchPatientsById","summary":"Atualizar paciente","tags":["Pacientes"],"description":"**Permissão:** `patients:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X PATCH \"{baseUrl}/v1/patients/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"<name>\",\n    \"birthDate\": \"2026-09-18\",\n    \"sex\": \"Feminino\",\n    \"cpf\": \"<cpf>\",\n    \"phone\": \"<phone>\",\n    \"email\": \"contato@exemplo.com\",\n    \"city\": \"<city>\",\n    \"address\": \"<address>\"\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string","minLength":2,"maxLength":128},"birthDate":{"anyOf":[{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","examples":["2026-09-18"]},{"type":"null"}]},"sex":{"anyOf":[{"type":"string","enum":["Feminino","Masculino","Outro","Não informado"]},{"type":"null"}]},"cpf":{"anyOf":[{"type":"string","pattern":"^\\d{3}\\.?\\d{3}\\.?\\d{3}-?\\d{2}$","description":"Write-only: nunca é devolvido completo."},{"type":"null"}]},"phone":{"anyOf":[{"type":"string","maxLength":32},{"type":"null"}]},"email":{"anyOf":[{"type":"string","format":"email","maxLength":160},{"type":"null"}]},"city":{"anyOf":[{"type":"string","maxLength":80},{"type":"null"}]},"address":{"anyOf":[{"type":"string","maxLength":255},{"type":"null"}]},"status":{"type":"string","enum":["ativo","inativo"]},"tags":{"type":"array","items":{"type":"string","maxLength":40},"maxItems":20},"serviceKey":{"anyOf":[{"type":"string","maxLength":64},{"type":"null"}]},"plan":{"anyOf":[{"type":"string","enum":["Particular","Convênio"]},{"type":"null"}]},"origin":{"anyOf":[{"type":"string","maxLength":64},{"type":"null"}]},"professionalKey":{"anyOf":[{"type":"string","maxLength":64},{"type":"null"}]},"leadId":{"anyOf":[{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9._-]+$"},{"type":"null"}]},"lgpdConsent":{"type":"boolean","description":"true registra o consentimento LGPD agora."}}}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PatientResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X PATCH \"{baseUrl}/v1/patients/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"<name>\",\n    \"birthDate\": \"2026-09-18\",\n    \"sex\": \"Feminino\",\n    \"cpf\": \"<cpf>\",\n    \"phone\": \"<phone>\",\n    \"email\": \"contato@exemplo.com\",\n    \"city\": \"<city>\",\n    \"address\": \"<address>\"\n  }'"}]},"delete":{"operationId":"deletePatientsById","summary":"Excluir paciente (exclusão lógica, recuperável)","tags":["Pacientes"],"description":"Auditado com nível alto. Não apaga prontuário nem transações (obrigação legal de guarda).\n\n**Permissão:** `patients:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X DELETE \"{baseUrl}/v1/patients/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"204":{"description":"Default Response"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X DELETE \"{baseUrl}/v1/patients/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/patients/{id}/timeline":{"get":{"operationId":"getPatientsByIdTimeline","summary":"Histórico do paciente (humanos e agentes no mesmo trilho)","tags":["Pacientes"],"description":"**Permissão:** `patients:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/patients/<id>/timeline?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryLimit"},{"$ref":"#/components/parameters/QueryCursor"},{"$ref":"#/components/parameters/QueryPage"},{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PatientTimelineEventList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/patients/<id>/timeline?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/patients/{id}/evolutions":{"get":{"operationId":"getPatientsByIdEvolutions","summary":"Evoluções / prontuário do paciente","tags":["Pacientes"],"description":"Conteúdo clínico: só perfis com `clinical:read` (Administrador, Profissional de saúde). Cada leitura é registrada na auditoria como \"Visualizar Prontuário\".\n\n**Permissão:** `clinical:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/patients/<id>/evolutions?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryLimit"},{"$ref":"#/components/parameters/QueryCursor"},{"$ref":"#/components/parameters/QueryPage"},{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ClinicalEvolutionList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/patients/<id>/evolutions?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"post":{"operationId":"postPatientsByIdEvolutions","summary":"Registrar evolução","tags":["Pacientes"],"description":"Registros clínicos são append-only (não há edição/exclusão pela API). O conteúdo nunca vai para o audit log.\n\n**Permissão:** `clinical:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/patients/<id>/evolutions\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"title\": \"<title>\",\n    \"content\": \"<content>\",\n    \"date\": \"2026-09-18\",\n    \"kind\": \"evolucao\",\n    \"appointmentId\": \"<appointmentId>\"\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["title","content"],"properties":{"date":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","example":"2026-09-18"},"title":{"type":"string","minLength":2,"maxLength":160},"content":{"type":"string","minLength":1,"maxLength":20000},"kind":{"type":"string","enum":["evolucao","anamnese","outro"]},"appointmentId":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9._-]+$"}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"201":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ClinicalEvolutionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/patients/<id>/evolutions\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"title\": \"<title>\",\n    \"content\": \"<content>\",\n    \"date\": \"2026-09-18\",\n    \"kind\": \"evolucao\",\n    \"appointmentId\": \"<appointmentId>\"\n  }'"}]}},"/v1/patients/{id}/tasks":{"get":{"operationId":"getPatientsByIdTasks","summary":"Tarefas do paciente","tags":["Pacientes"],"description":"**Permissão:** `patients:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/patients/<id>/tasks\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/PatientTask"}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/patients/<id>/tasks\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"post":{"operationId":"postPatientsByIdTasks","summary":"Criar tarefa","tags":["Pacientes"],"description":"**Permissão:** `patients:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/patients/<id>/tasks\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"label\":\"<label>\",\"dueAt\":\"2026-01-15T14:00:00.000Z\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["label"],"properties":{"label":{"type":"string","minLength":2,"maxLength":255},"dueAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"201":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PatientTaskResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/patients/<id>/tasks\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"label\":\"<label>\",\"dueAt\":\"2026-01-15T14:00:00.000Z\"}'"}]}},"/v1/patients/{id}/tasks/{taskId}":{"patch":{"operationId":"patchPatientsByIdTasksByTaskId","summary":"Atualizar / concluir tarefa","tags":["Pacientes"],"description":"**Permissão:** `patients:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X PATCH \"{baseUrl}/v1/patients/<id>/tasks/<taskId>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"label\":\"<label>\",\"done\":true,\"dueAt\":\"2026-01-15T14:00:00.000Z\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"label":{"type":"string","minLength":2,"maxLength":255},"done":{"type":"boolean"},"dueAt":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId2"},{"$ref":"#/components/parameters/PathTaskId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PatientTaskResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X PATCH \"{baseUrl}/v1/patients/<id>/tasks/<taskId>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"label\":\"<label>\",\"done\":true,\"dueAt\":\"2026-01-15T14:00:00.000Z\"}'"}]},"delete":{"operationId":"deletePatientsByIdTasksByTaskId","summary":"Excluir tarefa","tags":["Pacientes"],"description":"**Permissão:** `patients:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X DELETE \"{baseUrl}/v1/patients/<id>/tasks/<taskId>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId2"},{"$ref":"#/components/parameters/PathTaskId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"204":{"description":"Default Response"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X DELETE \"{baseUrl}/v1/patients/<id>/tasks/<taskId>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/services":{"get":{"operationId":"getServices","summary":"Listar serviços do cadastro","tags":["Serviços"],"description":"Selects e filtros de Agenda, Leads, Pacientes, Financeiro e Relatórios devem usar `?active=true` desta rota.\n\n**Permissão:** `services:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/services?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"schema":{"type":"integer","minimum":1,"maximum":100,"default":100},"in":"query","name":"limit","required":false},{"$ref":"#/components/parameters/QueryCursor"},{"$ref":"#/components/parameters/QueryPage"},{"schema":{"type":"string","maxLength":120},"example":"name","in":"query","name":"sort","required":false,"description":"Ordenação: campos separados por vírgula, prefixo \"-\" = decrescente. Permitidos: name, category, price, duration, demand, createdAt. Padrão: name."},{"schema":{"type":"string","maxLength":100},"in":"query","name":"q","required":false},{"schema":{"type":"boolean"},"in":"query","name":"active","required":false},{"$ref":"#/components/parameters/QueryCategory"},{"schema":{"type":"string","maxLength":64},"in":"query","name":"professional","required":false,"description":"professional_key."},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServiceList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/services?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"post":{"operationId":"postServices","summary":"Criar serviço","tags":["Serviços"],"description":"**Permissão:** `services:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/services\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"<name>\",\n    \"category\": \"Fisioterapia\",\n    \"duration\": 5,\n    \"key\": \"<key>\",\n    \"description\": \"<description>\",\n    \"price\": 1,\n    \"active\": true,\n    \"requiresProfessional\": true\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServiceCreate"}}}},"parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"201":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServiceResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/services\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"<name>\",\n    \"category\": \"Fisioterapia\",\n    \"duration\": 5,\n    \"key\": \"<key>\",\n    \"description\": \"<description>\",\n    \"price\": 1,\n    \"active\": true,\n    \"requiresProfessional\": true\n  }'"}]}},"/v1/services/{id}":{"get":{"operationId":"getServicesById","summary":"Detalhe do serviço","tags":["Serviços"],"description":"**Permissão:** `services:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/services/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServiceResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/services/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"patch":{"operationId":"patchServicesById","summary":"Editar / ativar / desativar serviço","tags":["Serviços"],"description":"Desativar (`active=false`) tira o serviço dos selects e dos agentes sem apagar histórico.\n\n**Permissão:** `services:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X PATCH \"{baseUrl}/v1/services/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"<name>\",\n    \"description\": \"<description>\",\n    \"category\": \"Fisioterapia\",\n    \"duration\": 5,\n    \"price\": 1,\n    \"active\": true,\n    \"requiresProfessional\": true,\n    \"aiDescription\": \"<aiDescription>\"\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string","minLength":2,"maxLength":128},"description":{"anyOf":[{"type":"string","maxLength":255},{"type":"null"}]},"category":{"type":"string","minLength":2,"maxLength":40,"example":"Fisioterapia"},"duration":{"type":"integer","minimum":5,"maximum":600},"price":{"anyOf":[{"type":"number","minimum":0,"maximum":10000000,"description":"Valor em reais (BRL). No banco: amount_minor (centavos)."},{"type":"null"}]},"active":{"type":"boolean","default":true},"requiresProfessional":{"type":"boolean","default":true},"aiDescription":{"anyOf":[{"type":"string","maxLength":1000},{"type":"null"}]},"rules":{"anyOf":[{"type":"string","maxLength":2000},{"type":"null"}]},"professionals":{"type":"array","items":{"type":"string","maxLength":64},"maxItems":50,"description":"professional_keys que atendem o serviço."}}}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServiceResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X PATCH \"{baseUrl}/v1/services/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"<name>\",\n    \"description\": \"<description>\",\n    \"category\": \"Fisioterapia\",\n    \"duration\": 5,\n    \"price\": 1,\n    \"active\": true,\n    \"requiresProfessional\": true,\n    \"aiDescription\": \"<aiDescription>\"\n  }'"}]},"delete":{"operationId":"deleteServicesById","summary":"Excluir serviço (exclusão lógica)","tags":["Serviços"],"description":"Prefira desativar. Excluir mantém o histórico de agendamentos/financeiro que referenciam o service_key.\n\n**Permissão:** `services:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X DELETE \"{baseUrl}/v1/services/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"204":{"description":"Default Response"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X DELETE \"{baseUrl}/v1/services/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/services/{id}/duplicate":{"post":{"operationId":"postServicesByIdDuplicate","summary":"Duplicar serviço (cópia inativa)","tags":["Serviços"],"description":"**Permissão:** `services:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/services/<id>/duplicate\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"201":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServiceResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/services/<id>/duplicate\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/professionals":{"get":{"operationId":"getProfessionals","summary":"Listar profissionais","tags":["Profissionais"],"description":"**Permissão:** `professionals:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/professionals?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"schema":{"type":"integer","minimum":1,"maximum":100,"default":100},"in":"query","name":"limit","required":false},{"$ref":"#/components/parameters/QueryCursor"},{"$ref":"#/components/parameters/QueryPage"},{"schema":{"type":"string","maxLength":120},"example":"name","in":"query","name":"sort","required":false,"description":"Ordenação: campos separados por vírgula, prefixo \"-\" = decrescente. Permitidos: name, createdAt. Padrão: name."},{"schema":{"type":"string","maxLength":100},"in":"query","name":"q","required":false},{"schema":{"type":"string","enum":["ativo","inativo"]},"in":"query","name":"status","required":false},{"schema":{"type":"string","maxLength":64},"in":"query","name":"service","required":false,"description":"service_key."},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProfessionalList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/professionals?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"post":{"operationId":"postProfessionals","summary":"Cadastrar profissional","tags":["Profissionais"],"description":"**Permissão:** `professionals:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/professionals\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"<name>\",\n    \"key\": \"<key>\",\n    \"specialty\": \"<specialty>\",\n    \"status\": \"ativo\",\n    \"room\": \"<room>\",\n    \"calendarRef\": \"<calendarRef>\",\n    \"timezone\": \"<timezone>\",\n    \"services\": [\n      \"<service>\"\n    ]\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProfessionalCreate"}}}},"parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"201":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProfessionalResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/professionals\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"<name>\",\n    \"key\": \"<key>\",\n    \"specialty\": \"<specialty>\",\n    \"status\": \"ativo\",\n    \"room\": \"<room>\",\n    \"calendarRef\": \"<calendarRef>\",\n    \"timezone\": \"<timezone>\",\n    \"services\": [\n      \"<service>\"\n    ]\n  }'"}]}},"/v1/professionals/{id}":{"get":{"operationId":"getProfessionalsById","summary":"Detalhe do profissional","tags":["Profissionais"],"description":"**Permissão:** `professionals:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/professionals/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProfessionalResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/professionals/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"patch":{"operationId":"patchProfessionalsById","summary":"Editar profissional","tags":["Profissionais"],"description":"**Permissão:** `professionals:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X PATCH \"{baseUrl}/v1/professionals/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"<name>\",\n    \"specialty\": \"<specialty>\",\n    \"status\": \"ativo\",\n    \"room\": \"<room>\",\n    \"calendarRef\": \"<calendarRef>\",\n    \"timezone\": \"<timezone>\",\n    \"services\": [\n      \"<service>\"\n    ]\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string","minLength":2,"maxLength":128},"specialty":{"anyOf":[{"type":"string","maxLength":128},{"type":"null"}]},"status":{"type":"string","enum":["ativo","inativo"]},"room":{"anyOf":[{"type":"string","maxLength":64},{"type":"null"}]},"calendarRef":{"anyOf":[{"type":"string","maxLength":255,"description":"Id do calendário (Google). Write-only: volta mascarado."},{"type":"null"}]},"timezone":{"anyOf":[{"type":"string","maxLength":64},{"type":"null"}]},"services":{"type":"array","items":{"type":"string","maxLength":64},"maxItems":100}}}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProfessionalResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X PATCH \"{baseUrl}/v1/professionals/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"<name>\",\n    \"specialty\": \"<specialty>\",\n    \"status\": \"ativo\",\n    \"room\": \"<room>\",\n    \"calendarRef\": \"<calendarRef>\",\n    \"timezone\": \"<timezone>\",\n    \"services\": [\n      \"<service>\"\n    ]\n  }'"}]},"delete":{"operationId":"deleteProfessionalsById","summary":"Excluir profissional (exclusão lógica)","tags":["Profissionais"],"description":"**Permissão:** `professionals:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X DELETE \"{baseUrl}/v1/professionals/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"204":{"description":"Default Response"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X DELETE \"{baseUrl}/v1/professionals/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/professionals/{id}/availability":{"get":{"operationId":"getProfessionalsByIdAvailability","summary":"Janelas de disponibilidade do profissional","tags":["Profissionais"],"description":"**Permissão:** `professionals:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/professionals/<id>/availability\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/AvailabilityWindow"}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/professionals/<id>/availability\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"put":{"operationId":"putProfessionalsByIdAvailability","summary":"Substituir janelas de disponibilidade","tags":["Profissionais"],"description":"Janelas anteriores são desativadas (não apagadas). A Vitória só oferece horários dentro destas janelas e livres no calendário.\n\n**Permissão:** `professionals:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X PUT \"{baseUrl}/v1/professionals/<id>/availability\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"windows\":[{\"weekday\":1,\"start\":\"14:00\",\"end\":\"14:00\"}]}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["windows"],"properties":{"windows":{"type":"array","items":{"$ref":"#/components/schemas/AvailabilityWindow"},"maxItems":70}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/AvailabilityWindow"}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X PUT \"{baseUrl}/v1/professionals/<id>/availability\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"windows\":[{\"weekday\":1,\"start\":\"14:00\",\"end\":\"14:00\"}]}'"}]}},"/v1/appointments":{"get":{"operationId":"getAppointments","summary":"Listar agendamentos (lista / filtros)","tags":["Agenda"],"description":"Profissional de saúde recebe apenas os próprios atendimentos. Campos clínicos vêm null sem `clinical:read`.\n\n**Permissão:** `schedule:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/appointments?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryLimit"},{"$ref":"#/components/parameters/QueryCursor"},{"$ref":"#/components/parameters/QueryPage"},{"$ref":"#/components/parameters/QuerySort"},{"schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"},"example":"2026-09-18","in":"query","name":"from","required":false,"description":"Data inicial (inclusive)."},{"schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"},"example":"2026-09-18","in":"query","name":"to","required":false,"description":"Data final (inclusive)."},{"$ref":"#/components/parameters/QueryProfessional"},{"$ref":"#/components/parameters/QueryService"},{"$ref":"#/components/parameters/QueryStatus"},{"$ref":"#/components/parameters/QueryOrigin"},{"schema":{"type":"string","enum":["presencial","online"]},"in":"query","name":"modality","required":false},{"schema":{"type":"string","maxLength":64},"in":"query","name":"room","required":false},{"schema":{"type":"string","enum":["consulta","interno"]},"in":"query","name":"kind","required":false},{"$ref":"#/components/parameters/QueryPatientId"},{"$ref":"#/components/parameters/QueryAgentState"},{"schema":{"type":"string","maxLength":100},"in":"query","name":"q","required":false,"description":"Nome do paciente."},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AppointmentList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/appointments?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"post":{"operationId":"postAppointments","summary":"Criar agendamento (ou evento interno)","tags":["Agenda"],"description":"Valida serviço/profissional no cadastro da clínica e conflito de horário do profissional (409 schedule_conflict). Origem = \"manual\" para humanos e \"agente\" para token de agente. Vincula ao lead (etapa → SCHEDULED) quando leadId é informado.\n\n**Permissão:** `schedule:write`\n\n**Eventos de automação:** `appointment.created`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/appointments\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"date\": \"2026-09-18\",\n    \"start\": \"14:00\",\n    \"kind\": \"consulta\",\n    \"patientId\": \"<patientId>\",\n    \"patientName\": \"<patientName>\",\n    \"leadId\": \"<leadId>\",\n    \"serviceKey\": \"<serviceKey>\",\n    \"professionalKey\": \"<professionalKey>\"\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AppointmentCreate"}}}},"parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"201":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AppointmentActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/appointments\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"date\": \"2026-09-18\",\n    \"start\": \"14:00\",\n    \"kind\": \"consulta\",\n    \"patientId\": \"<patientId>\",\n    \"patientName\": \"<patientName>\",\n    \"leadId\": \"<leadId>\",\n    \"serviceKey\": \"<serviceKey>\",\n    \"professionalKey\": \"<professionalKey>\"\n  }'"}]}},"/v1/appointments/calendar":{"get":{"operationId":"getAppointmentsCalendar","summary":"Agendamentos de um intervalo (visões semana/dia/mês, sem paginação)","tags":["Agenda"],"description":"Intervalo máximo de 62 dias; até 2.000 itens. Mesmos filtros da listagem.\n\n**Permissão:** `schedule:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/appointments/calendar?from=2026-01-15&to=2026-01-15&limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryLimit"},{"$ref":"#/components/parameters/QueryCursor"},{"$ref":"#/components/parameters/QueryPage"},{"$ref":"#/components/parameters/QuerySort"},{"schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"},"example":"2026-09-18","in":"query","name":"from","required":true},{"schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"},"example":"2026-09-18","in":"query","name":"to","required":true},{"$ref":"#/components/parameters/QueryProfessional"},{"$ref":"#/components/parameters/QueryService"},{"$ref":"#/components/parameters/QueryStatus"},{"$ref":"#/components/parameters/QueryOrigin"},{"schema":{"type":"string","enum":["presencial","online"]},"in":"query","name":"modality","required":false},{"schema":{"type":"string","maxLength":64},"in":"query","name":"room","required":false},{"schema":{"type":"string","enum":["consulta","interno"]},"in":"query","name":"kind","required":false},{"$ref":"#/components/parameters/QueryPatientId"},{"$ref":"#/components/parameters/QueryAgentState"},{"schema":{"type":"string","maxLength":100},"in":"query","name":"q","required":false,"description":"Nome do paciente."},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/Appointment"}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/appointments/calendar?from=2026-01-15&to=2026-01-15&limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/appointments/summary":{"get":{"operationId":"getAppointmentsSummary","summary":"KPIs de Atendimentos (semana / dia)","tags":["Agenda"],"description":"**Permissão:** `schedule:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/appointments/summary\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryFrom"},{"$ref":"#/components/parameters/QueryTo"},{"schema":{"type":"string"},"in":"query","name":"professional","required":false},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AppointmentSummaryResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/appointments/summary\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/appointments/attention":{"get":{"operationId":"getAppointmentsAttention","summary":"Sessões que dependem da equipe (contagens leves para a Início)","tags":["Agenda"],"description":"Consultas a partir de `from` (padrão: hoje) com status pendente/remarcação OU horário proposto por agente aguardando aprovação. Só contagens (3 consultas `limit=1` com total), sem itens.\n\n**Permissão:** `schedule:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/appointments/attention\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryFrom"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AppointmentAttentionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/appointments/attention\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/appointments/{id}":{"get":{"operationId":"getAppointmentsById","summary":"Detalhe do atendimento","tags":["Agenda"],"description":"**Permissão:** `schedule:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/appointments/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AppointmentResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/appointments/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"patch":{"operationId":"patchAppointmentsById","summary":"Editar sala, modalidade, tags, observações e registro clínico da sessão","tags":["Agenda"],"description":"`notes` (observações operacionais) exige só schedule:write. reason/nextSteps (registro clínico) exigem `clinical:write`. Status muda só pelas ações dedicadas (confirm, cancel, reschedule…).\n\n**Permissão:** `schedule:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X PATCH \"{baseUrl}/v1/appointments/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"room\": \"<room>\",\n    \"modality\": \"presencial\",\n    \"tags\": [\n      \"<tag>\"\n    ],\n    \"notes\": \"<notes>\",\n    \"reason\": \"<reason>\",\n    \"nextSteps\": [\n      {\n        \"label\": \"<label>\",\n        \"done\": true\n      }\n    ]\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AppointmentPatch"}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AppointmentResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X PATCH \"{baseUrl}/v1/appointments/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"room\": \"<room>\",\n    \"modality\": \"presencial\",\n    \"tags\": [\n      \"<tag>\"\n    ],\n    \"notes\": \"<notes>\",\n    \"reason\": \"<reason>\",\n    \"nextSteps\": [\n      {\n        \"label\": \"<label>\",\n        \"done\": true\n      }\n    ]\n  }'"}]}},"/v1/appointments/{id}/confirm":{"post":{"operationId":"postAppointmentsByIdConfirm","summary":"Confirmar presença","tags":["Agenda"],"description":"**Permissão:** `schedule:write`\n\n**Eventos de automação:** `appointment.confirmed`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/appointments/<id>/confirm\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AppointmentActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/appointments/<id>/confirm\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/appointments/{id}/start":{"post":{"operationId":"postAppointmentsByIdStart","summary":"Iniciar atendimento (em andamento)","tags":["Agenda"],"description":"**Permissão:** `schedule:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/appointments/<id>/start\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AppointmentActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/appointments/<id>/start\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/appointments/{id}/complete":{"post":{"operationId":"postAppointmentsByIdComplete","summary":"Marcar como realizada (compareceu)","tags":["Agenda"],"description":"Registra outcome ATTENDED (PRD §1.15) → Cecília. **Não** cria pagamento: recebimento só existe com transação explícita (PRD §17.1).\n\n**Permissão:** `schedule:write`\n\n**Eventos de automação:** `appointment.outcome`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/appointments/<id>/complete\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AppointmentActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/appointments/<id>/complete\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/appointments/{id}/no-show":{"post":{"operationId":"postAppointmentsByIdNoShow","summary":"Registrar falta (não compareceu)","tags":["Agenda"],"description":"Status \"faltou\" + outcome NO_SHOW → Letícia (recuperação).\n\n**Permissão:** `schedule:write`\n\n**Eventos de automação:** `appointment.outcome`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/appointments/<id>/no-show\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AppointmentActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/appointments/<id>/no-show\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/appointments/{id}/cancel":{"post":{"operationId":"postAppointmentsByIdCancel","summary":"Cancelar com motivo","tags":["Agenda"],"description":"O motivo fica em `cancelReason` (não sobrescreve as observações). Outcome CANCELLED → Letícia conforme política.\n\n**Permissão:** `schedule:write`\n\n**Eventos de automação:** `appointment.cancelled`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/appointments/<id>/cancel\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"reason\":\"<reason>\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"reason":{"type":"string","maxLength":500}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AppointmentActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/appointments/<id>/cancel\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"reason\":\"<reason>\"}'"}]}},"/v1/appointments/{id}/reschedule":{"post":{"operationId":"postAppointmentsByIdReschedule","summary":"Reagendar (nova data/horário e, opcionalmente, outro profissional)","tags":["Agenda"],"description":"**Permissão:** `schedule:write`\n\n**Eventos de automação:** `appointment.rescheduled`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/appointments/<id>/reschedule\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"date\":\"2026-09-18\",\"start\":\"14:00\",\"end\":\"14:00\",\"professionalKey\":\"<professionalKey>\",\"reason\":\"<reason>\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["date","start"],"properties":{"date":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","example":"2026-09-18"},"start":{"type":"string","pattern":"^([01]\\d|2[0-3]):[0-5]\\d$","example":"14:00"},"end":{"type":"string","pattern":"^([01]\\d|2[0-3]):[0-5]\\d$","example":"14:00"},"professionalKey":{"type":"string","maxLength":64},"reason":{"type":"string","maxLength":500}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AppointmentActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/appointments/<id>/reschedule\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"date\":\"2026-09-18\",\"start\":\"14:00\",\"end\":\"14:00\",\"professionalKey\":\"<professionalKey>\",\"reason\":\"<reason>\"}'"}]}},"/v1/appointments/{id}/approve":{"post":{"operationId":"postAppointmentsByIdApprove","summary":"Aprovar sugestão de agendamento do agente","tags":["Agenda"],"description":"Somente para agendamentos com agentState \"aguardando_aprovacao\" ou \"sugestao\".\n\n**Permissão:** `schedule:write` + `approvals:decide`\n\n**Eventos de automação:** `appointment.approval_decided`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/appointments/<id>/approve\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"note\":\"<note>\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"note":{"type":"string","maxLength":500}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AppointmentActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/appointments/<id>/approve\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"note\":\"<note>\"}'"}]}},"/v1/appointments/{id}/reject":{"post":{"operationId":"postAppointmentsByIdReject","summary":"Recusar sugestão de agendamento do agente","tags":["Agenda"],"description":"Somente para agendamentos com agentState \"aguardando_aprovacao\" ou \"sugestao\".\n\n**Permissão:** `schedule:write` + `approvals:decide`\n\n**Eventos de automação:** `appointment.approval_decided`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/appointments/<id>/reject\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"note\":\"<note>\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"note":{"type":"string","maxLength":500}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AppointmentActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/appointments/<id>/reject\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"note\":\"<note>\"}'"}]}},"/v1/appointments/{id}/rating":{"post":{"operationId":"postAppointmentsByIdRating","summary":"Registrar nota da pesquisa de satisfação (pós-atendimento)","tags":["Agenda"],"description":"Normalmente enviado pela agente Sofia (token de serviço) quando o paciente responde a pesquisa (nota 1–5). Só para atendimentos realizados; uma nova nota substitui a anterior. Alimenta Relatórios › Satisfação.\n\n**Permissão:** `schedule:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/appointments/<id>/rating\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"X-Agent-Key: <agent_key>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"score\":1,\"comment\":\"<comment>\",\"channel\":\"whatsapp\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["score"],"properties":{"score":{"type":"integer","minimum":1,"maximum":5},"comment":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}]},"channel":{"type":"string","enum":["whatsapp","sms","email","presencial"],"default":"whatsapp"}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AppointmentResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/appointments/<id>/rating\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"X-Agent-Key: <agent_key>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"score\":1,\"comment\":\"<comment>\",\"channel\":\"whatsapp\"}'"}]}},"/v1/leads":{"get":{"operationId":"getLeads","summary":"Listar leads (lista e colunas do funil)","tags":["Leads"],"description":"**Permissão:** `leads:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/leads?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryLimit"},{"$ref":"#/components/parameters/QueryCursor"},{"$ref":"#/components/parameters/QueryPage"},{"$ref":"#/components/parameters/QuerySort2"},{"$ref":"#/components/parameters/QueryQ"},{"$ref":"#/components/parameters/QueryStage"},{"$ref":"#/components/parameters/QuerySource"},{"$ref":"#/components/parameters/QueryChannel"},{"$ref":"#/components/parameters/QueryService"},{"$ref":"#/components/parameters/QueryProfessional"},{"schema":{"type":"boolean"},"in":"query","name":"qualified","required":false},{"schema":{"type":"boolean"},"in":"query","name":"ready","required":false},{"$ref":"#/components/parameters/QueryAppointment"},{"schema":{"type":"string","enum":["human","agent"]},"in":"query","name":"ownerType","required":false},{"$ref":"#/components/parameters/QueryOwner"},{"$ref":"#/components/parameters/QueryAgent"},{"$ref":"#/components/parameters/QueryCreatedFrom"},{"$ref":"#/components/parameters/QueryCreatedTo"},{"$ref":"#/components/parameters/QueryPeriodDays"},{"$ref":"#/components/parameters/QueryLabels"},{"$ref":"#/components/parameters/QueryCloseFrom"},{"$ref":"#/components/parameters/QueryCloseTo"},{"$ref":"#/components/parameters/QueryHasValue"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/LeadList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/leads?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"post":{"operationId":"postLeads","summary":"Cadastrar lead manualmente","tags":["Leads"],"description":"Entra em \"Novo\" com a Flávia (qualificacao) como responsável.\n\n**Permissão:** `leads:write`\n\n**Eventos de automação:** `lead.created`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/leads\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"<name>\",\n    \"phone\": \"<phone>\",\n    \"source\": \"META_ADS\",\n    \"channel\": \"WhatsApp\",\n    \"serviceKey\": \"<serviceKey>\",\n    \"email\": \"contato@exemplo.com\",\n    \"age\": 1,\n    \"sex\": \"<sex>\"\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/LeadCreate"}}}},"parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"201":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/LeadActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/leads\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"<name>\",\n    \"phone\": \"<phone>\",\n    \"source\": \"META_ADS\",\n    \"channel\": \"WhatsApp\",\n    \"serviceKey\": \"<serviceKey>\",\n    \"email\": \"contato@exemplo.com\",\n    \"age\": 1,\n    \"sex\": \"<sex>\"\n  }'"}]}},"/v1/leads/counts":{"get":{"operationId":"getLeadsCounts","summary":"Contagens dos segmentos (chips e KPIs da tela Leads)","tags":["Leads"],"description":"Só contagens (sem itens), independente da lista e da página. Cada contagem é uma consulta com total.\n\n**Permissão:** `leads:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/leads/counts\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/LeadCountsResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/leads/counts\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/leads/board":{"get":{"operationId":"getLeadsBoard","summary":"Quadro do funil: por etapa, o total e os primeiros cartões","tags":["Leads"],"description":"Uma consulta por etapa (limit = perStage, com total) — o quadro nunca baixa a base inteira. \"Ver mais\" de uma coluna: GET /leads?stage=<etapa>&cursor=<nextCursor> com os mesmos filtros. Aceita os mesmos filtros da listagem.\n\n**Permissão:** `leads:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/leads/board\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QuerySort2"},{"$ref":"#/components/parameters/QueryQ"},{"$ref":"#/components/parameters/QuerySource"},{"$ref":"#/components/parameters/QueryChannel"},{"$ref":"#/components/parameters/QueryService"},{"$ref":"#/components/parameters/QueryProfessional"},{"schema":{"type":"boolean"},"in":"query","name":"qualified","required":false},{"schema":{"type":"boolean"},"in":"query","name":"ready","required":false},{"$ref":"#/components/parameters/QueryAppointment"},{"schema":{"type":"string","enum":["human","agent"]},"in":"query","name":"ownerType","required":false},{"$ref":"#/components/parameters/QueryOwner"},{"$ref":"#/components/parameters/QueryAgent"},{"$ref":"#/components/parameters/QueryCreatedFrom"},{"$ref":"#/components/parameters/QueryCreatedTo"},{"$ref":"#/components/parameters/QueryPeriodDays"},{"$ref":"#/components/parameters/QueryLabels"},{"$ref":"#/components/parameters/QueryCloseFrom"},{"$ref":"#/components/parameters/QueryCloseTo"},{"$ref":"#/components/parameters/QueryHasValue"},{"schema":{"type":"integer","minimum":1,"maximum":50,"default":20},"in":"query","name":"perStage","required":false,"description":"Cartões por etapa (1–50)."},{"schema":{"type":"string"},"in":"query","name":"stages","required":false,"description":"Etapas (vírgula). Padrão: todas (NEW, DISCOVERY, QUALIFIED, READY_TO_SCHEDULE, SCHEDULED, COMPLETED, NURTURE, NOT_A_FIT, HUMAN_HANDOFF)."},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/LeadBoardColumn"}},"meta":{"$ref":"#/components/schemas/LeadValueTotals"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/leads/board\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/leads/forecast":{"get":{"operationId":"getLeadsForecast","summary":"Previsão de fechamento: leads abertos por mês previsto","tags":["Leads"],"description":"Para cada mês (a partir de `from`, padrão o mês atual no fuso da clínica): quantidade e soma de estimatedValue dos leads abertos (todas as etapas menos Virou paciente e Fora do perfil), por etapa, e os primeiros cartões. Aceita os mesmos filtros da listagem. Leads sem data prevista e com data vencida vêm em `noDate` e `overdue`.\n\n**Permissão:** `leads:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/leads/forecast\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryQ"},{"$ref":"#/components/parameters/QueryStage"},{"$ref":"#/components/parameters/QuerySource"},{"$ref":"#/components/parameters/QueryChannel"},{"$ref":"#/components/parameters/QueryService"},{"$ref":"#/components/parameters/QueryProfessional"},{"schema":{"type":"boolean"},"in":"query","name":"qualified","required":false},{"schema":{"type":"boolean"},"in":"query","name":"ready","required":false},{"$ref":"#/components/parameters/QueryAppointment"},{"schema":{"type":"string","enum":["human","agent"]},"in":"query","name":"ownerType","required":false},{"$ref":"#/components/parameters/QueryOwner"},{"$ref":"#/components/parameters/QueryAgent"},{"$ref":"#/components/parameters/QueryCreatedFrom"},{"$ref":"#/components/parameters/QueryCreatedTo"},{"$ref":"#/components/parameters/QueryPeriodDays"},{"$ref":"#/components/parameters/QueryLabels"},{"$ref":"#/components/parameters/QueryHasValue"},{"schema":{"type":"string","pattern":"^\\d{4}-(0[1-9]|1[0-2])$"},"in":"query","name":"from","required":false,"description":"Primeiro mês (YYYY-MM). Padrão: mês atual."},{"schema":{"type":"integer","minimum":1,"maximum":12,"default":6},"in":"query","name":"months","required":false,"description":"Quantos meses (1–12)."},{"schema":{"type":"integer","minimum":1,"maximum":50,"default":10},"in":"query","name":"perMonth","required":false,"description":"Cartões por mês (1–50)."},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/LeadForecastResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/leads/forecast\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/leads/metadata":{"get":{"operationId":"getLeadsMetadata","summary":"Etapas, origens, canais e motivos de \"Fora do perfil\"","tags":["Leads"],"description":"**Permissão:** `leads:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/leads/metadata\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"object","required":["stages","sources","channels","notFitReasons"],"properties":{"stages":{"type":"array","items":{"type":"object","required":["key","label","main"],"properties":{"key":{"type":"string","enum":["NEW","DISCOVERY","QUALIFIED","READY_TO_SCHEDULE","SCHEDULED","COMPLETED","NURTURE","NOT_A_FIT","HUMAN_HANDOFF"]},"label":{"type":"string"},"main":{"type":"boolean"}}}},"sources":{"type":"array","items":{"type":"object","required":["key","label"],"properties":{"key":{"type":"string","enum":["META_ADS","GOOGLE","INSTAGRAM","FECHADA","INFLUENCER","INDICACAO"]},"label":{"type":"string"}}}},"channels":{"type":"array","items":{"type":"string"}},"notFitReasons":{"type":"array","items":{"type":"string"}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/leads/metadata\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/leads/summary":{"get":{"operationId":"getLeadsSummary","summary":"KPIs, funil, origens e série semanal","tags":["Leads"],"description":"Aceita os mesmos filtros da listagem. Conversões só são calculadas quando há leads suficientes (PRD §12).\n\n**Permissão:** `leads:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/leads/summary\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryQ"},{"$ref":"#/components/parameters/QueryStage"},{"$ref":"#/components/parameters/QuerySource"},{"$ref":"#/components/parameters/QueryChannel"},{"$ref":"#/components/parameters/QueryService"},{"$ref":"#/components/parameters/QueryProfessional"},{"schema":{"type":"boolean"},"in":"query","name":"qualified","required":false},{"schema":{"type":"boolean"},"in":"query","name":"ready","required":false},{"$ref":"#/components/parameters/QueryAppointment"},{"schema":{"type":"string","enum":["human","agent"]},"in":"query","name":"ownerType","required":false},{"$ref":"#/components/parameters/QueryOwner"},{"$ref":"#/components/parameters/QueryAgent"},{"$ref":"#/components/parameters/QueryCreatedFrom"},{"$ref":"#/components/parameters/QueryCreatedTo"},{"$ref":"#/components/parameters/QueryPeriodDays"},{"$ref":"#/components/parameters/QueryLabels"},{"$ref":"#/components/parameters/QueryCloseFrom"},{"$ref":"#/components/parameters/QueryCloseTo"},{"$ref":"#/components/parameters/QueryHasValue"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/LeadSummaryResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/leads/summary\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/leads/{id}":{"get":{"operationId":"getLeadsById","summary":"Detalhe do lead","tags":["Leads"],"description":"**Permissão:** `leads:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/leads/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/LeadResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/leads/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"patch":{"operationId":"patchLeadsById","summary":"Atualizar lead (dados, responsável, próxima ação)","tags":["Leads"],"description":"score/qualified/ready só são aceitos de agentes (a qualificação é determinística — PRD §1.4). Etapa muda por POST /leads/{id}/stage.\n\n**Permissão:** `leads:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X PATCH \"{baseUrl}/v1/leads/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"<name>\",\n    \"phone\": \"<phone>\",\n    \"email\": \"contato@exemplo.com\",\n    \"age\": 1,\n    \"sex\": \"<sex>\",\n    \"city\": \"<city>\",\n    \"source\": \"META_ADS\",\n    \"channel\": \"WhatsApp\"\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/LeadPatch"}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/LeadResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X PATCH \"{baseUrl}/v1/leads/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"<name>\",\n    \"phone\": \"<phone>\",\n    \"email\": \"contato@exemplo.com\",\n    \"age\": 1,\n    \"sex\": \"<sex>\",\n    \"city\": \"<city>\",\n    \"source\": \"META_ADS\",\n    \"channel\": \"WhatsApp\"\n  }'"}]},"delete":{"operationId":"deleteLeadsById","summary":"Excluir lead (exclusão lógica, recuperável)","tags":["Leads"],"description":"**Permissão:** `leads:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X DELETE \"{baseUrl}/v1/leads/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"204":{"description":"Default Response"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X DELETE \"{baseUrl}/v1/leads/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/leads/{id}/timeline":{"get":{"operationId":"getLeadsByIdTimeline","summary":"Timeline do lead (mensagens, agentes, follow-ups, transferências)","tags":["Leads"],"description":"**Permissão:** `leads:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/leads/<id>/timeline?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryLimit"},{"$ref":"#/components/parameters/QueryCursor"},{"$ref":"#/components/parameters/QueryPage"},{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PatientTimelineEventList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/leads/<id>/timeline?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/leads/{id}/stage":{"post":{"operationId":"postLeadsByIdStage","summary":"Mover etapa do funil","tags":["Leads"],"description":"\"Fora do perfil\" (NOT_A_FIT) exige `reason` (motivos sugeridos em /leads/metadata). HUMAN_HANDOFF pode indicar o responsável humano. O payload do webhook traz `route_to` (agente que deve assumir).\n\n**Permissão:** `leads:write`\n\n**Eventos de automação:** `lead.stage_changed`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/leads/<id>/stage\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"stage\":\"NEW\",\"reason\":\"<reason>\",\"ownerMembershipId\":\"<ownerMembershipId>\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["stage"],"properties":{"stage":{"type":"string","enum":["NEW","DISCOVERY","QUALIFIED","READY_TO_SCHEDULE","SCHEDULED","COMPLETED","NURTURE","NOT_A_FIT","HUMAN_HANDOFF"]},"reason":{"type":"string","maxLength":255},"ownerMembershipId":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9._-]+$","description":"Responsável humano (HUMAN_HANDOFF)."}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/LeadActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/leads/<id>/stage\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"stage\":\"NEW\",\"reason\":\"<reason>\",\"ownerMembershipId\":\"<ownerMembershipId>\"}'"}]}},"/v1/leads/{id}/convert":{"post":{"operationId":"postLeadsByIdConvert","summary":"Converter lead em paciente (\"Virou paciente\")","tags":["Leads"],"description":"Cria o cadastro em Pacientes com origem \"Lead (<origem>)\" e move o lead para COMPLETED.\n\n**Permissão:** `leads:write` + `patients:write`\n\n**Eventos de automação:** `lead.converted`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/leads/<id>/convert\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"201":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"object","required":["lead","patientId"],"properties":{"lead":{"$ref":"#/components/schemas/Lead"},"patientId":{"type":"string"}}},"meta":{"$ref":"#/components/schemas/ActionMeta"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/leads/<id>/convert\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/leads/labels":{"get":{"operationId":"getLeadsLabels","summary":"Etiquetas de lead da clínica","tags":["Leads"],"description":"Catálogo da clínica: nome e cor de uma paleta fechada (blue, green, amber, red, violet, pink, teal, slate). Cada lead aceita até 5 etiquetas (`labelIds`).\n\n**Permissão:** `leads:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/leads/labels\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/LeadLabel"}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/leads/labels\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"post":{"operationId":"postLeadsLabels","summary":"Criar etiqueta de lead","tags":["Leads"],"description":"Até 30 etiquetas por clínica. Nome repetido (sem diferenciar maiúsculas e acentos) → 409 `duplicate`.\n\n**Permissão:** `leads:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/leads/labels\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"name\":\"<name>\",\"color\":\"blue\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/LeadLabelCreate"}}}},"parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"201":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/LeadLabelResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/leads/labels\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"name\":\"<name>\",\"color\":\"blue\"}'"}]}},"/v1/leads/labels/{id}":{"patch":{"operationId":"patchLeadsLabelsById","summary":"Renomear ou trocar a cor de uma etiqueta","tags":["Leads"],"description":"Os leads guardam o id: a mudança aparece em todos eles, sem reescrever os leads.\n\n**Permissão:** `leads:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X PATCH \"{baseUrl}/v1/leads/labels/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"name\":\"<name>\",\"color\":\"blue\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/LeadLabelPatch"}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/LeadLabelResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X PATCH \"{baseUrl}/v1/leads/labels/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"name\":\"<name>\",\"color\":\"blue\"}'"}]},"delete":{"operationId":"deleteLeadsLabelsById","summary":"Excluir etiqueta de lead","tags":["Leads"],"description":"Sai do catálogo e deixa de aparecer nos leads (os leads não são reescritos; o id órfão é ignorado na leitura).\n\n**Permissão:** `leads:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X DELETE \"{baseUrl}/v1/leads/labels/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"204":{"description":"Default Response"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X DELETE \"{baseUrl}/v1/leads/labels/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/conversations":{"get":{"operationId":"getConversations","summary":"Listar conversas (abas, canal, responsável, busca e ordenação no servidor)","tags":["Comunicação"],"description":"Projeção leve (sem contato/agendamentos — veja GET /conversations/{id}). Use `cursor` para rolagem infinita.\n\n**Permissão:** `conversations:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/conversations?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryLimit"},{"$ref":"#/components/parameters/QueryCursor"},{"$ref":"#/components/parameters/QueryPage"},{"$ref":"#/components/parameters/QueryChannel2"},{"$ref":"#/components/parameters/QueryAgent2"},{"$ref":"#/components/parameters/QueryQ2"},{"$ref":"#/components/parameters/QueryPatientId"},{"$ref":"#/components/parameters/QueryLeadId"},{"schema":{"type":"string","enum":["all","mine","unread","archived"],"default":"all"},"in":"query","name":"view","required":false,"description":"all exclui arquivadas."},{"schema":{"type":"string","maxLength":60,"default":"-lastMessageAt"},"in":"query","name":"sort","required":false,"description":"Campos: lastMessageAt, unread, name (prefixo - = decrescente). Ex.: -unread,-lastMessageAt."},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ConversationList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/conversations?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"post":{"operationId":"postConversations","summary":"Iniciar conversa com um contato","tags":["Comunicação"],"description":"Informe patientId ou leadId (recomendado) ou contactName + phone/email. Usado também pela automação de atendimento ao receber o primeiro contato.\n\n**Agent Preview (somente token de serviço):** `externalRef` = prefixo reservado de prévia + UUIDv4 em minúsculas e `channel = outros`, sem `patientId`, `leadId`, `contactName`, `phone` nem `email` (422). A sessão pertence ao agente que a criou; repetir a mesma sessão devolve **200** com `Idempotent-Replayed: true`; sessão de outro agente → 404.\n\n**Permissão:** `conversations:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/conversations\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"X-Agent-Key: <agent_key>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"channel\": \"whatsapp\",\n    \"patientId\": \"<patientId>\",\n    \"leadId\": \"<leadId>\",\n    \"contactName\": \"<contactName>\",\n    \"phone\": \"<phone>\",\n    \"email\": \"contato@exemplo.com\",\n    \"externalRef\": \"<externalRef>\"\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["channel"],"properties":{"channel":{"type":"string","enum":["whatsapp","email","sms","instagram","outros"]},"patientId":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9._-]+$"},"leadId":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9._-]+$"},"contactName":{"type":"string","minLength":2,"maxLength":128},"phone":{"type":"string","maxLength":32},"email":{"type":"string","format":"email","maxLength":160},"externalRef":{"type":"string","maxLength":255,"description":"Id da conversa no provedor (somente token de serviço)."}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ConversationResponse"}}}},"201":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ConversationResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/conversations\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"X-Agent-Key: <agent_key>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"channel\": \"whatsapp\",\n    \"patientId\": \"<patientId>\",\n    \"leadId\": \"<leadId>\",\n    \"contactName\": \"<contactName>\",\n    \"phone\": \"<phone>\",\n    \"email\": \"contato@exemplo.com\",\n    \"externalRef\": \"<externalRef>\"\n  }'"}]}},"/v1/conversations/counts":{"get":{"operationId":"getConversationsCounts","summary":"Contadores das abas da caixa de entrada (leve; sem itens)","tags":["Comunicação"],"description":"`all`/`unread`/`mine`/`archived` respeitam canal, responsável e busca (como a lista). `unreadByChannel` = conversas abertas com não lidas por canal (sem os filtros), para as abas de canal.\n\n**Permissão:** `conversations:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/conversations/counts\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryChannel2"},{"$ref":"#/components/parameters/QueryAgent2"},{"$ref":"#/components/parameters/QueryQ2"},{"$ref":"#/components/parameters/QueryPatientId"},{"$ref":"#/components/parameters/QueryLeadId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ConversationCountsResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/conversations/counts\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/conversations/{id}":{"get":{"operationId":"getConversationsById","summary":"Conversa com dados do contato e últimos agendamentos","tags":["Comunicação"],"description":"**Permissão:** `conversations:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/conversations/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ConversationDetailResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/conversations/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"patch":{"operationId":"patchConversationsById","summary":"Arquivar/desarquivar, marcar como lida, tags","tags":["Comunicação"],"description":"**Permissão:** `conversations:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X PATCH \"{baseUrl}/v1/conversations/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"archived\":true,\"read\":true,\"tags\":[\"<tag>\"]}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"archived":{"type":"boolean"},"read":{"type":"boolean","description":"Zera o contador de não lidas.","enum":[true]},"tags":{"type":"array","items":{"type":"string","maxLength":40},"maxItems":20}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ConversationResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X PATCH \"{baseUrl}/v1/conversations/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"archived\":true,\"read\":true,\"tags\":[\"<tag>\"]}'"}]}},"/v1/conversations/{id}/messages":{"get":{"operationId":"getConversationsByIdMessages","summary":"Mensagens da conversa (mais recentes primeiro; use o cursor para carregar as anteriores)","tags":["Comunicação"],"description":"**Permissão:** `conversations:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/conversations/<id>/messages?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryLimit"},{"$ref":"#/components/parameters/QueryCursor"},{"$ref":"#/components/parameters/QueryPage"},{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MessageList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/conversations/<id>/messages?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"post":{"operationId":"postConversationsByIdMessages","summary":"Enviar mensagem (humano ou agente) / registrar recebida (token de serviço)","tags":["Comunicação"],"description":"Humano enviando numa conversa conduzida por agente **assume a conversa** (o agente para de responder). `direction: \"inbound\"` e `externalRef` só são aceitos com token de serviço (automação registrando a mensagem do paciente).\n\n**Obsoleto:** `direction: \"inbound\"` continua funcionando por compatibilidade, mas não é idempotente nem gera `message.received`. Use **`POST /v1/inbound/messages`** (atômico, idempotente, com outbox). Respostas inbound trazem os cabeçalhos `Deprecation: true` e `Link: </v1/inbound/messages>; rel=\"successor-version\"`.\n\n**Agent Preview (`recordOnly: true`):** só o agente dono da sessão de prévia (token de serviço), `direction = outbound`, cabeçalho **`Idempotency-Key` obrigatório**, sem `externalRef`. Grava com `delivery = registrado` e não emite `message.send` nem outbox. Primeira gravação → **201**; repetição exata → **200** com `Idempotent-Replayed: true`; mesma chave com outro conteúdo → **409** `idempotency_key_reused`. Resposta incerta (erro 5xx/timeout): repita com a MESMA chave — a repetição conclui a gravação sem duplicar. Conversas de prévia não aceitam mensagem sem `recordOnly` (403 `preview_record_only`); outro agente → 404.\n\n**Permissão:** `conversations:write`\n\n**Eventos de automação:** `message.send`, `conversation.takeover`\n\n**Rate limit:** 60 requisições / 60 s.\n\n**E-mail verificado:** quando a verificação de e-mail está ligada no ambiente, contas com e-mail ainda não confirmado recebem 403 `email_not_verified`.\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/conversations/<id>/messages\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"X-Agent-Key: <agent_key>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"text\":\"<text>\",\"direction\":\"outbound\",\"externalRef\":\"<externalRef>\",\"recordOnly\":false}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["text"],"properties":{"text":{"type":"string","minLength":1,"maxLength":4000},"direction":{"type":"string","enum":["outbound","inbound"],"default":"outbound","description":"`inbound` está **obsoleto** (use POST /v1/inbound/messages)."},"externalRef":{"type":"string","maxLength":255},"recordOnly":{"type":"boolean","default":false,"description":"Somente token de serviço (agente dono da sessão): registra uma resposta de Agent Preview sem emitir message.send. Exige Idempotency-Key."}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"},{"schema":{"type":"string","minLength":1,"maxLength":255,"pattern":"^[\\x21-\\x7E]+$"},"in":"header","name":"idempotency-key","required":false,"description":"Obrigatória com `recordOnly: true` (chave técnica do turno da prévia; ASCII visível, sem espaços). Ignorada nos demais casos."}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MessageActionResponse"}}}},"201":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MessageActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/conversations/<id>/messages\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"X-Agent-Key: <agent_key>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"text\":\"<text>\",\"direction\":\"outbound\",\"externalRef\":\"<externalRef>\",\"recordOnly\":false}'"}]}},"/v1/conversations/{id}/messages/{messageId}":{"patch":{"operationId":"patchConversationsByIdMessagesByMessageId","summary":"Atualizar status de entrega (somente token de serviço)","tags":["Comunicação"],"description":"**Permissão:** `conversations:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X PATCH \"{baseUrl}/v1/conversations/<id>/messages/<messageId>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"X-Agent-Key: <agent_key>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"delivery\":\"enviando\",\"externalRef\":\"<externalRef>\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["delivery"],"properties":{"delivery":{"type":"string","enum":["enviando","entregue","lido","falhou","registrado"]},"externalRef":{"type":"string","maxLength":255}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId2"},{"schema":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9._-]+$"},"in":"path","name":"messageId","required":true},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MessageResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X PATCH \"{baseUrl}/v1/conversations/<id>/messages/<messageId>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"X-Agent-Key: <agent_key>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"delivery\":\"enviando\",\"externalRef\":\"<externalRef>\"}'"}]}},"/v1/conversations/{id}/takeover":{"post":{"operationId":"postConversationsByIdTakeover","summary":"Assumir conversa (pausar o agente nesta conversa)","tags":["Comunicação"],"description":"**Permissão:** `conversations:write`\n\n**Eventos de automação:** `conversation.takeover`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/conversations/<id>/takeover\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"agentKey\":\"<agentKey>\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"agentKey":{"type":"string","maxLength":64,"description":"release: agente que reassume (padrão: qualificacao)."}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ConversationActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/conversations/<id>/takeover\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"agentKey\":\"<agentKey>\"}'"}]}},"/v1/conversations/{id}/release":{"post":{"operationId":"postConversationsByIdRelease","summary":"Devolver conversa ao agente","tags":["Comunicação"],"description":"**Permissão:** `conversations:write`\n\n**Eventos de automação:** `conversation.released`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/conversations/<id>/release\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"agentKey\":\"<agentKey>\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"agentKey":{"type":"string","maxLength":64,"description":"release: agente que reassume (padrão: qualificacao)."}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ConversationActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/conversations/<id>/release\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"agentKey\":\"<agentKey>\"}'"}]}},"/v1/inbound/messages":{"post":{"operationId":"postInboundMessages","summary":"Registrar mensagem recebida do paciente (gateway; atômico e idempotente)","tags":["Comunicação"],"description":"Somente token de serviço (gateway do canal → motor de automação). Em uma operação: encontra ou cria a conversa por `(clínica, channel, externalChatRef)`, vincula paciente/lead pelo telefone **dentro da clínica**, grava a mensagem, atualiza não lidas/prévia e grava o evento `message.received` no **outbox** (reentrega com backoff; `event_id` estável).\n\n**Idempotência:** cabeçalho `Idempotency-Key` (padrão `<channel>:<externalMessageId>`). Primeira vez → **201**; repetição (sequencial ou simultânea) → **200** com o mesmo conteúdo e `meta.idempotent = true`, sem nova mensagem e sem novo evento. Mesma chave com outro conteúdo → 409 `idempotency_key_reused`. Mensagem já registrada por outro caminho com o mesmo `externalMessageId` na conversa também conta como repetição.\n\nMesmo `externalMessageId` já registrado na conversa com **outro texto** → 409 `idempotency_key_reused`, mesmo com outra `Idempotency-Key`.\n\n**Agent Preview:** `externalChatRef` = prefixo reservado de prévia + UUIDv4 em minúsculas e `channel = outros`, sem `phone`, `contactName` nem `media` (422). A sessão pertence ao agente autenticado (outro agente → 404), nunca é vinculada a paciente/lead e **não grava outbox nem dispara evento**: `data.event = null` e `meta.webhooks = []`.\n\n**Sandbox:** sem motor de automação configurado o evento fica no outbox com status `disabled` (visível em `GET /v1/outbox`, reenvio manual).\n\n**Permissão:** `conversations:write`\n\n**Eventos de automação:** `message.received`\n\n**Rate limit:** 600 requisições / 60 s.\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/inbound/messages\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"X-Agent-Key: <agent_key>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"channel\": \"whatsapp\",\n    \"externalMessageId\": \"<externalMessageId>\",\n    \"externalChatRef\": \"<externalChatRef>\",\n    \"text\": \"<text>\",\n    \"receivedAt\": \"2026-01-15T14:00:00.000Z\",\n    \"contactName\": \"<contactName>\",\n    \"phone\": \"<phone>\",\n    \"media\": {\n      \"type\": \"image\",\n      \"url\": \"https://exemplo.com\",\n      \"caption\": \"<caption>\"\n    }\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/InboundMessage"}}}},"parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"},{"schema":{"type":"string","minLength":1,"maxLength":255,"pattern":"^[\\x21-\\x7E]+$"},"in":"header","name":"idempotency-key","required":false,"description":"Chave de idempotência (ASCII visível, sem espaços). Padrão: `<channel>:<externalMessageId>`."}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InboundMessageResponse"}}}},"201":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InboundMessageResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/inbound/messages\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"X-Agent-Key: <agent_key>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"channel\": \"whatsapp\",\n    \"externalMessageId\": \"<externalMessageId>\",\n    \"externalChatRef\": \"<externalChatRef>\",\n    \"text\": \"<text>\",\n    \"receivedAt\": \"2026-01-15T14:00:00.000Z\",\n    \"contactName\": \"<contactName>\",\n    \"phone\": \"<phone>\",\n    \"media\": {\n      \"type\": \"image\",\n      \"url\": \"https://exemplo.com\",\n      \"caption\": \"<caption>\"\n    }\n  }'"}]}},"/v1/agents":{"get":{"operationId":"getAgents","summary":"Time de agentes habilitado na clínica","tags":["Agentes"],"description":"**Permissão:** `agents:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/agents\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/Agent"}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/agents\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/agents/summary":{"get":{"operationId":"getAgentsSummary","summary":"KPIs do módulo Agentes","tags":["Agentes"],"description":"**Permissão:** `agents:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/agents/summary\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"object","required":["active","running","handoffsToday","resolutionAvg","needsAttention"],"properties":{"active":{"type":"integer","description":"Habilitados com status ativo, em execução ou com a equipe (handoff) — mesma regra do filtro \"Ativos\" do painel; com falha ou em pausa não contam."},"running":{"type":"integer","description":"Em execução agora."},"handoffsToday":{"type":"integer"},"resolutionAvg":{"anyOf":[{"type":"number","description":"Média de \"Resolvidos sem a equipe\" (%)."},{"type":"null"}]},"needsAttention":{"type":"integer","description":"Com falha ou em pausa."}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/agents/summary\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/agents/pause":{"post":{"operationId":"postAgentsPause","summary":"Pausar todos os agentes da clínica","tags":["Agentes"],"description":"**Permissão:** `agents:manage`\n\n**Eventos de automação:** `agent.paused`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/agents/pause\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"reason\":\"<reason>\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["reason"],"properties":{"reason":{"type":"string","minLength":3,"maxLength":255}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/Agent"}},"meta":{"$ref":"#/components/schemas/ActionMeta"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/agents/pause\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"reason\":\"<reason>\"}'"}]}},"/v1/agents/{key}":{"get":{"operationId":"getAgentsByKey","summary":"Detalhe do agente (painel lateral)","tags":["Agentes"],"description":"**Permissão:** `agents:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/agents/<key>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathKey"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentDetailResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/agents/<key>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/agents/{key}/config":{"patch":{"operationId":"patchAgentsByKeyConfig","summary":"Alterar configuração do agente (horário, limite, aprovação, tom)","tags":["Agentes"],"description":"Prompts e versões centrais não são editáveis pela clínica (PRD §19).\n\n**Permissão:** `agents:manage`\n\n**Eventos de automação:** `agent.config_updated`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X PATCH \"{baseUrl}/v1/agents/<key>/config\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"schedule\":\"<schedule>\",\"dailyLimit\":\"<dailyLimit>\",\"approvalRequired\":true,\"tone\":\"<tone>\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"schedule":{"anyOf":[{"type":"string","maxLength":80},{"type":"null"}]},"dailyLimit":{"anyOf":[{"type":"string","maxLength":40},{"type":"null"}]},"approvalRequired":{"type":"boolean"},"tone":{"anyOf":[{"type":"string","maxLength":80},{"type":"null"}]}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathKey"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentConfigActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X PATCH \"{baseUrl}/v1/agents/<key>/config\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"schedule\":\"<schedule>\",\"dailyLimit\":\"<dailyLimit>\",\"approvalRequired\":true,\"tone\":\"<tone>\"}'"}]}},"/v1/agents/{key}/pause":{"post":{"operationId":"postAgentsByKeyPause","summary":"Pausar agente","tags":["Agentes"],"description":"Guarda o status atual (ativo, em execução, com falha, com a equipe) para o retomar restaurá-lo.\n\n**Permissão:** `agents:manage`\n\n**Eventos de automação:** `agent.paused`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/agents/<key>/pause\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"reason\":\"<reason>\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"reason":{"type":"string","maxLength":255}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathKey"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/agents/<key>/pause\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"reason\":\"<reason>\"}'"}]}},"/v1/agents/{key}/resume":{"post":{"operationId":"postAgentsByKeyResume","summary":"Retomar agente","tags":["Agentes"],"description":"Volta ao status que o agente tinha antes da pausa (ex.: \"Em execução\"); sem registro, volta para \"ativo\".\n\n**Permissão:** `agents:manage`\n\n**Eventos de automação:** `agent.resumed`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/agents/<key>/resume\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"reason\":\"<reason>\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"reason":{"type":"string","maxLength":255}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathKey"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/agents/<key>/resume\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"reason\":\"<reason>\"}'"}]}},"/v1/agents/{key}/runs":{"get":{"operationId":"getAgentsByKeyRuns","summary":"Execuções do agente (cursor; filtros de status e período)","tags":["Agentes"],"description":"**Permissão:** `agents:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/agents/<key>/runs?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryLimit"},{"$ref":"#/components/parameters/QueryCursor"},{"$ref":"#/components/parameters/QueryPage"},{"schema":{"type":"string"},"in":"query","name":"status","required":false,"description":"Status separados por vírgula: sucesso, falha, aprovacao, humano, execucao."},{"schema":{"type":"boolean"},"in":"query","name":"today","required":false},{"schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"},"example":"2026-09-18","in":"query","name":"from","required":false,"description":"Execuções iniciadas a partir desta data (inclusive)."},{"schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"},"example":"2026-09-18","in":"query","name":"to","required":false,"description":"Execuções iniciadas até esta data (inclusive)."},{"$ref":"#/components/parameters/PathKey"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentRunList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/agents/<key>/runs?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"post":{"operationId":"postAgentsByKeyRuns","summary":"Registrar execução (token de serviço)","tags":["Agentes"],"description":"Somente token de serviço com X-Agent-Key igual ao agente da rota. clinic_id vem do contexto.\n\n**Permissão:** `agents:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/agents/<key>/runs\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"X-Agent-Key: <agent_key>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"title\": \"<title>\",\n    \"status\": \"sucesso\",\n    \"detail\": \"<detail>\",\n    \"startedAt\": \"2026-01-15T14:00:00.000Z\",\n    \"finishedAt\": \"2026-01-15T14:00:00.000Z\",\n    \"traceId\": \"<traceId>\",\n    \"leadId\": \"<leadId>\",\n    \"conversationId\": \"<conversationId>\"\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["title","status"],"properties":{"title":{"type":"string","minLength":2,"maxLength":160},"detail":{"type":"string","maxLength":500},"status":{"type":"string","enum":["sucesso","falha","aprovacao","humano","execucao"]},"startedAt":{"type":"string","format":"date-time"},"finishedAt":{"type":"string","format":"date-time"},"traceId":{"type":"string","maxLength":64},"leadId":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9._-]+$"},"conversationId":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9._-]+$"},"errorCode":{"type":"string","maxLength":64},"retryOf":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9._-]+$"}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathKey"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"201":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentRunResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/agents/<key>/runs\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"X-Agent-Key: <agent_key>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"title\": \"<title>\",\n    \"status\": \"sucesso\",\n    \"detail\": \"<detail>\",\n    \"startedAt\": \"2026-01-15T14:00:00.000Z\",\n    \"finishedAt\": \"2026-01-15T14:00:00.000Z\",\n    \"traceId\": \"<traceId>\",\n    \"leadId\": \"<leadId>\",\n    \"conversationId\": \"<conversationId>\"\n  }'"}]}},"/v1/agents/{key}/runs/{runId}/retry":{"post":{"operationId":"postAgentsByKeyRunsByRunIdRetry","summary":"Tentar de novo uma execução com falha","tags":["Agentes"],"description":"Somente execuções com status \"falha\". A automação reprocessa e registra uma nova execução (retry_of = runId).\n\n**Permissão:** `agents:manage`\n\n**Eventos de automação:** `agent.run_retry`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/agents/<key>/runs/<runId>/retry\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathKey"},{"schema":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9._-]+$"},"in":"path","name":"runId","required":true},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"202":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentRunActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/agents/<key>/runs/<runId>/retry\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/agents/{key}/state":{"patch":{"operationId":"patchAgentsByKeyState","summary":"Atualizar estado e métricas do agente (token de serviço)","tags":["Agentes"],"description":"Status \"pausa\" só é definido por humanos (POST /pause); o agente não sai de pausa sozinho.\n\n**Permissão:** `agents:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X PATCH \"{baseUrl}/v1/agents/<key>/state\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"X-Agent-Key: <agent_key>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"status\": \"ativo\",\n    \"nextAction\": \"<nextAction>\",\n    \"activity\": \"<activity>\",\n    \"handoffsToday\": 0,\n    \"resolutionRate\": 1,\n    \"performance\": [\n      {\n        \"value\": \"<value>\",\n        \"label\": \"<label>\"\n      }\n    ]\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"status":{"type":"string","enum":["ativo","execucao","erro","handoff"]},"nextAction":{"anyOf":[{"type":"string","maxLength":128},{"type":"null"}]},"activity":{"anyOf":[{"type":"string","maxLength":255},{"type":"null"}]},"handoffsToday":{"type":"integer","minimum":0},"resolutionRate":{"anyOf":[{"type":"number","minimum":0,"maximum":100},{"type":"null"}]},"performance":{"type":"array","items":{"type":"object","required":["value","label"],"properties":{"value":{"type":"string","maxLength":20},"label":{"type":"string","maxLength":80}}},"maxItems":8}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathKey"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X PATCH \"{baseUrl}/v1/agents/<key>/state\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"X-Agent-Key: <agent_key>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"status\": \"ativo\",\n    \"nextAction\": \"<nextAction>\",\n    \"activity\": \"<activity>\",\n    \"handoffsToday\": 0,\n    \"resolutionRate\": 1,\n    \"performance\": [\n      {\n        \"value\": \"<value>\",\n        \"label\": \"<label>\"\n      }\n    ]\n  }'"}]}},"/v1/approvals":{"post":{"operationId":"postApprovals","summary":"Pedir aprovação humana (agente, token de serviço)","tags":["Aprovações"],"description":"**Permissão:** `agents:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/approvals\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"X-Agent-Key: <agent_key>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"action\": \"Enviar mensagem de retorno para 3 pacientes\",\n    \"context\": \"<context>\",\n    \"resourceType\": \"appointment\",\n    \"resourceId\": \"<resourceId>\",\n    \"payload\": {},\n    \"runId\": \"<runId>\"\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["action"],"properties":{"action":{"type":"string","minLength":3,"maxLength":255,"example":"Enviar mensagem de retorno para 3 pacientes"},"context":{"type":"string","maxLength":500},"resourceType":{"type":"string","enum":["appointment","lead","patient","transaction","conversation","campaign"]},"resourceId":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9._-]+$"},"payload":{"type":"object","description":"Dados que a automação executa depois da aprovação (sem segredos).","additionalProperties":{}},"runId":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9._-]+$"}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"201":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApprovalResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/approvals\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"X-Agent-Key: <agent_key>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"action\": \"Enviar mensagem de retorno para 3 pacientes\",\n    \"context\": \"<context>\",\n    \"resourceType\": \"appointment\",\n    \"resourceId\": \"<resourceId>\",\n    \"payload\": {},\n    \"runId\": \"<runId>\"\n  }'"}]},"get":{"operationId":"getApprovals","summary":"Fila de aprovações da clínica (tela Aprovações, Início, painel do agente, Agenda)","tags":["Aprovações"],"description":"Lista paginada (page/limit ou cursor) e leve: sem o `payload` que a automação executa. Todos os filtros são opcionais — sem `agent` devolve a fila inteira da clínica, mais recentes primeiro. `status` padrão: pendente.\n\n**Permissão (qualquer uma):** `approvals:decide`, `agents:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/approvals?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryLimit"},{"$ref":"#/components/parameters/QueryCursor"},{"$ref":"#/components/parameters/QueryPage"},{"schema":{"type":"string","enum":["pendente","aprovado","rejeitado","expirado"],"default":"pendente"},"in":"query","name":"status","required":false},{"schema":{"type":"string","maxLength":64},"in":"query","name":"agent","required":false,"description":"Chave do agente (opcional)."},{"schema":{"type":"string","maxLength":32},"in":"query","name":"resourceType","required":false,"description":"Tipo do recurso: appointment, lead, patient, transaction, conversation, campaign."},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApprovalList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/approvals?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/approvals/{id}/approve":{"post":{"operationId":"postApprovalsByIdApprove","summary":"Aprovar ação do agente","tags":["Aprovações"],"description":"A automação executa a ação aprovada.\n\n**Permissão:** `approvals:decide`\n\n**Eventos de automação:** `agent.approval_decided`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/approvals/<id>/approve\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"note\":\"<note>\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"note":{"type":"string","maxLength":500}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApprovalActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/approvals/<id>/approve\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"note\":\"<note>\"}'"}]}},"/v1/approvals/{id}/reject":{"post":{"operationId":"postApprovalsByIdReject","summary":"Rejeitar ação do agente","tags":["Aprovações"],"description":"Motivo obrigatório (fica no histórico e volta ao agente).\n\n**Permissão:** `approvals:decide`\n\n**Eventos de automação:** `agent.approval_decided`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/approvals/<id>/reject\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"note\":\"<note>\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["note"],"properties":{"note":{"type":"string","minLength":3,"maxLength":500}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApprovalActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/approvals/<id>/reject\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"note\":\"<note>\"}'"}]}},"/v1/agents/{key}/preflight":{"post":{"operationId":"postAgentsByKeyPreflight","summary":"Observar os gates F02 do agente (sem autorizar execução)","tags":["Agentes"],"description":"Somente token de serviço, e `key` precisa ser o próprio agente autenticado (`X-Agent-Key`). Humanos → 403 `service_only`; outro agente → 403 `agent_context_mismatch`.\n\nCorpo aceita só `trace_id`, `requested_operation` (declaração não confiável; não comprova PURPOSE_ALLOWED) e `conversation_id`. Qualquer outro campo (ex.: `allowed`, `consent`, `clinic_id`) → 400 `preflight_untrusted_field`.\n\nResposta com 16 gates `PASS | FAIL | UNVERIFIED`, sem dados pessoais. Sem fonte canônica = UNVERIFIED → `HOLD`; algum FAIL → `DENY`. **`authorized` e `send` são sempre false**: é evidência para o motor de automação, não licença de execução nem snapshot transacional (não reserva lock nem limite, não grava nada, não chama o motor de automação nem modelo de linguagem).\n\nConversa de outra clínica, inexistente ou sessão de prévia de outro agente → 404.\n\n**Permissão:** `agents:read`\n\n**Rate limit:** 60 requisições / 60 s.\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/agents/<key>/preflight\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"X-Agent-Key: <agent_key>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"trace_id\":\"<trace_id>\",\"requested_operation\":\"<requested_operation>\",\"conversation_id\":\"<conversation_id>\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentPreflightRequest"}}}},"parameters":[{"schema":{"type":"string","pattern":"^[a-z0-9-]{2,64}$"},"in":"path","name":"key","required":true},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentPreflightResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/agents/<key>/preflight\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"X-Agent-Key: <agent_key>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"trace_id\":\"<trace_id>\",\"requested_operation\":\"<requested_operation>\",\"conversation_id\":\"<conversation_id>\"}'"}]}},"/v1/automations":{"get":{"operationId":"getAutomations","summary":"Catálogo de automações com o estado da clínica","tags":["Automações"],"description":"**Permissão:** `automations:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/automations\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"schema":{"type":"string"},"in":"query","name":"category","required":false,"description":"Categorias: agendamento, relacionamento, receita, leads, ia, pos-atendimento, retencao, extensoes."},{"schema":{"type":"boolean"},"in":"query","name":"subscribed","required":false,"description":"true = só \"Minhas automações\" (ativas, em teste ou canceladas ainda vigentes)."},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/Automation"}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/automations\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/automations/{id}":{"get":{"operationId":"getAutomationsById","summary":"Detalhe da automação (painel lateral)","tags":["Automações"],"description":"**Permissão:** `automations:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/automations/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AutomationResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/automations/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/automations/{id}/subscription":{"post":{"operationId":"postAutomationsByIdSubscription","summary":"Contratar ou iniciar teste de 7 dias","tags":["Automações"],"description":"`mode: \"trial\"` só na primeira vez (409 trial_unavailable depois). `mode: \"active\"` cobra o proporcional do ciclo atual; reativar no mesmo ciclo após desativar mantém a data original (já cobrada).\n\n**Permissão:** `automations:manage`\n\n**Eventos de automação:** `automation.subscribed`\n\n**E-mail verificado:** quando a verificação de e-mail está ligada no ambiente, contas com e-mail ainda não confirmado recebem 403 `email_not_verified`.\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/automations/<id>/subscription\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"mode\":\"trial\",\"settings\":{}}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["mode"],"properties":{"mode":{"type":"string","enum":["trial","active"]},"settings":{"type":"object","additionalProperties":{"anyOf":[{"type":"boolean"},{"type":"string"}]}}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"201":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AutomationSubscribedActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/automations/<id>/subscription\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"mode\":\"trial\",\"settings\":{}}'"}]},"patch":{"operationId":"patchAutomationsByIdSubscription","summary":"Alterar configurações da automação contratada","tags":["Automações"],"description":"**Permissão:** `automations:manage`\n\n**Eventos de automação:** `automation.settings_updated`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X PATCH \"{baseUrl}/v1/automations/<id>/subscription\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"settings\":{}}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["settings"],"properties":{"settings":{"type":"object","additionalProperties":{"anyOf":[{"type":"boolean"},{"type":"string"}]}}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AutomationActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X PATCH \"{baseUrl}/v1/automations/<id>/subscription\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"settings\":{}}'"}]},"delete":{"operationId":"deleteAutomationsByIdSubscription","summary":"Desativar automação","tags":["Automações"],"description":"Em teste: encerra sem cobrança. Ativa: continua até o fim do ciclo já cobrado (activeUntil) e sai da próxima fatura.\n\n**Permissão:** `automations:manage`\n\n**Eventos de automação:** `automation.cancelled`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X DELETE \"{baseUrl}/v1/automations/<id>/subscription\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AutomationActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X DELETE \"{baseUrl}/v1/automations/<id>/subscription\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/billing":{"get":{"operationId":"getBilling","summary":"Plano atual, uso, automações e próxima fatura","tags":["Plano e assinatura"],"description":"**Permissão:** `billing:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/billing\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/BillingResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/billing\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/billing/plans":{"get":{"operationId":"getBillingPlans","summary":"Planos disponíveis (comparação + avisos de limite)","tags":["Plano e assinatura"],"description":"**Permissão:** `billing:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/billing/plans\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/Plan"}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/billing/plans\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/billing/plan-changes":{"post":{"operationId":"postBillingPlanChanges","summary":"Solicitar mudança de plano","tags":["Plano e assinatura"],"description":"Responde 202: a troca é agendada para o fim do ciclo (`pendingPlanId`) e efetivada pelo provedor de pagamento. **Durante o teste grátis do plano** (status `teste`) a troca vale na hora (`appliedNow: true`) e o fim do teste não muda. Plano sob consulta (\"Rede de clínicas\") NÃO agenda troca: registra um pedido de proposta (`quoteRequest`, webhook billing.quote_requested). Avisos de limite vêm em `warnings`.\n\n**Permissão:** `billing:manage`\n\n**Eventos de automação:** `billing.plan_change_requested`, `billing.quote_requested`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/billing/plan-changes\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"planId\":\"<planId>\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["planId"],"properties":{"planId":{"type":"string","maxLength":32}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"202":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"object","required":["requestedPlanId","contactSales","warnings","quoteRequest","appliedNow"],"properties":{"requestedPlanId":{"type":"string"},"contactSales":{"type":"boolean","description":"true = plano sob consulta: virou pedido de proposta (quoteRequest), não mudança agendada."},"warnings":{"type":"array","items":{"type":"string"}},"quoteRequest":{"anyOf":[{"$ref":"#/components/schemas/BillingQuoteRequest"},{"type":"null"}]},"appliedNow":{"type":"boolean","description":"true = a troca já valeu (teste grátis do plano); false = agendada para o fim do ciclo ou pedido de proposta."}}},"meta":{"$ref":"#/components/schemas/ActionMeta"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/billing/plan-changes\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"planId\":\"<planId>\"}'"}]},"delete":{"operationId":"deleteBillingPlanChanges","summary":"Desfazer mudança de plano agendada","tags":["Plano e assinatura"],"description":"Remove `pendingPlanId` (a clínica continua no plano atual). 409 se não houver mudança agendada. Pedido de proposta (quoteRequest) não é afetado.\n\n**Permissão:** `billing:manage`\n\n**Eventos de automação:** `billing.plan_change_reverted`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X DELETE \"{baseUrl}/v1/billing/plan-changes\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/BillingPlanChangeUndoActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X DELETE \"{baseUrl}/v1/billing/plan-changes\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/billing/cancellations":{"post":{"operationId":"postBillingCancellations","summary":"Solicitar cancelamento da assinatura","tags":["Plano e assinatura"],"description":"Responde 202. O acesso segue até o fim do ciclo pago; o provedor de pagamento confirma o cancelamento. Durante o teste grátis do plano → 409 `trial_not_cancellable` (nada é cobrado; basta não ativar).\n\n**Permissão:** `billing:manage`\n\n**Eventos de automação:** `billing.cancellation_requested`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/billing/cancellations\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"reason\":\"<reason>\",\"feedback\":\"<feedback>\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["reason"],"properties":{"reason":{"type":"string","minLength":3,"maxLength":500},"feedback":{"type":"string","maxLength":1000}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"202":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"object","required":["status","accessUntil"],"properties":{"status":{"type":"string"},"accessUntil":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}]}}},"meta":{"$ref":"#/components/schemas/ActionMeta"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/billing/cancellations\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"reason\":\"<reason>\",\"feedback\":\"<feedback>\"}'"}]},"delete":{"operationId":"deleteBillingCancellations","summary":"Desfazer cancelamento da assinatura (\"Manter assinatura\")","tags":["Plano e assinatura"],"description":"Só enquanto o cancelamento está solicitado (antes do fim do ciclo). A assinatura volta a \"ativa\" e a próxima fatura segue normal. 409 se não houver cancelamento pendente.\n\n**Permissão:** `billing:manage`\n\n**Eventos de automação:** `billing.cancellation_reverted`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X DELETE \"{baseUrl}/v1/billing/cancellations\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/BillingCancellationUndoActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X DELETE \"{baseUrl}/v1/billing/cancellations\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/billing/profile":{"patch":{"operationId":"patchBillingProfile","summary":"Dados e preferências de cobrança (frequência, notas por e-mail, lembrete de vencimento, razão social, CNPJ)","tags":["Plano e assinatura"],"description":"Cartão/forma de pagamento é alterado somente na página segura do provedor (nunca pela API). `cycle` (Mensal/Anual) vale a partir da próxima fatura; `invoiceEmailEnabled` e `reminderEnabled` são os interruptores da tela. Mudanças de frequência/preferências disparam billing.profile_updated para o provedor de pagamento.\n\n**Permissão:** `billing:manage`\n\n**Eventos de automação:** `billing.profile_updated`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X PATCH \"{baseUrl}/v1/billing/profile\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"cycle\": \"Mensal\",\n    \"invoiceEmail\": \"contato@exemplo.com\",\n    \"invoiceEmailEnabled\": true,\n    \"reminderDays\": 1,\n    \"reminderEnabled\": true,\n    \"legalName\": \"<legalName>\",\n    \"cnpj\": \"<cnpj>\"\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"cycle":{"type":"string","enum":["Mensal","Anual"]},"invoiceEmail":{"type":"string","format":"email","maxLength":160},"invoiceEmailEnabled":{"type":"boolean"},"reminderDays":{"type":"integer","minimum":0,"maximum":15},"reminderEnabled":{"type":"boolean"},"legalName":{"type":"string","maxLength":160},"cnpj":{"type":"string","pattern":"^\\d{2}\\.?\\d{3}\\.?\\d{3}/?\\d{4}-?\\d{2}$"}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/BillingProfileActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X PATCH \"{baseUrl}/v1/billing/profile\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"cycle\": \"Mensal\",\n    \"invoiceEmail\": \"contato@exemplo.com\",\n    \"invoiceEmailEnabled\": true,\n    \"reminderDays\": 1,\n    \"reminderEnabled\": true,\n    \"legalName\": \"<legalName>\",\n    \"cnpj\": \"<cnpj>\"\n  }'"}]}},"/v1/billing/invoices":{"get":{"operationId":"getBillingInvoices","summary":"Faturas da plataforma","tags":["Plano e assinatura"],"description":"**Permissão:** `billing:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/billing/invoices?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryLimit"},{"$ref":"#/components/parameters/QueryCursor"},{"$ref":"#/components/parameters/QueryPage"},{"schema":{"type":"string","enum":["pago","a-pagar","atrasado"]},"in":"query","name":"status","required":false},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InvoiceList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/billing/invoices?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/billing/invoices/{id}":{"get":{"operationId":"getBillingInvoicesById","summary":"Detalhe da fatura","tags":["Plano e assinatura"],"description":"**Permissão:** `billing:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/billing/invoices/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InvoiceResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/billing/invoices/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/billing/invoices/{id}/resend":{"post":{"operationId":"postBillingInvoicesByIdResend","summary":"Reenviar nota fiscal por e-mail","tags":["Plano e assinatura"],"description":"**Permissão:** `billing:read`\n\n**Eventos de automação:** `billing.invoice_resend`\n\n**Rate limit:** 5 requisições / 600 s.\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/billing/invoices/<id>/resend\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"202":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"object","required":["invoiceId","sentTo"],"properties":{"invoiceId":{"type":"string"},"sentTo":{"anyOf":[{"type":"string"},{"type":"null"}]}}},"meta":{"$ref":"#/components/schemas/ActionMeta"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/billing/invoices/<id>/resend\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/clinics/{id}/subscription/activate":{"post":{"operationId":"postClinicsByIdSubscriptionActivate","summary":"Ativar a assinatura de uma clínica — somente admin da plataforma","tags":["Plano e assinatura"],"description":"Ativação manual enquanto a cobrança é feita fora do sistema: status `ativa`, abre o primeiro ciclo pago a partir de agora (mensal ou anual) e libera o logo da clínica. Encerra o teste grátis (o painel sai do modo somente leitura). Sem assinatura (clínica antiga), cria uma — informe `planId`. Corpo vazio (`{}`) mantém plano e ciclo atuais. Já ativa no mesmo plano → 409 `already_active`. Registra no histórico da clínica.\n\n**Eventos de automação:** `billing.subscription_activated`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/clinics/<id>/subscription/activate\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"planId\":\"<planId>\",\"cycle\":\"mensal\",\"note\":\"<note>\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"planId":{"type":"string","pattern":"^[a-z0-9-]{1,32}$","description":"Troca o plano na ativação (inclusive planos sob consulta negociados)."},"cycle":{"type":"string","enum":["mensal","anual"]},"note":{"type":"string","maxLength":500,"description":"Observação para o histórico (ex.: referência do pagamento)."}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SubscriptionActivatedActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/clinics/<id>/subscription/activate\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"planId\":\"<planId>\",\"cycle\":\"mensal\",\"note\":\"<note>\"}'"}]}},"/v1/finance/transactions":{"get":{"operationId":"getFinanceTransactions","summary":"Transações (receitas e despesas)","tags":["Financeiro"],"description":"**Permissão:** `finance:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/finance/transactions?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryLimit"},{"$ref":"#/components/parameters/QueryCursor"},{"$ref":"#/components/parameters/QueryPage"},{"schema":{"type":"string","maxLength":120},"example":"-occurredAt","in":"query","name":"sort","required":false,"description":"Ordenação: campos separados por vírgula, prefixo \"-\" = decrescente. Permitidos: occurredAt, amount, dueDate, createdAt. Padrão: -occurredAt."},{"schema":{"type":"string","enum":["receita","despesa"]},"in":"query","name":"type","required":false},{"$ref":"#/components/parameters/QueryStatus2"},{"$ref":"#/components/parameters/QueryMethod"},{"$ref":"#/components/parameters/QueryFrom"},{"$ref":"#/components/parameters/QueryTo"},{"$ref":"#/components/parameters/QueryService"},{"$ref":"#/components/parameters/QueryPatientId"},{"$ref":"#/components/parameters/QueryProfessional"},{"$ref":"#/components/parameters/QueryIncludeReversed"},{"$ref":"#/components/parameters/QueryQ3"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/TransactionList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/finance/transactions?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"post":{"operationId":"postFinanceTransactions","summary":"Lançar receita ou despesa","tags":["Financeiro"],"description":"Status deve ser compatível com o tipo. Vincular appointmentId não muda o atendimento (e o atendimento nunca cria pagamento sozinho).\n\n**Permissão:** `finance:write`\n\n**Eventos de automação:** `finance.transaction_changed`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/finance/transactions\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"type\": \"receita\",\n    \"description\": \"<description>\",\n    \"amount\": 1,\n    \"status\": \"recebido\",\n    \"method\": \"Pix\",\n    \"occurredAt\": \"2026-01-15T14:00:00.000Z\",\n    \"dueDate\": \"2026-09-18\",\n    \"party\": \"<party>\"\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TransactionCreate"}}}},"parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"201":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/TransactionActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/finance/transactions\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"type\": \"receita\",\n    \"description\": \"<description>\",\n    \"amount\": 1,\n    \"status\": \"recebido\",\n    \"method\": \"Pix\",\n    \"occurredAt\": \"2026-01-15T14:00:00.000Z\",\n    \"dueDate\": \"2026-09-18\",\n    \"party\": \"<party>\"\n  }'"}]}},"/v1/finance/totals":{"get":{"operationId":"getFinanceTotals","summary":"Totais dos lançamentos filtrados (quantidade e soma por status)","tags":["Financeiro"],"description":"Mesmos filtros de `GET /finance/transactions`, sem paginação: alimenta os cartões de Recebimentos/Pagamentos enquanto a tabela é paginada no servidor. Estornadas ficam de fora, salvo quando pedidas.\n\n**Permissão:** `finance:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/finance/totals\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"schema":{"type":"string","enum":["receita","despesa"]},"in":"query","name":"type","required":false},{"$ref":"#/components/parameters/QueryStatus2"},{"$ref":"#/components/parameters/QueryMethod"},{"$ref":"#/components/parameters/QueryFrom"},{"$ref":"#/components/parameters/QueryTo"},{"$ref":"#/components/parameters/QueryService"},{"$ref":"#/components/parameters/QueryPatientId"},{"$ref":"#/components/parameters/QueryProfessional"},{"$ref":"#/components/parameters/QueryIncludeReversed"},{"$ref":"#/components/parameters/QueryQ3"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FinanceTotalsResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/finance/totals\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/finance/series":{"get":{"operationId":"getFinanceSeries","summary":"Séries diárias do período (recebido acumulado e saldo a receber)","tags":["Financeiro"],"description":"Calculadas no servidor a partir das receitas do período (exceto estornadas) — antes o front baixava todas as receitas para montar os cartões \"Recebido\" e \"A receber\". `professional` filtra as receitas.\n\n**Permissão:** `finance:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/finance/series\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryFrom"},{"$ref":"#/components/parameters/QueryTo"},{"$ref":"#/components/parameters/QueryProfessional2"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FinanceSeriesResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/finance/series\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/finance/summary":{"get":{"operationId":"getFinanceSummary","summary":"Resumo do período (Visão geral e Transações)","tags":["Financeiro"],"description":"Padrão: mês corrente até hoje. `previous` = período anterior equivalente (mês cheio → mês anterior cheio; parcial a partir do dia 1 → mesmo intervalo do mês anterior; senão, o mesmo número de dias imediatamente antes). `professional` filtra as receitas por profissional (despesas não têm profissional e ficam de fora).\n\n**Permissão:** `finance:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/finance/summary\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryFrom"},{"$ref":"#/components/parameters/QueryTo"},{"$ref":"#/components/parameters/QueryProfessional2"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FinanceSummaryResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/finance/summary\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/finance/transactions/{id}":{"get":{"operationId":"getFinanceTransactionsById","summary":"Detalhe da transação","tags":["Financeiro"],"description":"**Permissão:** `finance:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/finance/transactions/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/TransactionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/finance/transactions/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"patch":{"operationId":"patchFinanceTransactionsById","summary":"Atualizar transação (ex.: marcar como recebida/paga)","tags":["Financeiro"],"description":"**Permissão:** `finance:write`\n\n**Eventos de automação:** `finance.transaction_changed`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X PATCH \"{baseUrl}/v1/finance/transactions/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"description\": \"<description>\",\n    \"amount\": 1,\n    \"status\": \"recebido\",\n    \"method\": \"Pix\",\n    \"dueDate\": \"2026-09-18\",\n    \"party\": \"<party>\",\n    \"serviceKey\": \"<serviceKey>\",\n    \"category\": \"aluguel\"\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TransactionPatch"}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/TransactionActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X PATCH \"{baseUrl}/v1/finance/transactions/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"description\": \"<description>\",\n    \"amount\": 1,\n    \"status\": \"recebido\",\n    \"method\": \"Pix\",\n    \"dueDate\": \"2026-09-18\",\n    \"party\": \"<party>\",\n    \"serviceKey\": \"<serviceKey>\",\n    \"category\": \"aluguel\"\n  }'"}]}},"/v1/finance/transactions/{id}/reverse":{"post":{"operationId":"postFinanceTransactionsByIdReverse","summary":"Estornar transação","tags":["Financeiro"],"description":"Não apaga: marca como \"estornado\" (sai dos totais) e registra o motivo na auditoria (nível alto).\n\n**Permissão:** `finance:write`\n\n**Eventos de automação:** `finance.transaction_changed`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/finance/transactions/<id>/reverse\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"reason\":\"<reason>\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["reason"],"properties":{"reason":{"type":"string","minLength":3,"maxLength":255}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/TransactionActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/finance/transactions/<id>/reverse\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"reason\":\"<reason>\"}'"}]}},"/v1/finance/receivables":{"get":{"operationId":"getFinanceReceivables","summary":"Próximos recebimentos (a receber e atrasados)","tags":["Financeiro"],"description":"**Permissão:** `finance:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/finance/receivables?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"schema":{"type":"integer","minimum":1,"maximum":90,"default":30},"in":"query","name":"days","required":false},{"$ref":"#/components/parameters/QueryLimit2"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/FinanceUpcoming"}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/finance/receivables?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/finance/payables":{"get":{"operationId":"getFinancePayables","summary":"Contas a pagar (despesas lançadas + recorrentes)","tags":["Financeiro"],"description":"**Permissão:** `finance:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/finance/payables?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"schema":{"type":"integer","minimum":1,"maximum":90,"default":30},"in":"query","name":"days","required":false},{"$ref":"#/components/parameters/QueryLimit2"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/FinanceUpcoming"}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/finance/payables?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/finance/recurring-expenses":{"get":{"operationId":"getFinanceRecurringExpenses","summary":"Despesas recorrentes","tags":["Financeiro"],"description":"**Permissão:** `finance:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/finance/recurring-expenses\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/RecurringExpense"}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/finance/recurring-expenses\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"post":{"operationId":"postFinanceRecurringExpenses","summary":"Cadastrar despesa recorrente","tags":["Financeiro"],"description":"**Permissão:** `finance:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/finance/recurring-expenses\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"name\":\"<name>\",\"nextDueDate\":\"2026-09-18\",\"amount\":1,\"frequency\":\"Mensal\",\"kind\":\"aluguel\",\"active\":true}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["name","nextDueDate","amount"],"properties":{"name":{"type":"string","minLength":2,"maxLength":128},"frequency":{"type":"string","enum":["Mensal","Bimestral","Trimestral","Anual"]},"nextDueDate":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","example":"2026-09-18"},"amount":{"type":"number","minimum":0,"maximum":10000000,"description":"Valor em reais (BRL). No banco: amount_minor (centavos).","exclusiveMinimum":0},"kind":{"type":"string","enum":["aluguel","internet","sistema","outro"]},"active":{"type":"boolean"}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"201":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RecurringExpenseResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/finance/recurring-expenses\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"name\":\"<name>\",\"nextDueDate\":\"2026-09-18\",\"amount\":1,\"frequency\":\"Mensal\",\"kind\":\"aluguel\",\"active\":true}'"}]}},"/v1/finance/recurring-expenses/{id}":{"patch":{"operationId":"patchFinanceRecurringExpensesById","summary":"Editar despesa recorrente","tags":["Financeiro"],"description":"**Permissão:** `finance:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X PATCH \"{baseUrl}/v1/finance/recurring-expenses/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"name\":\"<name>\",\"frequency\":\"Mensal\",\"nextDueDate\":\"2026-09-18\",\"amount\":1,\"kind\":\"aluguel\",\"active\":true}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string","minLength":2,"maxLength":128},"frequency":{"type":"string","enum":["Mensal","Bimestral","Trimestral","Anual"]},"nextDueDate":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","example":"2026-09-18"},"amount":{"type":"number","minimum":0,"maximum":10000000,"description":"Valor em reais (BRL). No banco: amount_minor (centavos).","exclusiveMinimum":0},"kind":{"type":"string","enum":["aluguel","internet","sistema","outro"]},"active":{"type":"boolean"}}}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RecurringExpenseResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X PATCH \"{baseUrl}/v1/finance/recurring-expenses/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"name\":\"<name>\",\"frequency\":\"Mensal\",\"nextDueDate\":\"2026-09-18\",\"amount\":1,\"kind\":\"aluguel\",\"active\":true}'"}]},"delete":{"operationId":"deleteFinanceRecurringExpensesById","summary":"Excluir despesa recorrente","tags":["Financeiro"],"description":"**Permissão:** `finance:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X DELETE \"{baseUrl}/v1/finance/recurring-expenses/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"204":{"description":"Default Response"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X DELETE \"{baseUrl}/v1/finance/recurring-expenses/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/fiscal/settings":{"get":{"operationId":"getFiscalSettings","summary":"Central fiscal: configuração, prontidão e modos","tags":["Fiscal"],"description":"Dados do emissor, documento, regime, gatilho, modo atual (Simulação, Homologação, Produção), provedor (configurado sim/não, nunca o segredo), aprovação do contador, portão de produção e, para cada modo, o que o bloqueia e por quê.\n\n**Permissão:** `fiscal:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/fiscal/settings\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalSettingsResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/fiscal/settings\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"put":{"operationId":"putFiscalSettings","summary":"Salvar dados do emissor e preferências fiscais","tags":["Fiscal"],"description":"Alterar documento, regime, dados do emissor, série, numeração ou exigências do tomador **anula a aprovação do contador** (é preciso registrar de novo) e é **proibido em Produção** (409 `leave_production_first`: volte para Homologação antes). Nenhum certificado, senha ou token é aceito aqui.\n\n**Permissão:** `fiscal:configure`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X PUT \"{baseUrl}/v1/fiscal/settings\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"documentType\": \"pendente\",\n    \"taxRegime\": \"pendente\",\n    \"trigger\": \"atendimento_realizado\",\n    \"autoCandidates\": true,\n    \"legalName\": \"<legalName>\",\n    \"tradeName\": \"<tradeName>\",\n    \"cnpj\": \"11.222.333/0001-81\",\n    \"municipalRegistration\": \"<municipalRegistration>\"\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalSettingsUpdate"}}}},"parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalSettingsResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X PUT \"{baseUrl}/v1/fiscal/settings\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"documentType\": \"pendente\",\n    \"taxRegime\": \"pendente\",\n    \"trigger\": \"atendimento_realizado\",\n    \"autoCandidates\": true,\n    \"legalName\": \"<legalName>\",\n    \"tradeName\": \"<tradeName>\",\n    \"cnpj\": \"11.222.333/0001-81\",\n    \"municipalRegistration\": \"<municipalRegistration>\"\n  }'"}]}},"/v1/fiscal/settings/approval":{"post":{"operationId":"postFiscalSettingsApproval","summary":"Registrar a aprovação do contador (empresa)","tags":["Fiscal"],"description":"Registra quem aprovou documento, regime e dados do emissor, e onde está a evidência. Exige tudo preenchido. Qualquer alteração fiscal posterior anula este registro.\n\n**Permissão:** `fiscal:configure`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/fiscal/settings/approval\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"approvedByName\":\"<approvedByName>\",\"evidence\":\"<evidence>\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["approvedByName","evidence"],"properties":{"approvedByName":{"type":"string","minLength":3,"maxLength":128,"description":"Contador/responsável fiscal que aprovou."},"evidence":{"type":"string","minLength":10,"maxLength":500,"description":"Onde está a aprovação (ex.: e-mail de 01/10/2026, assunto \"Regras NFS-e\")."}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalSettingsResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/fiscal/settings/approval\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"approvedByName\":\"<approvedByName>\",\"evidence\":\"<evidence>\"}'"}]}},"/v1/fiscal/mode":{"post":{"operationId":"postFiscalMode","summary":"Trocar o modo (Simulação, Homologação, Produção)","tags":["Fiscal"],"description":"Simulação: sempre. Homologação: exige provedor e credencial de homologação no servidor, dados do emissor, documento e série. **Produção:** exige todos os itens de prontidão, a liberação no servidor e a frase exata `ATIVAR PRODUÇÃO`. Mesmo em Produção, cada lote e cada cancelamento pedem confirmação própria.\n\n**Permissão:** `fiscal:configure`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/fiscal/mode\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"mode\":\"simulacao\",\"phrase\":\"<phrase>\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["mode"],"properties":{"mode":{"type":"string","enum":["simulacao","homologacao","producao"]},"phrase":{"type":"string","maxLength":80,"description":"Frase de confirmação exigida em Produção (exata)."}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalSettingsResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/fiscal/mode\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"mode\":\"simulacao\",\"phrase\":\"<phrase>\"}'"}]}},"/v1/fiscal/gate":{"post":{"operationId":"postFiscalGate","summary":"Registrar (ou retirar) evidência do portão de produção","tags":["Fiscal"],"description":"Itens: `prefeitura_confirmada` (Prefeitura confirmou o padrão de emissão (Emissor/Ambiente Nacional ou sistema municipal) e a inscrição municipal); `certificado` (Certificado digital A1 cadastrado no provedor, titular = CNPJ da clínica, com validade conferida); `numeracao_reconciliada` (Série e último número (RPS/DPS) conferidos com o sistema anterior e a prefeitura); `homologacao_cenarios` (Cenários da ficha do contador emitidos e conferidos em Homologação); `backup_restauracao` (Guarda dos XML/PDF (prazo legal) definida e restauração testada); `piloto_revisado` (Piloto pequeno (até 3 notas) revisado pelo responsável). `certificado` exige `validUntil` (o certificado nunca passa pelo My Clinic: fica no provedor). Retirar um item com a clínica em Produção a devolve para Homologação.\n\n**Permissão:** `fiscal:configure`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/fiscal/gate\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"item\":\"prefeitura_confirmada\",\"evidence\":\"<evidence>\",\"validUntil\":\"2026-09-18\",\"clear\":true}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["item"],"properties":{"item":{"type":"string","enum":["prefeitura_confirmada","certificado","numeracao_reconciliada","homologacao_cenarios","backup_restauracao","piloto_revisado"]},"evidence":{"type":"string","minLength":10,"maxLength":500},"validUntil":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","example":"2026-09-18"},"clear":{"type":"boolean"}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalSettingsResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/fiscal/gate\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"item\":\"prefeitura_confirmada\",\"evidence\":\"<evidence>\",\"validUntil\":\"2026-09-18\",\"clear\":true}'"}]}},"/v1/fiscal/service-rules":{"get":{"operationId":"getFiscalServiceRules","summary":"Regras fiscais por serviço (com versões)","tags":["Fiscal"],"description":"Cada serviço do cadastro com a regra vigente e o histórico de versões (rascunho, aprovada, substituída, descartada).\n\n**Permissão:** `fiscal:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/fiscal/service-rules\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/FiscalServiceRules"}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/fiscal/service-rules\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"post":{"operationId":"postFiscalServiceRules","summary":"Criar rascunho de regra fiscal para um serviço","tags":["Fiscal"],"description":"Cria a próxima versão como **rascunho**. Rascunho funciona em Simulação e Homologação; Produção exige a regra **aprovada** pelo contador. Um serviço tem no máximo um rascunho aberto.\n\n**Permissão:** `fiscal:configure`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/fiscal/service-rules\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"serviceKey\": \"<serviceKey>\",\n    \"description\": \"<description>\",\n    \"nationalTaxCode\": \"<nationalTaxCode>\",\n    \"lc116Item\": \"04.08\",\n    \"nbsCode\": \"<nbsCode>\",\n    \"municipalTaxCode\": \"<municipalTaxCode>\",\n    \"cnae\": \"<cnae>\",\n    \"issRate\": 1\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalServiceRuleCreate"}}}},"parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"201":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalServiceRuleResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/fiscal/service-rules\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"serviceKey\": \"<serviceKey>\",\n    \"description\": \"<description>\",\n    \"nationalTaxCode\": \"<nationalTaxCode>\",\n    \"lc116Item\": \"04.08\",\n    \"nbsCode\": \"<nbsCode>\",\n    \"municipalTaxCode\": \"<municipalTaxCode>\",\n    \"cnae\": \"<cnae>\",\n    \"issRate\": 1\n  }'"}]}},"/v1/fiscal/service-rules/{id}":{"patch":{"operationId":"patchFiscalServiceRulesById","summary":"Editar rascunho de regra","tags":["Fiscal"],"description":"Só rascunho é editável. Regra aprovada é imutável: para corrigir, crie uma nova versão.\n\n**Permissão:** `fiscal:configure`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X PATCH \"{baseUrl}/v1/fiscal/service-rules/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"description\": \"<description>\",\n    \"nationalTaxCode\": \"<nationalTaxCode>\",\n    \"lc116Item\": \"04.08\",\n    \"nbsCode\": \"<nbsCode>\",\n    \"municipalTaxCode\": \"<municipalTaxCode>\",\n    \"cnae\": \"<cnae>\",\n    \"issRate\": 1,\n    \"issWithheld\": true\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalServiceRulePatch"}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalServiceRuleResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X PATCH \"{baseUrl}/v1/fiscal/service-rules/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"description\": \"<description>\",\n    \"nationalTaxCode\": \"<nationalTaxCode>\",\n    \"lc116Item\": \"04.08\",\n    \"nbsCode\": \"<nbsCode>\",\n    \"municipalTaxCode\": \"<municipalTaxCode>\",\n    \"cnae\": \"<cnae>\",\n    \"issRate\": 1,\n    \"issWithheld\": true\n  }'"}]}},"/v1/fiscal/service-rules/{id}/approve":{"post":{"operationId":"postFiscalServiceRulesByIdApprove","summary":"Registrar aprovação do contador para a regra","tags":["Fiscal"],"description":"A regra precisa estar completa para o tipo de documento da clínica. A versão aprovada anterior do mesmo serviço vira **substituída** (vigência até o dia anterior). Notas já emitidas guardam a versão que usaram.\n\n**Permissão:** `fiscal:configure`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/fiscal/service-rules/<id>/approve\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"approvedByName\":\"<approvedByName>\",\"evidence\":\"<evidence>\",\"validFrom\":\"2026-09-18\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["approvedByName","evidence"],"properties":{"approvedByName":{"type":"string","minLength":3,"maxLength":128,"description":"Contador/responsável fiscal que aprovou."},"evidence":{"type":"string","minLength":10,"maxLength":500,"description":"Onde está a aprovação (ex.: e-mail de 01/10/2026, assunto \"Regras NFS-e\")."},"validFrom":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","description":"Início da vigência (padrão: hoje).","example":"2026-09-18"}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalServiceRuleResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/fiscal/service-rules/<id>/approve\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"approvedByName\":\"<approvedByName>\",\"evidence\":\"<evidence>\",\"validFrom\":\"2026-09-18\"}'"}]}},"/v1/fiscal/service-rules/{id}/discard":{"post":{"operationId":"postFiscalServiceRulesByIdDiscard","summary":"Descartar rascunho de regra","tags":["Fiscal"],"description":"**Permissão:** `fiscal:configure`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/fiscal/service-rules/<id>/discard\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalServiceRuleResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/fiscal/service-rules/<id>/discard\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/fiscal/candidates/sync":{"post":{"operationId":"postFiscalCandidatesSync","summary":"Buscar atendimentos realizados (e pagamentos) do período","tags":["Fiscal"],"description":"Gera candidatos a nota a partir da Agenda (atendimento **realizado**) e, para serviços cujo gatilho é o pagamento, dos recebimentos. **Idempotente:** a mesma origem nunca gera dois candidatos; candidatos existentes não são alterados. Nada é emitido. Período máximo: 93 dias.\n\n**Permissão:** `fiscal:emit`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/fiscal/candidates/sync\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"from\":\"2026-09-18\",\"to\":\"2026-09-18\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["from","to"],"properties":{"from":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","example":"2026-09-18"},"to":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","example":"2026-09-18"}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalSyncResultResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/fiscal/candidates/sync\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"from\":\"2026-09-18\",\"to\":\"2026-09-18\"}'"}]}},"/v1/fiscal/candidates":{"get":{"operationId":"getFiscalCandidates","summary":"Fila de revisão (candidatos a nota)","tags":["Fiscal"],"description":"Cada candidato traz a situação no modo atual e as pendências explícitas (o que falta e onde corrigir). CPF sempre mascarado.\n\n**Permissão:** `fiscal:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/fiscal/candidates?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryLimit"},{"$ref":"#/components/parameters/QueryCursor"},{"$ref":"#/components/parameters/QueryPage"},{"schema":{"type":"string","enum":["fila","emitidas","ignoradas","todas"],"default":"fila"},"in":"query","name":"view","required":false,"description":"fila = ainda sem nota no modo atual; emitidas = com nota no modo atual."},{"$ref":"#/components/parameters/QueryFrom"},{"$ref":"#/components/parameters/QueryTo"},{"schema":{"type":"string","maxLength":100},"in":"query","name":"q","required":false,"description":"Nome do tomador ou serviço."},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalCandidateList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/fiscal/candidates?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/fiscal/summary":{"get":{"operationId":"getFiscalSummary","summary":"Contagens da fila e das notas no modo atual","tags":["Fiscal"],"description":"**Permissão:** `fiscal:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/fiscal/summary\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalSummaryResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/fiscal/summary\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/fiscal/candidates/{id}":{"get":{"operationId":"getFiscalCandidatesById","summary":"Detalhe do candidato","tags":["Fiscal"],"description":"**Permissão:** `fiscal:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/fiscal/candidates/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalCandidateResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/fiscal/candidates/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"patch":{"operationId":"patchFiscalCandidatesById","summary":"Revisar candidato (tomador, valor, confirmação)","tags":["Fiscal"],"description":"Completa o que falta **com a procedência \"revisão\"**: nome, CPF (validado; nunca de outra pessoa), endereço estruturado e valor. Não altera o cadastro do paciente. Bloqueado com o candidato em lote ou com nota no modo atual.\n\n**Permissão:** `fiscal:emit`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X PATCH \"{baseUrl}/v1/fiscal/candidates/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"taker\": {\n      \"name\": \"<name>\",\n      \"cpf\": \"<cpf>\",\n      \"address\": {\n        \"street\": \"<street>\",\n        \"number\": \"<number>\",\n        \"district\": \"<district>\",\n        \"zip\": \"<zip>\",\n        \"cityIbge\": \"<cityIbge>\",\n        \"uf\": \"<uf>\"\n      }\n    },\n    \"amount\": 1,\n    \"confirmAmount\": true,\n    \"acknowledgeReview\": true\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalCandidateReview"}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalCandidateResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X PATCH \"{baseUrl}/v1/fiscal/candidates/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"taker\": {\n      \"name\": \"<name>\",\n      \"cpf\": \"<cpf>\",\n      \"address\": {\n        \"street\": \"<street>\",\n        \"number\": \"<number>\",\n        \"district\": \"<district>\",\n        \"zip\": \"<zip>\",\n        \"cityIbge\": \"<cityIbge>\",\n        \"uf\": \"<uf>\"\n      }\n    },\n    \"amount\": 1,\n    \"confirmAmount\": true,\n    \"acknowledgeReview\": true\n  }'"}]}},"/v1/fiscal/candidates/{id}/ignore":{"post":{"operationId":"postFiscalCandidatesByIdIgnore","summary":"Marcar como \"não emitir\" (com motivo)","tags":["Fiscal"],"description":"Tira da fila sem apagar (ex.: cortesia registrada por engano). Reversível.\n\n**Permissão:** `fiscal:emit`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/fiscal/candidates/<id>/ignore\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"reason\":\"<reason>\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["reason"],"properties":{"reason":{"type":"string","minLength":5,"maxLength":500}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalCandidateResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/fiscal/candidates/<id>/ignore\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"reason\":\"<reason>\"}'"}]}},"/v1/fiscal/candidates/{id}/restore":{"post":{"operationId":"postFiscalCandidatesByIdRestore","summary":"Voltar para a fila","tags":["Fiscal"],"description":"**Permissão:** `fiscal:emit`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/fiscal/candidates/<id>/restore\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalCandidateResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/fiscal/candidates/<id>/restore\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/fiscal/batches":{"post":{"operationId":"postFiscalBatches","summary":"Montar lote com prévia (nada é emitido)","tags":["Fiscal"],"description":"Valida de novo cada candidato (inclusive a origem: atendimento ainda realizado, pagamento não estornado) e congela a prévia: itens, quantidade, valor, ambiente e próximo número. Candidatos com pendência ficam de fora, com o motivo. Máximo 50 por lote. O modo precisa estar liberado (409 com os bloqueios).\n\n**Permissão:** `fiscal:emit`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/fiscal/batches\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"candidateIds\":[\"<candidateId>\"]}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["candidateIds"],"properties":{"candidateIds":{"type":"array","items":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9._-]+$"},"minItems":1,"maxItems":50}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"201":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalBatchResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/fiscal/batches\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"candidateIds\":[\"<candidateId>\"]}'"}]},"get":{"operationId":"getFiscalBatches","summary":"Lotes","tags":["Fiscal"],"description":"**Permissão:** `fiscal:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/fiscal/batches?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryLimit"},{"$ref":"#/components/parameters/QueryCursor"},{"$ref":"#/components/parameters/QueryPage"},{"schema":{"type":"string","enum":["rascunho","emitindo","concluido","concluido_com_falhas","interrompido","descartado"]},"in":"query","name":"status","required":false},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalBatchList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/fiscal/batches?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/fiscal/batches/{id}":{"get":{"operationId":"getFiscalBatchesById","summary":"Detalhe do lote (prévia e resultado)","tags":["Fiscal"],"description":"**Permissão:** `fiscal:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/fiscal/batches/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalBatchResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/fiscal/batches/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/fiscal/batches/{id}/emit":{"post":{"operationId":"postFiscalBatchesByIdEmit","summary":"Emitir o lote (confirmando a prévia)","tags":["Fiscal"],"description":"A confirmação precisa repetir **ambiente, quantidade e valor** da prévia (409 `confirmation_mismatch` se não bater; 409 `preview_stale` se o modo mudou). **Produção** exige também a frase exata (`EMITIR 3 NOTAS EM PRODUÇÃO`, com a quantidade do lote). Simulação usa só o provedor simulado; Homologação/Produção só o provedor real (sem ele: 409, nada é marcado como emitido). A emissão para no primeiro resultado **incerto** (consulta antes de qualquer reenvio).\n\n**Permissão:** `fiscal:emit`\n\n**Eventos de automação:** `fiscal.document_authorized`, `fiscal.document_rejected`, `fiscal.batch_finished`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/fiscal/batches/<id>/emit\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"environment\":\"simulacao\",\"count\":1,\"total\":0,\"phrase\":\"<phrase>\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["environment","count","total"],"properties":{"environment":{"type":"string","enum":["simulacao","homologacao","producao"]},"count":{"type":"integer","minimum":1},"total":{"type":"number","minimum":0},"phrase":{"type":"string","maxLength":80,"description":"Frase de confirmação exigida em Produção (exata)."}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalBatchResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/fiscal/batches/<id>/emit\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"environment\":\"simulacao\",\"count\":1,\"total\":0,\"phrase\":\"<phrase>\"}'"}]}},"/v1/fiscal/batches/{id}/discard":{"post":{"operationId":"postFiscalBatchesByIdDiscard","summary":"Descartar lote em rascunho","tags":["Fiscal"],"description":"**Permissão:** `fiscal:emit`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/fiscal/batches/<id>/discard\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalBatchResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/fiscal/batches/<id>/discard\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/fiscal/documents":{"get":{"operationId":"getFiscalDocuments","summary":"Notas (histórico)","tags":["Fiscal"],"description":"Padrão: notas do modo atual.\n\n**Permissão:** `fiscal:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/fiscal/documents?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryLimit"},{"$ref":"#/components/parameters/QueryCursor"},{"$ref":"#/components/parameters/QueryPage"},{"schema":{"type":"string","enum":["simulacao","homologacao","producao"]},"in":"query","name":"environment","required":false},{"schema":{"type":"string"},"in":"query","name":"status","required":false,"description":"Status separados por vírgula: reservada, enviando, processando, autorizada, rejeitada, incerta, erro, cancelamento_solicitado, cancelada."},{"schema":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9._-]+$"},"in":"query","name":"candidateId","required":false},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalDocumentList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/fiscal/documents?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/fiscal/documents/{id}":{"get":{"operationId":"getFiscalDocumentsById","summary":"Detalhe da nota com histórico de tentativas","tags":["Fiscal"],"description":"**Permissão:** `fiscal:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/fiscal/documents/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalDocumentDetailResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/fiscal/documents/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/fiscal/documents/{id}/refresh":{"post":{"operationId":"postFiscalDocumentsByIdRefresh","summary":"Consultar a nota no provedor","tags":["Fiscal"],"description":"Para notas em processamento, **incertas** ou com cancelamento pendente. Consulta pela referência; nunca reenvia.\n\n**Permissão:** `fiscal:emit`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/fiscal/documents/<id>/refresh\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalDocumentResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/fiscal/documents/<id>/refresh\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/fiscal/documents/{id}/cancel":{"post":{"operationId":"postFiscalDocumentsByIdCancel","summary":"Cancelar nota autorizada (evento fiscal, nunca exclusão)","tags":["Fiscal"],"description":"Motivo obrigatório (15–255 caracteres). **Produção:** mesmo portão da emissão + frase exata `CANCELAR NOTA <número>`. A nota continua no histórico como cancelada e o candidato volta para revisão.\n\n**Permissão:** `fiscal:emit`\n\n**Eventos de automação:** `fiscal.document_cancelled`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/fiscal/documents/<id>/cancel\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"reason\":\"<reason>\",\"phrase\":\"<phrase>\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["reason"],"properties":{"reason":{"type":"string","minLength":15,"maxLength":255},"phrase":{"type":"string","maxLength":80,"description":"Frase de confirmação exigida em Produção (exata)."}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalDocumentResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/fiscal/documents/<id>/cancel\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"reason\":\"<reason>\",\"phrase\":\"<phrase>\"}'"}]}},"/v1/fiscal/documents/{id}/files/{kind}":{"get":{"operationId":"getFiscalDocumentsByIdFilesByKind","summary":"Baixar XML ou PDF da nota","tags":["Fiscal"],"description":"Arquivo guardado na emissão (imutável). A integridade é conferida pelo sha256 antes de enviar.\n\n**Permissão:** `fiscal:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/fiscal/documents/<id>/files/<kind>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId2"},{"schema":{"type":"string","enum":["xml","pdf"]},"in":"path","name":"kind","required":true},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Conteúdo do arquivo.","content":{"application/xml":{"schema":{"type":"string","description":"Conteúdo do arquivo."}},"application/pdf":{"schema":{"type":"string","description":"Conteúdo do arquivo."}}}},"400":{"$ref":"#/components/responses/BadRequest2"},"401":{"$ref":"#/components/responses/Unauthorized2"},"403":{"$ref":"#/components/responses/Forbidden2"},"404":{"$ref":"#/components/responses/NotFound2"},"422":{"$ref":"#/components/responses/UnprocessableEntity2"},"429":{"$ref":"#/components/responses/TooManyRequests2"},"500":{"$ref":"#/components/responses/InternalError2"},"503":{"$ref":"#/components/responses/ServiceUnavailable3"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/fiscal/documents/<id>/files/<kind>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/fiscal/webhooks/{provider}":{"post":{"operationId":"postFiscalWebhooksByProvider","summary":"Aviso do provedor de emissão (webhook)","tags":["Fiscal"],"description":"Chamado pelo provedor quando uma nota muda de situação (não é para uso do painel). Autenticação: `Authorization` com o segredo combinado (com ou sem o prefixo Bearer) (comparação em tempo constante; sem segredo configurado a rota responde 503). O aviso é **gravado antes** de processar, com id determinístico (repetição não repete efeito), e **nunca é aceito como verdade**: a API consulta a nota no provedor pela referência antes de mudar qualquer estado.\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/fiscal/webhooks/<provider>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{},"additionalProperties":true}}}},"parameters":[{"schema":{"type":"string","pattern":"^[a-z0-9-]{2,32}$"},"in":"path","name":"provider","required":true}],"security":[{"providerWebhook":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiscalWebhookResultResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/fiscal/webhooks/<provider>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{}'"}]}},"/v1/knowledge/articles":{"get":{"operationId":"getKnowledgeArticles","summary":"Listar artigos, FAQs, protocolos e materiais (projeção leve)","tags":["Conhecimento"],"description":"Itens sem o conteúdo completo (intro, passos, dica, sinônimos, governança detalhada): o detalhe vem de `GET /knowledge/articles/{id}`. Contagens por categoria/situação: `GET /knowledge/counts`.\n\n**Permissão:** `knowledge:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/knowledge/articles?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryLimit"},{"$ref":"#/components/parameters/QueryCursor"},{"$ref":"#/components/parameters/QueryPage"},{"schema":{"type":"string","maxLength":120},"example":"-updatedAt","in":"query","name":"sort","required":false,"description":"Ordenação: campos separados por vírgula, prefixo \"-\" = decrescente. Permitidos: updatedAt, title, createdAt. Padrão: -updatedAt."},{"schema":{"type":"string","maxLength":100},"in":"query","name":"q","required":false},{"schema":{"type":"string"},"in":"query","name":"type","required":false,"description":"Tipos separados por vírgula."},{"$ref":"#/components/parameters/QueryCategory"},{"schema":{"type":"string"},"in":"query","name":"status","required":false,"description":"publicado, em_revisao, rascunho (vírgula)."},{"schema":{"type":"string","enum":["aprovado","pendente","reprovado"]},"in":"query","name":"reviewStatus","required":false},{"schema":{"type":"string","maxLength":64},"in":"query","name":"service","required":false},{"schema":{"type":"string","maxLength":64},"in":"query","name":"professional","required":false},{"schema":{"type":"boolean"},"in":"query","name":"safeForAi","required":false},{"schema":{"type":"string","maxLength":64},"in":"query","name":"agent","required":false,"description":"Somente artigos usados por este agent_key."},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/KnowledgeArticleListItemList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/knowledge/articles?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"post":{"operationId":"postKnowledgeArticles","summary":"Criar artigo (rascunho ou enviado para revisão)","tags":["Conhecimento"],"description":"**Permissão:** `knowledge:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/knowledge/articles\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"title\": \"<title>\",\n    \"type\": \"artigo\",\n    \"category\": \"atendimento\",\n    \"excerpt\": \"<excerpt>\",\n    \"intro\": \"<intro>\",\n    \"steps\": [\n      {\n        \"title\": \"<title>\",\n        \"text\": \"<text>\"\n      }\n    ],\n    \"tip\": \"<tip>\",\n    \"keywords\": [\n      \"<keyword>\"\n    ]\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/KnowledgeArticleInput"}}}},"parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"201":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/KnowledgeArticleResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/knowledge/articles\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"title\": \"<title>\",\n    \"type\": \"artigo\",\n    \"category\": \"atendimento\",\n    \"excerpt\": \"<excerpt>\",\n    \"intro\": \"<intro>\",\n    \"steps\": [\n      {\n        \"title\": \"<title>\",\n        \"text\": \"<text>\"\n      }\n    ],\n    \"tip\": \"<tip>\",\n    \"keywords\": [\n      \"<keyword>\"\n    ]\n  }'"}]}},"/v1/knowledge/counts":{"get":{"operationId":"getKnowledgeCounts","summary":"Contagens da base (categorias e situações do tipo pedido)","tags":["Conhecimento"],"description":"Alimenta os contadores de categoria/aba sem baixar a lista. `type` restringe ao tipo (FAQ, protocolo…); `all` é a base inteira (0 = base vazia). Agrupamento avaliado sobre a base da clínica (até 5.000 itens).\n\n**Permissão:** `knowledge:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/knowledge/counts\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"schema":{"type":"string"},"in":"query","name":"type","required":false,"description":"Tipos separados por vírgula."},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/KnowledgeCountsResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/knowledge/counts\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/knowledge/categories":{"get":{"operationId":"getKnowledgeCategories","summary":"Categorias com contagem de itens","tags":["Conhecimento"],"description":"**Permissão:** `knowledge:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/knowledge/categories\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"array","items":{"type":"object","required":["id","name","count"],"properties":{"id":{"type":"string"},"name":{"type":"string"},"count":{"type":"integer"}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/knowledge/categories\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/knowledge/summary":{"get":{"operationId":"getKnowledgeSummary","summary":"KPIs da base (publicados, categorias, agentes usando, avaliação)","tags":["Conhecimento"],"description":"**Permissão:** `knowledge:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/knowledge/summary\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"object","required":["published","categories","agentsUsing","pendingReview","ratingAvg","previous"],"properties":{"published":{"type":"integer"},"categories":{"type":"integer"},"agentsUsing":{"type":"integer"},"pendingReview":{"type":"integer"},"ratingAvg":{"anyOf":[{"type":"number","description":"Média das avaliações das respostas (alimentada pelas automações)."},{"type":"null"}]},"previous":{"$ref":"#/components/schemas/KnowledgeSummaryPrevious"}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/knowledge/summary\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/knowledge/articles/{id}":{"get":{"operationId":"getKnowledgeArticlesById","summary":"Detalhe do artigo","tags":["Conhecimento"],"description":"**Permissão:** `knowledge:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/knowledge/articles/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/KnowledgeArticleResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/knowledge/articles/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"patch":{"operationId":"patchKnowledgeArticlesById","summary":"Editar artigo","tags":["Conhecimento"],"description":"Alterar conteúdo ou governança de um artigo publicado o devolve para \"Em revisão\" (agentes deixam de usar até aprovação). `status: \"rascunho\"` despublica.\n\n**Permissão:** `knowledge:write`\n\n**Eventos de automação:** `knowledge.updated`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X PATCH \"{baseUrl}/v1/knowledge/articles/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"title\": \"<title>\",\n    \"excerpt\": \"<excerpt>\",\n    \"type\": \"artigo\",\n    \"category\": \"atendimento\",\n    \"intro\": \"<intro>\",\n    \"steps\": [\n      {\n        \"title\": \"<title>\",\n        \"text\": \"<text>\"\n      }\n    ],\n    \"tip\": \"<tip>\",\n    \"keywords\": [\n      \"<keyword>\"\n    ]\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"title":{"type":"string","minLength":3,"maxLength":200},"excerpt":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}]},"type":{"type":"string","enum":["artigo","faq","protocolo","material"]},"category":{"type":"string","enum":["atendimento","procedimentos","tratamentos","pos-atendimento","financeiro","convenios","marketing","gestao","equipe","juridico","outros"]},"intro":{"anyOf":[{"type":"string","maxLength":2000},{"type":"null"}]},"steps":{"type":"array","items":{"$ref":"#/components/schemas/KnowledgeStep"},"maxItems":30},"tip":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}]},"keywords":{"type":"array","items":{"type":"string","maxLength":64},"maxItems":30},"aliases":{"type":"array","items":{"type":"string","maxLength":128},"maxItems":30},"serviceKey":{"anyOf":[{"type":"string","maxLength":64},{"type":"null"}]},"professionalKey":{"anyOf":[{"type":"string","maxLength":64},{"type":"null"}]},"source":{"anyOf":[{"type":"string","maxLength":255},{"type":"null"}]},"validUntil":{"anyOf":[{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"},{"type":"null"}]},"safeForAi":{"type":"boolean"},"requiresHuman":{"type":"boolean"},"requiresClinicalAssessment":{"type":"boolean"},"usedBy":{"type":"array","items":{"type":"string","maxLength":64},"maxItems":20,"description":"agent_keys que podem usar o artigo."},"status":{"type":"string","enum":["rascunho","em_revisao"],"description":"Publicação só via revisão (POST /review)."}}}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/KnowledgeArticleActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X PATCH \"{baseUrl}/v1/knowledge/articles/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"title\": \"<title>\",\n    \"excerpt\": \"<excerpt>\",\n    \"type\": \"artigo\",\n    \"category\": \"atendimento\",\n    \"intro\": \"<intro>\",\n    \"steps\": [\n      {\n        \"title\": \"<title>\",\n        \"text\": \"<text>\"\n      }\n    ],\n    \"tip\": \"<tip>\",\n    \"keywords\": [\n      \"<keyword>\"\n    ]\n  }'"}]},"delete":{"operationId":"deleteKnowledgeArticlesById","summary":"Excluir artigo (exclusão lógica)","tags":["Conhecimento"],"description":"**Permissão:** `knowledge:write`\n\n**Eventos de automação:** `knowledge.updated`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X DELETE \"{baseUrl}/v1/knowledge/articles/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"204":{"description":"Default Response"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X DELETE \"{baseUrl}/v1/knowledge/articles/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/knowledge/articles/{id}/submit-review":{"post":{"operationId":"postKnowledgeArticlesByIdSubmitReview","summary":"Enviar para revisão","tags":["Conhecimento"],"description":"**Permissão:** `knowledge:write`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/knowledge/articles/<id>/submit-review\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/KnowledgeArticleResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/knowledge/articles/<id>/submit-review\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/knowledge/articles/{id}/review":{"post":{"operationId":"postKnowledgeArticlesByIdReview","summary":"Revisar artigo (aprovar = publicar; reprovar exige motivo)","tags":["Conhecimento"],"description":"**Permissão:** `knowledge:review`\n\n**Eventos de automação:** `knowledge.updated`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/knowledge/articles/<id>/review\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"decision\":\"approve\",\"note\":\"<note>\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["decision"],"properties":{"decision":{"type":"string","enum":["approve","reject"]},"note":{"type":"string","maxLength":500}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/KnowledgeArticleActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/knowledge/articles/<id>/review\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"decision\":\"approve\",\"note\":\"<note>\"}'"}]}},"/v1/integrations":{"get":{"operationId":"getIntegrations","summary":"Catálogo de integrações com o status da clínica","tags":["Integrações"],"description":"**Permissão:** `integrations:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/integrations\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"schema":{"type":"string","maxLength":32},"in":"query","name":"category","required":false},{"schema":{"type":"string","maxLength":20},"in":"query","name":"status","required":false},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/Integration"}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/integrations\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/integrations/{id}":{"get":{"operationId":"getIntegrationsById","summary":"Detalhe da integração (conta, sincronização, avisos automáticos)","tags":["Integrações"],"description":"**Permissão:** `integrations:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/integrations/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId3"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/IntegrationDetailResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/integrations/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/integrations/{id}/connection":{"post":{"operationId":"postIntegrationsByIdConnection","summary":"Conectar integração","tags":["Integrações"],"description":"Responde 202 com status \"conectando\". Para OAuth, a plataforma devolve a URL de autorização em `next.url` (redirecione o usuário). Para API key/SMTP/WhatsApp as credenciais vão direto para o cofre de credenciais. A confirmação chega depois em POST /integrations/{id}/connection/confirm. Integração \"em breve\" (hoje, todas exceto whatsapp e google-calendar) responde 409 `integration_unavailable`.\n\n**Permissão:** `integrations:manage`\n\n**Eventos de automação:** `integration.connect_requested`\n\n**E-mail verificado:** quando a verificação de e-mail está ligada no ambiente, contas com e-mail ainda não confirmado recebem 403 `email_not_verified`.\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/integrations/<id>/connection\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"scopes\": [\n      \"<scope>\"\n    ],\n    \"syncMode\": \"Tempo real (recomendado)\",\n    \"calendars\": [\n      {\n        \"id\": \"<id>\",\n        \"name\": \"<name>\",\n        \"enabled\": true\n      }\n    ],\n    \"credentials\": {\n      \"apiKey\": \"<apiKey>\",\n      \"smtpHost\": \"<smtpHost>\",\n      \"smtpPort\": 1\n    }\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["scopes"],"properties":{"scopes":{"type":"array","items":{"type":"string","maxLength":64},"maxItems":30,"description":"Escopos autorizados (os obrigatórios do catálogo precisam estar presentes)."},"syncMode":{"type":"string","enum":["Tempo real (recomendado)","A cada 15 minutos","A cada hora","Manual"]},"calendars":{"type":"array","items":{"$ref":"#/components/schemas/IntegrationCalendarInput"},"maxItems":50,"description":"Calendários a sincronizar (Google Calendar). Gravados em config.calendars; no máximo um isDefault (se nenhum, o primeiro ativo vira o padrão)."},"credentials":{"type":"object","properties":{"apiKey":{"type":"string","maxLength":500,"writeOnly":true},"smtpHost":{"type":"string","maxLength":255},"smtpPort":{"type":"integer","minimum":1,"maximum":65535},"smtpUser":{"type":"string","maxLength":255},"smtpPassword":{"type":"string","maxLength":500,"writeOnly":true},"senderEmail":{"type":"string","format":"email"},"phoneNumber":{"type":"string","maxLength":32}},"additionalProperties":false,"description":"WRITE-ONLY. Repassado ao cofre de credenciais da plataforma e descartado — nunca gravado, logado, auditado ou devolvido."}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId3"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"202":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data","meta"],"properties":{"data":{"type":"object","required":["integration","next"],"properties":{"integration":{"$ref":"#/components/schemas/Integration"},"next":{"type":"object","required":["type","url"],"properties":{"type":{"type":"string","enum":["oauth_redirect","none"]},"url":{"anyOf":[{"type":"string"},{"type":"null"}]}}}}},"meta":{"type":"object","required":["webhooks"],"properties":{"webhooks":{"type":"array","items":{"$ref":"#/components/schemas/WebhookMeta"}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/integrations/<id>/connection\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"scopes\": [\n      \"<scope>\"\n    ],\n    \"syncMode\": \"Tempo real (recomendado)\",\n    \"calendars\": [\n      {\n        \"id\": \"<id>\",\n        \"name\": \"<name>\",\n        \"enabled\": true\n      }\n    ],\n    \"credentials\": {\n      \"apiKey\": \"<apiKey>\",\n      \"smtpHost\": \"<smtpHost>\",\n      \"smtpPort\": 1\n    }\n  }'"}]},"patch":{"operationId":"patchIntegrationsByIdConnection","summary":"Pausar/retomar e ajustar sincronização (modo, calendários, opções)","tags":["Integrações"],"description":"**Permissão:** `integrations:manage`\n\n**Eventos de automação:** `integration.settings_updated`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X PATCH \"{baseUrl}/v1/integrations/<id>/connection\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"paused\": true,\n    \"syncMode\": \"Tempo real (recomendado)\",\n    \"calendars\": [\n      {\n        \"id\": \"<id>\",\n        \"enabled\": true\n      }\n    ],\n    \"syncSettings\": [\n      {\n        \"id\": \"<id>\",\n        \"value\": true\n      }\n    ]\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"paused":{"type":"boolean"},"syncMode":{"type":"string","enum":["Tempo real (recomendado)","A cada 15 minutos","A cada hora","Manual"]},"calendars":{"type":"array","items":{"type":"object","required":["id","enabled"],"properties":{"id":{"type":"string","maxLength":128},"enabled":{"type":"boolean"}}},"maxItems":50},"syncSettings":{"type":"array","items":{"type":"object","required":["id","value"],"properties":{"id":{"type":"string","maxLength":64},"value":{"type":"boolean"}}},"maxItems":30}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId3"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/IntegrationDetailActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X PATCH \"{baseUrl}/v1/integrations/<id>/connection\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"paused\": true,\n    \"syncMode\": \"Tempo real (recomendado)\",\n    \"calendars\": [\n      {\n        \"id\": \"<id>\",\n        \"enabled\": true\n      }\n    ],\n    \"syncSettings\": [\n      {\n        \"id\": \"<id>\",\n        \"value\": true\n      }\n    ]\n  }'"}]},"delete":{"operationId":"deleteIntegrationsByIdConnection","summary":"Desconectar integração","tags":["Integrações"],"description":"A plataforma revoga/remove a credencial. A referência é apagada daqui; o histórico permanece.\n\n**Permissão:** `integrations:manage`\n\n**Eventos de automação:** `integration.disconnected`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X DELETE \"{baseUrl}/v1/integrations/<id>/connection\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId3"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/IntegrationActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X DELETE \"{baseUrl}/v1/integrations/<id>/connection\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/integrations/{id}/connection/confirm":{"post":{"operationId":"postIntegrationsByIdConnectionConfirm","summary":"Confirmar conexão (callback da plataforma — somente token de serviço)","tags":["Integrações"],"description":"**Permissão:** `integrations:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/integrations/<id>/connection/confirm\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"X-Agent-Key: <agent_key>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"status\": \"ativa\",\n    \"credentialRef\": \"<credentialRef>\",\n    \"account\": \"<account>\",\n    \"errorCode\": \"<errorCode>\",\n    \"calendars\": [\n      {\n        \"id\": \"<id>\",\n        \"name\": \"<name>\",\n        \"enabled\": true\n      }\n    ],\n    \"webhooks\": [\n      {\n        \"id\": \"<id>\",\n        \"event\": \"<event>\",\n        \"endpoint\": \"<endpoint>\",\n        \"active\": true\n      }\n    ]\n  }'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["status"],"properties":{"status":{"type":"string","enum":["ativa","erro"]},"credentialRef":{"type":"string","maxLength":128,"description":"Id da credencial no cofre (não é o segredo)."},"account":{"type":"string","maxLength":255},"errorCode":{"type":"string","maxLength":64},"calendars":{"type":"array","items":{"type":"object","required":["id","name","enabled"],"properties":{"id":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"enabled":{"type":"boolean"},"isDefault":{"type":"boolean"}}},"maxItems":50},"webhooks":{"type":"array","items":{"type":"object","required":["id","event","endpoint","active"],"properties":{"id":{"type":"string"},"event":{"type":"string"},"endpoint":{"type":"string"},"active":{"type":"boolean"}}},"maxItems":20}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/PathId3"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/IntegrationResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/integrations/<id>/connection/confirm\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"X-Agent-Key: <agent_key>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"status\": \"ativa\",\n    \"credentialRef\": \"<credentialRef>\",\n    \"account\": \"<account>\",\n    \"errorCode\": \"<errorCode>\",\n    \"calendars\": [\n      {\n        \"id\": \"<id>\",\n        \"name\": \"<name>\",\n        \"enabled\": true\n      }\n    ],\n    \"webhooks\": [\n      {\n        \"id\": \"<id>\",\n        \"event\": \"<event>\",\n        \"endpoint\": \"<endpoint>\",\n        \"active\": true\n      }\n    ]\n  }'"}]}},"/v1/integrations/{id}/test":{"post":{"operationId":"postIntegrationsByIdTest","summary":"Testar conexão","tags":["Integrações"],"description":"Síncrono: aguarda a resposta do serviço de integrações (com tempo limite). Resultado vai para o histórico da integração.\n\n**Permissão:** `integrations:manage`\n\n**Eventos de automação:** `integration.test`\n\n**Rate limit:** 10 requisições / 60 s.\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/integrations/<id>/test\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId3"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"object","required":["ok","message","latencyMs","testedAt"],"properties":{"ok":{"type":"boolean"},"message":{"type":"string"},"latencyMs":{"anyOf":[{"type":"integer"},{"type":"null"}]},"testedAt":{"type":"string","format":"date-time"}}},"meta":{"$ref":"#/components/schemas/ActionMeta"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/integrations/<id>/test\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/integrations/{id}/logs":{"get":{"operationId":"getIntegrationsByIdLogs","summary":"Histórico da integração","tags":["Integrações"],"description":"**Permissão:** `integrations:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/integrations/<id>/logs?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryLimit"},{"$ref":"#/components/parameters/QueryCursor"},{"$ref":"#/components/parameters/QueryPage"},{"schema":{"type":"string","enum":["ok","info","erro"]},"in":"query","name":"kind","required":false},{"$ref":"#/components/parameters/PathId3"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/IntegrationLogList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/integrations/<id>/logs?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/outbox":{"get":{"operationId":"getOutbox","summary":"Eventos do outbox da clínica (entregas ao motor de automação)","tags":["Integrações"],"description":"Admin da clínica ou da plataforma (`integrations:manage`) ou token de serviço de agente com `conversations:write`. Não devolve o conteúdo do evento.\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/outbox?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"X-Agent-Key: <agent_key>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryLimit"},{"$ref":"#/components/parameters/QueryCursor"},{"$ref":"#/components/parameters/QueryPage"},{"schema":{"type":"string"},"in":"query","name":"status","required":false,"description":"Status separados por vírgula: pending, sent, failed, dead, disabled."},{"schema":{"type":"string","maxLength":64},"in":"query","name":"event","required":false},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OutboxEventList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/outbox?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"X-Agent-Key: <agent_key>\""}]}},"/v1/outbox/{id}/retry":{"post":{"operationId":"postOutboxByIdRetry","summary":"Reenviar evento do outbox agora","tags":["Integrações"],"description":"Volta o registro para `pending` (zera tentativas se estava `dead`/`disabled`) e tenta entregar ao motor de automação. Mesmo `event_id` — o consumidor descarta se já tiver processado. Evento já `sent` → 409.\n\n**Eventos de automação:** `message.received`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/outbox/<id>/retry\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OutboxEventActionResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/outbox/<id>/retry\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/audit-log":{"get":{"operationId":"getAuditLog","summary":"Histórico de ações (humanos e agentes no mesmo trilho)","tags":["Auditoria"],"description":"**Permissão:** `audit:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/audit-log?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryLimit"},{"$ref":"#/components/parameters/QueryCursor"},{"$ref":"#/components/parameters/QueryPage"},{"$ref":"#/components/parameters/QueryAction"},{"$ref":"#/components/parameters/QueryResource"},{"schema":{"type":"string"},"in":"query","name":"level","required":false,"description":"info, medio, alto (vírgula)."},{"schema":{"type":"string","enum":["humano","agente","sistema"]},"in":"query","name":"actorKind","required":false},{"schema":{"type":"string","maxLength":64},"in":"query","name":"actorId","required":false},{"$ref":"#/components/parameters/QueryActorName"},{"$ref":"#/components/parameters/QueryFrom"},{"$ref":"#/components/parameters/QueryTo"},{"$ref":"#/components/parameters/QueryQ4"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AuditEventList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/audit-log?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/audit-log/summary":{"get":{"operationId":"getAuditLogSummary","summary":"Indicadores e opções de filtro do período","tags":["Auditoria"],"description":"KPIs do período (total, nível alto, pessoas com atividade, último evento) e as opções dos filtros (autores, ações, recursos) — antes calculados no navegador a partir de todos os eventos. Agregação sobre até 5.000 eventos do período.\n\n**Permissão:** `audit:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/audit-log/summary\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryFrom"},{"$ref":"#/components/parameters/QueryTo"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AuditSummaryResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/audit-log/summary\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/audit-log/export":{"get":{"operationId":"getAuditLogExport","summary":"Exportar histórico (CSV, UTF-8 com BOM, até 10.000 linhas)","tags":["Auditoria"],"description":"Mesmos filtros da listagem. A exportação também é registrada no histórico.\n\n**Permissão:** `audit:export`\n\n**Rate limit:** 5 requisições / 60 s.\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/audit-log/export\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryPage"},{"$ref":"#/components/parameters/QueryAction"},{"$ref":"#/components/parameters/QueryResource"},{"schema":{"type":"string"},"in":"query","name":"level","required":false,"description":"info, medio, alto (vírgula)."},{"schema":{"type":"string","enum":["humano","agente","sistema"]},"in":"query","name":"actorKind","required":false},{"schema":{"type":"string","maxLength":64},"in":"query","name":"actorId","required":false},{"$ref":"#/components/parameters/QueryActorName"},{"$ref":"#/components/parameters/QueryFrom"},{"$ref":"#/components/parameters/QueryTo"},{"$ref":"#/components/parameters/QueryQ4"},{"schema":{"type":"string","enum":["csv"],"default":"csv"},"in":"query","name":"format","required":false},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Arquivo CSV.","content":{"text/csv":{"schema":{"type":"string","description":"Arquivo CSV."}}}},"400":{"$ref":"#/components/responses/BadRequest3"},"401":{"$ref":"#/components/responses/Unauthorized3"},"403":{"$ref":"#/components/responses/Forbidden3"},"422":{"$ref":"#/components/responses/UnprocessableEntity3"},"429":{"$ref":"#/components/responses/TooManyRequests3"},"500":{"$ref":"#/components/responses/InternalError3"},"503":{"$ref":"#/components/responses/ServiceUnavailable4"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/audit-log/export\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/audit-log/{id}":{"get":{"operationId":"getAuditLogById","summary":"Detalhe do evento","tags":["Auditoria"],"description":"**Permissão:** `audit:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/audit-log/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/PathId"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AuditEventResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/audit-log/<id>\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/me/data-requests":{"get":{"operationId":"getMeDataRequests","summary":"Meus pedidos LGPD (exportação/exclusão) e o andamento","tags":["Privacidade"],"description":"Somente os pedidos do usuário autenticado na clínica ativa, do mais recente para o mais antigo.\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/me/data-requests?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryLimit"},{"$ref":"#/components/parameters/QueryCursor"},{"$ref":"#/components/parameters/QueryPage"},{"schema":{"type":"string","enum":["solicitado","em_andamento","concluido","recusado"]},"in":"query","name":"status","required":false},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/DataRequestList"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/me/data-requests?limit=25\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]},"post":{"operationId":"postMeDataRequests","summary":"Pedir exportação ou exclusão dos meus dados (LGPD)","tags":["Privacidade"],"description":"Registra o pedido; a execução (gerar arquivo / anonimizar) é feita por automação com revisão humana.\n\n**Rate limit:** 3 requisições / 3600 s.\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X POST \"{baseUrl}/v1/me/data-requests\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"kind\":\"export\",\"reason\":\"<reason>\"}'\n```","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["kind"],"properties":{"kind":{"type":"string","enum":["export","deletion"]},"reason":{"type":"string","maxLength":500}},"additionalProperties":false}}}},"parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"201":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"object","required":["id","kind","status","requestedAt"],"properties":{"id":{"type":"string"},"kind":{"type":"string"},"status":{"type":"string"},"requestedAt":{"type":"string","format":"date-time"}}},"meta":{"$ref":"#/components/schemas/ActionMeta"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X POST \"{baseUrl}/v1/me/data-requests\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"kind\":\"export\",\"reason\":\"<reason>\"}'"}]}},"/v1/reports/home":{"get":{"operationId":"getReportsHome","summary":"KPIs da Home (Command Center)","tags":["Relatórios"],"description":"Campos sem permissão do perfil vêm null. \"Agentes em ação\", mensagens recentes e aprovações vêm de /agents, /conversations?limit=3 e /approvals.\n\n**Permissão:** `clinic:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/reports/home\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"object","required":["pacientesAtivos","pacientesTotal","leadsEmConversa","taxaRetorno","sessoesHoje","sessoesHojeRealizadas","aprovacoesPendentes","conversasNaoLidas"],"properties":{"pacientesAtivos":{"anyOf":[{"type":"integer"},{"type":"null"}]},"pacientesTotal":{"anyOf":[{"type":"integer"},{"type":"null"}]},"leadsEmConversa":{"anyOf":[{"type":"integer","description":"Leads em \"Em conversa\"/\"Qualificado\" conduzidos por agente."},{"type":"null"}]},"taxaRetorno":{"anyOf":[{"type":"number"},{"type":"null"}]},"sessoesHoje":{"anyOf":[{"type":"integer"},{"type":"null"}]},"sessoesHojeRealizadas":{"anyOf":[{"type":"integer"},{"type":"null"}]},"aprovacoesPendentes":{"anyOf":[{"type":"integer"},{"type":"null"}]},"conversasNaoLidas":{"anyOf":[{"type":"integer"},{"type":"null"}]}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/reports/home\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/reports/overview":{"get":{"operationId":"getReportsOverview","summary":"Aba \"Visão geral\"","tags":["Relatórios"],"description":"**Permissão:** `reports:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/reports/overview\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryFrom2"},{"$ref":"#/components/parameters/QueryTo2"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"object","required":["period","kpis","evolucaoMensal","evolucaoSemanal","distribuicaoServicos","principaisServicos","canaisOrigem","canaisOrigemLeads","monthlyRevenueGoal"],"properties":{"period":{"$ref":"#/components/schemas/Period"},"kpis":{"type":"object","required":["pacientes","consultas","receita","retorno"],"properties":{"pacientes":{"type":"integer","description":"Pacientes únicos atendidos (realizados)."},"consultas":{"type":"integer","description":"Atendimentos realizados."},"receita":{"anyOf":[{"type":"number","description":"null sem reports:finance."},{"type":"null"}]},"retorno":{"anyOf":[{"type":"number"},{"type":"null"}]}}},"evolucaoMensal":{"type":"array","items":{"type":"object","required":["periodo","consultas","pacientes"],"properties":{"periodo":{"type":"string"},"consultas":{"type":"integer"},"pacientes":{"type":"integer"}}}},"evolucaoSemanal":{"type":"array","items":{"type":"object","required":["periodo","consultas","pacientes"],"properties":{"periodo":{"type":"string"},"consultas":{"type":"integer"},"pacientes":{"type":"integer"}}}},"distribuicaoServicos":{"type":"array","items":{"$ref":"#/components/schemas/LabelValue"}},"principaisServicos":{"type":"array","items":{"type":"object","required":["servico","serviceKey","consultas","receita"],"properties":{"servico":{"type":"string"},"serviceKey":{"anyOf":[{"type":"string","description":"null = receitas sem serviço (\"Outros\")."},{"type":"null"}]},"consultas":{"type":"integer"},"receita":{"anyOf":[{"type":"number"},{"type":"null"}]}}},"description":"Todos os serviços com atendimento realizado OU receita no período (inclui planos/pacotes). A soma de receita = kpis.receita."},"canaisOrigem":{"type":"array","items":{"$ref":"#/components/schemas/LabelValue"},"description":"De onde vêm os pacientes: % dos pacientes atendidos no período por origem do cadastro."},"canaisOrigemLeads":{"type":"array","items":{"$ref":"#/components/schemas/LabelValue"},"description":"% dos leads criados no período por fonte."},"monthlyRevenueGoal":{"anyOf":[{"type":"number","description":"Meta de receita mensal da clínica (reais). null = não definida ou sem reports:finance."},{"type":"null"}]}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/reports/overview\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/reports/patients":{"get":{"operationId":"getReportsPatients","summary":"Aba \"Pacientes\"","tags":["Relatórios"],"description":"**Permissão:** `reports:read` + `patients:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/reports/patients\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryFrom2"},{"$ref":"#/components/parameters/QueryTo2"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"object","required":["period","total","ativos","inativos","novos","atendidos","taxaRetorno","porOrigem","porFaixaEtaria","porSexo"],"properties":{"period":{"$ref":"#/components/schemas/Period"},"total":{"type":"integer"},"ativos":{"type":"integer"},"inativos":{"type":"integer"},"novos":{"type":"integer","description":"Cadastrados no período."},"atendidos":{"type":"integer","description":"Pacientes únicos com atendimento realizado no período."},"taxaRetorno":{"type":"array","items":{"type":"object","required":["mes","taxa"],"properties":{"mes":{"type":"string"},"taxa":{"anyOf":[{"type":"number"},{"type":"null"}]}}}},"porOrigem":{"type":"array","items":{"$ref":"#/components/schemas/LabelValue"}},"porFaixaEtaria":{"type":"array","items":{"$ref":"#/components/schemas/LabelValue"}},"porSexo":{"type":"array","items":{"$ref":"#/components/schemas/LabelValue"}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/reports/patients\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/reports/leads":{"get":{"operationId":"getReportsLeads","summary":"Aba \"Leads\" (funil do período)","tags":["Relatórios"],"description":"**Permissão:** `reports:read` + `leads:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/reports/leads\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryFrom2"},{"$ref":"#/components/parameters/QueryTo2"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"object","required":["period","funil","conversao","porOrigem","foraDoPerfil"],"properties":{"period":{"$ref":"#/components/schemas/Period"},"funil":{"type":"array","items":{"type":"object","required":["label","value"],"properties":{"label":{"type":"string"},"value":{"type":"integer"}}}},"conversao":{"anyOf":[{"type":"number","description":"% de leads do período que viraram paciente."},{"type":"null"}]},"porOrigem":{"type":"array","items":{"type":"object","required":["source","label","total","convertidos"],"properties":{"source":{"type":"string"},"label":{"type":"string"},"total":{"type":"integer"},"convertidos":{"type":"integer"}}}},"foraDoPerfil":{"type":"array","items":{"$ref":"#/components/schemas/LabelValue"}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/reports/leads\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/reports/schedule":{"get":{"operationId":"getReportsSchedule","summary":"Aba \"Agenda\" (ocupação por dia da semana e status)","tags":["Relatórios"],"description":"Ocupação = minutos agendados (exceto cancelados) ÷ minutos disponíveis nas janelas de disponibilidade dos profissionais. null quando não há disponibilidade cadastrada.\n\n**Permissão:** `reports:read` + `schedule:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/reports/schedule\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryFrom2"},{"$ref":"#/components/parameters/QueryTo2"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"object","required":["period","ocupacao","status","porOrigem"],"properties":{"period":{"$ref":"#/components/schemas/Period"},"ocupacao":{"type":"array","items":{"$ref":"#/components/schemas/LabelValue"}},"status":{"type":"object","required":["realizadas","faltas","canceladas","remarcadas","agendadas"],"properties":{"realizadas":{"type":"integer"},"faltas":{"type":"integer"},"canceladas":{"type":"integer"},"remarcadas":{"type":"integer"},"agendadas":{"type":"integer"}}},"porOrigem":{"type":"array","items":{"$ref":"#/components/schemas/LabelValue"}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/reports/schedule\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/reports/finance":{"get":{"operationId":"getReportsFinance","summary":"Aba \"Financeiro\" (receita × despesas acumuladas, comparação com o período anterior)","tags":["Relatórios"],"description":"**Permissão:** `reports:read` + `reports:finance`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/reports/finance\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryFrom2"},{"$ref":"#/components/parameters/QueryTo2"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"object","required":["period","acumulado","totais","anterior","inadimplencia","monthlyRevenueGoal"],"properties":{"period":{"$ref":"#/components/schemas/Period"},"acumulado":{"type":"array","items":{"type":"object","required":["dia","receita","despesas"],"properties":{"dia":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$","example":"2026-09-18"},"receita":{"type":"number"},"despesas":{"type":"number"}}}},"totais":{"type":"object","required":["receita","receitaAnterior","despesas","despesasAnterior"],"properties":{"receita":{"type":"number"},"receitaAnterior":{"type":"number"},"despesas":{"type":"number"},"despesasAnterior":{"type":"number"}}},"anterior":{"$ref":"#/components/schemas/Period"},"inadimplencia":{"type":"object","required":["atual","serie","benchmarkLabel"],"properties":{"atual":{"anyOf":[{"type":"number","description":"% das receitas do período em atraso."},{"type":"null"}]},"serie":{"type":"array","items":{"$ref":"#/components/schemas/SeriesPoint"}},"benchmarkLabel":{"anyOf":[{"type":"string"},{"type":"null"}]}},"description":"Série mensal (6 meses até o fim do período); benchmark = referência do plano."},"monthlyRevenueGoal":{"anyOf":[{"type":"number","description":"Meta de receita mensal da clínica (reais). null = não definida ou sem reports:finance."},{"type":"null"}]}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/reports/finance\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/reports/communication":{"get":{"operationId":"getReportsCommunication","summary":"Aba \"Atendimento\" (mensagens por canal, tempo de resposta, resolução por agente)","tags":["Relatórios"],"description":"**Permissão:** `reports:read` + `conversations:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/reports/communication\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryFrom2"},{"$ref":"#/components/parameters/QueryTo2"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"object","required":["period","canais","kpis"],"properties":{"period":{"$ref":"#/components/schemas/Period"},"canais":{"type":"array","items":{"$ref":"#/components/schemas/LabelValue"}},"kpis":{"type":"object","required":["mensagens","tempoRespostaMin","resolvidasAgente","transferencias"],"properties":{"mensagens":{"type":"integer"},"tempoRespostaMin":{"anyOf":[{"type":"number","description":"Mediana (min) entre mensagem recebida e a primeira resposta."},{"type":"null"}]},"resolvidasAgente":{"anyOf":[{"type":"number","description":"% de conversas do período sem transferência para a equipe."},{"type":"null"}]},"transferencias":{"type":"integer"}}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/reports/communication\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/reports/team":{"get":{"operationId":"getReportsTeam","summary":"Aba \"Equipe\" (desempenho por profissional)","tags":["Relatórios"],"description":"receita só com reports:finance. satisfacao = média das notas (1–5) dos atendimentos realizados no período; null sem avaliações.\n\n**Permissão:** `reports:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/reports/team\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryFrom2"},{"$ref":"#/components/parameters/QueryTo2"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"array","items":{"type":"object","required":["key","name","specialty","atendimentos","receita","retorno","satisfacao","avaliacoes"],"properties":{"key":{"type":"string"},"name":{"type":"string"},"specialty":{"anyOf":[{"type":"string"},{"type":"null"}]},"atendimentos":{"type":"integer"},"receita":{"anyOf":[{"type":"number"},{"type":"null"}]},"retorno":{"anyOf":[{"type":"number"},{"type":"null"}]},"satisfacao":{"anyOf":[{"type":"number"},{"type":"null"}]},"avaliacoes":{"type":"integer","description":"Quantidade de notas no período."}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/reports/team\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/reports/performance":{"get":{"operationId":"getReportsPerformance","summary":"Séries mensais (6 meses) — receita, consultas, pacientes, retorno, leads, conversão, ticket médio","tags":["Relatórios"],"description":"Métricas derivadas (conversão, ticket) são calculadas das séries-base. receita/ticket só com reports:finance. retorno/satisfacao trazem `benchmark` (referência do plano contratado; rótulo em benchmarkLabel).\n\n**Permissão:** `reports:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/reports/performance\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryTo"},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"object","required":["receita","consultas","pacientes","retorno","leads","conversao","ticket","satisfacao","benchmarkLabel"],"properties":{"receita":{"type":"array","items":{"$ref":"#/components/schemas/SeriesPoint"}},"consultas":{"type":"array","items":{"$ref":"#/components/schemas/SeriesPoint"}},"pacientes":{"type":"array","items":{"$ref":"#/components/schemas/SeriesPoint"}},"retorno":{"type":"array","items":{"$ref":"#/components/schemas/SeriesPoint"}},"leads":{"type":"array","items":{"$ref":"#/components/schemas/SeriesPoint"}},"conversao":{"type":"array","items":{"$ref":"#/components/schemas/SeriesPoint"}},"ticket":{"type":"array","items":{"$ref":"#/components/schemas/SeriesPoint"}},"satisfacao":{"type":"array","items":{"$ref":"#/components/schemas/SeriesPoint"}},"benchmarkLabel":{"anyOf":[{"type":"string","description":"Ex.: \"Clínicas do mesmo porte (plano Profissional)\". null = sem referência."},{"type":"null"}]}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/reports/performance\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}},"/v1/reports/satisfaction":{"get":{"operationId":"getReportsSatisfaction","summary":"Satisfação dos pacientes (pesquisa pós-atendimento, nota 1–5)","tags":["Relatórios"],"description":"Notas gravadas nos atendimentos realizados do período (POST /v1/appointments/{id}/rating). distribuicao = % por nota, de 5 a 1. comentarios = últimos 5, sem nome do paciente.\n\n**Permissão:** `reports:read`\n\n**Exemplo (cURL)**\n\n```bash\ncurl -X GET \"{baseUrl}/v1/reports/satisfaction\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\"\n```","parameters":[{"$ref":"#/components/parameters/QueryFrom2"},{"$ref":"#/components/parameters/QueryTo2"},{"schema":{"type":"string","maxLength":64},"in":"query","name":"professional","required":false},{"$ref":"#/components/parameters/HeaderXClinicId"}],"security":[{"platformJwt":[]},{"serviceToken":[]}],"responses":{"200":{"description":"Default Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SatisfactionReportResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"422":{"$ref":"#/components/responses/UnprocessableEntity"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable2"}},"x-codeSamples":[{"lang":"cURL","label":"curl","source":"curl -X GET \"{baseUrl}/v1/reports/satisfaction\" \\\n  -H \"Authorization: Bearer <TOKEN>\" \\\n  -H \"X-Clinic-Id: <clinic_id>\""}]}}},"servers":[{"url":"{baseUrl}","description":"Ambiente da API (troque a variável pela URL do seu ambiente).","variables":{"baseUrl":{"default":"https://myclinc.leadpoint.com.br","description":"URL base pública da API, sem barra no fim."}}}],"security":[{"platformJwt":[]}],"tags":[{"name":"Sistema","description":"Saúde do serviço (sem autenticação)."},{"name":"Cadastro","description":"Autocadastro da clínica pelo próprio dono: clínica, acesso de administrador e teste grátis do plano numa chamada idempotente."},{"name":"Sessão","description":"Usuário autenticado, clínicas acessíveis e contexto ativo."},{"name":"Clínica","description":"Dados da clínica ativa e logo. Admin da plataforma: cadastro de tenants."},{"name":"Usuários","description":"Vínculos (memberships), perfis de acesso e convites (PRD §10, §33)."},{"name":"Pacientes","description":"Cadastro, ficha, evoluções (prontuário) e tarefas."},{"name":"Serviços","description":"Cadastro de serviços — fonte única do painel (PRD §13)."},{"name":"Profissionais","description":"Equipe que atende e disponibilidade (PRD §14)."},{"name":"Agenda","description":"Agendamentos/sessões: criar, confirmar, reagendar, cancelar com motivo, marcar realizada/falta (PRD §16, §1.15)."},{"name":"Leads","description":"CRM e funil: etapas, mover com motivo, próxima ação, conversão (PRD §11–12)."},{"name":"Comunicação","description":"Caixa de entrada omnichannel: conversas, mensagens, assumir/devolver ao agente."},{"name":"Agentes","description":"Time de agentes da clínica: status, pausar/retomar, execuções, tentar de novo (PRD §18–21, §29)."},{"name":"Aprovações","description":"Ações propostas por agentes aguardando decisão humana."},{"name":"Automações","description":"Catálogo de add-ons, contratar, testar 7 dias, desativar (cobrança proporcional)."},{"name":"Plano e assinatura","description":"Plano, uso, próxima fatura, faturas, mudar plano, cancelar."},{"name":"Financeiro","description":"Transações (fonte explícita — PRD §17.1), a receber, a pagar, resumo."},{"name":"Fiscal","description":"Emissor de NFS-e da clínica via provedor de emissão: configuração com aprovação do contador, regras versionadas por serviço, fila de revisão gerada pela Agenda, lotes com prévia, modos Simulação/Homologação/Produção (Produção travada por portão e confirmação por ação), histórico por tentativa, XML/PDF imutáveis e webhook do provedor."},{"name":"Conhecimento","description":"Base de conhecimento por clínica, governança de uso por IA e revisão (PRD §15)."},{"name":"Integrações","description":"Conectar/desconectar/testar, sincronização e histórico. Segredos nunca são devolvidos (PRD §24)."},{"name":"Auditoria","description":"Histórico de ações (append-only), filtros e exportação CSV (PRD §34)."},{"name":"Relatórios","description":"Endpoints agregados usados pelas abas de Relatórios e pela Home (PRD §28, §35)."},{"name":"Privacidade","description":"Pedidos LGPD do próprio usuário."}]}