{
  "name": "Logixb2b — Reporting CRM → Sheets (Cron)",
  "meta": {
    "templateCredsSetupCompleted": false,
    "description": "Lunes 08:00 Europe/Madrid → GET CRM → métricas → append Google Sheets → resumen Slack sin PII."
  },
  "settings": {
    "executionOrder": "v1",
    "timezone": "Europe/Madrid"
  },
  "active": false,
  "pinData": {},
  "tags": [
    {
      "name": "Logixb2b"
    },
    {
      "name": "recursos"
    },
    {
      "name": "crm"
    },
    {
      "name": "reporting"
    }
  ],
  "nodes": [
    {
      "id": "sticky-instrucciones-logix",
      "name": "INSTRUCCIONES (conectar + VPS)",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -480,
        40
      ],
      "parameters": {
        "content": "## INSTRUCCIONES — Reporting CRM → Sheets (Cron)\n\n**Recurso:** `/recursos/reporting-crm-sheets-cron`\n**Guía:** /como-conectar-n8n-google-sheets-reporting-comercial\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 lunes 08:00** (`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 reporting** (`Set` Config): **no lleva credencial**. Aquí van URLs/placeholders (`REEMPLAZA_*`, `example.com`, `TU-CRM`). Sustituye todos antes de Active.\n- **Obtener Leads del 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 métricas** (`Set`): sin credencial. Revisa expresiones `={{ }}` y campos de salida.\n- **¿CRM OK?** (`IF`): sin credencial. Comprueba la condición (email, umbral, over_limit, etc.) con datos reales de prueba.\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- **Slack — fallo lectura CRM** (`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": "rep-schedule",
      "name": "Cada lunes 08:00",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        300
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "cronExpression",
              "expression": "0 8 * * 1"
            }
          ]
        }
      }
    },
    {
      "id": "rep-config",
      "name": "Config reporting",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        300,
        300
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "assignments": {
          "assignments": [
            {
              "id": "rep-c1",
              "name": "crmDealsUrl",
              "value": "https://TU-CRM.ejemplo/api/leads?status=open",
              "type": "string"
            },
            {
              "id": "rep-c2",
              "name": "crmApiKey",
              "value": "sustituye-con-tu-clave-del-crm",
              "type": "string"
            },
            {
              "id": "rep-c3",
              "name": "sheetsAppendUrl",
              "value": "https://sheets.googleapis.com/v4/spreadsheets/TU_SHEET_ID/values/Reporte!A1:append?valueInputOption=USER_ENTERED",
              "type": "string"
            },
            {
              "id": "rep-c4",
              "name": "slackWebhookUrl",
              "value": "https://example.com/aviso-equipo-slack",
              "type": "string"
            },
            {
              "id": "rep-c5",
              "name": "reportDate",
              "value": "={{ $now.setZone('Europe/Madrid').toFormat('yyyy-MM-dd') }}",
              "type": "string"
            },
            {
              "id": "rep-c6",
              "name": "reportAt",
              "value": "={{ $now.setZone('Europe/Madrid').toFormat('yyyy-MM-dd HH:mm') }}",
              "type": "string"
            }
          ]
        }
      }
    },
    {
      "id": "rep-crm",
      "name": "Obtener Leads del CRM",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        600,
        300
      ],
      "parameters": {
        "method": "GET",
        "url": "={{ $json.crmDealsUrl }}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "=Bearer {{ $json.crmApiKey }}"
            }
          ]
        },
        "options": {
          "timeout": 30000,
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": true
            }
          }
        }
      }
    },
    {
      "id": "rep-metrics",
      "name": "Calcular métricas",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        900,
        300
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "assignments": {
          "assignments": [
            {
              "id": "rep-m1",
              "name": "crmStatus",
              "value": "={{ $json.statusCode }}",
              "type": "number"
            },
            {
              "id": "rep-m2",
              "name": "crmOk",
              "value": "={{ Number($json.statusCode) >= 200 && Number($json.statusCode) < 300 }}",
              "type": "boolean"
            },
            {
              "id": "rep-m3",
              "name": "openDeals",
              "value": "={{ (() => { const b = $json.body; const arr = Array.isArray(b?.deals) ? b.deals : (Array.isArray(b?.data) ? b.data : (Array.isArray(b) ? b : [])); return arr.length; })() }}",
              "type": "number"
            },
            {
              "id": "rep-m4",
              "name": "pipelineValue",
              "value": "={{ (() => { const b = $json.body; const arr = Array.isArray(b?.deals) ? b.deals : (Array.isArray(b?.data) ? b.data : (Array.isArray(b) ? b : [])); return arr.reduce((s, d) => s + Number(d.amount || d.value || 0), 0); })() }}",
              "type": "number"
            },
            {
              "id": "rep-m5",
              "name": "avgDeal",
              "value": "={{ (() => { const b = $json.body; const arr = Array.isArray(b?.deals) ? b.deals : (Array.isArray(b?.data) ? b.data : (Array.isArray(b) ? b : [])); const n = arr.length; if (!n) return 0; const total = arr.reduce((s, d) => s + Number(d.amount || d.value || 0), 0); return Math.round(total / n); })() }}",
              "type": "number"
            },
            {
              "id": "rep-m6",
              "name": "reportDate",
              "value": "={{ $('Config reporting').item.json.reportDate }}",
              "type": "string"
            },
            {
              "id": "rep-m7",
              "name": "reportAt",
              "value": "={{ $('Config reporting').item.json.reportAt }}",
              "type": "string"
            },
            {
              "id": "rep-m8",
              "name": "sheetsAppendUrl",
              "value": "={{ $('Config reporting').item.json.sheetsAppendUrl }}",
              "type": "string"
            },
            {
              "id": "rep-m9",
              "name": "slackWebhookUrl",
              "value": "={{ $('Config reporting').item.json.slackWebhookUrl }}",
              "type": "string"
            },
            {
              "id": "rep-m10",
              "name": "summaryText",
              "value": "={{ ':bar_chart: *Reporte semanal CRM* — ' + $('Config reporting').item.json.reportDate + '\\nLeads abiertos: *' + (() => { const b = $json.body; const arr = Array.isArray(b?.deals) ? b.deals : (Array.isArray(b?.data) ? b.data : (Array.isArray(b) ? b : [])); return arr.length; })() + '*\\nPipeline (€): *' + (() => { const b = $json.body; const arr = Array.isArray(b?.deals) ? b.deals : (Array.isArray(b?.data) ? b.data : (Array.isArray(b) ? b : [])); return arr.reduce((s, d) => s + Number(d.amount || d.value || 0), 0); })() + '*\\nTicket medio: ' + (() => { const b = $json.body; const arr = Array.isArray(b?.deals) ? b.deals : (Array.isArray(b?.data) ? b.data : (Array.isArray(b) ? b : [])); const n = arr.length; if (!n) return 0; return Math.round(arr.reduce((s, d) => s + Number(d.amount || d.value || 0), 0) / n); })() + '\\nHTTP CRM: ' + $json.statusCode + '\\nHora: ' + $('Config reporting').item.json.reportAt + ' (Europe/Madrid)' }}",
              "type": "string"
            }
          ]
        }
      }
    },
    {
      "id": "rep-if-ok",
      "name": "¿CRM OK?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1200,
        300
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "rep-cond-ok",
              "leftValue": "={{ $json.crmOk }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        }
      }
    },
    {
      "id": "rep-sheets",
      "name": "Append Google Sheets",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1500,
        40
      ],
      "parameters": {
        "method": "POST",
        "url": "={{ $json.sheetsAppendUrl }}",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ values: [[ $json.reportDate, $json.openDeals, $json.pipelineValue, $json.avgDeal, $json.reportAt ]] }) }}",
        "options": {
          "timeout": 20000,
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": true
            }
          }
        }
      }
    },
    {
      "id": "rep-slack",
      "name": "Slack — resumen semanal",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1800,
        40
      ],
      "parameters": {
        "method": "POST",
        "url": "={{ $('Calcular métricas').item.json.slackWebhookUrl }}",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ text: $json.slackText || 'Actualización Logixb2b' }) }}",
        "options": {
          "timeout": 10000
        }
      }
    },
    {
      "id": "rep-fail",
      "name": "Slack — fallo lectura CRM",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1500,
        560
      ],
      "parameters": {
        "method": "POST",
        "url": "={{ $json.slackWebhookUrl }}",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ text: ':warning: *Reporte semanal* — fallo GET CRM\\nHTTP: ' + $json.crmStatus + '\\nHora: ' + $json.reportAt + ' (Europe/Madrid)\\nRevisa credenciales / URL.' }) }}",
        "options": {
          "timeout": 10000
        }
      }
    }
  ],
  "connections": {
    "Cada lunes 08:00": {
      "main": [
        [
          {
            "node": "Config reporting",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Config reporting": {
      "main": [
        [
          {
            "node": "Obtener Leads del CRM",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Obtener Leads del CRM": {
      "main": [
        [
          {
            "node": "Calcular métricas",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Calcular métricas": {
      "main": [
        [
          {
            "node": "¿CRM OK?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "¿CRM OK?": {
      "main": [
        [
          {
            "node": "Append Google Sheets",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Slack — fallo lectura CRM",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Append Google Sheets": {
      "main": [
        [
          {
            "node": "Slack — resumen semanal",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}
