{
  "name": "Rank Drop Alert Monitor",
  "nodes": [
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "hours",
              "hoursInterval": 24,
              "triggerAtHour": 8
            }
          ]
        }
      },
      "id": "cron-trigger",
      "name": "Daily Check",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.1,
      "position": [
        250,
        300
      ]
    },
    {
      "parameters": {
        "documentId": {
          "__rl": true,
          "value": "={{$credentials.rankTrackerSheetId}}",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Keywords",
          "mode": "name"
        },
        "options": {}
      },
      "id": "get-keywords",
      "name": "Get Tracked Keywords",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.2,
      "position": [
        470,
        300
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "batchSize": 10,
        "options": {}
      },
      "id": "batch-keywords",
      "name": "Batch Keywords",
      "type": "n8n-nodes-base.splitInBatches",
      "typeVersion": 3,
      "position": [
        690,
        300
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{$credentials.rankTrackerApiUrl}}/check",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"keyword\": \"{{$json.keyword}}\",\n  \"domain\": \"{{$credentials.targetDomain}}\",\n  \"location\": \"{{$json.location || 'United States'}}\"\n}",
        "options": {}
      },
      "id": "check-rank",
      "name": "Check Current Rank",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.1,
      "position": [
        910,
        300
      ],
      "credentials": {
        "httpHeaderAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// Compare current rank with previous and detect drops\nconst items = $input.all();\nconst today = new Date().toISOString().split('T')[0];\nconst results = [];\nconst drops = [];\n\nfor (const item of items) {\n  const data = item.json;\n  const keyword = data.keyword;\n  const currentRank = data.position || data.rank || 0;\n  const previousRank = data.previousRank || data.previous_position || currentRank;\n  const change = previousRank - currentRank; // Positive = improved, Negative = dropped\n  \n  const result = {\n    keyword,\n    currentRank,\n    previousRank,\n    change,\n    url: data.url || '',\n    date: today\n  };\n  \n  results.push(result);\n  \n  // Track significant drops (more than 3 positions)\n  if (change < -3) {\n    drops.push({\n      keyword,\n      currentRank,\n      previousRank,\n      drop: Math.abs(change),\n      url: data.url || ''\n    });\n  }\n}\n\n// Sort drops by severity\ndrops.sort((a, b) => b.drop - a.drop);\n\nreturn {\n  json: {\n    date: today,\n    totalKeywords: results.length,\n    dropsDetected: drops.length,\n    significantDrops: drops,\n    allResults: results,\n    averagePosition: Math.round(results.reduce((sum, r) => sum + r.currentRank, 0) / results.length * 10) / 10\n  }\n};"
      },
      "id": "analyze-changes",
      "name": "Analyze Changes",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1130,
        300
      ]
    },
    {
      "parameters": {
        "documentId": {
          "__rl": true,
          "value": "={{$credentials.rankTrackerSheetId}}",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Daily Ranks",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Date": "={{$json.date}}",
            "Total Keywords": "={{$json.totalKeywords}}",
            "Average Position": "={{$json.averagePosition}}",
            "Drops Detected": "={{$json.dropsDetected}}"
          }
        },
        "options": {}
      },
      "id": "save-daily",
      "name": "Save Daily Summary",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.2,
      "position": [
        1350,
        200
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "has-drops",
              "leftValue": "={{ $json.dropsDetected }}",
              "rightValue": 0,
              "operator": {
                "type": "number",
                "operation": "gt"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "check-drops",
      "name": "Check for Drops",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        1350,
        400
      ]
    },
    {
      "parameters": {
        "channel": "#seo-alerts",
        "text": "=\ud83d\udea8 *Rank Drop Alert!*\n\n*Date:* {{$json.date}}\n*Keywords Dropped:* {{$json.dropsDetected}}\n\n*Significant Drops (>3 positions):*\n{{$json.significantDrops.slice(0, 10).map(d => `\u2022 *${d.keyword}*: ${d.previousRank} \u2192 ${d.currentRank} (\u2193${d.drop})`).join('\\n')}}\n\n*Average Position:* {{$json.averagePosition}}\n*Total Keywords Tracked:* {{$json.totalKeywords}}\n\n\u26a1 *Action Required:* Review affected pages and check for issues.",
        "otherOptions": {}
      },
      "id": "slack-alert",
      "name": "Slack Alert",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.1,
      "position": [
        1570,
        400
      ],
      "credentials": {
        "slackApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "fromEmail": "rank-alerts@yourdomain.com",
        "toEmail": "={{$credentials.alertEmail}}",
        "subject": "=\ud83d\udea8 Rank Drop Alert: {{$json.dropsDetected}} keywords dropped",
        "text": "=Rank Drop Alert\n\nDate: {{$json.date}}\nKeywords with significant drops: {{$json.dropsDetected}}\n\nDropped Keywords (>3 positions):\n{{$json.significantDrops.slice(0, 20).map(d => `- ${d.keyword}: ${d.previousRank} \u2192 ${d.currentRank} (dropped ${d.drop} positions)`).join('\\n')}}\n\nSummary:\n- Total Keywords Tracked: {{$json.totalKeywords}}\n- Average Position: {{$json.averagePosition}}\n\nPlease investigate these drops and take corrective action."
      },
      "id": "email-alert",
      "name": "Email Alert",
      "type": "n8n-nodes-base.emailSend",
      "typeVersion": 2.1,
      "position": [
        1790,
        400
      ]
    },
    {
      "parameters": {
        "jsCode": "// Prepare individual keyword updates for sheet\nconst data = $input.first().json;\nreturn data.allResults.map(r => ({\n  json: {\n    Date: data.date,\n    Keyword: r.keyword,\n    'Current Rank': r.currentRank,\n    'Previous Rank': r.previousRank,\n    Change: r.change,\n    URL: r.url\n  }\n}));"
      },
      "id": "prepare-details",
      "name": "Prepare Details",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1570,
        200
      ]
    },
    {
      "parameters": {
        "documentId": {
          "__rl": true,
          "value": "={{$credentials.rankTrackerSheetId}}",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Rank History",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "autoMapInputData"
        },
        "options": {}
      },
      "id": "save-history",
      "name": "Save History",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.2,
      "position": [
        1790,
        200
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      }
    }
  ],
  "connections": {
    "Daily Check": {
      "main": [
        [
          {
            "node": "Get Tracked Keywords",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Tracked Keywords": {
      "main": [
        [
          {
            "node": "Batch Keywords",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Batch Keywords": {
      "main": [
        [
          {
            "node": "Check Current Rank",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Current Rank": {
      "main": [
        [
          {
            "node": "Batch Keywords",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Analyze Changes": {
      "main": [
        [
          {
            "node": "Save Daily Summary",
            "type": "main",
            "index": 0
          },
          {
            "node": "Check for Drops",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save Daily Summary": {
      "main": [
        [
          {
            "node": "Prepare Details",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check for Drops": {
      "main": [
        [
          {
            "node": "Slack Alert",
            "type": "main",
            "index": 0
          }
        ],
        []
      ]
    },
    "Slack Alert": {
      "main": [
        [
          {
            "node": "Email Alert",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare Details": {
      "main": [
        [
          {
            "node": "Save History",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "staticData": null,
  "meta": {
    "templateId": "rank-drop-alert"
  },
  "tags": [
    {
      "name": "rank-tracking",
      "id": "1"
    },
    {
      "name": "alerts",
      "id": "2"
    },
    {
      "name": "seo",
      "id": "3"
    },
    {
      "name": "maximo",
      "id": "4"
    }
  ]
}