{
  "name": "Logixb2b — Alerta de errores en producción",
  "meta": {
    "templateCredsSetupCompleted": false,
    "description": "Cada 15 min consulta ejecuciones fallidas vía Public API de n8n y avisa por Slack si hay errores en la ventana de lookback."
  },
  "settings": {
    "executionOrder": "v1",
    "timezone": "Europe/Madrid"
  },
  "active": false,
  "pinData": {},
  "tags": [
    {
      "name": "Logixb2b"
    },
    {
      "name": "recursos"
    },
    {
      "name": "ops"
    },
    {
      "name": "produccion"
    }
  ],
  "nodes": [
    {
      "id": "sticky-instrucciones-logix",
      "name": "INSTRUCCIONES (conectar + VPS)",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -480,
        40
      ],
      "parameters": {
        "content": "## INSTRUCCIONES — Alerta de errores en producción\n\n**Recurso:** `/recursos/n8n-produccion-alerta-errores`\n**Guía:** /errores-comunes-desplegar-n8n-produccion\n**Zona:** Europe/Madrid · `active: false` al importar (tú lo activas).\n\n### 1) Importar\n1. n8n → ⋯ → **Import from File** → este JSON.\n2. El flujo llega **inactive**. No pegues secretos en el lienzo ni en el archivo.\n\n### 2) Credenciales y configuración por nodo\n- **Cada 15 minutos** (`schedule`): sin credencial. Revisa expresión cron / intervalo y zona **Europe/Madrid** (settings del workflow). Solo dispara si n8n está **Active** 24/7.\n- **Config alerta errores** (`Set` Config): **no lleva credencial**. Aquí van URLs/placeholders (`REEMPLAZA_*`, `example.com`, `TU-CRM`). Sustituye todos antes de Active.\n- **GET executions error** (`HTTP Request` API n8n): Credentials → **Header Auth** con API key de n8n (`X-N8N-API-KEY`). URL base = tu instancia (`https://n8n.tudominio.com`).\n- **Contar fallos recientes** (`Set`): sin credencial. Revisa expresiones `={{ }}` y campos de salida.\n- **¿Hay fallos recientes?** (`IF`): sin credencial. Comprueba la condición (email, umbral, over_limit, etc.) con datos reales de prueba.\n- **Alerta Slack (errores)** (`HTTP Request` → Slack/Teams): crea Incoming Webhook en Slack (o Adaptive Card URL en Teams). Pega la URL en **Config** o en este nodo. Auth: none (la URL ya es secreta).\n\n### 3) Orden recomendado de puesta en marcha\n1. Rellena el nodo **Config** (URLs reales, umbrales, webhooks de Slack).\n2. Crea Credentials en n8n (candado de cada nodo HTTP / Sheets / OpenAI) y **enlázalas**.\n3. Ejecuta **una vez** (Manual / Test URL del Webhook / \"Execute workflow\").\n4. Verifica CRM + Slack/Sheets (y que la IA no escriba en producción sin HITL).\n5. Solo entonces: interruptor **Active**.\n\n### 4) Producción 24/7 en VPS (UE)\nImportar en localhost no basta: webhooks y cron necesitan n8n encendido.\n\n1. VPS en UE (Hetzner/OVH/IONOS…) + Docker Compose + **Postgres** + HTTPS (Caddy/Nginx).\n2. Variables mínimas: `GENERIC_TIMEZONE=Europe/Madrid`, `WEBHOOK_URL=https://n8n.tudominio.com/`, `N8N_ENCRYPTION_KEY`, `N8N_HOST` / `N8N_PROTOCOL=https`.\n3. Firewall: solo 80/443 (+ SSH). Backups del volumen Postgres + export de workflows.\n4. Importa este JSON en la instancia de producción, vuelve a crear Credentials (no se copian solas), actualiza URLs del Config al dominio real.\n5. Pon **Active**. Prueba el Webhook de producción o espera el próximo cron.\n6. Alternativa: **n8n Cloud** (mismo JSON; Credentials en la UI Cloud).\n\n### 5) RGPD + EU AI Act (resumen)\nSi hay nodos IA sois **deployers** (Reglamento UE 2024/1689). Art. 4 alfabetización. **HITL** antes de outreach, scores masivos o pausas de cuenta. Minimiza PII en Slack/logs. Informativo — no es asesoramiento legal. /uso-responsable-de-ia-y-transparencia\n",
        "height": 1500,
        "width": 580,
        "color": 4
      }
    },
    {
      "id": "err-trigger-schedule",
      "name": "Cada 15 minutos",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        300
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "minutes",
              "minutesInterval": 15
            }
          ]
        }
      }
    },
    {
      "id": "err-set-config",
      "name": "Config alerta errores",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        300,
        300
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "assignments": {
          "assignments": [
            {
              "id": "err-c1",
              "name": "n8nApiBase",
              "value": "https://TU-N8N.ejemplo",
              "type": "string"
            },
            {
              "id": "err-c2",
              "name": "apiKey",
              "value": "sustituye-con-tu-clave-de-acceso-n8n",
              "type": "string"
            },
            {
              "id": "err-c3",
              "name": "slackWebhookUrl",
              "value": "https://example.com/aviso-equipo-slack",
              "type": "string"
            },
            {
              "id": "err-c4",
              "name": "lookbackMinutes",
              "value": 20,
              "type": "number"
            },
            {
              "id": "err-c5",
              "name": "checkedAt",
              "value": "={{ $now.setZone('Europe/Madrid').toFormat('yyyy-MM-dd HH:mm') }}",
              "type": "string"
            }
          ]
        }
      }
    },
    {
      "id": "err-http-executions",
      "name": "GET executions error",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        600,
        300
      ],
      "parameters": {
        "method": "GET",
        "url": "={{ $json.n8nApiBase }}/api/v1/executions?status=error&limit=50",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "X-N8N-API-KEY",
              "value": "={{ $json.apiKey }}"
            }
          ]
        },
        "options": {
          "timeout": 20000,
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": true
            }
          }
        }
      }
    },
    {
      "id": "err-set-summary",
      "name": "Contar fallos recientes",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        900,
        300
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "assignments": {
          "assignments": [
            {
              "id": "err-s1",
              "name": "statusCode",
              "value": "={{ $json.statusCode }}",
              "type": "number"
            },
            {
              "id": "err-s2",
              "name": "lookbackMinutes",
              "value": "={{ $('Config alerta errores').item.json.lookbackMinutes }}",
              "type": "number"
            },
            {
              "id": "err-s3",
              "name": "failedCount",
              "value": "={{ (() => { const lookback = Number($('Config alerta errores').item.json.lookbackMinutes) || 20; const cutoff = Date.now() - lookback * 60 * 1000; const rows = Array.isArray($json.body?.data) ? $json.body.data : (Array.isArray($json.body) ? $json.body : []); return rows.filter(e => { const t = e.stoppedAt || e.startedAt || e.createdAt; return t ? new Date(t).getTime() >= cutoff : true; }).length; })() }}",
              "type": "number"
            },
            {
              "id": "err-s4",
              "name": "failedWorkflowNames",
              "value": "={{ (() => { const lookback = Number($('Config alerta errores').item.json.lookbackMinutes) || 20; const cutoff = Date.now() - lookback * 60 * 1000; const rows = Array.isArray($json.body?.data) ? $json.body.data : (Array.isArray($json.body) ? $json.body : []); const names = rows.filter(e => { const t = e.stoppedAt || e.startedAt || e.createdAt; return t ? new Date(t).getTime() >= cutoff : true; }).map(e => e.workflowData?.name || e.workflowId || 'desconocido'); return [...new Set(names)].slice(0, 20).join(', ') || '(ninguno)'; })() }}",
              "type": "string"
            },
            {
              "id": "err-s5",
              "name": "hasFailures",
              "value": "={{ (() => { const lookback = Number($('Config alerta errores').item.json.lookbackMinutes) || 20; const cutoff = Date.now() - lookback * 60 * 1000; const rows = Array.isArray($json.body?.data) ? $json.body.data : (Array.isArray($json.body) ? $json.body : []); const n = rows.filter(e => { const t = e.stoppedAt || e.startedAt || e.createdAt; return t ? new Date(t).getTime() >= cutoff : true; }).length; return n > 0 && Number($json.statusCode) >= 200 && Number($json.statusCode) < 300; })() }}",
              "type": "boolean"
            },
            {
              "id": "err-s6",
              "name": "slackWebhookUrl",
              "value": "={{ $('Config alerta errores').item.json.slackWebhookUrl }}",
              "type": "string"
            },
            {
              "id": "err-s7",
              "name": "n8nApiBase",
              "value": "={{ $('Config alerta errores').item.json.n8nApiBase }}",
              "type": "string"
            },
            {
              "id": "err-s8",
              "name": "checkedAt",
              "value": "={{ $('Config alerta errores').item.json.checkedAt }}",
              "type": "string"
            }
          ]
        }
      }
    },
    {
      "id": "err-if-failures",
      "name": "¿Hay fallos recientes?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1200,
        300
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "err-cond-fail",
              "leftValue": "={{ $json.hasFailures }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        }
      }
    },
    {
      "id": "err-slack",
      "name": "Alerta Slack (errores)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1500,
        40
      ],
      "parameters": {
        "method": "POST",
        "url": "={{ $json.slackWebhookUrl }}",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ text: $json.slackText || 'Actualización Logixb2b' }) }}",
        "options": {
          "timeout": 10000
        }
      }
    },
    {
      "id": "err-noop-ok",
      "name": "OK — sin alerta",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        1500,
        560
      ],
      "parameters": {}
    }
  ],
  "connections": {
    "Cada 15 minutos": {
      "main": [
        [
          {
            "node": "Config alerta errores",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Config alerta errores": {
      "main": [
        [
          {
            "node": "GET executions error",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GET executions error": {
      "main": [
        [
          {
            "node": "Contar fallos recientes",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Contar fallos recientes": {
      "main": [
        [
          {
            "node": "¿Hay fallos recientes?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "¿Hay fallos recientes?": {
      "main": [
        [
          {
            "node": "Alerta Slack (errores)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "OK — sin alerta",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}
