> ## 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.

# Atualizar Regra

> Atualizar a configuração de uma regra existente — no motor de regras gu1 para compliance e detecção de risco, com exemplos para update.

## Visão Geral

Actualiza la configuración de una regla existente. Todos los campos son opcionales - solo incluya los campos que desea actualizar. Actualizar una regla incrementa automáticamente su número de versión y mantiene el historial de versiones para propósitos de auditoría.

## Endpoint

```
PATCH http://api.gu1.ai/rules/{id}
```

## Autenticação

Requer uma chave API válida no cabeçalho de Authorization:

```bash theme={null}
Authorization: Bearer YOUR_API_KEY
```

## Parâmetros de Rota

<ParamField path="id" type="string" required>
  UUID de la regla a actualizar
</ParamField>

## Corpo da Requisição

Todos los campos son opcionales. Solo incluya los campos que desea modificar.

<ParamField body="name" type="string">
  Actualizar nombre de la regla
</ParamField>

<ParamField body="description" type="string">
  Actualizar descripción de la regla
</ParamField>

<ParamField body="category" type="string">
  Actualizar categoría: `kyc`, `kyb`, `aml`, `fraud`, `compliance`, `custom`
</ParamField>

<ParamField body="enabled" type="boolean">
  Habilitar o deshabilitar la regla
</ParamField>

<ParamField body="priority" type="number">
  Actualizar prioridad (1-100)
</ParamField>

<ParamField body="score" type="number">
  Actualizar puntaje de riesgo (0-100)
</ParamField>

<ParamField body="status" type="string">
  Actualizar estado: `draft`, `in_progress`, `in_review`, `active`, `shadow`, `archived`, `inactive`
</ParamField>

<ParamField body="conditions" type="object">
  Actualizar lógica de condiciones
</ParamField>

<ParamField body="actions" type="array">
  Actualizar array de acciones
</ParamField>

<ParamField body="targetEntityTypes" type="array">
  Actualizar tipos de entidad objetivo
</ParamField>

<ParamField body="evaluationMode" type="string">
  Actualizar modo de evaluación: `sync` o `async`
</ParamField>

<ParamField body="riskMatrixId" type="string">
  Actualizar UUID de matriz de riesgo asociada
</ParamField>

<ParamField body="scope" type="object">
  Actualizar configuración de alcance
</ParamField>

<ParamField body="tags" type="array">
  Actualizar array de etiquetas
</ParamField>

## Respuesta

<ResponseField name="id" type="string">
  UUID de la regla actualizada
</ResponseField>

<ResponseField name="version" type="number">
  Nuevo número de versión (incrementado)
</ResponseField>

<ResponseField name="previousVersionId" type="string">
  UUID de la versión anterior
</ResponseField>

<ResponseField name="updatedBy" type="string">
  ID del usuario que actualizó la regla
</ResponseField>

<ResponseField name="updatedAt" type="string">
  Marca de tiempo ISO de la actualización
</ResponseField>

Devuelve el objeto de regla actualizado completo con todos los campos.

## Exemplos de Requisições

### Habilitar/Deshabilitar Regla

