{
  "name": "Weekly Sequence Performance 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"
            }
          ]
        },
        "options": {}
      },
      "id": "set-dates",
      "name": "Set Dates",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [220, 0]
    },
    {
      "parameters": {
        "method": "GET",
        "url": "https://api.hubapi.com/crm/v3/objects/sequences",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "hubspotApi",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "limit",
              "value": "100"
            },
            {
              "name": "properties",
              "value": "hs_sequence_name"
            }
          ]
        },
        "options": {}
      },
      "id": "fetch-sequences",
      "name": "Fetch Sequences",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [440, 0],
      "credentials": {
        "hubspotApi": {
          "id": "credential-id",
          "name": "HubSpot API"
        }
      }
    },
    {
      "parameters": {
        "options": {}
      },
      "id": "split-sequences",
      "name": "Loop Over Sequences",
      "type": "n8n-nodes-base.splitInBatches",
      "typeVersion": 3,
      "position": [660, 0]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.hubapi.com/crm/v3/objects/sequence_enrollments/search",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "hubspotApi",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={ \"filterGroups\": [{ \"filters\": [{ \"propertyName\": \"hs_sequence_id\", \"operator\": \"EQ\", \"value\": \"{{ $json.id }}\" }, { \"propertyName\": \"hs_enrollment_start_date\", \"operator\": \"GTE\", \"value\": \"{{ $('Set Dates').first().json.seven_days_ago_ms }}\" }] }], \"properties\": [\"hs_sequence_id\", \"hs_enrollment_state\", \"hs_was_email_opened\", \"hs_was_email_replied\", \"hs_was_meeting_booked\"], \"limit\": 100 }",
        "options": {}
      },
      "id": "fetch-enrollments",
      "name": "Fetch Enrollments",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [880, 0],
      "credentials": {
        "hubspotApi": {
          "id": "credential-id",
          "name": "HubSpot API"
        }
      }
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const sequences = $('Fetch Sequences').first().json.results || [];\nconst enrollmentBatches = $('Fetch Enrollments').all();\n\n// Build sequence name lookup\nconst seqMap = {};\nfor (const seq of sequences) {\n  seqMap[seq.id] = seq.properties?.hs_sequence_name || `Sequence ${seq.id}`;\n}\n\n// Aggregate per sequence\nconst metrics = {};\nfor (const batch of enrollmentBatches) {\n  const enrollments = batch.json.results || [];\n  for (const e of enrollments) {\n    const seqId = e.properties.hs_sequence_id;\n    if (!metrics[seqId]) {\n      metrics[seqId] = {\n        name: seqMap[seqId] || `Sequence ${seqId}`,\n        enrolled: 0,\n        opened: 0,\n        replied: 0,\n        meetingsBooked: 0,\n      };\n    }\n    metrics[seqId].enrolled++;\n    if (e.properties.hs_was_email_opened === 'true') metrics[seqId].opened++;\n    if (e.properties.hs_was_email_replied === 'true') metrics[seqId].replied++;\n    if (e.properties.hs_was_meeting_booked === 'true') metrics[seqId].meetingsBooked++;\n  }\n}\n\n// Calculate rates and format\nconst report = Object.values(metrics)\n  .filter(m => m.enrolled > 0)\n  .sort((a, b) => b.enrolled - a.enrolled)\n  .map(m => ({\n    ...m,\n    openRate: (m.opened / m.enrolled * 100).toFixed(1),\n    replyRate: (m.replied / m.enrolled * 100).toFixed(1),\n    meetingRate: (m.meetingsBooked / m.enrolled * 100).toFixed(1),\n  }));\n\nconst totalEnrolled = report.reduce((s, r) => s + r.enrolled, 0);\nconst totalReplied = report.reduce((s, r) => s + r.replied, 0);\nconst totalMeetings = report.reduce((s, r) => s + r.meetingsBooked, 0);\n\nreturn [{\n  json: { report, totalEnrolled, totalReplied, totalMeetings }\n}];"
      },
      "id": "calc-metrics",
      "name": "Calculate Metrics",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [1100, 0]
    },
    {
      "parameters": {
        "select": "channel",
        "channelId": {
          "__rl": true,
          "value": "sales-reports",
          "mode": "name"
        },
        "messageType": "block",
        "blocksUi": "={\n  \"blocks\": [\n    {\n      \"type\": \"header\",\n      \"text\": {\n        \"type\": \"plain_text\",\n        \"text\": \"\ud83d\udce7 Weekly Sequence Performance Report\"\n      }\n    },\n    {\n      \"type\": \"section\",\n      \"fields\": [\n        {\n          \"type\": \"mrkdwn\",\n          \"text\": \"*Total Enrolled*\\n\" + $json.totalEnrolled\n        },\n        {\n          \"type\": \"mrkdwn\",\n          \"text\": \"*Total Replies*\\n\" + $json.totalReplied\n        },\n        {\n          \"type\": \"mrkdwn\",\n          \"text\": \"*Meetings Booked*\\n\" + $json.totalMeetings\n        }\n      ]\n    },\n    {\n      \"type\": \"divider\"\n    },\n    {\n      \"type\": \"section\",\n      \"text\": {\n        \"type\": \"mrkdwn\",\n        \"text\": \"*Per-Sequence Breakdown*\\n\\n\" + $json.report.map(r => `*${r.name}* (${r.enrolled} enrolled)\\n    Open: ${r.openRate}% | Reply: ${r.replyRate}% | Meeting: ${r.meetingRate}%`).join('\\n\\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": [1320, 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 Sequences",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Sequences": {
      "main": [
        [
          {
            "node": "Loop Over Sequences",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Loop Over Sequences": {
      "main": [
        [
          {
            "node": "Calculate Metrics",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Fetch Enrollments",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Enrollments": {
      "main": [
        [
          {
            "node": "Loop Over Sequences",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "staticData": null,
  "tags": [],
  "triggerCount": 0,
  "active": false,
  "meta": {
    "instanceId": "",
    "templateId": "revi-sequence-report"
  }
}
