{
  "name": "Self-Reported Attribution Reconciler",
  "nodes": [
    {
      "id": "cebc0495-c3ee-44d9-95b9-e6fa300ba9a1",
      "name": "Weekly Attribution Check",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        100,
        300
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "cronExpression",
              "expression": "10 8 * * 1"
            }
          ]
        }
      }
    },
    {
      "id": "347de0f0-530a-4c74-8159-3ff1005a98b2",
      "name": "Get Demo Answers",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        300,
        300
      ],
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "p7iMXqqBTDi2HZzF",
          "cachedResultName": "Demo Request Answers"
        },
        "returnAll": true
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "6dff4d1b-b04a-45f7-9560-129fc265ad8a",
      "name": "Get Opportunities",
      "type": "n8n-nodes-base.salesforce",
      "typeVersion": 1.1,
      "position": [
        500,
        300
      ],
      "parameters": {
        "resource": "search",
        "operation": "query",
        "query": "SELECT Id, Name, Amount, StageName, IsWon, IsClosed, Account.Name FROM Opportunity"
      },
      "credentials": {
        "salesforceOAuth2Api": {
          "id": "553Tae1kPe5Wpthq",
          "name": "Salesforce account"
        }
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "ce91d216-c9f7-4dc1-af88-4b2167ef99bb",
      "name": "Prepare Answers",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        700,
        300
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Join each demo request's \"How did you hear about us?\" answer to its Salesforce opportunity and to the channel\n// the software recorded (UTM source and medium). Software channels use the same names buyers do, so they compare.\nconst runDate = $today.toFormat('yyyy-MM-dd');\nconst days = (a, b) => Math.round((Date.parse(String(b).slice(0, 10) + 'T00:00:00Z') - Date.parse(String(a).slice(0, 10) + 'T00:00:00Z')) / 86400000);\nconst opps = {}; for (const o of $('Get Opportunities').all().map(i => i.json).filter(o => o.Id)) opps[o.Id] = o;\nconst software = (src, med) => {\n  const s = String(src || '').toLowerCase(), m = String(med || '').toLowerCase();\n  if (['cpc', 'ppc', 'paid_search', 'organic'].includes(m)) return 'Search';\n  if (['paid_social', 'social'].includes(m)) return 'Social ads';\n  if (m === 'email') return 'Email';\n  if (['badge_scan', 'event'].includes(m) || s === 'event') return 'Event';\n  if (m === 'referral') return 'Referral link';\n  if (s === '(direct)' || m === '(none)' || !s) return 'Direct (no source)';\n  return 'Other';\n};\nconst rows = [];\nfor (const r of $('Get Demo Answers').all().map(i => i.json).filter(r => r.requestId)) {\n  if (days(r.requestedOn, runDate) > 90) continue;\n  const o = opps[r.opportunityId];\n  const lost = o && o.IsClosed && !o.IsWon;\n  rows.push({ requestId: r.requestId, requestedOn: r.requestedOn, company: r.company, answer: r.heardAbout || '',\n    utm: (r.utmSource || '') + ' / ' + (r.utmMedium || ''), softwareChannel: software(r.utmSource, r.utmMedium),\n    opportunity: o ? o.Name : '', stage: o ? o.StageName : 'no opportunity yet', pipeline: o && !lost ? Number(o.Amount) || 0 : 0, won: !!(o && o.IsWon) });\n}\nreturn [{ json: { runDate, rows, forClaude: rows.map(r => ({ requestId: r.requestId, answer: r.answer })) } }];\n"
      },
      "executeOnce": true
    },
    {
      "id": "c00eedb1-fe79-46af-bfce-9627a7e17630",
      "name": "Source Reader",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 3.1,
      "position": [
        300,
        450
      ],
      "parameters": {
        "promptType": "define",
        "text": "={{ JSON.stringify($json.forClaude, null, 1) }}",
        "hasOutputParser": true,
        "options": {
          "systemMessage": "You classify answers to the demo form question \"How did you hear about us?\" for Fortavault, Inc. (a fictional data protection company). Each answer is free text typed by the buyer.\n\nFor each answer return requestId, channel and quote. channel must be exactly one of: Search, Social ads, Email, Event, Peer referral, Podcast, Community, Review site, AI assistant, Partner / MSP, Unclear.\n- Search: Google, Bing or a search ad. Social ads: an ad on LinkedIn, Facebook and similar. Email: an email or newsletter from us. Event: a conference, talk, booth or webinar. Peer referral: a colleague, friend, peer or another customer told them. Podcast: any podcast. Community: Reddit, Slack groups, forums, online communities. Review site: G2, Capterra, TrustRadius and similar. AI assistant: ChatGPT, Perplexity, Gemini, Copilot or another AI tool. Partner / MSP: a reseller, consultant or managed service provider.\n- If the answer names more than one source, choose the one where they FIRST heard of us, not the step that followed.\n- quote: the exact words from the answer that name that source, copied word for word (a short phrase is fine). Never paraphrase.\n- Use Unclear with an empty quote when no source is named (\"don't remember\", \"website\", \"n/a\", \"online\").\nReturn one entry per answer."
        }
      },
      "executeOnce": true,
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000
    },
    {
      "id": "0d5eaf70-98f7-4422-9af5-7d46e611dba1",
      "name": "Claude Sonnet",
      "type": "@n8n/n8n-nodes-langchain.lmChatAnthropic",
      "typeVersion": 1.3,
      "position": [
        100,
        450
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "claude-sonnet-4-6",
          "cachedResultName": "Claude Sonnet 4.6"
        },
        "options": {
          "temperature": 0
        }
      },
      "credentials": {
        "anthropicApi": {
          "id": "3d3ZiTi7BwnkFwqU",
          "name": "Anthropic account"
        }
      }
    },
    {
      "id": "0db6eaee-0aaa-40e5-a615-46c4f279231f",
      "name": "Source Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "typeVersion": 1.3,
      "position": [
        100,
        600
      ],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\"type\":\"object\",\"properties\":{\"answers\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"requestId\":{\"type\":\"string\"},\"channel\":{\"type\":\"string\",\"enum\":[\"Search\",\"Social ads\",\"Email\",\"Event\",\"Peer referral\",\"Podcast\",\"Community\",\"Review site\",\"AI assistant\",\"Partner / MSP\",\"Unclear\"]},\"quote\":{\"type\":\"string\"}},\"required\":[\"requestId\",\"channel\",\"quote\"]}}},\"required\":[\"answers\"]}"
      }
    },
    {
      "id": "ca25d31e-ce0c-4d55-ba16-870d1644769f",
      "name": "Reconcile Channels",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        500,
        450
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Keep Claude's channel only if its quote is word for word in the buyer's answer; otherwise the answer counts as\n// Unclear. Then total pipeline by channel twice, once as software saw it and once as buyers said it, and list where they disagree.\nconst p = $('Prepare Answers').first().json;\nconst out = $('Source Reader').first().json.output || {};\nconst norm = s => String(s || '').replace(/[‘’]/g, \"'\").replace(/[“”]/g, '\"').replace(/\\s+/g, ' ').trim().toLowerCase();\nconst safe = t => String(t || '').replace(/~/g, '≈');\nconst CH = ['Search', 'Social ads', 'Email', 'Event', 'Peer referral', 'Podcast', 'Community', 'Review site', 'AI assistant', 'Partner / MSP', 'Unclear'];\nconst read = {}; for (const a of (out.answers || [])) read[a.requestId] = a;\nlet dropped = 0;\nconst rows = p.rows.map(r => {\n  const a = read[r.requestId] || {};\n  let ch = CH.includes(a.channel) ? a.channel : 'Unclear', quote = '';\n  if (ch !== 'Unclear') { if (a.quote && norm(a.quote).length >= 3 && norm(r.answer).includes(norm(a.quote))) quote = a.quote.trim(); else { ch = 'Unclear'; dropped++; } }\n  return { ...r, buyerChannel: ch, quote, agrees: ch === r.softwareChannel };\n});\nconst money = n => '$' + Math.round((n || 0) / 1000) + 'K';\nconst tot = (key) => { const t = {}; for (const r of rows) { t[r[key]] = t[r[key]] || { pipeline: 0, n: 0 }; t[r[key]].pipeline += r.pipeline; t[r[key]].n++; } return t; };\nconst sw = tot('softwareChannel'), by = tot('buyerChannel');\nconst chans = [...new Set(Object.keys(sw).concat(Object.keys(by)))].sort((a, b) => ((by[b] || {}).pipeline || 0) + ((sw[b] || {}).pipeline || 0) - ((by[a] || {}).pipeline || 0) - ((sw[a] || {}).pipeline || 0));\nconst pad = (s, n) => (String(s) + ' '.repeat(n)).slice(0, n), lpad = (s, n) => (' '.repeat(n) + String(s)).slice(-n);\nconst table = pad('Channel', 20) + lpad('Software says', 14) + lpad('Buyers say', 12) + '\\n' + chans.map(c => pad(c, 20) + lpad(money((sw[c] || {}).pipeline || 0) + ' (' + ((sw[c] || {}).n || 0) + ')', 14) + lpad(money((by[c] || {}).pipeline || 0) + ' (' + ((by[c] || {}).n || 0) + ')', 12)).join('\\n');\nconst total = rows.reduce((s, r) => s + r.pipeline, 0);\nconst invisible = chans.filter(c => c !== 'Unclear' && ((by[c] || {}).pipeline || 0) > 0 && !((sw[c] || {}).n)).map(c => ({ c, pipeline: by[c].pipeline, n: by[c].n })).sort((a, b) => b.pipeline - a.pipeline);\nconst over = chans.filter(c => ((sw[c] || {}).pipeline || 0) > ((by[c] || {}).pipeline || 0)).map(c => ({ c, gap: sw[c].pipeline - ((by[c] || {}).pipeline || 0) })).sort((a, b) => b.gap - a.gap);\nconst disagree = rows.filter(r => !r.agrees && r.buyerChannel !== 'Unclear').sort((a, b) => b.pipeline - a.pipeline);\nconst unclear = rows.filter(r => r.buyerChannel === 'Unclear');\nconst agreeN = rows.filter(r => r.agrees).length;\nlet text = ':compass: *Self-Reported Attribution Reconciler* (' + p.runDate + '): ' + rows.length + ' demo requests in the last 90 days, ' + money(total) + ' of open and won pipeline in Salesforce. Software and buyer agree on ' + agreeN + ' of ' + rows.length + '.\\n' +\n  '\\n*Pipeline by channel* (deals in brackets)\\n```' + table + '```\\n' +\n  (invisible.length ? '\\n*What the software cannot see*: ' + invisible.map(i => i.c + ' ' + money(i.pipeline) + ' (' + i.n + ')').join(' · ') + '. Buyers named these; tracking credited them to something else.\\n' : '') +\n  (over.length ? '*Most over-credited by software*: ' + over.slice(0, 2).map(o => o.c + ' by ' + money(o.gap)).join(' · ') + '\\n' : '') +\n  '\\n*Biggest disagreements*\\n' + disagree.slice(0, 6).map(r => '• *' + r.company + '* (' + money(r.pipeline) + ', ' + r.stage + '): software *' + r.softwareChannel + '* (' + r.utm + ') · buyer *' + r.buyerChannel + '*: _“' + safe(r.quote) + '”_').join('\\n') +\n  (disagree.length > 6 ? '\\n_+' + (disagree.length - 6) + ' smaller disagreements in the Attribution Gap Log._' : '') +\n  (unclear.length ? '\\n\\n_Unclear answers (' + unclear.length + ', ' + money(unclear.reduce((s, r) => s + r.pipeline, 0)) + '): ' + unclear.map(r => r.company + ' “' + safe(r.answer) + '”').join('; ') + '. Counted, not guessed._' : '') +\n  (dropped ? '\\n_' + dropped + ' classification(s) dropped: quote not found in the answer._' : '');\nif (text.length > 2900) text = text.slice(0, 2850).slice(0, text.slice(0, 2850).lastIndexOf('\\n')) + '\\n_…cut to fit Slack; every answer is in the Attribution Gap Log._';\nconst now = $now.toISO();\nconst logs = rows.map(r => ({ runDate: p.runDate, requestId: r.requestId, company: r.company, pipeline: r.pipeline, softwareChannel: r.softwareChannel, buyerChannel: r.buyerChannel, quote: r.quote, agrees: r.agrees, loggedAt: now }));\nreturn [{ json: { reconText: text, logs, check: rows.map(r => [r.requestId, r.softwareChannel, r.buyerChannel, r.pipeline]), dropped } }];\n"
      },
      "executeOnce": true
    },
    {
      "id": "4e08f34e-044e-4171-8880-c41ae7ca3516",
      "name": "Post Attribution Gap",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.7,
      "position": [
        700,
        450
      ],
      "parameters": {
        "resource": "message",
        "operation": "post",
        "select": "channel",
        "channelId": {
          "__rl": true,
          "mode": "id",
          "value": "C0BQ3G96HL6",
          "cachedResultName": "general"
        },
        "text": "={{ $json.reconText }}",
        "otherOptions": {
          "includeLinkToWorkflow": false
        }
      },
      "credentials": {
        "slackApi": {
          "id": "mv7TIi8kucFPqPg6",
          "name": "Slack account"
        }
      }
    },
    {
      "id": "aab7d650-54af-4a40-9e96-04733915a371",
      "name": "Split Log Rows",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        700,
        600
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $('Reconcile Channels').first().json.logs.map(json => ({ json }));"
      }
    },
    {
      "id": "e88e5c4f-16dd-4f95-9147-18586943033d",
      "name": "Log Attribution Gap",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        900,
        600
      ],
      "parameters": {
        "resource": "row",
        "operation": "insert",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "bISvyG0DkaROWKLl",
          "cachedResultName": "Attribution Gap Log"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {}
        }
      }
    }
  ],
  "connections": {
    "Weekly Attribution Check": {
      "main": [
        [
          {
            "node": "Get Demo Answers",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Demo Answers": {
      "main": [
        [
          {
            "node": "Get Opportunities",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Opportunities": {
      "main": [
        [
          {
            "node": "Prepare Answers",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare Answers": {
      "main": [
        [
          {
            "node": "Source Reader",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Source Reader": {
      "main": [
        [
          {
            "node": "Reconcile Channels",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Claude Sonnet": {
      "ai_languageModel": [
        [
          {
            "node": "Source Reader",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Source Parser": {
      "ai_outputParser": [
        [
          {
            "node": "Source Reader",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Reconcile Channels": {
      "main": [
        [
          {
            "node": "Post Attribution Gap",
            "type": "main",
            "index": 0
          },
          {
            "node": "Split Log Rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split Log Rows": {
      "main": [
        [
          {
            "node": "Log Attribution Gap",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  }
}