<CodeGroup>
  ```bash cURL theme={null}
  curl -X PATCH http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "enabled": false
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea',
    {
      method: 'PATCH',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        enabled: false
      })
    }
  );

  const rule = await response.json();
  console.log('Regla deshabilitada. Nueva versión:', rule.version);
  ```

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

  response = requests.patch(
      'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
      },
      json={
          'enabled': False
      }
  )

  rule = response.json()
  print(f"Regla deshabilitada. Nueva versión: {rule['version']}")
  ```
</CodeGroup>

### Actualizar Prioridad y Puntaje

<CodeGroup>
  ```bash cURL theme={null}
  curl -X PATCH http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "priority": 90,
      "score": 75
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea',
    {
      method: 'PATCH',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        priority: 90,
        score: 75
      })
    }
  );

  const rule = await response.json();
  console.log('Prioridad y puntaje actualizados');
  ```

  ```python Python theme={null}
  response = requests.patch(
      'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
      },
      json={
          'priority': 90,
          'score': 75
      }
  )

  rule = response.json()
  print('Prioridad y puntaje actualizados')
  ```
</CodeGroup>

### Actualizar Condiciones

<CodeGroup>
  ```bash cURL theme={null}
  curl -X PATCH http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "conditions": {
        "operator": "OR",
        "conditions": [
          {
            "id": "cond-1",
            "type": "simple",
            "field": "enrichmentData.normalized.taxId",
            "operator": "eq",
            "value": "33.592.510/0001-54",
            "filters": []
          },
          {
            "id": "cond-2",
            "type": "simple",
            "field": "enrichmentData.normalized.taxId",
            "operator": "eq",
            "value": "12.345.678/0001-90",
            "filters": []
          }
        ]
      }
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea',
    {
      method: 'PATCH',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        conditions: {
          operator: 'OR',
          conditions: [
            {
              id: 'cond-1',
              type: 'simple',
              field: 'enrichmentData.normalized.taxId',
              operator: 'eq',
              value: '33.592.510/0001-54',
              filters: []
            },
            {
              id: 'cond-2',
              type: 'simple',
              field: 'enrichmentData.normalized.taxId',
              operator: 'eq',
              value: '12.345.678/0001-90',
              filters: []
            }
          ]
        }
      })
    }
  );

  const rule = await response.json();
  console.log('Condiciones actualizadas. Ahora verificando 2 CNPJs');
  ```

  ```python Python theme={null}
  response = requests.patch(
      'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
      },
      json={
          'conditions': {
              'operator': 'OR',
              'conditions': [
                  {
                      'id': 'cond-1',
                      'type': 'simple',
                      'field': 'enrichmentData.normalized.taxId',
                      'operator': 'eq',
                      'value': '33.592.510/0001-54',
                      'filters': []
                  },
                  {
                      'id': 'cond-2',
                      'type': 'simple',
                      'field': 'enrichmentData.normalized.taxId',
                      'operator': 'eq',
                      'value': '12.345.678/0001-90',
                      'filters': []
                  }
              ]
          }
      }
  )

  rule = response.json()
  print('Condiciones actualizadas. Ahora verificando 2 CNPJs')
  ```
</CodeGroup>

### Agregar Acciones

<CodeGroup>
  ```bash cURL theme={null}
  curl -X PATCH http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "actions": [
        {
          "type": "createAlert",
          "createAlert": {
            "type": "COMPLIANCE",
            "title": "High Risk Entity Detected",
            "description": "Entity matched high-risk criteria",
            "severity": "CRITICAL",
            "recipients": ["compliance@company.com", "security@company.com"]
          },
          "tags": ["high-risk", "urgent"]
        },
        {
          "type": "updateEntityStatus",
          "updateEntityStatus": {
            "status": "under_review",
            "reason": "Flagged by automated rule"
          }
        },
        {
          "type": "sendNotification",
          "sendNotification": {
            "channel": "email",
            "recipients": ["compliance-lead@company.com"],
            "message": "Immediate review required for high-risk entity"
          }
        }
      ]
    }'
  ```
</CodeGroup>

### Actualizar Estado a Modo Shadow

<CodeGroup>
  ```bash cURL theme={null}
  curl -X PATCH http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "status": "shadow",
      "enabled": true
    }'
  ```

  ```javascript JavaScript theme={null}
  // Desplegar regla en modo shadow (registra coincidencias sin ejecutar acciones)
  const response = await fetch(
    'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea',
    {
      method: 'PATCH',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        status: 'shadow',
        enabled: true
      })
    }
  );

  const rule = await response.json();
  console.log('Regla desplegada en modo shadow para pruebas');
  ```

  ```python Python theme={null}
  # Desplegar regla en modo shadow
  response = requests.patch(
      'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
      },
      json={
          'status': 'shadow',
          'enabled': True
      }
  )

  rule = response.json()
  print('Regla desplegada en modo shadow para pruebas')
  ```
</CodeGroup>

### Actualizar Etiquetas

<CodeGroup>
  ```bash cURL theme={null}
  curl -X PATCH http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "tags": ["blocklist", "high-priority", "brazil", "automated"]
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea',
    {
      method: 'PATCH',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        tags: ['blocklist', 'high-priority', 'brazil', 'automated']
      })
    }
  );

  const rule = await response.json();
  console.log('Etiquetas actualizadas');
  ```

  ```python Python theme={null}
  response = requests.patch(
      'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
      },
      json={
          'tags': ['blocklist', 'high-priority', 'brazil', 'automated']
      }
  )

  rule = response.json()
  print('Etiquetas actualizadas')
  ```
</CodeGroup>

## Exemplo de Resposta

```json theme={null}
{
  "id": "e2cdd639-52cc-4749-9b16-927bfa5dfaea",
  "organizationId": "71e8f908-e032-4fcb-b0ce-ad0cd0ffb236",
  "name": "CNPJ Blocklist Check",
  "description": "Block companies with specific CNPJ",
  "category": "kyb",
  "status": "active",
  "enabled": true,
  "priority": 90,
  "score": 75,
  "conditions": {...},
  "actions": [...],
  "scope": {...},
  "targetEntityTypes": ["company"],
  "evaluationMode": "sync",
  "riskMatrixId": "d257247b-af7b-402a-ad8f-eac209e2990e",
  "version": 2,
  "previousVersionId": "e2cdd639-52cc-4749-9b16-927bfa5dfaea-v1",
  "tags": ["blocklist", "high-priority"],
  "createdBy": "f35c10cb-9b67-4cda-9aea-f36567375dba",
  "createdAt": "2024-12-22T14:10:28.131Z",
  "updatedBy": "f35c10cb-9b67-4cda-9aea-f36567375dba",
  "updatedAt": "2024-12-23T10:30:00.000Z",
  "stats": {
    "failures": 0,
    "successes": 7,
    "executions": 7
  }
}
```

## Respostas de Erro

### 404 Not Found

```json theme={null}
{
  "error": "Rule not found",
  "id": "e2cdd639-52cc-4749-9b16-927bfa5dfaea"
}
```

### 400 Bad Request - Datos Inválidos

```json theme={null}
{
  "error": "Validation failed",
  "details": {
    "field": "priority",
    "message": "Priority must be between 1 and 100"
  }
}
```

### 401 Unauthorized

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

### 403 Forbidden

```json theme={null}
{
  "error": "Access denied",
  "message": "You don't have permission to update this rule"
}
```

### 409 Conflict

```json theme={null}
{
  "error": "Rule is currently being executed",
  "message": "Cannot update rule during active execution"
}
```

## Casos de Uso

### Refinamiento Progresivo de Reglas

```javascript theme={null}
// Comenzar con modo shadow, luego activar gradualmente
async function deployRuleProgressively(ruleId) {
  // Fase 1: Desplegar en modo shadow
  console.log('Fase 1: Despliegue en modo shadow...');
  await fetch(`http://api.gu1.ai/rules/${ruleId}`, {
    method: 'PATCH',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      status: 'shadow',
      enabled: true
    })
  });

  // Esperar y monitorear por 1 semana...
  console.log('Monitoreando modo shadow por 1 semana...');

  // Fase 2: Activar con baja prioridad
  console.log('Fase 2: Activando con baja prioridad...');
  await fetch(`http://api.gu1.ai/rules/${ruleId}`, {
    method: 'PATCH',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      status: 'active',
      priority: 20
    })
  });

  // Esperar y monitorear rendimiento...
  console.log('Monitoreando rendimiento...');

  // Fase 3: Aumentar prioridad si funciona bien
  console.log('Fase 3: Aumentando prioridad...');
  await fetch(`http://api.gu1.ai/rules/${ruleId}`, {
    method: 'PATCH',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      priority: 80
    })
  });

  console.log('Regla completamente desplegada');
}
```

### Actualización Masiva de Reglas por Categoría

```python theme={null}
def bulk_update_by_category(category, updates):
    """Actualizar todas las reglas en una categoría"""
    # Obtener todas las reglas en la categoría
    response = requests.get(
        'http://api.gu1.ai/rules',
        headers={
            'Authorization': 'Bearer YOUR_API_KEY'
        },
        params={
            'category': category,
            'pageSize': 100
        }
    )

    rules = response.json()['rules']

    print(f"Actualizando {len(rules)} reglas en categoría '{category}'...")

    for rule in rules:
        update_response = requests.patch(
            f'http://api.gu1.ai/rules/{rule["id"]}',
            headers={
                'Authorization': 'Bearer YOUR_API_KEY',
                'Content-Type': 'application/json'
            },
            json=updates
        )

        if update_response.status_code == 200:
            print(f"  Actualizada: {rule['name']}")
        else:
            print(f"  Falló: {rule['name']}")

    print(f"Actualización masiva completada")

