{
  "name": "GA4 weekly reporting",
  "nodes": [
    {
      "parameters": {},
      "id": "0a6cd12a-c929-4950-af46-498bb2d579fe",
      "name": "Run manually",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        0
      ]
    },
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "weeks",
              "triggerAtDay": [
                3
              ],
              "triggerAtHour": 9,
              "triggerAtMinute": 0
            }
          ]
        }
      },
      "id": "a030bd17-694c-45a3-8572-acd3c761d8ec",
      "name": "Every Wednesday",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        220
      ]
    },
    {
      "parameters": {
        "jsCode": "const propertyId = '';\nconst reportingTimeZone = 'Etc/UTC';\nconst slackChannel = '';\nconst useSample = true;\nconst sendToSlack = false;\n\nif (typeof useSample !== 'boolean' || typeof sendToSlack !== 'boolean') {\n  throw new Error('Set useSample and sendToSlack to true or false.');\n}\nif (!useSample && (typeof propertyId !== 'string' || !/^[1-9][0-9]*$/.test(propertyId))) {\n  throw new Error('Set propertyId to the numeric GA4 property ID as a string.');\n}\nif (!useSample && sendToSlack && (typeof slackChannel !== 'string' || !/^[CGD][A-Z0-9]+$/.test(slackChannel))) {\n  throw new Error('Set slackChannel to a Slack conversation ID.');\n}\n\nconst parts = new Intl.DateTimeFormat('en-US', {\n  timeZone: reportingTimeZone,\n  calendar: 'gregory',\n  year: 'numeric',\n  month: 'numeric',\n  day: 'numeric',\n}).formatToParts(new Date());\nconst part = type => Number(parts.find(entry => entry.type === type).value);\nconst today = new Date(Date.UTC(part('year'), part('month') - 1, part('day')));\nconst currentMonday = today.getUTCDate() - ((today.getUTCDay() + 6) % 7);\nconst format = day => {\n  const date = new Date(today);\n  date.setUTCDate(day);\n  return date.toISOString().slice(0, 10);\n};\nconst dateRange = { startDate: format(currentMonday - 7), endDate: format(currentMonday - 1) };\nconst metrics = ['sessions', 'activeUsers', 'keyEvents'];\nconst reportRequest = {\n  dateRanges: [dateRange],\n  metrics: metrics.map(name => ({ name })),\n  returnPropertyQuota: true,\n  keepEmptyRows: true,\n};\n\nreturn [{ json: { propertyId, reportingTimeZone, slackChannel, useSample, sendToSlack, dateRange, metrics, reportRequest } }];"
      },
      "id": "1849c981-01e1-4d57-bcb3-bf0d882791ed",
      "name": "Configure report",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        240,
        100
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "77dfe550-e6de-433e-b545-979d83507bf6",
              "leftValue": "={{ $json.useSample }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        }
      },
      "id": "60041ad1-fc60-4753-944a-297e4ee10f96",
      "name": "Use sample?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        480,
        100
      ]
    },
    {
      "parameters": {
        "jsCode": "return [{ json: {\n  \"metricHeaders\": [\n    {\n      \"name\": \"sessions\"\n    },\n    {\n      \"name\": \"activeUsers\"\n    },\n    {\n      \"name\": \"keyEvents\"\n    }\n  ],\n  \"rows\": [\n    {\n      \"metricValues\": [\n        {\n          \"value\": \"1234\"\n        },\n        {\n          \"value\": \"824\"\n        },\n        {\n          \"value\": \"30\"\n        }\n      ]\n    }\n  ],\n  \"rowCount\": 1\n} }];"
      },
      "id": "8fcd789d-4b1a-47ff-8da9-d85532f74187",
      "name": "Sample GA4 response",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        720,
        0
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ 'https://analyticsdata.googleapis.com/v1beta/properties/' + $json.propertyId + ':runReport' }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "oAuth2Api",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ $json.reportRequest }}",
        "options": {
          "timeout": 30000
        }
      },
      "id": "5f9f3218-449f-4fd8-ab77-4c1a60310d38",
      "name": "Read GA4 totals",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        720,
        220
      ],
      "disabled": true
    },
    {
      "parameters": {
        "jsCode": "const config = $('Configure report').first().json;\nconst report = $input.first().json;\nconst metadata = report.metadata ?? {};\nconst canonicalZone = timeZone => new Intl.DateTimeFormat('en', { timeZone }).resolvedOptions().timeZone;\nif (!config.useSample && (!metadata.timeZone || canonicalZone(metadata.timeZone) !== canonicalZone(config.reportingTimeZone))) {\n  throw new Error('GA4 response timezone differs from the configured reporting timezone or is missing.');\n}\nif (metadata.subjectToThresholding || metadata.samplingMetadatas?.length || metadata.dataLossFromOtherRow ||\n    metadata.schemaRestrictionResponse?.activeMetricRestrictions?.length || metadata.emptyReason) {\n  throw new Error('GA4 returned quality warnings or an empty report. Check response metadata before publishing.');\n}\nconst names = report.metricHeaders?.map(header => header.name);\nconst values = report.rows?.[0]?.metricValues;\nif (report.rowCount !== 1 || report.rows?.length !== 1 || names?.join(',') !== config.metrics.join(',') ||\n    values?.length !== config.metrics.length) {\n  throw new Error('GA4 did not return a single complete totals row.');\n}\nconst totals = Object.fromEntries(values.map(({ value }, index) => {\n  if (typeof value !== 'string' || !/^[0-9]+(?:[.][0-9]+)?$/.test(value) || !Number.isFinite(Number(value))) {\n    throw new Error('GA4 returned an invalid metric value.');\n  }\n  return [names[index], Number(value)];\n}));\nconst { startDate, endDate } = config.dateRange;\nconst format = value => value.toLocaleString('en-US', { maximumFractionDigits: 3 });\nconst message = [\n  config.useSample ? 'Sample GA4 weekly report' : 'GA4 weekly report',\n  startDate + ' to ' + endDate + ' (' + config.reportingTimeZone + ')',\n  'Sessions: ' + format(totals.sessions),\n  'Active users: ' + format(totals.activeUsers),\n  'Key events: ' + format(totals.keyEvents),\n].join('\\n');\n\nreturn [{ json: { dateRange: config.dateRange, totals, message, slackChannel: config.slackChannel,\n  deliver: !config.useSample && config.sendToSlack, propertyQuota: report.propertyQuota ?? null } }];"
      },
      "id": "18e33e09-c332-4a95-90b3-e7e4bdf0a701",
      "name": "Format report",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        960,
        100
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "57ffb0b7-263e-4bdd-8830-c69d97ad7a49",
              "leftValue": "={{ $json.deliver }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        }
      },
      "id": "9aa402b7-3f5c-46a5-9ae2-ee7bbe2642e6",
      "name": "Send to Slack?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1200,
        100
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://slack.com/api/chat.postMessage",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ { channel: $json.slackChannel, text: $json.message, unfurl_links: false, unfurl_media: false } }}",
        "options": {
          "timeout": 30000
        }
      },
      "id": "bc5194c3-5b1b-4d52-abce-af688c44f42d",
      "name": "Post to Slack",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1440,
        100
      ],
      "disabled": true
    },
    {
      "parameters": {
        "jsCode": "const response = $input.first().json;\nconst report = $('Format report').first().json;\nif (response.ok !== true || response.channel !== report.slackChannel || !response.ts) {\n  throw new Error('Slack did not confirm delivery to the configured channel. Check the channel before retrying.');\n}\nreturn [{ json: { dateRange: report.dateRange, totals: report.totals, channel: response.channel, timestamp: response.ts } }];"
      },
      "id": "9af8a3f8-bd1b-4e08-b4e3-a7be3e85f8db",
      "name": "Confirm Slack delivery",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1680,
        100
      ]
    }
  ],
  "connections": {
    "Run manually": {
      "main": [
        [
          {
            "node": "Configure report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Every Wednesday": {
      "main": [
        [
          {
            "node": "Configure report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Configure report": {
      "main": [
        [
          {
            "node": "Use sample?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Use sample?": {
      "main": [
        [
          {
            "node": "Sample GA4 response",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Read GA4 totals",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Sample GA4 response": {
      "main": [
        [
          {
            "node": "Format report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read GA4 totals": {
      "main": [
        [
          {
            "node": "Format report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Format report": {
      "main": [
        [
          {
            "node": "Send to Slack?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send to Slack?": {
      "main": [
        [
          {
            "node": "Post to Slack",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Post to Slack": {
      "main": [
        [
          {
            "node": "Confirm Slack delivery",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "timezone": "Etc/UTC"
  },
  "pinData": {},
  "tags": []
}
