{
  "name": "Weekly Lead-to-MQL Conversion Report",
  "nodes": [
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "triggerAtDay": 1,
              "triggerAtHour": 9,
              "triggerAtMinute": 0
            }
          ]
        }
      },
      "id": "schedule-trigger",
      "name": "Schedule Trigger",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [0, 0]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "seven_days_ago_ms",
              "name": "seven_days_ago_ms",
              "value": "={{ new Date(Date.now() - 7 * 86400000).setHours(0,0,0,0).toString() }}",
              "type": "string"
            },
            {
              "id": "today_ms",
              "name": "today_ms",
              "value": "={{ new Date().setHours(0,0,0,0).toString() }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "set-dates",
      "name": "Set Dates",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [220, 0]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.hubapi.com/crm/v3/objects/contacts/search",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "hubspotApi",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={ \"filterGroups\": [{ \"filters\": [{ \"propertyName\": \"createdate\", \"operator\": \"GTE\", \"value\": \"{{ $json.seven_days_ago_ms }}\" }, { \"propertyName\": \"createdate\", \"operator\": \"LT\", \"value\": \"{{ $json.today_ms }}\" }] }], \"properties\": [\"hs_analytics_source\", \"lifecyclestage\", \"createdate\"], \"limit\": 100 }",
        "options": {}
      },
      "id": "fetch-leads",
      "name": "Fetch Leads",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [440, -60],
      "credentials": {
        "hubspotApi": {
          "id": "credential-id",
          "name": "HubSpot API"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.hubapi.com/crm/v3/objects/contacts/search",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "hubspotApi",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={ \"filterGroups\": [{ \"filters\": [{ \"propertyName\": \"createdate\", \"operator\": \"GTE\", \"value\": \"{{ $('Set Dates').first().json.seven_days_ago_ms }}\" }, { \"propertyName\": \"createdate\", \"operator\": \"LT\", \"value\": \"{{ $('Set Dates').first().json.today_ms }}\" }, { \"propertyName\": \"lifecyclestage\", \"operator\": \"EQ\", \"value\": \"marketingqualifiedlead\" }] }], \"properties\": [\"hs_analytics_source\", \"lifecyclestage\", \"createdate\"], \"limit\": 100 }",
        "options": {}
      },
      "id": "fetch-mqls",
      "name": "Fetch MQLs",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [440, 60],
      "credentials": {
        "hubspotApi": {
          "id": "credential-id",
          "name": "HubSpot API"
        }
      }
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const allLeads = $('Fetch Leads').first().json.results || [];\nconst mqls = $('Fetch MQLs').first().json.results || [];\n\n// Group leads by source\nconst leadsBySource = {};\nfor (const lead of allLeads) {\n  const source = lead.properties.hs_analytics_source || 'UNKNOWN';\n  leadsBySource[source] = (leadsBySource[source] || 0) + 1;\n}\n\n// Group MQLs by source\nconst mqlsBySource = {};\nfor (const mql of mqls) {\n  const source = mql.properties.hs_analytics_source || 'UNKNOWN';\n  mqlsBySource[source] = (mqlsBySource[source] || 0) + 1;\n}\n\n// Calculate conversion rate per source\nconst sources = [...new Set([...Object.keys(leadsBySource), ...Object.keys(mqlsBySource)])];\nconst report = sources\n  .map(source => ({\n    source,\n    leads: leadsBySource[source] || 0,\n    mqls: mqlsBySource[source] || 0,\n    rate: leadsBySource[source]\n      ? ((mqlsBySource[source] || 0) / leadsBySource[source] * 100).toFixed(1)\n      : '0.0',\n  }))\n  .sort((a, b) => b.leads - a.leads);\n\nconst totalLeads = allLeads.length;\nconst totalMQLs = mqls.length;\nconst overallRate = totalLeads > 0 ? (totalMQLs / totalLeads * 100).toFixed(1) : '0.0';\n\nreturn [{\n  json: {\n    report,\n    totalLeads,\n    totalMQLs,\n    overallRate,\n  }\n}];"
      },
      "id": "calc-conversion",
      "name": "Calculate Conversion",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [660, 0]
    },
    {
      "parameters": {
        "select": "channel",
        "channelId": {
          "__rl": true,
          "value": "marketing-reports",
          "mode": "name"
        },
        "messageType": "block",
        "blocksUi": "={\n  \"blocks\": [\n    {\n      \"type\": \"header\",\n      \"text\": {\n        \"type\": \"plain_text\",\n        \"text\": \"\ud83d\udcc8 Weekly Lead-to-MQL Conversion Report\"\n      }\n    },\n    {\n      \"type\": \"section\",\n      \"fields\": [\n        {\n          \"type\": \"mrkdwn\",\n          \"text\": \"*Total Leads*\\n\" + $json.totalLeads\n        },\n        {\n          \"type\": \"mrkdwn\",\n          \"text\": \"*Total MQLs*\\n\" + $json.totalMQLs\n        },\n        {\n          \"type\": \"mrkdwn\",\n          \"text\": \"*Overall Conversion*\\n\" + $json.overallRate + \"%\"\n        }\n      ]\n    },\n    {\n      \"type\": \"divider\"\n    },\n    {\n      \"type\": \"section\",\n      \"text\": {\n        \"type\": \"mrkdwn\",\n        \"text\": \"*Conversion by Source*\\n\" + $json.report.map(r => `\u2022 *${r.source}*: ${r.leads} leads \u2192 ${r.mqls} MQLs (${r.rate}%)`).join('\\n')\n      }\n    },\n    {\n      \"type\": \"context\",\n      \"elements\": [\n        {\n          \"type\": \"mrkdwn\",\n          \"text\": \"Last 7 days | Generated \" + new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' })\n        }\n      ]\n    }\n  ]\n}",
        "otherOptions": {
          "unfurl_links": false
        }
      },
      "id": "notify-slack",
      "name": "Post Report",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.3,
      "position": [880, 0],
      "credentials": {
        "slackApi": {
          "id": "credential-id",
          "name": "Slack API"
        }
      }
    }
  ],
  "connections": {
    "Schedule Trigger": {
      "main": [
        [
          {
            "node": "Set Dates",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set Dates": {
      "main": [
        [
          {
            "node": "Fetch Leads",
            "type": "main",
            "index": 0
          },
          {
            "node": "Fetch MQLs",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Leads": {
      "main": [
        [
          {
            "node": "Calculate Conversion",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch MQLs": {
      "main": [
        [
          {
            "node": "Calculate Conversion",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Calculate Conversion": {
      "main": [
        [
          {
            "node": "Post Report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "staticData": null,
  "tags": [],
  "triggerCount": 0,
  "active": false,
  "meta": {
    "instanceId": "",
    "templateId": "revi-conversion-report"
  }
}