# Ejemplo: Deshabilitar todas las reglas AML temporalmente
bulk_update_by_category('aml', {'enabled': False})
```

### Pruebas A/B de Reglas

```javascript theme={null}
async function setupRuleABTest(ruleId) {
  // Obtener regla original
  const originalResponse = await fetch(
    `http://api.gu1.ai/rules/${ruleId}`,
    {
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY'
      }
    }
  );

  const original = await originalResponse.json();

  // Crear variante con diferente puntaje
  const variantResponse = await fetch(
    'http://api.gu1.ai/rules',
    {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        ...original,
        id: undefined,
        name: original.name + ' (Variante)',
        score: original.score + 10,
        tags: [...original.tags, 'ab-test', 'variant'],
        enabled: false // Iniciar deshabilitada
      })
    }
  );

  const variant = await variantResponse.json();

  // Etiquetar original como control
  await fetch(`http://api.gu1.ai/rules/${ruleId}`, {
    method: 'PATCH',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      tags: [...original.tags, 'ab-test', 'control']
    })
  });

  console.log('Prueba A/B configurada completamente');
  console.log('Control:', ruleId);
  console.log('Variante:', variant.id);

  return { control: ruleId, variant: variant.id };
}
```

### Rotar Destinatarios de Acciones

```python theme={null}
def rotate_alert_recipients(rule_id, new_recipients):
    """Actualizar destinatarios de alertas para una regla"""
    # Obtener regla actual
    response = requests.get(
        f'http://api.gu1.ai/rules/{rule_id}',
        headers={
            'Authorization': 'Bearer YOUR_API_KEY'
        }
    )

    rule = response.json()

    # Actualizar destinatarios de alertas en acciones
    updated_actions = []
    for action in rule['actions']:
        if action['type'] == 'createAlert':
            action['createAlert']['recipients'] = new_recipients
        updated_actions.append(action)

    # Actualizar regla
    update_response = requests.patch(
        f'http://api.gu1.ai/rules/{rule_id}',
        headers={
            'Authorization': 'Bearer YOUR_API_KEY',
            'Content-Type': 'application/json'
        },
        json={
            'actions': updated_actions
        }
    )

    if update_response.status_code == 200:
        print(f"Destinatarios de alerta actualizados a: {new_recipients}")
    else:
        print(f"Falló la actualización de destinatarios")

    return update_response.json()
