{
  "name": "WF6 - Controle de Vig\u00eancia | JurisAI",
  "nodes": [
    {
      "id": "sticky_overview",
      "name": "\ud83d\udccb WF6 - Controle de Vig\u00eancia",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -200,
        -100
      ],
      "parameters": {
        "content": "## WF6 \u2014 Controle de Vig\u00eancia\n\n**Chamado por:** WF1 (ingest\u00e3o) e WF3 (consulta)  \n**Entrada:** `{ document_id, source_url, current_status, title }`  \n**Sa\u00edda:** `{ document_id, new_status, changed, message }`\n\n**Fluxo:**\n1. Recebe documento via Execute Workflow\n2. Faz HEAD request na source_url\n3. Analisa resposta HTTP para inferir vig\u00eancia\n4. Se status mudou \u2192 atualiza Supabase\n5. Retorna resultado ao workflow chamador\n\n\u2699\ufe0f **Ap\u00f3s importar:** configure a credencial Supabase",
        "height": 240,
        "width": 380,
        "color": 4
      }
    },
    {
      "id": "trigger_wf6",
      "name": "Receber do Workflow Pai",
      "type": "n8n-nodes-base.executeWorkflowTrigger",
      "typeVersion": 1,
      "position": [
        250,
        300
      ],
      "parameters": {}
    },
    {
      "id": "check_source_url",
      "name": "Checar Source URL",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        500,
        300
      ],
      "parameters": {
        "method": "HEAD",
        "url": "={{ $json.source_url }}",
        "options": {
          "timeout": 10000,
          "allowUnauthorizedCerts": false,
          "redirect": {
            "redirect": {
              "followRedirects": true,
              "maxRedirects": 3
            }
          }
        },
        "ignoreResponseCode": true
      },
      "continueOnFail": true
    },
    {
      "id": "analyze_vigencia",
      "name": "Analisar Vig\u00eancia",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        750,
        300
      ],
      "parameters": {
        "jsCode": "// Recebe o resultado do HEAD request e os dados originais do documento\nconst httpResult = $input.first().json;\nconst originalData = $('Receber do Workflow Pai').first().json;\n\nconst statusCode = httpResult.statusCode || 0;\nconst currentStatus = originalData.current_status || 'em_vigor';\n\nlet newStatus = currentStatus;\nlet changed = false;\nlet message = '';\n\n// L\u00f3gica de infer\u00eancia de vig\u00eancia a partir do status HTTP\nif (statusCode === 0 || statusCode >= 500) {\n  // URL inacess\u00edvel ou erro de servidor \u2014 n\u00e3o muda status, apenas alerta\n  message = `Fonte inacess\u00edvel (HTTP ${statusCode}) \u2014 status mantido como ${currentStatus}`;\n} else if (statusCode === 404) {\n  // Documento removido da fonte\n  if (currentStatus === 'em_vigor') {\n    newStatus = 'arquivado';\n    changed = true;\n    message = 'Documento removido da fonte (404) \u2014 marcado como arquivado';\n  } else {\n    message = `Documento n\u00e3o encontrado (404) \u2014 status j\u00e1 era ${currentStatus}`;\n  }\n} else if (statusCode === 301 || statusCode === 302 || statusCode === 308) {\n  // Redirecionamento pode indicar mudan\u00e7a de local \u2014 precisa curadoria\n  message = `Redirecionamento detectado (HTTP ${statusCode}) \u2014 verifica\u00e7\u00e3o manual recomendada`;\n} else if (statusCode === 200 || statusCode === 206) {\n  // Documento acess\u00edvel\n  if (currentStatus === 'arquivado') {\n    // Estava arquivado mas voltou a ser acess\u00edvel \u2014 n\u00e3o muda autom\u00e1tico, alerta curador\n    message = `Documento arquivado ainda acess\u00edvel na fonte (HTTP ${statusCode}) \u2014 verifica\u00e7\u00e3o manual recomendada`;\n  } else {\n    message = `Documento acess\u00edvel (HTTP ${statusCode}) \u2014 status mantido como ${currentStatus}`;\n  }\n} else {\n  message = `Status HTTP inesperado: ${statusCode} \u2014 sem altera\u00e7\u00e3o autom\u00e1tica`;\n}\n\nreturn [{\n  json: {\n    document_id: originalData.document_id,\n    title: originalData.title,\n    source_url: originalData.source_url,\n    previous_status: currentStatus,\n    new_status: newStatus,\n    changed: changed,\n    http_status_code: statusCode,\n    message: message,\n    checked_at: new Date().toISOString()\n  }\n}];"
      }
    },
    {
      "id": "if_status_changed",
      "name": "Status Mudou?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        1000,
        300
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "cond_changed",
              "leftValue": "={{ $json.changed }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        }
      }
    },
    {
      "id": "update_document_status",
      "name": "Atualizar Status no Supabase",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1250,
        200
      ],
      "parameters": {
        "method": "PATCH",
        "url": "={{ $env.SUPABASE_URL }}/rest/v1/documents?id=eq.{{ $json.document_id }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "apikey",
              "value": "={{ $env.SUPABASE_SERVICE_KEY }}"
            },
            {
              "name": "Authorization",
              "value": "=Bearer {{ $env.SUPABASE_SERVICE_KEY }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            },
            {
              "name": "Prefer",
              "value": "return=representation"
            }
          ]
        },
        "sendBody": true,
        "contentType": "json",
        "body": "={{ JSON.stringify({ status: $json.new_status, updated_at: $json.checked_at, metadata: { last_vigencia_check: $json.checked_at, vigencia_http_status: $json.http_status_code } }) }}"
      }
    },
    {
      "id": "insert_version_log",
      "name": "Registrar Vers\u00e3o",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1500,
        200
      ],
      "parameters": {
        "method": "POST",
        "url": "={{ $env.SUPABASE_URL }}/rest/v1/document_versions",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "apikey",
              "value": "={{ $env.SUPABASE_SERVICE_KEY }}"
            },
            {
              "name": "Authorization",
              "value": "=Bearer {{ $env.SUPABASE_SERVICE_KEY }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "contentType": "json",
        "body": "={{ JSON.stringify({ document_id: $('Analisar Vig\u00eancia').first().json.document_id, version: Date.now(), change_type: 'revogacao_total', change_reason: $('Analisar Vig\u00eancia').first().json.message, changed_by: 'wf6_auto', snapshot: { previous_status: $('Analisar Vig\u00eancia').first().json.previous_status, new_status: $('Analisar Vig\u00eancia').first().json.new_status, http_status_code: $('Analisar Vig\u00eancia').first().json.http_status_code } }) }}"
      },
      "continueOnFail": true
    },
    {
      "id": "no_change_output",
      "name": "Sem Altera\u00e7\u00e3o",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        1250,
        400
      ],
      "parameters": {}
    },
    {
      "id": "output_result",
      "name": "Retornar Resultado",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        1750,
        300
      ],
      "parameters": {
        "mode": "manual",
        "assignments": {
          "assignments": [
            {
              "id": "a1",
              "name": "document_id",
              "value": "={{ $('Analisar Vig\u00eancia').first().json.document_id }}",
              "type": "string"
            },
            {
              "id": "a2",
              "name": "new_status",
              "value": "={{ $('Analisar Vig\u00eancia').first().json.new_status }}",
              "type": "string"
            },
            {
              "id": "a3",
              "name": "changed",
              "value": "={{ $('Analisar Vig\u00eancia').first().json.changed }}",
              "type": "boolean"
            },
            {
              "id": "a4",
              "name": "message",
              "value": "={{ $('Analisar Vig\u00eancia').first().json.message }}",
              "type": "string"
            },
            {
              "id": "a5",
              "name": "checked_at",
              "value": "={{ $('Analisar Vig\u00eancia').first().json.checked_at }}",
              "type": "string"
            }
          ]
        }
      }
    }
  ],
  "connections": {
    "Receber do Workflow Pai": {
      "main": [
        [
          {
            "node": "Checar Source URL",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Checar Source URL": {
      "main": [
        [
          {
            "node": "Analisar Vig\u00eancia",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Analisar Vig\u00eancia": {
      "main": [
        [
          {
            "node": "Status Mudou?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Status Mudou?": {
      "main": [
        [
          {
            "node": "Atualizar Status no Supabase",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Sem Altera\u00e7\u00e3o",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Atualizar Status no Supabase": {
      "main": [
        [
          {
            "node": "Registrar Vers\u00e3o",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Registrar Vers\u00e3o": {
      "main": [
        [
          {
            "node": "Retornar Resultado",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Sem Altera\u00e7\u00e3o": {
      "main": [
        [
          {
            "node": "Retornar Resultado",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "saveManualExecutions": false,
    "callerPolicy": "workflowsFromSameOwner",
    "errorWorkflow": ""
  },
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "tags": [
    {
      "id": "jurisai",
      "name": "JurisAI"
    },
    {
      "id": "subworkflow",
      "name": "subworkflow"
    }
  ]
}