{
  "name": "Logixb2b — Pipeline de analítica predictiva",
  "meta": {
    "templateCredsSetupCompleted": false,
    "description": "Schedule semanal → GET CRM → features → LLM forecast → Sheets append → Slack. Sin PII en el resumen. Incluye Asistente IA (OpenAI) configurable."
  },
  "settings": {
    "executionOrder": "v1",
    "timezone": "Europe/Madrid"
  },
  "active": false,
  "pinData": {},
  "tags": [
    {
      "name": "Logixb2b"
    },
    {
      "name": "recursos"
    },
    {
      "name": "analitica"
    },
    {
      "name": "pipeline"
    }
  ],
  "nodes": [
    {
      "id": "sticky-instrucciones-logix",
      "name": "INSTRUCCIONES (conectar + VPS)",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -480,
        40
      ],
      "parameters": {
        "content": "## INSTRUCCIONES — Pipeline de analítica predictiva\n\n**Recurso:** `/recursos/analitica-predictiva-pipeline`\n**Guía:** /analitica-predictiva-ventas-herramientas-metodologia\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- **Lunes 08:00 Madrid** (`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 analítica** (`Set` Config): **no lleva credencial**. Aquí van URLs/placeholders (`REEMPLAZA_*`, `example.com`, `TU-CRM`). Sustituye todos antes de Active.\n- **GET pipeline abierto CRM** (`HTTP Request` CRM): Credentials → **Header Auth** / OAuth del CRM. Sustituye `crm*Url` en el nodo **Config**. Prueba con un Lead de sandbox.\n- **Calcular features** (`Set`): sin credencial. Revisa expresiones `={{ }}` y campos de salida.\n- **Unir forecast + features** (`Set`): sin credencial. Revisa expresiones `={{ }}` y campos de salida.\n- **Append Google Sheets** (`HTTP Request` Sheets): mejor migrar a nodo Google Sheets; si dejas HTTP, usa OAuth2 Bearer de Google.\n- **Slack resumen semanal** (`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- **Preparar prompt IA** (`Set`): sin credencial. Revisa expresiones `={{ }}` y campos de salida.\n- **Asistente IA** (`AI Agent`): no lleva API key propia; debe estar cableado al nodo **Modelo OpenAI**. Revisa el prompt del sistema y que la salida pase por revisión humana (HITL) antes de escribir al CRM.\n- **Modelo OpenAI** (`OpenAI / LLM`): Credentials → **OpenAI API** (o compatible: base URL + API key). Nunca pegues la key en el JSON. El Asistente IA depende de este nodo.\n- **Aplicar salida IA** (`Set`): sin credencial. Revisa expresiones `={{ }}` y campos de salida.\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": "sched-weekly",
      "name": "Lunes 08:00 Madrid",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        300
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "cronExpression",
              "expression": "0 8 * * 1"
            }
          ]
        }
      }
    },
    {
      "id": "set-config",
      "name": "Config analítica",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        300,
        300
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "assignments": {
          "assignments": [
            {
              "id": "c1",
              "name": "crmPipelineUrl",
              "value": "https://TU-CRM.ejemplo/api/leads?status=open",
              "type": "string"
            },
            {
              "id": "c2",
              "name": "sheetsAppendUrl",
              "value": "https://sheets.googleapis.com/v4/spreadsheets/TU_SHEET_ID/values/Pipeline!A1:append?valueInputOption=USER_ENTERED",
              "type": "string"
            },
            {
              "id": "c3",
              "name": "llmUrl",
              "value": "https://api.openai.com/v1/chat/completions",
              "type": "string"
            },
            {
              "id": "c4",
              "name": "apiKey",
              "value": "sustituye-con-tu-clave-del-modelo-ia",
              "type": "string"
            },
            {
              "id": "c5",
              "name": "model",
              "value": "gpt-4o-mini",
              "type": "string"
            },
            {
              "id": "c6",
              "name": "slackWebhookUrl",
              "value": "https://example.com/aviso-equipo-slack",
              "type": "string"
            }
          ]
        }
      }
    },
    {
      "id": "http-crm",
      "name": "GET pipeline abierto CRM",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        600,
        300
      ],
      "parameters": {
        "method": "GET",
        "url": "={{ $json.crmPipelineUrl }}",
        "options": {
          "timeout": 30000
        }
      }
    },
    {
      "id": "set-features",
      "name": "Calcular features",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        900,
        300
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "assignments": {
          "assignments": [
            {
              "id": "f1",
              "name": "dealCount",
              "value": "={{ Array.isArray($json.deals) ? $json.deals.length : (Array.isArray($json) ? $json.length : Number($json.count || 0)) }}",
              "type": "number"
            },
            {
              "id": "f2",
              "name": "avgAmount",
              "value": "={{ (() => { const arr = Array.isArray($json.deals) ? $json.deals : (Array.isArray($json) ? $json : []); if (!arr.length) return Number($json.avgAmount || 0); const sum = arr.reduce((s, d) => s + Number(d.amount || d.value || 0), 0); return Math.round((sum / arr.length) * 100) / 100; })() }}",
              "type": "number"
            },
            {
              "id": "f3",
              "name": "totalAmount",
              "value": "={{ (() => { const arr = Array.isArray($json.deals) ? $json.deals : (Array.isArray($json) ? $json : []); if (!arr.length) return Number($json.totalAmount || 0); return arr.reduce((s, d) => s + Number(d.amount || d.value || 0), 0); })() }}",
              "type": "number"
            },
            {
              "id": "f4",
              "name": "weekOf",
              "value": "={{ $now.toISO() }}",
              "type": "string"
            },
            {
              "id": "f5",
              "name": "llmUrl",
              "value": "={{ $('Config analítica').item.json.llmUrl }}",
              "type": "string"
            },
            {
              "id": "f6",
              "name": "apiKey",
              "value": "={{ $('Config analítica').item.json.apiKey }}",
              "type": "string"
            },
            {
              "id": "f7",
              "name": "model",
              "value": "={{ $('Config analítica').item.json.model }}",
              "type": "string"
            },
            {
              "id": "f8",
              "name": "sheetsAppendUrl",
              "value": "={{ $('Config analítica').item.json.sheetsAppendUrl }}",
              "type": "string"
            },
            {
              "id": "f9",
              "name": "slackWebhookUrl",
              "value": "={{ $('Config analítica').item.json.slackWebhookUrl }}",
              "type": "string"
            }
          ]
        }
      }
    },
    {
      "id": "set-forecast",
      "name": "Unir forecast + features",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        2100,
        300
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "assignments": {
          "assignments": [
            {
              "id": "u1",
              "name": "dealCount",
              "value": "={{ $('Calcular features').item.json.dealCount }}",
              "type": "number"
            },
            {
              "id": "u2",
              "name": "avgAmount",
              "value": "={{ $('Calcular features').item.json.avgAmount }}",
              "type": "number"
            },
            {
              "id": "u3",
              "name": "totalAmount",
              "value": "={{ $('Calcular features').item.json.totalAmount }}",
              "type": "number"
            },
            {
              "id": "u4",
              "name": "weekOf",
              "value": "={{ $('Calcular features').item.json.weekOf }}",
              "type": "string"
            },
            {
              "id": "u5",
              "name": "forecastNote",
              "value": "={{ (() => { try { return JSON.parse($json.aiOutput).forecastNote; } catch(e) { return 'Sin nota LLM'; } })() }}",
              "type": "string"
            },
            {
              "id": "u6",
              "name": "risk",
              "value": "={{ (() => { try { return JSON.parse($json.aiOutput).risk; } catch(e) { return 'medio'; } })() }}",
              "type": "string"
            },
            {
              "id": "u7",
              "name": "sheetsAppendUrl",
              "value": "={{ $('Calcular features').item.json.sheetsAppendUrl }}",
              "type": "string"
            },
            {
              "id": "u8",
              "name": "slackWebhookUrl",
              "value": "={{ $('Calcular features').item.json.slackWebhookUrl }}",
              "type": "string"
            }
          ]
        }
      }
    },
    {
      "id": "http-sheets",
      "name": "Append Google Sheets",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2400,
        300
      ],
      "parameters": {
        "method": "POST",
        "url": "={{ $json.sheetsAppendUrl }}",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ values: [[ $json.weekOf, $json.dealCount, $json.avgAmount, $json.totalAmount, $json.risk, $json.forecastNote ]] }) }}",
        "options": {
          "timeout": 30000
        }
      }
    },
    {
      "id": "http-slack",
      "name": "Slack resumen semanal",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2700,
        300
      ],
      "parameters": {
        "method": "POST",
        "url": "={{ $('Unir forecast + features').item.json.slackWebhookUrl }}",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ text: ':chart_with_upwards_trend: *Pipeline semanal*\\nLeads: ' + $('Unir forecast + features').item.json.dealCount + ' · Media: ' + $('Unir forecast + features').item.json.avgAmount + ' · Total: ' + $('Unir forecast + features').item.json.totalAmount + '\\nRiesgo: ' + $('Unir forecast + features').item.json.risk + '\\n' + $('Unir forecast + features').item.json.forecastNote }) }}",
        "options": {
          "timeout": 10000
        }
      }
    },
    {
      "id": "ai-prep-analitica-pr",
      "name": "Preparar prompt IA",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        1200,
        300
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "includeOtherFields": true,
        "assignments": {
          "assignments": [
            {
              "id": "p1",
              "name": "aiPrompt",
              "value": "={{ \"Eres analista predictivo. Con las features del pipeline, escribe una nota de forecast (5 líneas) y un riesgo. Español.\\n\\nFeatures:\\n\" + JSON.stringify($json) + \"\" }}",
              "type": "string"
            }
          ]
        }
      }
    },
    {
      "id": "ai-agent-analitica-pr",
      "name": "Asistente IA",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 1.7,
      "position": [
        1500,
        300
      ],
      "parameters": {
        "promptType": "define",
        "text": "={{ $json.aiPrompt }}",
        "options": {}
      }
    },
    {
      "id": "ai-model-analitica-pr",
      "name": "Modelo OpenAI",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.2,
      "position": [
        1500,
        580
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4o-mini"
        },
        "options": {}
      }
    },
    {
      "id": "ai-apply-analitica-pr",
      "name": "Aplicar salida IA",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        1800,
        300
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "includeOtherFields": true,
        "assignments": {
          "assignments": [
            {
              "id": "a1",
              "name": "aiOutput",
              "value": "={{ $json.output || $json.text || $json.message || JSON.stringify($json) }}",
              "type": "string"
            },
            {
              "id": "a2",
              "name": "slackText",
              "value": "={{ ($json.output || $json.text || '').toString() || 'Revisa el resultado del Asistente IA.' }}",
              "type": "string"
            }
          ]
        }
      }
    }
  ],
  "connections": {
    "Lunes 08:00 Madrid": {
      "main": [
        [
          {
            "node": "Config analítica",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Config analítica": {
      "main": [
        [
          {
            "node": "GET pipeline abierto CRM",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GET pipeline abierto CRM": {
      "main": [
        [
          {
            "node": "Calcular features",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Calcular features": {
      "main": [
        [
          {
            "node": "Preparar prompt IA",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Unir forecast + features": {
      "main": [
        [
          {
            "node": "Append Google Sheets",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Append Google Sheets": {
      "main": [
        [
          {
            "node": "Slack resumen semanal",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Preparar prompt IA": {
      "main": [
        [
          {
            "node": "Asistente IA",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Asistente IA": {
      "main": [
        [
          {
            "node": "Aplicar salida IA",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Modelo OpenAI": {
      "ai_languageModel": [
        [
          {
            "node": "Asistente IA",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Aplicar salida IA": {
      "main": [
        [
          {
            "node": "Unir forecast + features",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}
