{
  "name": "Informe SEO semanal (Search Console)",
  "nodes": [
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "weeks",
              "triggerAtDay": [
                1
              ],
              "triggerAtHour": 8
            }
          ]
        }
      },
      "name": "Cada lunes a las 8:00",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        0
      ]
    },
    {
      "parameters": {
        "jsCode": "// Semana actual: los 7 días que terminan ayer. Semana anterior: los 7 días previos.\nconst dia = (n) => {\n  const d = new Date();\n  d.setUTCDate(d.getUTCDate() - n);\n  return d.toISOString().slice(0, 10);\n};\nreturn [{ json: {\n  inicio: dia(7), fin: dia(1),\n  inicioAnterior: dia(14), finAnterior: dia(8),\n} }];"
      },
      "name": "Fechas",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        220,
        0
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://www.googleapis.com/webmasters/v3/sites/{{ encodeURIComponent('sc-domain:tudominio.com') }}/searchAnalytics/query",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleApi",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"startDate\": \"{{ $('Fechas').first().json.inicio }}\",\n  \"endDate\": \"{{ $('Fechas').first().json.fin }}\",\n  \"dimensions\": [\"page\"],\n  \"rowLimit\": 1000\n}",
        "options": {}
      },
      "name": "Semana actual",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        440,
        0
      ],
      "credentials": {
        "googleApi": {
          "id": "",
          "name": "Cuenta de servicio de Google"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://www.googleapis.com/webmasters/v3/sites/{{ encodeURIComponent('sc-domain:tudominio.com') }}/searchAnalytics/query",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleApi",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"startDate\": \"{{ $('Fechas').first().json.inicioAnterior }}\",\n  \"endDate\": \"{{ $('Fechas').first().json.finAnterior }}\",\n  \"dimensions\": [\"page\"],\n  \"rowLimit\": 1000\n}",
        "options": {}
      },
      "name": "Semana anterior",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        660,
        0
      ],
      "credentials": {
        "googleApi": {
          "id": "",
          "name": "Cuenta de servicio de Google"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// Compara las dos semanas por página y prepara el correo\nconst actual = $('Semana actual').first().json.rows ?? [];\nconst anterior = $('Semana anterior').first().json.rows ?? [];\nconst f = $('Fechas').first().json;\n\nconst previas = new Map(anterior.map((r) => [r.keys[0], r]));\nconst total = (filas, campo) => filas.reduce((s, r) => s + r[campo], 0);\nconst fmt = (n) => n.toLocaleString('es-ES');\nconst dif = (a, b) => (a - b > 0 ? '+' : '') + fmt(a - b);\n\nconst clics = total(actual, 'clicks'), clicsAnt = total(anterior, 'clicks');\nconst impr = total(actual, 'impressions'), imprAnt = total(anterior, 'impressions');\n\nconst filas = actual.slice(0, 10).map((r) => {\n  const p = previas.get(r.keys[0]);\n  return `<tr><td>${r.keys[0]}</td><td>${fmt(r.clicks)}</td><td>${dif(r.clicks, p ? p.clicks : 0)}</td><td>${r.position.toFixed(1)}</td></tr>`;\n}).join('');\n\nconst html = `<h2>Informe SEO semanal</h2>\n<p>Del ${f.inicio} al ${f.fin}, comparado con la semana anterior.</p>\n<ul>\n  <li><strong>Clics:</strong> ${fmt(clics)} (${dif(clics, clicsAnt)})</li>\n  <li><strong>Impresiones:</strong> ${fmt(impr)} (${dif(impr, imprAnt)})</li>\n</ul>\n<h3>Páginas con más clics</h3>\n<table border=\"1\" cellpadding=\"6\" cellspacing=\"0\">\n  <tr><th>Página</th><th>Clics</th><th>Cambio</th><th>Posición media</th></tr>\n  ${filas}\n</table>`;\n\nreturn [{ json: { asunto: `Informe SEO semanal: ${f.inicio} a ${f.fin}`, html } }];"
      },
      "name": "Informe",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        880,
        0
      ]
    },
    {
      "parameters": {
        "fromEmail": "informes@tudominio.com",
        "toEmail": "tu@email.com",
        "subject": "={{ $json.asunto }}",
        "emailFormat": "html",
        "html": "={{ $json.html }}",
        "options": {}
      },
      "name": "Enviar correo",
      "type": "n8n-nodes-base.emailSend",
      "typeVersion": 2.1,
      "position": [
        1100,
        0
      ],
      "credentials": {
        "smtp": {
          "id": "",
          "name": "SMTP"
        }
      }
    }
  ],
  "connections": {
    "Cada lunes a las 8:00": {
      "main": [
        [
          {
            "node": "Fechas",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fechas": {
      "main": [
        [
          {
            "node": "Semana actual",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Semana actual": {
      "main": [
        [
          {
            "node": "Semana anterior",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Semana anterior": {
      "main": [
        [
          {
            "node": "Informe",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Informe": {
      "main": [
        [
          {
            "node": "Enviar correo",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "active": false
}
