{
  "name": "Logixb2b — Agente IA asistente en CRM",
  "meta": {
    "templateCredsSetupCompleted": false,
    "description": "Webhook CRM → normaliza → LLM (resumen + siguiente acción) → nota CRM → Slack. Revisión humana obligatoria. Incluye Asistente IA (OpenAI) configurable."
  },
  "settings": {
    "executionOrder": "v1",
    "timezone": "Europe/Madrid"
  },
  "active": false,
  "pinData": {},
  "tags": [
    {
      "name": "Logixb2b"
    },
    {
      "name": "recursos"
    },
    {
      "name": "ia"
    },
    {
      "name": "crm"
    }
  ],
  "nodes": [
    {
      "id": "sticky-instrucciones-logix",
      "name": "INSTRUCCIONES (conectar + VPS)",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -480,
        40
      ],
      "parameters": {
        "content": "## INSTRUCCIONES — Agente IA asistente en CRM\n\n**Recurso:** `/recursos/agente-ia-crm-asistente`\n**Guía:** /que-es-agente-ia-ventas-como-implementarlo-crm\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- **Webhook CRM evento** (`webhook`): sin credencial. Tras Active, copia **URL de producción** (HTTPS del VPS/Cloud). El emisor (formulario, CRM, bot) debe POST a esa URL.\n- **Config agente** (`Set` Config): **no lleva credencial**. Aquí van URLs/placeholders (`REEMPLAZA_*`, `example.com`, `TU-CRM`). Sustituye todos antes de Active.\n- **Normalizar campos** (`Set`): sin credencial. Revisa expresiones `={{ }}` y campos de salida.\n- **Parsear respuesta LLM** (`Set`): sin credencial. Revisa expresiones `={{ }}` y campos de salida.\n- **POST nota CRM (borrador IA)** (`HTTP Request` CRM): Credentials → **Header Auth** / OAuth del CRM. Sustituye `crm*Url` en el nodo **Config**. Prueba con un Lead de sandbox.\n- **Slack aviso (revisión humana)** (`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": "wh-crm",
      "name": "Webhook CRM evento",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        300
      ],
      "webhookId": "wh-crm",
      "parameters": {
        "httpMethod": "POST",
        "path": "crm-agente-ia",
        "responseMode": "onReceived",
        "options": {}
      }
    },
    {
      "id": "set-config",
      "name": "Config agente",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        300,
        300
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "assignments": {
          "assignments": [
            {
              "id": "c1",
              "name": "llmUrl",
              "value": "https://api.openai.com/v1/chat/completions",
              "type": "string"
            },
            {
              "id": "c2",
              "name": "apiKey",
              "value": "sustituye-con-tu-clave-del-modelo-ia",
              "type": "string"
            },
            {
              "id": "c3",
              "name": "model",
              "value": "gpt-4o-mini",
              "type": "string"
            },
            {
              "id": "c4",
              "name": "crmNoteUrl",
              "value": "https://TU-CRM.ejemplo/api/notes",
              "type": "string"
            },
            {
              "id": "c5",
              "name": "slackWebhookUrl",
              "value": "https://example.com/aviso-equipo-slack",
              "type": "string"
            }
          ]
        }
      }
    },
    {
      "id": "set-norm",
      "name": "Normalizar campos",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        600,
        300
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "assignments": {
          "assignments": [
            {
              "id": "n1",
              "name": "leadId",
              "value": "={{ ($('Webhook CRM evento').item.json.body || $('Webhook CRM evento').item.json).leadId || ($('Webhook CRM evento').item.json.body || $('Webhook CRM evento').item.json).id || '' }}",
              "type": "string"
            },
            {
              "id": "n2",
              "name": "company",
              "value": "={{ ($('Webhook CRM evento').item.json.body || $('Webhook CRM evento').item.json).company || '' }}",
              "type": "string"
            },
            {
              "id": "n3",
              "name": "noteText",
              "value": "={{ ($('Webhook CRM evento').item.json.body || $('Webhook CRM evento').item.json).note || ($('Webhook CRM evento').item.json.body || $('Webhook CRM evento').item.json).notes || ($('Webhook CRM evento').item.json.body || $('Webhook CRM evento').item.json).text || '' }}",
              "type": "string"
            },
            {
              "id": "n4",
              "name": "owner",
              "value": "={{ ($('Webhook CRM evento').item.json.body || $('Webhook CRM evento').item.json).owner || '' }}",
              "type": "string"
            },
            {
              "id": "n5",
              "name": "llmUrl",
              "value": "={{ $('Config agente').item.json.llmUrl }}",
              "type": "string"
            },
            {
              "id": "n6",
              "name": "apiKey",
              "value": "={{ $('Config agente').item.json.apiKey }}",
              "type": "string"
            },
            {
              "id": "n7",
              "name": "model",
              "value": "={{ $('Config agente').item.json.model }}",
              "type": "string"
            },
            {
              "id": "n8",
              "name": "crmNoteUrl",
              "value": "={{ $('Config agente').item.json.crmNoteUrl }}",
              "type": "string"
            },
            {
              "id": "n9",
              "name": "slackWebhookUrl",
              "value": "={{ $('Config agente').item.json.slackWebhookUrl }}",
              "type": "string"
            }
          ]
        }
      }
    },
    {
      "id": "set-parse",
      "name": "Parsear respuesta LLM",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        1800,
        300
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "assignments": {
          "assignments": [
            {
              "id": "p1",
              "name": "llmRaw",
              "value": "={{ $json.choices && $json.choices[0] && $json.choices[0].message ? $json.aiOutput : '' }}",
              "type": "string"
            },
            {
              "id": "p2",
              "name": "resumen",
              "value": "={{ (() => { try { return JSON.parse($json.aiOutput).resumen; } catch(e) { return ($json.choices && $json.choices[0] && $json.choices[0].message && $json.aiOutput) || ''; } })() }}",
              "type": "string"
            },
            {
              "id": "p3",
              "name": "siguienteAccion",
              "value": "={{ (() => { try { return JSON.parse($json.aiOutput).siguienteAccion; } catch(e) { return ''; } })() }}",
              "type": "string"
            },
            {
              "id": "p4",
              "name": "prioridad",
              "value": "={{ (() => { try { return JSON.parse($json.aiOutput).prioridad; } catch(e) { return 'media'; } })() }}",
              "type": "string"
            },
            {
              "id": "p5",
              "name": "leadId",
              "value": "={{ $('Normalizar campos').item.json.leadId }}",
              "type": "string"
            },
            {
              "id": "p6",
              "name": "company",
              "value": "={{ $('Normalizar campos').item.json.company }}",
              "type": "string"
            },
            {
              "id": "p7",
              "name": "crmNoteUrl",
              "value": "={{ $('Normalizar campos').item.json.crmNoteUrl }}",
              "type": "string"
            },
            {
              "id": "p8",
              "name": "slackWebhookUrl",
              "value": "={{ $('Normalizar campos').item.json.slackWebhookUrl }}",
              "type": "string"
            }
          ]
        }
      }
    },
    {
      "id": "http-crm-note",
      "name": "POST nota CRM (borrador IA)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2100,
        300
      ],
      "parameters": {
        "method": "POST",
        "url": "={{ $json.crmNoteUrl }}",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ leadId: $json.leadId, type: 'ai_suggestion', needs_human_review: true, body: '[IA — revisar] Resumen: ' + $json.resumen + '\\nSiguiente acción: ' + $json.siguienteAccion + '\\nPrioridad: ' + $json.prioridad }) }}",
        "options": {
          "timeout": 30000
        }
      }
    },
    {
      "id": "http-slack",
      "name": "Slack aviso (revisión humana)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2400,
        300
      ],
      "parameters": {
        "method": "POST",
        "url": "={{ $('Parsear respuesta LLM').item.json.slackWebhookUrl }}",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ text: ':robot_face: *Sugerencia IA (revisar)* — ' + $('Parsear respuesta LLM').item.json.company + '\\nResumen: ' + $('Parsear respuesta LLM').item.json.resumen + '\\nAcción: ' + $('Parsear respuesta LLM').item.json.siguienteAccion + '\\n_No enviar al cliente sin revisión._' }) }}",
        "options": {
          "timeout": 10000
        }
      }
    },
    {
      "id": "ai-prep-agente-ia-cr",
      "name": "Preparar prompt IA",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        900,
        300
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "includeOtherFields": true,
        "assignments": {
          "assignments": [
            {
              "id": "p1",
              "name": "aiPrompt",
              "value": "={{ \"Eres un agente IA de ventas en CRM. Devuelve JSON con keys summary y nextAction (español) a partir del lead/nota. Sin inventar datos.\\n\\nEntrada:\\n\" + JSON.stringify($json) + \"\" }}",
              "type": "string"
            }
          ]
        }
      }
    },
    {
      "id": "ai-agent-agente-ia-cr",
      "name": "Asistente IA",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 1.7,
      "position": [
        1200,
        300
      ],
      "parameters": {
        "promptType": "define",
        "text": "={{ $json.aiPrompt }}",
        "options": {}
      }
    },
    {
      "id": "ai-model-agente-ia-cr",
      "name": "Modelo OpenAI",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.2,
      "position": [
        1200,
        580
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4o-mini"
        },
        "options": {}
      }
    },
    {
      "id": "ai-apply-agente-ia-cr",
      "name": "Aplicar salida IA",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        1500,
        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": {
    "Webhook CRM evento": {
      "main": [
        [
          {
            "node": "Config agente",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Config agente": {
      "main": [
        [
          {
            "node": "Normalizar campos",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Normalizar campos": {
      "main": [
        [
          {
            "node": "Preparar prompt IA",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parsear respuesta LLM": {
      "main": [
        [
          {
            "node": "POST nota CRM (borrador IA)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "POST nota CRM (borrador IA)": {
      "main": [
        [
          {
            "node": "Slack aviso (revisión humana)",
            "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": "Parsear respuesta LLM",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}