```

## Melhores Práticas

1. **Actualizaciones Parciales**: Solo envíe campos que desea cambiar
2. **Probar Primero**: Use endpoint de ejecución para probar antes de actualizar reglas de producción
3. **Modo Shadow**: Pruebe cambios de condiciones en modo shadow antes de activar
4. **Historial de Versiones**: Mantenga registro de números de versión para capacidad de rollback
5. **Monitorear Estadísticas**: Observe estadísticas de ejecución después de actualizaciones
6. **Despliegue Gradual**: Actualice prioridad gradualmente al desplegar nueva lógica
7. **Etiquetar Cambios**: Etiquete reglas con metadatos de actualización para seguimiento

## Versionamiento

Cada actualización crea una nueva versión:

* `version`: Se incrementa en 1
* `previousVersionId`: Enlaza a versión anterior
* El historial de versiones se mantiene para auditoría y rollback

## Notas

* Las actualizaciones se aplican inmediatamente para reglas sync
* Las reglas async pueden tomar algunos minutos en reflejar cambios
* Las estadísticas se preservan a través de actualizaciones
* Las reglas deshabilitadas no se ejecutan pero permanecen en el sistema

## Veja Também

* [Obter Regra](/pt/api-reference/rules/get) - Recuperar estado actual de regla
* [Executar Regra](/pt/api-reference/rules/execute) - Probar reglas actualizadas
* [Criar Regra](/pt/api-reference/rules/create) - Crear nuevas reglas
* [Listar Regras](/pt/api-reference/rules/list) - Consultar reglas
