> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gu1.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Listar Validações KYC de uma Entidade

> Recupera todo o histórico de validações KYC de uma entidade específica — na API KYC da gu1 para fluxos de verificação de identidade.

## Visão Geral

Este endpoint recupera o histórico completo de validações KYC de uma entidade específica. Isso é útil para auditorias, acompanhamento de conformidade e compreensão da jornada de verificação de uma entidade.

**Recursos principais:**

* Retorna todas as validações (atuais e históricas) de uma entidade
* Suporta paginação para grandes históricos de validações
* Inclui detalhes completos de verificação para cada validação
* Ordenado por data de criação (mais recente primeiro)
* Mostra qual validação está atualmente ativa

## Quando Usar Isso

* **Auditar histórico de verificação**: Ver todas as tentativas de KYC e seus resultados
* **Relatórios de conformidade**: Rastrear tentativas de verificação para conformidade regulatória
* **Suporte ao usuário**: Investigar por que a verificação de um usuário falhou ou teve sucesso
* **Análises**: Analisar taxas de sucesso de verificação e padrões de abandono
* **Depuração**: Solucionar problemas de verificação revisando o histórico completo

## Solicitação

### Endpoint

```
GET https://api.gu1.ai/api/kyc/entities/{entityId}/validations
```

### Parâmetros de Rota

<ParamField path="entityId" type="string" required>
  O UUID da entidade para recuperar validações
</ParamField>

### Parâmetros de Query

<ParamField query="page" type="integer" default="1">
  Número da página para paginação (começa em 1)
</ParamField>

<ParamField query="limit" type="integer" default="100">
  Número de validações por página (máx 100)
</ParamField>

<ParamField query="status" type="string">
  Filtrar validações por status. Valores possíveis:

  * `pending` - Validação criada, usuário não começou
  * `in_progress` - Usuário está completando ativamente a verificação (preenchendo formulário)
  * `in_review` - Verificação completa, requer revisão manual da equipe de compliance
  * `approved` - Verificação bem-sucedida
  * `rejected` - Verificação falhou
  * `expired` - Validação expirou (usuário não completou a tempo)
  * `abandoned` - Usuário começou mas não completou
  * `cancelled` - Validação foi cancelada pela organização
</ParamField>

<ParamField query="isCurrent" type="boolean">
  Filtrar para mostrar apenas a validação ativa atual (`true`) ou validações históricas (`false`)
</ParamField>

### Cabeçalhos

```json theme={null}
{
  "Authorization": "Bearer YOUR_API_KEY"
}
```

## Resposta

### Resposta de Sucesso (200 OK)

Retorna uma lista paginada de validações:

