{
  "name": "Content-to-Revenue Tracker",
  "nodes": [
    {
      "id": "f6afce58-08fb-4dc8-b4e7-48992fe90288",
      "name": "Monthly Content Review",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        100,
        300
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "cronExpression",
              "expression": "20 8 1 * *"
            }
          ]
        }
      }
    },
    {
      "id": "845237f7-8845-445a-a82e-4544cd8beca5",
      "name": "Get Closed Opportunities",
      "type": "n8n-nodes-base.salesforce",
      "typeVersion": 1.1,
      "position": [
        300,
        300
      ],
      "parameters": {
        "resource": "search",
        "operation": "query",
        "query": "SELECT Id, Name, IsWon, CloseDate, Description, NextStep, Account.Industry FROM Opportunity WHERE IsClosed = true"
      },
      "credentials": {
        "salesforceOAuth2Api": {
          "id": "553Tae1kPe5Wpthq",
          "name": "Salesforce account"
        }
      },
      "executeOnce": true
    },
    {
      "id": "6e644ed4-2a1a-4384-8bd8-2728243e9724",
      "name": "Get Stage History",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        500,
        300
      ],
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "FDaiEFabviIBiRoM",
          "cachedResultName": "Seeded Stage History"
        },
        "returnAll": true
      },
      "executeOnce": true
    },
    {
      "id": "39b6d05c-4280-4f04-899e-39af497a3ebc",
      "name": "Get Content Library",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        700,
        300
      ],
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "2gf7i5SufszxuRHG",
          "cachedResultName": "Enablement Content Library"
        },
        "returnAll": true
      },
      "executeOnce": true
    },
    {
      "id": "02d9d2a3-c2cd-45c3-a1fc-16e1388afd18",
      "name": "Get Delivery Log",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        900,
        300
      ],
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "Rj5swqphaNRUYWcY",
          "cachedResultName": "Deal Moment Log"
        },
        "returnAll": true
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "42f9f7e2-9ef3-497e-9484-f6f2b660c526",
      "name": "Compute Content Performance",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1100,
        300
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Content-to-revenue, computed entirely in code. Claude only narrates the result.\nconst runDate = $today.toFormat('yyyy-MM-dd');\nconst DAY = 86400000, t0 = Date.parse(runDate + 'T00:00:00Z');\nconst since90 = new Date(t0 - 90 * DAY).toISOString().slice(0, 10);\nconst closed = $('Get Closed Opportunities').all().map(i => i.json).filter(r => r.Id);\nconst hist = $('Get Stage History').all().map(i => i.json).filter(r => r.stage);\nconst lib = $('Get Content Library').all().map(i => i.json).filter(a => a.assetId);\nconst log = $('Get Delivery Log').all().map(i => i.json).filter(r => r.dealId);\nconst split = s => String(s || '').split(',').map(x => x.trim()).filter(Boolean);\nconst COMPETITORS = ['Veyron Data', 'Ashcombe Systems', 'Cyphertide', 'Northgate Cloud Security', 'Ridgeline Compliance'];\nconst BUCKET = { 'Prospecting': 'Qualification', 'Qualification': 'Qualification', 'Needs Analysis': 'Discovery', 'Value Proposition': 'Discovery',\n  'Id. Decision Makers': 'Discovery', 'Perception Analysis': 'Discovery', 'Proposal/Price Quote': 'Proposal', 'Proposal/Negotiation': 'Proposal', 'Negotiation/Review': 'Negotiation' };\nconst bucket = s => BUCKET[s] || s;\n\n// Closed-deal outcomes and the stages each deal reached.\nconst deal = {};\nfor (const o of closed) {\n  const text = [o.Description, o.NextStep].filter(Boolean).join(' ');\n  deal[o.Id] = { won: !!o.IsWon, industry: (o.Account || {}).Industry || '', competitors: COMPETITORS.filter(c => text.includes(c)), reached: new Set() };\n}\n// Stall line per stage = 2x median days in stage (same rule as the Playbook); a deal 'stalled at S' if it sat in S past that line.\nconst STAGES = ['Qualification', 'Discovery', 'Proposal', 'Negotiation'];\nconst median = a => { const s = [...a].sort((x, y) => x - y), m = s.length >> 1; return s.length ? (s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2) : null; };\nconst stallLine = {}; for (const s of STAGES) stallLine[s] = Math.round(median(hist.filter(h => h.stage === s).map(h => Number(h.daysInStage))) * 2);\nfor (const o of Object.values(deal)) o.stalled = new Set();\nfor (const h of hist) if (deal[h.opportunityId]) { deal[h.opportunityId].reached.add(h.stage); if (Number(h.daysInStage) > stallLine[h.stage]) deal[h.opportunityId].stalled.add(h.stage); }\nconst closedIds = Object.keys(deal).filter(id => deal[id].reached.size);\n\nconst deliveries = log.filter(r => r.assetId);\nconst received = {}; // assetId -> dealId -> { stage, type } of the first delivery\nfor (const r of deliveries.slice().sort((a, b) => String(a.deliveredAt).localeCompare(String(b.deliveredAt)))) {\n  received[r.assetId] = received[r.assetId] || {};\n  if (!(r.dealId in received[r.assetId])) received[r.assetId][r.dealId] = { stage: bucket(r.stage), type: r.momentType };\n}\n\n// Per asset: moment-matched comparison (indirect standardisation). For each closed deal that received the asset at stage S, the expected\n// win chance is the win rate of closed deals that hit the same moment (reached S, or stalled in S for stall content) but never received it,\n// in the same industry / naming the same competitor when the asset is specific. Without this, late-stage assets look like winners just\n// because only advancing deals get them (survivorship), and stall assets look like losers because stalled deals lose more anyway.\nconst MIN_CTRL = 5, MIN_N = 5;\nconst rows = lib.map(a => {\n  const inds = split(a.industries).filter(x => x !== 'any');\n  const got = received[a.assetId] || {};\n  const sent90 = deliveries.filter(r => r.assetId === a.assetId && String(r.deliveredAt).slice(0, 10) >= since90);\n  const treated = Object.keys(got).filter(id => deal[id]);\n  let usable = 0, obs = 0, exp = 0, v = 0;\n  for (const id of treated) {\n    const S = got[id].stage, hit = got[id].type === 'stalled' ? 'stalled' : 'reached';\n    const ctrl = closedIds.filter(c => !(c in got) && deal[c][hit].has(S) && (!inds.length || inds.includes(deal[c].industry)) && (!a.competitor || deal[c].competitors.includes(a.competitor)));\n    if (ctrl.length < MIN_CTRL) continue;\n    const p = ctrl.filter(c => deal[c].won).length / ctrl.length;\n    usable++; obs += deal[id].won ? 1 : 0; exp += p; v += p * (1 - p);\n  }\n  const wins = treated.filter(id => deal[id].won).length;\n  const z = usable >= MIN_N && v > 0 ? (obs - exp) / Math.sqrt(v) : null;\n  let verdict;\n  if (!treated.length) verdict = 'no closed deals yet';\n  else if (treated.length < MIN_N) verdict = 'too thin';\n  else if (usable < MIN_N) verdict = 'no comparison group';\n  else if (z >= 1.96) verdict = 'outperforming';\n  else if (z <= -1.96) verdict = 'underperforming';\n  else verdict = 'no measurable difference';\n  const flags = [];\n  if (!sent90.length) flags.push('unused in 90 days');\n  if (verdict === 'underperforming') flags.push('review or retire');\n  if (verdict === 'no comparison group') flags.push('every comparable deal got it' + (inds.length ? ' (inseparable from ' + inds.join('/') + ')' : ''));\n  const reviewedDays = a.lastReviewed ? Math.round((t0 - Date.parse(a.lastReviewed + 'T00:00:00Z')) / DAY) : null;\n  if (reviewedDays != null && reviewedDays > 180) flags.push('last reviewed ' + reviewedDays + 'd ago');\n  return { assetId: a.assetId, title: a.title, type: a.assetType, specific: inds.join('/') || a.competitor || '', sent90: sent90.length,\n    dealsTouched90: new Set(sent90.map(r => r.dealId)).size, closedDeals: treated.length, winRate: treated.length ? +(wins / treated.length).toFixed(3) : null,\n    usable, expectedWinRate: usable ? +(exp / usable).toFixed(3) : null, observedOnUsable: usable ? +(obs / usable).toFixed(3) : null,\n    z: z == null ? null : +z.toFixed(2), verdict, flags };\n});\n\n// Content gaps: unique deal moments with a gap, grouped by industry.\nconst gapMoments = {};\nfor (const r of log) if (r.gap) gapMoments[r.dealId + '|' + r.momentKey] = r.gap;\nconst gapCount = {}; for (const g of Object.values(gapMoments)) gapCount[g] = (gapCount[g] || 0) + 1;\nconst byIndustry = {};\nfor (const [g, n] of Object.entries(gapCount)) { const m = g.match(/^No (.+) asset for (\\w+)$/); if (m) { byIndustry[m[1]] = byIndustry[m[1]] || { moments: 0, stages: [] }; byIndustry[m[1]].moments += n; byIndustry[m[1]].stages.push(m[2]); } }\nconst topGaps = Object.entries(byIndustry).sort((a, b) => b[1].moments - a[1].moments).slice(0, 4).map(([ind, x]) => ({ industry: ind, moments: x.moments, stages: x.stages }));\nconst noIndustry = gapCount['Account has no industry in Salesforce, so only generic assets can match'] || 0;\n\nconst seededRows = log.filter(r => r.source === 'seeded').length, liveRows = log.filter(r => r.source === 'live').length;\nconst liveSince = log.filter(r => r.source === 'live').map(r => String(r.deliveredAt).slice(0, 10)).sort()[0] || null;\nreturn [{ json: { runDate, since90, closedDeals: closedIds.length, baselineWinRate: +(closedIds.filter(id => deal[id].won).length / closedIds.length).toFixed(3),\n  deliveries: deliveries.length, seededRows, liveRows, liveSince, assets: rows, topGaps, noIndustryMoments: noIndustry } }];\n"
      },
      "executeOnce": true
    },
    {
      "id": "5453dce1-bab6-4bbd-9de6-dc3a020ca608",
      "name": "Content Performance Narrator",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 3.1,
      "position": [
        300,
        450
      ],
      "parameters": {
        "promptType": "define",
        "text": "={{ JSON.stringify($json, null, 1) }}",
        "hasOutputParser": true,
        "options": {
          "systemMessage": "You write the monthly content-to-revenue note for Fortavault, Inc. (a fictional data protection company) enablement and sales leadership. Every number was computed in code; you never compute, round differently or change any figure.\n\nEach asset carries a verdict from a moment-matched comparison: the win rate of closed deals that received it versus deals that hit the same moment without it (reached the same stage, or stalled in it; same industry or competitor when the asset is specific to one).\n\nWrite:\n- narrative: at most 3 sentences and 80 words. Say which assets show a measurable difference (outperforming or underperforming); if none do, say so plainly. If several assets have the verdict 'no comparison group', explain in one plain sentence that rule-based delivery sends them to every comparable deal, so their effect cannot be measured without holding some deals out. Name the single biggest content gap to fill next. Do not list the review list; it is shown separately.\n- caveat: one sentence. If seededRows is above 0, it must say that delivery history before liveSince is seeded by replaying the Playbook's rules over seeded stage history, so the verdicts demonstrate the method rather than prove what content works, while won/lost outcomes and industries are real Salesforce data.\n\nNever call a result proven or causal. Use asset IDs and titles exactly as given. Never invent assets, deals or numbers."
        }
      },
      "executeOnce": true,
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000
    },
    {
      "id": "e17eeaf1-f845-492f-87f4-41fc85753b44",
      "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.2
        }
      },
      "credentials": {
        "anthropicApi": {
          "id": "3d3ZiTi7BwnkFwqU",
          "name": "Anthropic account"
        }
      }
    },
    {
      "id": "b603ffa6-dc3a-4171-83a9-0fc1d0d728f4",
      "name": "Note Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "typeVersion": 1.3,
      "position": [
        100,
        600
      ],
      "parameters": {
        "schemaType": "fromJson",
        "jsonSchemaExample": "{ \"narrative\": \"x\", \"caveat\": \"x\" }"
      }
    },
    {
      "id": "a5b53edb-a032-4e18-9cf2-877a715f6efc",
      "name": "Build Monthly Post",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        500,
        450
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const f = $('Compute Content Performance').first().json;\nconst n = $('Content Performance Narrator').first().json.output || {};\nconst safe = t => String(t || '').replace(/~/g, '≈');\nconst pct = p => p == null ? '  – ' : String(Math.round(p * 100)).padStart(3) + '%';\nconst pad = (s, w) => String(s).length > w ? String(s).slice(0, w - 1) + '…' : String(s).padEnd(w);\nconst order = { outperforming: 0, underperforming: 1, 'no measurable difference': 2, 'no comparison group': 3, 'too thin': 4, 'no closed deals yet': 5 };\nconst list = f.assets.slice().sort((a, b) => order[a.verdict] - order[b.verdict] || b.sent90 - a.sent90);\nconst table = [pad('Asset', 34) + ' 90d  deals  won  vs matched     verdict', ...list.map(a => pad(a.assetId + ' ' + a.title, 34) + ' ' + String(a.sent90).padStart(3) + '  ' +\n  String(a.closedDeals).padStart(5) + ' ' + pct(a.winRate) + '  ' + (a.expectedWinRate == null ? '     –       ' : (pct(a.observedOnUsable) + ' vs ' + pct(a.expectedWinRate).trim()).padEnd(13)) + '  ' + a.verdict)].join('\\n');\nconst ids = cond => f.assets.filter(cond).map(a => a.assetId);\nconst under = ids(a => a.verdict === 'underperforming'), unused = ids(a => a.flags.includes('unused in 90 days'));\nconst stale = f.assets.filter(a => a.flags.some(x => x.startsWith('last reviewed'))).map(a => a.assetId + ' (' + a.flags.find(x => x.startsWith('last reviewed')).replace('last reviewed ', '') + ')');\nconst flagLines = [under.length && 'Underperforming: ' + under.join(', '), unused.length && 'Unused in 90 days: ' + unused.join(', '), stale.length && 'Not reviewed in 180+ days: ' + stale.join(', ')].filter(Boolean).map(x => '• ' + x);\nconst gapLine = f.topGaps.map(g => g.industry + ' (' + g.moments + ' moments, no asset at ' + g.stages.join('/') + ')').join(', ');\nconst text = ':bar_chart: *Content-to-Revenue Tracker* (run ' + f.runDate + ')\\n' +\n  f.deliveries + ' logged deliveries across ' + f.closedDeals + ' closed deals (baseline win rate ' + Math.round(f.baselineWinRate * 100) + '%). Each asset is compared with deals that hit the same moment without it (reached the same stage, or stalled in it), so content doesn\\'t look good or bad just because of where in the funnel it gets sent.\\n\\n' +\n  safe(n.narrative) + '\\n\\n```' + table + '```\\n\\n' +\n  (flagLines.length ? '*Review list:*\\n' + flagLines.join('\\n') + '\\n\\n' : '') +\n  ':jigsaw: *Biggest content gaps:* ' + gapLine + (f.noIndustryMoments ? '; plus ' + f.noIndustryMoments + ' moments on accounts with no industry in Salesforce.' : '.') +\n  '\\n\\n_' + safe(n.caveat) + '_';\nreturn [{ json: { slackText: text.slice(0, 3900) } }];\n"
      }
    },
    {
      "id": "d850d11f-a004-4968-9774-34007cbe61d3",
      "name": "Post Review to Slack",
      "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.slackText }}",
        "otherOptions": {
          "includeLinkToWorkflow": false
        }
      },
      "credentials": {
        "slackApi": {
          "id": "mv7TIi8kucFPqPg6",
          "name": "Slack account"
        }
      }
    },
    {
      "id": "fb5107e4-5dac-4d0d-8f7c-9126a0ff287b",
      "name": "Build Snapshot Rows",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        700,
        600
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const f = $('Compute Content Performance').first().json;\nconst now = $now.toISO();\nreturn f.assets.map(a => ({ json: { runDate: f.runDate, assetId: a.assetId, assetTitle: a.title, sent90: a.sent90, closedDeals: a.closedDeals,\n  winRate: a.winRate, expectedWinRate: a.expectedWinRate, z: a.z, verdict: a.verdict, flags: a.flags.join('; '), loggedAt: now } }));"
      }
    },
    {
      "id": "9715b631-522b-4d21-995c-c3f2a7e0b061",
      "name": "Log Content Snapshot",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        900,
        600
      ],
      "parameters": {
        "resource": "row",
        "operation": "insert",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "rt3Z17t5lvqBio9G",
          "cachedResultName": "Content Performance Snapshots"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {}
        }
      }
    }
  ],
  "connections": {
    "Monthly Content Review": {
      "main": [
        [
          {
            "node": "Get Closed Opportunities",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Closed Opportunities": {
      "main": [
        [
          {
            "node": "Get Stage History",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Stage History": {
      "main": [
        [
          {
            "node": "Get Content Library",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Content Library": {
      "main": [
        [
          {
            "node": "Get Delivery Log",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Delivery Log": {
      "main": [
        [
          {
            "node": "Compute Content Performance",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Compute Content Performance": {
      "main": [
        [
          {
            "node": "Content Performance Narrator",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Content Performance Narrator": {
      "main": [
        [
          {
            "node": "Build Monthly Post",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Claude Sonnet": {
      "ai_languageModel": [
        [
          {
            "node": "Content Performance Narrator",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Note Parser": {
      "ai_outputParser": [
        [
          {
            "node": "Content Performance Narrator",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Build Monthly Post": {
      "main": [
        [
          {
            "node": "Post Review to Slack",
            "type": "main",
            "index": 0
          },
          {
            "node": "Build Snapshot Rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Snapshot Rows": {
      "main": [
        [
          {
            "node": "Log Content Snapshot",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  }
}