{
  "id": "wf010-analytics-collection-000000",
  "name": "WF-010-analytics-collection",
  "nodes": [
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "cronExpression",
              "expression": "0 2 * * *"
            }
          ]
        }
      },
      "id": "c10100000-0010-0010-0010-000000000001",
      "name": "Schedule 02:00 UTC",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        500
      ]
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT pr.*, ca.id AS asset_id FROM publishing_records pr JOIN content_assets ca ON ca.id = pr.asset_id WHERE pr.status = 'published' AND pr.published_at > NOW() - INTERVAL '90 days'",
        "options": {}
      },
      "id": "c10100000-0010-0010-0010-000000000002",
      "name": "Poll Published Records",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.5,
      "position": [
        220,
        500
      ],
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "const records = $input.all().map(i => i.json);\nif (records.length === 0) return [];\n\nconst yesterday = new Date();\nyesterday.setUTCDate(yesterday.getUTCDate() - 1);\nconst ninetyDaysAgo = new Date();\nninetyDaysAgo.setUTCDate(ninetyDaysAgo.getUTCDate() - 90);\nconst fmt = d => d.toISOString().slice(0, 10);\n\nconst byVideoId = {};\nrecords.forEach(r => { if (r.platform_id) byVideoId[r.platform_id] = r; });\n\nreturn [{ json: {\n  video_ids: Object.keys(byVideoId),\n  filters_video: Object.keys(byVideoId).join(','),\n  start_date: fmt(ninetyDaysAgo),\n  end_date: fmt(yesterday),\n  collection_date: fmt(yesterday),\n  records_by_video_id: byVideoId,\n  total_records: records.length\n} }];"
      },
      "id": "c10100000-0010-0010-0010-000000000003",
      "name": "Build Analytics Request",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        440,
        500
      ]
    },
    {
      "parameters": {
        "method": "GET",
        "url": "https://youtubeanalytics.googleapis.com/v2/reports",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "youTubeOAuth2Api",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "ids",
              "value": "channel==MINE"
            },
            {
              "name": "startDate",
              "value": "={{ $('Build Analytics Request').first().json.start_date }}"
            },
            {
              "name": "endDate",
              "value": "={{ $('Build Analytics Request').first().json.end_date }}"
            },
            {
              "name": "metrics",
              "value": "views,estimatedMinutesWatched,averageViewDuration,averageViewPercentage,annotationClickThroughRate,subscribersGained,likes,comments,shares,estimatedRevenue,cpm"
            },
            {
              "name": "dimensions",
              "value": "video"
            },
            {
              "name": "filters",
              "value": "=video=={{ $('Build Analytics Request').first().json.filters_video }}"
            }
          ]
        },
        "options": {}
      },
      "id": "c10100000-0010-0010-0010-000000000006",
      "name": "Fetch YouTube Analytics",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1100,
        400
      ],
      "onError": "continueRegularOutput",
      "credentials": {
        "youTubeOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "typeValidation": "loose"
          },
          "conditions": [
            {
              "leftValue": "={{ $json.rows }}",
              "rightValue": "",
              "operator": {
                "type": "array",
                "operation": "notEmpty"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "c10100000-0010-0010-0010-000000000007",
      "name": "Analytics Fetch Success?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1320,
        400
      ]
    },
    {
      "parameters": {
        "jsCode": "const resp = $json;\nconst req = $('Build Analytics Request').first().json;\nconst headers = (resp.columnHeaders || []).map(h => h.name);\nconst videoIdx = headers.indexOf('video');\n\nreturn (resp.rows || []).map(row => {\n  const get = name => { const i = headers.indexOf(name); return i === -1 ? null : row[i]; };\n  const videoId = row[videoIdx];\n  const rec = req.records_by_video_id[videoId];\n  if (!rec) return null;\n\n  return { json: {\n    publishing_record_id: rec.id,\n    channel_id: rec.channel_id,\n    collection_date: req.collection_date,\n    views: get('views') || 0,\n    watch_time_seconds: Math.round((get('estimatedMinutesWatched') || 0) * 60),\n    avg_view_duration_s: get('averageViewDuration') || 0,\n    retention_rate: (get('averageViewPercentage') || 0) / 100,\n    ctr: get('annotationClickThroughRate') || 0,\n    likes: get('likes') || 0,\n    comments: get('comments') || 0,\n    shares: get('shares') || 0,\n    subscribers_gained: get('subscribersGained') || 0,\n    rpm: get('cpm') || 0,\n    revenue_usd: get('estimatedRevenue') || 0,\n    raw_data: JSON.stringify({ columnHeaders: resp.columnHeaders, row })\n  } };\n}).filter(Boolean);"
      },
      "id": "c10100000-0010-0010-0010-000000000008",
      "name": "Parse Analytics Rows",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1540,
        300
      ]
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "=INSERT INTO analytics (publishing_record_id, channel_id, collection_date, views, watch_time_seconds, avg_view_duration_s, retention_rate, ctr, likes, comments, shares, subscribers_gained, rpm, revenue_usd, raw_data) VALUES ({{ $json.publishing_record_id }}, {{ $json.channel_id }}, '{{ $json.collection_date }}', {{ $json.views }}, {{ $json.watch_time_seconds }}, {{ $json.avg_view_duration_s }}, {{ $json.retention_rate }}, {{ $json.ctr }}, {{ $json.likes }}, {{ $json.comments }}, {{ $json.shares }}, {{ $json.subscribers_gained }}, {{ $json.rpm }}, {{ $json.revenue_usd }}, '{{ $json.raw_data.replace(/'/g, \"''\") }}'::jsonb) ON CONFLICT (publishing_record_id, collection_date) DO UPDATE SET views = EXCLUDED.views, watch_time_seconds = EXCLUDED.watch_time_seconds, avg_view_duration_s = EXCLUDED.avg_view_duration_s, retention_rate = EXCLUDED.retention_rate, ctr = EXCLUDED.ctr, likes = EXCLUDED.likes, comments = EXCLUDED.comments, shares = EXCLUDED.shares, subscribers_gained = EXCLUDED.subscribers_gained, rpm = EXCLUDED.rpm, revenue_usd = EXCLUDED.revenue_usd, raw_data = EXCLUDED.raw_data, collected_at = NOW() RETURNING id",
        "options": {}
      },
      "id": "c10100000-0010-0010-0010-000000000009",
      "name": "Upsert Analytics",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.5,
      "position": [
        1760,
        300
      ],
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "aggregate": "aggregateAllItemData",
        "destinationFieldName": "upserted"
      },
      "id": "c10100000-0010-0010-0010-000000000010",
      "name": "Aggregate Results",
      "type": "n8n-nodes-base.aggregate",
      "typeVersion": 1,
      "position": [
        1980,
        300
      ]
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "=INSERT INTO workflow_logs (workflow_name, execution_id, status, input_summary, output_summary) VALUES ('WF-010-analytics-collection', '{{ $execution.id }}', 'completed', '{{ JSON.stringify({ total_records: $('Build Analytics Request').first().json.total_records }) }}'::jsonb, '{{ JSON.stringify({ videos_processed: $json.upserted.length }) }}'::jsonb)",
        "options": {}
      },
      "id": "c10100000-0010-0010-0010-000000000011",
      "name": "Log Result",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.5,
      "position": [
        2200,
        300
      ],
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "return [{ json: {\n  workflow_name: 'WF-010-analytics-collection',\n  execution_id: String($execution.id),\n  node_name: 'Fetch YouTube Analytics',\n  error_type: 'analytics_fetch_failed',\n  error_message: `YouTube Analytics fetch failed: ${JSON.stringify($json.error || $json)}`.slice(0, 1000),\n  payload: { video_ids: $('Build Analytics Request').first().json.video_ids }\n} }];"
      },
      "id": "c10100000-0010-0010-0010-000000000012",
      "name": "Build DLQ Payload",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1320,
        620
      ]
    },
    {
      "parameters": {
        "workflowId": {
          "__rl": true,
          "value": "sub002-dead-letter-queue-0000000",
          "mode": "id"
        },
        "options": {}
      },
      "id": "c10100000-0010-0010-0010-000000000013",
      "name": "Log to SUB-002",
      "type": "n8n-nodes-base.executeWorkflow",
      "typeVersion": 1.1,
      "position": [
        1540,
        620
      ]
    }
  ],
  "connections": {
    "Schedule 02:00 UTC": {
      "main": [
        [
          {
            "node": "Poll Published Records",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Poll Published Records": {
      "main": [
        [
          {
            "node": "Build Analytics Request",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Analytics Request": {
      "main": [
        [
          {
            "node": "Fetch YouTube Analytics",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch YouTube Analytics": {
      "main": [
        [
          {
            "node": "Analytics Fetch Success?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Analytics Fetch Success?": {
      "main": [
        [
          {
            "node": "Parse Analytics Rows",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Build DLQ Payload",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build DLQ Payload": {
      "main": [
        [
          {
            "node": "Log to SUB-002",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse Analytics Rows": {
      "main": [
        [
          {
            "node": "Upsert Analytics",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Upsert Analytics": {
      "main": [
        [
          {
            "node": "Aggregate Results",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Aggregate Results": {
      "main": [
        [
          {
            "node": "Log Result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  }
}