```json theme={null}
{
  "validations": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "entityId": "123e4567-e89b-12d3-a456-426614174000",
      "organizationId": "org_abc123",
      "validationSessionId": "session_xyz789",
      "status": "approved",
      "provider": "Gu1 KYC",
      "providerSessionUrl": "https://verify.example.com/session_xyz789",
      "isCurrent": true,
      "decision": {
      "status": "Approved",
      "workflow_type": "standard",
      "session_id": "7c0fa22d-0cfa-4a78-8090-7c842397e788",
      "session_number": 921,
      "features": ["ID_VERIFICATION", "LIVENESS", "FACE_MATCH", "IP_ANALYSIS"],
      "images": {
        "documentFront": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/document-front.jpg",
        "documentBack": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/document-back.jpg",
        "selfie": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/selfie.jpg"
      },
      "id_verification": {
        "status": "Approved",
        "node_id": "feature_ocr",
        "document_type": "Passport",
        "document_number": "AB123456",
        "first_name": "John",
        "last_name": "Doe",
        "full_name": "John Doe",
        "date_of_birth": "1990-05-20",
        "nationality": "US",
        "gender": "M",
        "age": 35,
        "issuing_state": "US",
        "expiration_date": "2030-05-20",
        "date_of_issue": "2020-05-20",
        "front_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/document-front.jpg",
        "back_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/document-back.jpg",
        "portrait_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/selfie.jpg",
        "warnings": [],
        "matches": []
      },
      "id_verifications": [
        {
          "status": "Approved",
          "node_id": "feature_ocr",
          "document_type": "Passport",
          "document_number": "AB123456",
          "first_name": "John",
          "last_name": "Doe",
          "full_name": "John Doe",
          "date_of_birth": "1990-05-20",
          "nationality": "US",
          "gender": "M",
          "age": 35,
          "issuing_state": "US",
          "expiration_date": "2030-05-20",
          "date_of_issue": "2020-05-20",
          "front_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/document-front.jpg",
          "back_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/document-back.jpg",
          "portrait_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/selfie.jpg",
          "warnings": [],
          "matches": []
        }
      ],
      "liveness": {
        "status": "Approved",
        "node_id": "feature_liveness",
        "score": 98,
        "method": "PASSIVE",
        "reference_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/liveness-reference.jpg",
        "video_url": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/liveness-video.webm",
        "face_quality": 92.5,
        "warnings": [],
        "matches": []
      },
      "liveness_checks": [
        {
          "status": "Approved",
          "node_id": "feature_liveness",
          "score": 98,
          "method": "PASSIVE",
          "reference_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/liveness-reference.jpg",
          "video_url": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/liveness-video.webm",
          "face_quality": 92.5,
          "warnings": [],
          "matches": []
        }
      ],
      "face_match": {
        "status": "Approved",
        "node_id": "feature_face_match",
        "score": 95,
        "source_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/document-front.jpg",
        "target_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/selfie.jpg",
        "warnings": []
      },
      "face_matches": [
        {
          "status": "Approved",
          "node_id": "feature_face_match",
          "score": 95,
          "source_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/document-front.jpg",
          "target_image": "kyc/global_gueno_validation_kyc/org-uuid/entity-uuid/validation-uuid/selfie.jpg",
          "warnings": []
        }
      ],
      "aml_screening": {
        "status": "Approved",
        "node_id": "feature_aml",
        "warnings": []
      },
      "aml_screenings": [
        {
          "status": "Approved",
          "node_id": "feature_aml",
          "warnings": []
        }
      ],
      "ip_analysis": {
        "status": "Approved",
        "node_id": "feature_ip_analysis",
        "ip_address": "203.0.113.10",
        "country": "US",
        "region": "New York",
        "city": "New York",
        "is_vpn": false,
        "is_proxy": false,
        "warnings": []
      },
      "ip_analyses": [
        {
          "status": "Approved",
          "node_id": "feature_ip_analysis",
          "ip_address": "203.0.113.10",
          "country": "US",
          "region": "New York",
          "city": "New York",
          "is_vpn": false,
          "is_proxy": false,
          "warnings": []
        }
      ]
    },
      "extractedData": {
        "firstName": "John",
        "lastName": "Doe",
        "dateOfBirth": "1990-01-15",
        "documentType": "Passport"
      },
      "verifiedAt": "2025-01-27T10:30:00Z",
      "createdAt": "2025-01-27T09:00:00Z",
      "updatedAt": "2025-01-27T10:30:00Z",
      "metadata": {
        "integrationCode": "global_gueno_validation_kyc",
        "integrationName": "Gu1 KYC"
      }
    },
    {
      "id": "440e8400-e29b-41d4-a716-446655440001",
      "entityId": "123e4567-e89b-12d3-a456-426614174000",
      "organizationId": "org_abc123",
      "validationSessionId": "session_abc456",
      "status": "abandoned",
      "provider": "Gu1 KYC",
      "providerSessionUrl": "https://verify.example.com/session_abc456",
      "isCurrent": false,
      "decision": null,
      "extractedData": null,
      "verifiedAt": null,
      "createdAt": "2025-01-20T14:00:00Z",
      "updatedAt": "2025-01-21T10:00:00Z",
      "metadata": {
        "integrationCode": "global_gueno_validation_kyc",
        "integrationName": "Gu1 KYC"
      }
    }
  ],
  "total": 2,
  "page": 1,
  "limit": 100
}
```

### Campos de Resposta

<ResponseField name="validations" type="array">
  Array de objetos de validação
</ResponseField>

<ResponseField name="total" type="integer">
  Número total de validações que correspondem à consulta
</ResponseField>

