{
  "name": "Creator posts to Shopify order report",
  "nodes": [
    {
      "id": "f4fa304a-3eba-403b-8e10-9a2633ef3b04",
      "name": "Read me first",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -1390,
        0
      ],
      "parameters": {
        "content": "## Creator posts to Shopify order report\nEach day it matches creator posts to tagged Shopify orders and writes one report row.\n\n### You need\n- A Google Sheets login and one sheet with 4 tabs:\n- Creator Campaigns: Creator ID, Campaign, Shopify Product ID\n- Creator Posts: Post ID, Post URL, Creator ID, Campaign, Placement, Views, Engagements\n- Tagged Orders: Order ID, Campaign, Placement, Shopify Product ID, Cancelled\n- Creator Report: Report Date, Generated At, Matched Posts, Posts to Review, Matched Orders, Campaign Only Orders, Report\n- A Telegram bot and your chat ID, for the failure alert\n\n### Set it up\n1. Pick the same sheet in every Google Sheets step.\n2. Fill the first 3 tabs. Keep IDs as plain text.\n3. Set your time zone in Workflow settings.\n4. Failure alert: put your chat ID in **Write the failure alert** and your bot in **Send the failure alert**. Then in Workflow settings, set Error workflow to this workflow.\n\n### Test it\n- Click Test workflow with **Run manually** picked.\n- Creator Report gets a row for today. Posts that do not match are listed for review.",
        "height": 780,
        "width": 560,
        "color": 4
      }
    },
    {
      "name": "Refresh report daily",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "id": "4c296d4b-9e40-4e60-827b-9fd6d9ac956b",
      "position": [
        -750,
        0
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "days",
              "daysInterval": 1,
              "triggerAtHour": 10,
              "triggerAtMinute": 0
            }
          ]
        }
      }
    },
    {
      "name": "Run manually",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "id": "1837efdb-b73a-4ec3-a707-36482787672e",
      "position": [
        -750,
        175
      ],
      "parameters": {}
    },
    {
      "name": "Read approved creator campaigns",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "id": "d7e152f7-dd3a-4ce8-9357-a7fc06355229",
      "position": [
        -510,
        0
      ],
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "url"
        },
        "sheetName": {
          "__rl": true,
          "value": "Creator Campaigns",
          "mode": "name"
        },
        "options": {}
      },
      "alwaysOutputData": true
    },
    {
      "name": "Read creator posts",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "id": "4ef475c4-e1ea-4224-bb7d-e43a99c23d06",
      "position": [
        -270,
        0
      ],
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "url"
        },
        "sheetName": {
          "__rl": true,
          "value": "Creator Posts",
          "mode": "name"
        },
        "options": {}
      },
      "alwaysOutputData": true,
      "executeOnce": true
    },
    {
      "name": "Read tagged orders",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "id": "e1c3386b-d286-43e8-8ac8-f2145ce4313a",
      "position": [
        -30,
        0
      ],
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "url"
        },
        "sheetName": {
          "__rl": true,
          "value": "Tagged Orders",
          "mode": "name"
        },
        "options": {}
      },
      "alwaysOutputData": true,
      "executeOnce": true
    },
    {
      "name": "Match placements and generate report",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "id": "6dc7d9a2-e354-472d-8f80-80b95185bf36",
      "position": [
        210,
        0
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const value = entry => String(entry ?? '').trim();\nconst key = (...fields) => JSON.stringify(fields);\nconst field = (record, label) => value(record[label]);\nconst roster = $('Read approved creator campaigns').all().map(item => item.json);\nconst posts = $('Read creator posts').all().map(item => item.json)\n  .filter(row => field(row, 'Post ID') || field(row, 'Post URL'));\nconst orders = $input.all().map(item => item.json).filter(row => field(row, 'Order ID'));\nconst rosterKeys = new Map();\nconst approvedCampaignProducts = new Set();\nfor (const row of roster) {\n  const creator = field(row, 'Creator ID');\n  const campaign = field(row, 'Campaign');\n  const product = field(row, 'Shopify Product ID');\n  if (!creator || !campaign || !product) continue;\n  const id = key(creator, campaign);\n  const products = rosterKeys.get(id) || new Set();\n  products.add(product);\n  rosterKeys.set(id, products);\n  approvedCampaignProducts.add(key(campaign, product));\n}\n\nconst idCounts = new Map();\nconst placementCounts = new Map();\nfor (const row of posts) {\n  const id = field(row, 'Post ID');\n  const campaign = field(row, 'Campaign');\n  const placement = field(row, 'Placement');\n  idCounts.set(id, (idCounts.get(id) || 0) + 1);\n  if (campaign && placement) {\n    const k = key(campaign, placement);\n    placementCounts.set(k, (placementCounts.get(k) || 0) + 1);\n  }\n}\n\nconst attributionByOrderProduct = new Map();\nfor (const row of orders) {\n  const id = field(row, 'Order ID');\n  if (['yes', 'true', '1'].includes(field(row, 'Cancelled').toLowerCase())) continue;\n  const campaign = field(row, 'Campaign');\n  const placement = field(row, 'Placement');\n  const product = field(row, 'Shopify Product ID');\n  if (!approvedCampaignProducts.has(key(campaign, product))) continue;\n  const orderKey = key(id, product);\n  const tags = attributionByOrderProduct.get(orderKey) || new Map();\n  tags.set(key(campaign, placement), { id, campaign, placement, product });\n  attributionByOrderProduct.set(orderKey, tags);\n}\nconst ordersByPlacement = new Map();\nconst campaignOnlyOrders = new Set();\nlet conflicts = 0;\nfor (const tags of attributionByOrderProduct.values()) {\n  if (tags.size !== 1) {\n    conflicts += 1;\n    continue;\n  }\n  const { id, campaign, placement, product } = tags.values().next().value;\n  if (!placement) {\n    campaignOnlyOrders.add(id);\n    continue;\n  }\n  const k = key(campaign, placement, product);\n  const ids = ordersByPlacement.get(k) || new Set();\n  ids.add(id);\n  ordersByPlacement.set(k, ids);\n}\nfunction metric(row, column) {\n  const raw = field(row, column);\n  return /^\\d+$/.test(raw) ? raw : 'missing';\n}\n\nconst results = [];\nconst issues = [];\nconst reportedOrders = new Set();\nfor (const post of posts) {\n  const id = field(post, 'Post ID');\n  const url = field(post, 'Post URL');\n  const creator = field(post, 'Creator ID');\n  const campaign = field(post, 'Campaign');\n  const placement = field(post, 'Placement');\n  const products = rosterKeys.get(key(creator, campaign));\n  if (!id || !/^https:\\/\\/[^/\\s]+\\//.test(url) || !placement || !products || products.size !== 1 ||\n      idCounts.get(id) !== 1 || placementCounts.get(key(campaign, placement)) !== 1) {\n    issues.push((id || url || 'Missing post ID') + ': verify ID, URL, unique placement, and creator/campaign mapping');\n    continue;\n  }\n\n  const product = [...products][0];\n  const matchedOrders = ordersByPlacement.get(key(campaign, placement, product)) || new Set();\n  for (const orderId of matchedOrders) reportedOrders.add(orderId);\n  const orderCount = orders.length ? String(matchedOrders.size) : 'feed empty';\n  results.push([\n    creator + ' | Shopify product ' + product + ' | ' + campaign + '/' + placement,\n    'Views ' + metric(post, 'Views') + ' | Engagements ' + metric(post, 'Engagements') +\n      ' | Orders matched to this post ' + orderCount,\n    url,\n  ].join('\\n'));\n}\n\nfunction summary(title, entries) {\n  const max = 25;\n  return [title + ' (' + entries.length + ')', ...entries.slice(0, max).map(text => text.slice(0, 900)),\n    ...(entries.length > max ? ['See source tabs for ' + (entries.length - max) + ' more.'] : []),\n  ].join('\\n\\n');\n}\nreturn [{ json: {\n  'Report Date': $now.toISODate(),\n  'Generated At': $now.toISO(),\n  'Matched Posts': results.length,\n  'Posts to Review': issues.length,\n  'Matched Orders': orders.length ? reportedOrders.size : '',\n  'Campaign Only Orders': orders.length ? campaignOnlyOrders.size : '',\n  Report: [\n    'Snapshot of the inputs supplied. Shared campaign-only orders stay outside individual post totals.',\n    orders.length ? '' : 'Tagged Orders is empty. Post order counts are unavailable.',\n    conflicts ? conflicts + ' order and product pairs had conflicting tags and were excluded.' : '',\n    summary('Matched creator posts', results),\n    summary('Posts to review', issues),\n  ].filter(Boolean).join('\\n\\n'),\n} }];"
      }
    },
    {
      "name": "Save today's creator report",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "id": "5e8bc5e0-affd-4236-92f8-8bf434984ff9",
      "position": [
        450,
        0
      ],
      "parameters": {
        "operation": "appendOrUpdate",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "url"
        },
        "sheetName": {
          "__rl": true,
          "value": "Creator Report",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Report Date": "={{ $json[\"Report Date\"] }}",
            "Generated At": "={{ $json[\"Generated At\"] }}",
            "Matched Posts": "={{ $json[\"Matched Posts\"] }}",
            "Posts to Review": "={{ $json[\"Posts to Review\"] }}",
            "Matched Orders": "={{ $json[\"Matched Orders\"] }}",
            "Campaign Only Orders": "={{ $json[\"Campaign Only Orders\"] }}",
            "Report": "={{ $json[\"Report\"] }}"
          },
          "matchingColumns": [
            "Report Date"
          ],
          "schema": [
            {
              "id": "Report Date",
              "displayName": "Report Date",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Generated At",
              "displayName": "Generated At",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Matched Posts",
              "displayName": "Matched Posts",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "number",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Posts to Review",
              "displayName": "Posts to Review",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "number",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Matched Orders",
              "displayName": "Matched Orders",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "number",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Campaign Only Orders",
              "displayName": "Campaign Only Orders",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "number",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Report",
              "displayName": "Report",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            }
          ]
        },
        "options": {
          "cellFormat": "RAW"
        }
      }
    },
    {
      "id": "3eb94fbf-7566-4f20-98d1-7c67d4ee64fc",
      "name": "When this workflow fails",
      "type": "n8n-nodes-base.errorTrigger",
      "typeVersion": 1,
      "position": [
        -1350,
        860
      ],
      "parameters": {}
    },
    {
      "id": "bdcc23d2-5906-4dd6-b20c-a9603d3a5f8c",
      "name": "Write the failure alert",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -1130,
        860
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "f1",
              "name": "telegramChatId",
              "type": "string",
              "value": "YOUR_TELEGRAM_CHAT_ID"
            },
            {
              "id": "f2",
              "name": "message",
              "type": "string",
              "value": "={{ 'A workflow stopped.\\n\\nWorkflow: ' + (($json.workflow || {}).name || 'unknown') + '\\nFailed step: ' + (($json.execution || {}).lastNodeExecuted || 'unknown') + '\\nWhy: ' + String((($json.execution || {}).error || {}).message || 'n8n did not give a reason.').slice(0, 300) + (($json.execution || {}).url ? '\\nOpen the run: ' + $json.execution.url : '') }}"
            }
          ]
        },
        "includeOtherFields": false,
        "options": {}
      }
    },
    {
      "id": "b0c04532-17f8-45f7-979e-0f2f365bf7ac",
      "name": "Send the failure alert",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        -910,
        860
      ],
      "parameters": {
        "chatId": "={{ $json.telegramChatId }}",
        "text": "={{ $json.message }}",
        "additionalFields": {
          "appendAttribution": false
        }
      }
    }
  ],
  "connections": {
    "Refresh report daily": {
      "main": [
        [
          {
            "node": "Read approved creator campaigns",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Run manually": {
      "main": [
        [
          {
            "node": "Read approved creator campaigns",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read approved creator campaigns": {
      "main": [
        [
          {
            "node": "Read creator posts",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read creator posts": {
      "main": [
        [
          {
            "node": "Read tagged orders",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read tagged orders": {
      "main": [
        [
          {
            "node": "Match placements and generate report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Match placements and generate report": {
      "main": [
        [
          {
            "node": "Save today's creator report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "When this workflow fails": {
      "main": [
        [
          {
            "node": "Write the failure alert",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Write the failure alert": {
      "main": [
        [
          {
            "node": "Send the failure alert",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {}
}