<ResponseField name="page" type="integer">
  Número da página atual
</ResponseField>

<ResponseField name="limit" type="integer">
  Número de validações por página
</ResponseField>

## Exemplos de Solicitações

### Obter Todas as Validações de uma Entidade

<CodeGroup>
  ```javascript Node.js theme={null}
  const entityId = '123e4567-e89b-12d3-a456-426614174000';

  const response = await fetch(
    `https://api.gu1.ai/api/kyc/entities/${entityId}/validations`,
    {
      method: 'GET',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
      },
    }
  );

  const result = await response.json();
  console.log(`Encontradas ${result.total} validações`);
  console.log(`Página atual: ${result.page} de ${Math.ceil(result.total / result.limit)}`);

  result.validations.forEach(validation => {
    console.log(`${validation.id}: ${validation.status} (${validation.isCurrent ? 'atual' : 'histórica'})`);
  });
  ```

  ```python Python theme={null}
  import requests

  entity_id = '123e4567-e89b-12d3-a456-426614174000'

  response = requests.get(
      f'https://api.gu1.ai/api/kyc/entities/{entity_id}/validations',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY',
      }
  )

  result = response.json()
  print(f"Encontradas {result['total']} validações")
  print(f"Página atual: {result['page']} de {result['total'] // result['limit'] + 1}")

  for validation in result['validations']:
      current_status = 'atual' if validation['isCurrent'] else 'histórica'
      print(f"{validation['id']}: {validation['status']} ({current_status})")
  ```

  ```curl cURL theme={null}
  curl -X GET "https://api.gu1.ai/api/kyc/entities/123e4567-e89b-12d3-a456-426614174000/validations" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```
</CodeGroup>

***

### Filtrar por Status

Obter apenas validações aprovadas:

<CodeGroup>
  ```javascript Node.js theme={null}
  const entityId = '123e4567-e89b-12d3-a456-426614174000';

  const response = await fetch(
    `https://api.gu1.ai/api/kyc/entities/${entityId}/validations?status=approved`,
    {
      method: 'GET',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
      },
    }
  );

  const result = await response.json();
  console.log(`Encontradas ${result.total} validações aprovadas`);
  ```

  ```python Python theme={null}
  import requests

  entity_id = '123e4567-e89b-12d3-a456-426614174000'

  response = requests.get(
      f'https://api.gu1.ai/api/kyc/entities/{entity_id}/validations',
      headers={'Authorization': 'Bearer YOUR_API_KEY'},
      params={'status': 'approved'}
  )

  result = response.json()
  print(f"Encontradas {result['total']} validações aprovadas")
  ```

  ```curl cURL theme={null}
  curl -X GET "https://api.gu1.ai/api/kyc/entities/123e4567-e89b-12d3-a456-426614174000/validations?status=approved" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```
</CodeGroup>

***

### Obter Apenas a Validação Atual

<CodeGroup>
  ```javascript Node.js theme={null}
  const entityId = '123e4567-e89b-12d3-a456-426614174000';

  const response = await fetch(
    `https://api.gu1.ai/api/kyc/entities/${entityId}/validations?isCurrent=true`,
    {
      method: 'GET',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
      },
    }
  );

  const result = await response.json();

  if (result.validations.length > 0) {
    const currentValidation = result.validations[0];
    console.log('Status da validação atual:', currentValidation.status);
  } else {
    console.log('Nenhuma validação atual encontrada');
  }
  ```

  ```python Python theme={null}
  import requests

  entity_id = '123e4567-e89b-12d3-a456-426614174000'

  response = requests.get(
      f'https://api.gu1.ai/api/kyc/entities/{entity_id}/validations',
      headers={'Authorization': 'Bearer YOUR_API_KEY'},
      params={'isCurrent': 'true'}
  )

  result = response.json()

  if result['validations']:
      current_validation = result['validations'][0]
      print(f"Status da validação atual: {current_validation['status']}")
  else:
      print('Nenhuma validação atual encontrada')
  ```

  ```curl cURL theme={null}
  curl -X GET "https://api.gu1.ai/api/kyc/entities/123e4567-e89b-12d3-a456-426614174000/validations?isCurrent=true" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```
</CodeGroup>

***

### Exemplo de Paginação

<CodeGroup>
  ```javascript Node.js theme={null}
  const entityId = '123e4567-e89b-12d3-a456-426614174000';

  async function getAllValidations(entityId) {
    let page = 1;
    const limit = 50;
    let allValidations = [];

    while (true) {
      const response = await fetch(
        `https://api.gu1.ai/api/kyc/entities/${entityId}/validations?page=${page}&limit=${limit}`,
        {
          method: 'GET',
          headers: {
            'Authorization': 'Bearer YOUR_API_KEY',
          },
        }
      );

      const result = await response.json();
      allValidations = allValidations.concat(result.validations);

      console.log(`Página ${page} obtida: ${result.validations.length} validações`);

      // Verificar se obtivemos todas as validações
      if (allValidations.length >= result.total) {
        break;
      }

      page++;
    }

    return allValidations;
  }

  const validations = await getAllValidations(entityId);
  console.log(`Total de validações obtidas: ${validations.length}`);
  ```

  ```python Python theme={null}
  import requests

  def get_all_validations(entity_id, api_key):
      page = 1
      limit = 50
      all_validations = []

      while True:
          response = requests.get(
              f'https://api.gu1.ai/api/kyc/entities/{entity_id}/validations',
              headers={'Authorization': f'Bearer {api_key}'},
              params={'page': page, 'limit': limit}
          )

          result = response.json()
          all_validations.extend(result['validations'])

          print(f"Página {page} obtida: {len(result['validations'])} validações")

          # Verificar se obtivemos todas as validações
          if len(all_validations) >= result['total']:
              break

          page += 1

      return all_validations

  entity_id = '123e4567-e89b-12d3-a456-426614174000'
  validations = get_all_validations(entity_id, 'YOUR_API_KEY')
  print(f"Total de validações obtidas: {len(validations)}")
  ```
</CodeGroup>

## Respostas de Erro

### Entidade Não Encontrada (404)

```json theme={null}
{
  "error": "NOT_FOUND",
  "message": "Entity not found"
}
```

### Parâmetros de Query Inválidos (400)

```json theme={null}
{
  "error": "VALIDATION_ERROR",
  "message": "Invalid status value. Must be one of: pending, in_progress, approved, rejected, expired, abandoned, cancelled"
}
```

### Não Autorizado (401)

```json theme={null}
{
  "error": "UNAUTHORIZED",
  "message": "Invalid or missing API key"
}
```

## Casos de Uso

### 1. Trilha de Auditoria para Conformidade

Rastrear todas as tentativas de verificação para conformidade regulatória:

```javascript theme={null}
async function getVerificationAuditTrail(entityId) {
  const response = await fetch(
    `https://api.gu1.ai/api/kyc/entities/${entityId}/validations`,
    {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    }
  );

  const result = await response.json();

  // Gerar relatório de auditoria
  const auditReport = result.validations.map(v => ({
    validationId: v.id,
    status: v.status,
    provider: v.provider,
    createdAt: v.createdAt,
    completedAt: v.verifiedAt || v.updatedAt,
    isCurrent: v.isCurrent,
    manualAction: v.metadata?.manuallyApprovedBy || v.metadata?.manuallyRejectedBy,
  }));

  return auditReport;
}
```

***

### 2. Calcular Taxa de Sucesso

Analisar taxas de sucesso de verificação:

```javascript theme={null}
async function calculateSuccessRate(entityId) {
  const response = await fetch(
    `https://api.gu1.ai/api/kyc/entities/${entityId}/validations`,
    {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    }
  );

  const result = await response.json();
  const validations = result.validations;

  const completed = validations.filter(v =>
    ['approved', 'rejected'].includes(v.status)
  );

  const approved = validations.filter(v => v.status === 'approved');
  const rejected = validations.filter(v => v.status === 'rejected');
  const abandoned = validations.filter(v => v.status === 'abandoned');

  return {
    total: validations.length,
    completed: completed.length,
    approved: approved.length,
    rejected: rejected.length,
    abandoned: abandoned.length,
    successRate: completed.length > 0
      ? (approved.length / completed.length * 100).toFixed(2) + '%'
      : 'N/A',
    abandonmentRate: validations.length > 0
      ? (abandoned.length / validations.length * 100).toFixed(2) + '%'
      : 'N/A',
  };
}
```

***

### 3. Encontrar Validações Falhadas para Suporte

Ajudar usuários que tiveram problemas de verificação:

```javascript theme={null}
async function findFailedValidations(entityId) {
  const response = await fetch(
    `https://api.gu1.ai/api/kyc/entities/${entityId}/validations?status=rejected`,
    {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    }
  );

  const result = await response.json();

  // Extrair razões de falha
  const failures = result.validations.map(v => ({
    validationId: v.id,
    rejectedAt: v.updatedAt,
    reason: v.metadata?.rejectionReason || 'Não especificado',
    warnings: v.warnings || [],
    decision: v.decision,
  }));

  return failures;
}
```

***

### 4. Exportar Histórico de Validação

Exportar histórico completo de validação para relatórios:

```javascript theme={null}
async function exportValidationHistory(entityId) {
  const validations = await getAllValidations(entityId); // Do exemplo de paginação

  // Converter para formato CSV
  const csv = [
    'ID Validação,Status,Provedor,Criado,Verificado,É Atual',
    ...validations.map(v =>
      `${v.id},${v.status},${v.provider},${v.createdAt},${v.verifiedAt || ''},${v.isCurrent}`
    )
  ].join('\n');

  return csv;
}
```

## Notas Importantes

<AccordionGroup>
  <Accordion title="Paginação Padrão">
    Por padrão, este endpoint retorna até 100 validações por página. Se uma entidade tiver mais de 100 validações, você precisará usar paginação para recuperar todos os registros.
  </Accordion>

  <Accordion title="Ordenação">
    As validações são retornadas em ordem decrescente por data de criação (mais recente primeiro). A validação atual normalmente aparecerá primeiro na lista.
  </Accordion>

  <Accordion title="Flag isCurrent">
    Apenas uma validação por entidade pode ter `isCurrent: true` por vez. Quando uma nova validação é criada, a validação atual anterior é automaticamente marcada como `isCurrent: false`.
  </Accordion>

  <Accordion title="Retenção de Dados Históricos">
    Todas as validações são retidas indefinidamente para fins de auditoria e conformidade. As validações históricas nunca são excluídas, mesmo que estejam abandonadas ou expiradas.
  </Accordion>

  <Accordion title="Considerações de Desempenho">
    Para entidades com muitas validações (>100), considere usar paginação e filtros de status para reduzir o tamanho da resposta e melhorar o desempenho.
  </Accordion>
</AccordionGroup>

## Diferenças com Endpoints Similares

| Endpoint                                      | Propósito                                            | Caso de Uso                                   |
| --------------------------------------------- | ---------------------------------------------------- | --------------------------------------------- |
| `GET /api/kyc/entities/:entityId/validations` | Obter **todas as validações** de uma entidade        | Trilha de auditoria, histórico, análises      |
| `GET /api/kyc/entities/:entityId/current`     | Obter **apenas a validação atual**                   | Verificar se o usuário está verificado agora  |
| `GET /api/kyc/validations/:id`                | Obter **validação específica** por ID                | Recuperar detalhes de uma validação conhecida |
| `GET /api/kyc/validations`                    | Listar **todas as validações** de todas as entidades | Análises em nível de organização              |

## Próximos Passos

<CardGroup cols={2}>
  <Card title="Obter Validação Atual" icon="check-circle" href="/pt/use-cases/kyc/current-validation">
    Obter apenas a validação ativa de uma entidade
  </Card>

  <Card title="Criar Validação KYC" icon="play" href="/pt/use-cases/kyc/create-validation">
    Iniciar uma nova sessão de verificação
  </Card>

  <Card title="Verificar Status da Entidade" icon="shield-check" href="/pt/use-cases/kyc/check-status">
    Obter resumo do status de verificação
  </Card>

  <Card title="Sincronizar Validação" icon="arrows-rotate" href="/pt/use-cases/kyc/sync-validation">
    Atualizar dados de validação manualmente
  </Card>
</CardGroup>
