{
  "name": "Deal-Moment Playbook",
  "nodes": [
    {
      "id": "d315a2ea-e7d9-4d7e-ad50-959b7d13db1d",
      "name": "Business-Hours Moment Check",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        100,
        300
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "cronExpression",
              "expression": "15 8-18 * * 1-5"
            }
          ]
        }
      }
    },
    {
      "id": "d8d3192a-eea6-4c4a-8c3f-3565735f1e8c",
      "name": "Get Open Opportunities",
      "type": "n8n-nodes-base.salesforce",
      "typeVersion": 1.1,
      "position": [
        300,
        300
      ],
      "parameters": {
        "resource": "search",
        "operation": "query",
        "query": "SELECT Id, Name, StageName, Amount, CloseDate, CreatedDate, LastStageChangeDate, Description, NextStep, Owner.Name, Account.Name, Account.Industry FROM Opportunity WHERE IsClosed = false"
      },
      "credentials": {
        "salesforceOAuth2Api": {
          "id": "553Tae1kPe5Wpthq",
          "name": "Salesforce account"
        }
      },
      "executeOnce": true
    },
    {
      "id": "01ddfc8b-a2e2-4910-adb2-ce2025d194eb",
      "name": "Get Content Library",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        500,
        300
      ],
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "2gf7i5SufszxuRHG",
          "cachedResultName": "Enablement Content Library"
        },
        "returnAll": true
      },
      "executeOnce": true
    },
    {
      "id": "66afe46a-8baf-4cee-94af-73f832eceda3",
      "name": "Get Stage History",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        700,
        300
      ],
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "FDaiEFabviIBiRoM",
          "cachedResultName": "Seeded Stage History"
        },
        "returnAll": true
      },
      "executeOnce": true
    },
    {
      "id": "15b55024-b910-433e-a913-3ee0cb712c83",
      "name": "Get Stage Snapshot",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        900,
        300
      ],
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "3XCVx283Da2zzGSG",
          "cachedResultName": "Deal Stage Snapshot"
        },
        "returnAll": true
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "4e8ddbc7-7361-43d9-917b-9cf3a11d2ad4",
      "name": "Get Moment Log",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        1100,
        300
      ],
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "Rj5swqphaNRUYWcY",
          "cachedResultName": "Deal Moment Log"
        },
        "returnAll": true
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "fa472965-827c-49f0-b79c-818cdcb9efad",
      "name": "Detect Moments & Match Content",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1300,
        300
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Deal-moment detection and content matching, all in code. Claude only explains the picks afterwards.\nconst runAsOf = $today.toFormat('yyyy-MM-dd');\nconst DAY = 86400000, t0 = Date.parse(runAsOf + 'T00:00:00Z');\nconst daysSince = d => Math.round((t0 - Date.parse(String(d).slice(0, 10) + 'T00:00:00Z')) / DAY);\nconst open = $('Get Open Opportunities').all().map(i => i.json).filter(r => r.Id);\nconst lib = $('Get Content Library').all().map(i => i.json).filter(a => a.assetId);\nconst hist = $('Get Stage History').all().map(i => i.json).filter(r => r.stage);\nconst snaps = $('Get Stage Snapshot').all().map(i => i.json).filter(r => r.dealId);\nconst logged = $('Get Moment Log').all().map(i => i.json).filter(r => r.dealId && r.source === 'live');\n\nconst COMPETITORS = ['Veyron Data', 'Ashcombe Systems', 'Cyphertide', 'Northgate Cloud Security', 'Ridgeline Compliance'];\nconst BUCKET = { 'Prospecting': 'Qualification', 'Qualification': 'Qualification',\n  'Needs Analysis': 'Discovery', 'Value Proposition': 'Discovery', 'Id. Decision Makers': 'Discovery', 'Perception Analysis': 'Discovery',\n  'Proposal/Price Quote': 'Proposal', 'Proposal/Negotiation': 'Proposal', 'Negotiation/Review': 'Negotiation' };\nconst STAGES = ['Qualification', 'Discovery', 'Proposal', 'Negotiation'];\nconst split = s => String(s || '').split(',').map(x => x.trim()).filter(Boolean);\n\n// Stall line per stage = 2x the median days in that stage in the stage history (same rule as the Pipeline Forecast Engine).\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 = {};\nfor (const s of STAGES) { const m = median(hist.filter(h => h.stage === s).map(h => Number(h.daysInStage))); stallLine[s] = m ? Math.round(m * 2) : null; }\n\nconst prevStage = {}; for (const s of snaps) prevStage[s.dealId] = s.stage;\nconst alreadySent = new Set(logged.map(r => r.dealId + '|' + r.momentKey));\n\nconst moments = [], snapshotRows = [];\nlet skippedAbandoned = 0, baselineDeals = 0, duplicateMoments = 0;\nfor (const o of open) {\n  if (o.CloseDate && daysSince(o.CloseDate) > 180) { skippedAbandoned++; continue; } // abandoned: close date 180+ days past\n  const stage = BUCKET[o.StageName];\n  snapshotRows.push({ dealId: o.Id, dealName: o.Name, stage: o.StageName, seenAt: $now.toISO() });\n  if (!stage) continue;\n  const base = { dealId: o.Id, dealName: o.Name, accountName: (o.Account || {}).Name || '', industry: (o.Account || {}).Industry || '',\n    stage, sfStage: o.StageName, amount: Number(o.Amount) || 0, owner: (o.Owner || {}).Name || '' };\n  const found = [];\n  // 1. The deal entered a new stage since the last run (first sighting is a baseline, not a moment).\n  const prev = prevStage[o.Id];\n  if (prev === undefined) baselineDeals++;\n  else if (prev !== o.StageName) found.push({ ...base, momentType: 'stage_entered', momentKey: 'stage_entered:' + o.StageName, detail: 'moved from ' + prev + ' to ' + o.StageName });\n  // 2. A competitor is named in the deal notes.\n  const text = [o.Description, o.NextStep].filter(Boolean).join(' ');\n  for (const c of COMPETITORS) if (text.includes(c)) found.push({ ...base, momentType: 'competitor', momentKey: 'competitor:' + c, competitor: c, detail: c + ' named in the deal notes' });\n  // 3. The deal has sat in its stage past the stall line.\n  const entered = (o.LastStageChangeDate || o.CreatedDate || '').slice(0, 10);\n  const inStage = entered ? daysSince(entered) : null;\n  if (inStage != null && stallLine[stage] && inStage > stallLine[stage]) found.push({ ...base, momentType: 'stalled', momentKey: 'stalled:' + o.StageName, daysInStage: inStage,\n    detail: inStage + 'd in ' + o.StageName + ' (stall line ' + stallLine[stage] + 'd)' });\n  for (const m of found) { if (alreadySent.has(m.dealId + '|' + m.momentKey)) duplicateMoments++; else moments.push(m); }\n}\n\n// Match each moment to library assets: the moment type must fit, stage must fit (competitor battlecards fit any stage),\n// and industry-specific assets only match their own industry. Score: competitor 5, stage 3, industry 3. Top 2 per moment.\nfunction match(m) {\n  const out = [];\n  for (const a of lib) {\n    if (!split(a.moments).includes(m.momentType)) continue;\n    const reasons = []; let score = 0;\n    if (m.momentType === 'competitor') { if (a.competitor !== m.competitor) continue; score += 5; reasons.push('battlecard for ' + m.competitor); }\n    else if (a.competitor) continue;\n    if (split(a.stages).includes(m.stage)) { score += 3; reasons.push(m.stage + ' stage'); }\n    else if (m.momentType !== 'competitor') continue;\n    const inds = split(a.industries);\n    if (!inds.includes('any')) { if (m.industry && inds.includes(m.industry)) { score += 3; reasons.push(m.industry + ' industry'); } else continue; }\n    out.push({ a, score, reasons });\n  }\n  out.sort((x, y) => y.score - x.score || x.a.assetId.localeCompare(y.a.assetId));\n  return out.slice(0, 2);\n}\n// Content gaps: a moment with no match, an industry with no asset of its own at this stage, or an account with no industry on record.\nfunction gapFor(m, picks) {\n  if (!picks.length) return 'No asset for a ' + m.momentType.replace('_', ' ') + ' moment at ' + m.stage;\n  if (m.momentType === 'competitor') return '';\n  if (!m.industry) return 'Account has no industry in Salesforce, so only generic assets can match';\n  const own = lib.some(a => split(a.industries).includes(m.industry) && split(a.stages).includes(m.stage));\n  return own ? '' : 'No ' + m.industry + ' asset for ' + m.stage;\n}\n\nconst deliveries = [], gaps = [];\nfor (const m of moments) {\n  const picks = match(m), gap = gapFor(m, picks);\n  if (gap) gaps.push({ dealName: m.dealName, momentKey: m.momentKey, gap });\n  for (const p of picks) deliveries.push({ key: m.dealId + '|' + m.momentKey + '|' + p.a.assetId, ...m, assetId: p.a.assetId, assetTitle: p.a.title,\n    assetType: p.a.assetType, talkTrack: p.a.talkTrack, persona: p.a.persona, matchScore: p.score, matchReasons: p.reasons.join(', '), gap });\n  if (!picks.length) deliveries.push({ key: m.dealId + '|' + m.momentKey + '|none', ...m, assetId: '', assetTitle: '', matchScore: 0, matchReasons: '', gap });\n}\nreturn [{ json: { runAsOf, openDeals: open.length, skippedAbandoned, baselineDeals, duplicateMoments, stallLine, moments: moments.length, deliveries, gaps, snapshotRows } }];\n"
      },
      "executeOnce": true
    },
    {
      "id": "713bcd3c-8ef2-4362-88db-62cc8e91a681",
      "name": "Prepare Explainer Input",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1500,
        300
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Only call Claude when there is something to send. Each pick goes in with the deal facts and the asset's own talk track.\nconst d = $('Detect Moments & Match Content').first().json;\nconst sends = d.deliveries.filter(x => x.assetId);\nif (!sends.length) return [];\nreturn [{ json: { picks: sends.map(x => ({ key: x.key, deal: x.dealName, account: x.accountName, industry: x.industry || 'unknown', stage: x.sfStage,\n  amount: x.amount, moment: x.detail, asset: x.assetTitle, assetType: x.assetType, persona: x.persona, talkTrack: x.talkTrack, matchedOn: x.matchReasons })) } }];\n"
      }
    },
    {
      "id": "6d213bf3-2d5c-4b00-a661-4620527adca5",
      "name": "Why-This-Asset Writer",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 3.1,
      "position": [
        300,
        450
      ],
      "parameters": {
        "promptType": "define",
        "text": "={{ JSON.stringify($json.picks, null, 1) }}",
        "hasOutputParser": true,
        "options": {
          "systemMessage": "You write one sentence per content pick for a sales rep at Fortavault, Inc. (a fictional data protection and security company). Each pick pairs a live deal moment with an enablement asset that code has ALREADY chosen; you never choose, drop or re-rank assets.\n\nFor each pick, write `why`: one sentence of at most 35 words telling the rep why this asset fits this moment on this deal and how to open with it, grounded in the asset's talk track and the deal facts given.\n\nRules: use only the facts in the input. Never invent anything about the customer, people, meetings, numbers or history. `persona` is the audience the asset is written for, not a person known to be on the deal: write 'for a finance audience' or 'if a CFO is involved', never 'Castleton's CFO'. If the industry is unknown, do not guess one. Return every key exactly once, unchanged."
        }
      },
      "executeOnce": true
    },
    {
      "id": "8ca5cc6f-7dce-4ff4-a9b9-6ea778959fd2",
      "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.3
        }
      },
      "credentials": {
        "anthropicApi": {
          "id": "3d3ZiTi7BwnkFwqU",
          "name": "Anthropic account"
        }
      }
    },
    {
      "id": "dcd3bfcf-eec7-475e-9eee-98f13411801c",
      "name": "Why Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "typeVersion": 1.3,
      "position": [
        100,
        600
      ],
      "parameters": {
        "schemaType": "fromJson",
        "jsonSchemaExample": "{ \"items\": [{ \"key\": \"x\", \"why\": \"x\" }] }"
      }
    },
    {
      "id": "20063301-e7aa-4103-94c0-de29a0d80d56",
      "name": "Build Digest & Log Rows",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        500,
        450
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Slack digest grouped by deal, plus the log rows for every delivery and gap.\nconst d = $('Detect Moments & Match Content').first().json;\nconst out = ($('Why-This-Asset Writer').first().json.output || {});\nconst why = {}; for (const i of (out.items || [])) why[i.key] = i.why;\nconst safe = t => String(t || '').replace(/~/g, '≈'); // Slack renders ~text~ as strikethrough\nconst K = v => v ? '$' + Math.round(v / 1000) + 'K' : 'no amount';\nconst icon = { stage_entered: ':arrow_right:', competitor: ':crossed_swords:', stalled: ':hourglass_flowing_sand:' };\nconst byDeal = {};\nfor (const x of d.deliveries) (byDeal[x.dealId] = byDeal[x.dealId] || []).push(x);\nconst blocks = Object.values(byDeal).map(list => {\n  const f = list[0];\n  const byMoment = {}; for (const x of list) (byMoment[x.momentKey] = byMoment[x.momentKey] || []).push(x);\n  const lines = Object.values(byMoment).map(ms => icon[ms[0].momentType] + ' ' + ms[0].detail + '\\n' +\n    ms.filter(x => x.assetId).map(x => '      → *' + x.assetTitle + '* (' + x.assetType + ')\\n        _' + safe(why[x.key] || x.talkTrack) + '_').join('\\n') +\n    (ms.some(x => !x.assetId) ? '      → _no matching asset in the library_' : ''));\n  return '*' + f.dealName + '* · ' + (f.industry || 'industry unknown') + ' · ' + K(f.amount) + ' · ' + f.sfStage + (f.owner ? ' · owner ' + f.owner : '') + '\\n' + lines.join('\\n');\n});\nconst gapLines = [...new Set(d.gaps.map(g => g.gap))];\nconst text = ':dart: *Deal-Moment Playbook* (run ' + d.runAsOf + ')\\n' + d.moments + ' new moment' + (d.moments === 1 ? '' : 's') + ' on ' + blocks.length + ' deal' + (blocks.length === 1 ? '' : 's') + ', each with the content that fits it:\\n\\n' +\n  blocks.join('\\n\\n') +\n  (gapLines.length ? '\\n\\n:jigsaw: *Content gaps for enablement:* ' + gapLines.join('; ') + '.' : '') +\n  '\\n\\n_Assets are matched in code by moment, stage, industry and competitor; Claude only writes the one-line why. The content library is seeded Fortavault demo content._';\nconst now = $now.toISO();\nconst rows = d.deliveries.map(x => ({ runAsOf: d.runAsOf, dealId: x.dealId, dealName: x.dealName, accountName: x.accountName, industry: x.industry, stage: x.sfStage,\n  momentType: x.momentType, momentKey: x.momentKey, momentDetail: x.detail, assetId: x.assetId, assetTitle: x.assetTitle, matchScore: x.matchScore,\n  matchReasons: x.matchReasons, gap: x.gap, why: x.assetId ? (why[x.key] || '') : '', source: 'live', deliveredAt: now }));\nreturn [{ json: { slackText: text.slice(0, 3900), rows } }];\n"
      }
    },
    {
      "id": "49082728-78b2-46c7-b8a1-66cb7b369610",
      "name": "Post Playbook 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": "7df3752e-81e8-434f-9ddc-b1478ba158f7",
      "name": "Split Log Rows",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        700,
        600
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $('Build Digest & Log Rows').first().json.rows.map(json => ({ json }));"
      }
    },
    {
      "id": "b61e0dad-b2bb-438f-b229-0cfc9090bae4",
      "name": "Log Deliveries",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        900,
        600
      ],
      "parameters": {
        "resource": "row",
        "operation": "insert",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "Rj5swqphaNRUYWcY",
          "cachedResultName": "Deal Moment Log"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {}
        }
      }
    },
    {
      "id": "b1e06402-8cec-4792-aa8c-00aed1594453",
      "name": "Build Snapshot Rows",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1500,
        450
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $('Detect Moments & Match Content').first().json.snapshotRows.map(json => ({ json }));"
      }
    },
    {
      "id": "e04d030c-549a-4227-96db-e50ca78e0ec4",
      "name": "Update Stage Snapshot",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        1700,
        450
      ],
      "parameters": {
        "resource": "row",
        "operation": "upsert",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "3XCVx283Da2zzGSG",
          "cachedResultName": "Deal Stage Snapshot"
        },
        "matchType": "allConditions",
        "filters": {
          "conditions": [
            {
              "keyName": "dealId",
              "condition": "eq",
              "keyValue": "={{ $json.dealId }}"
            }
          ]
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {}
        }
      }
    }
  ],
  "connections": {
    "Business-Hours Moment Check": {
      "main": [
        [
          {
            "node": "Get Open Opportunities",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Open Opportunities": {
      "main": [
        [
          {
            "node": "Get Content Library",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Content Library": {
      "main": [
        [
          {
            "node": "Get Stage History",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Stage History": {
      "main": [
        [
          {
            "node": "Get Stage Snapshot",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Stage Snapshot": {
      "main": [
        [
          {
            "node": "Get Moment Log",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Moment Log": {
      "main": [
        [
          {
            "node": "Detect Moments & Match Content",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Detect Moments & Match Content": {
      "main": [
        [
          {
            "node": "Prepare Explainer Input",
            "type": "main",
            "index": 0
          },
          {
            "node": "Build Snapshot Rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare Explainer Input": {
      "main": [
        [
          {
            "node": "Why-This-Asset Writer",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Why-This-Asset Writer": {
      "main": [
        [
          {
            "node": "Build Digest & Log Rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Claude Sonnet": {
      "ai_languageModel": [
        [
          {
            "node": "Why-This-Asset Writer",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Why Parser": {
      "ai_outputParser": [
        [
          {
            "node": "Why-This-Asset Writer",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Build Digest & Log Rows": {
      "main": [
        [
          {
            "node": "Post Playbook to Slack",
            "type": "main",
            "index": 0
          },
          {
            "node": "Split Log Rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split Log Rows": {
      "main": [
        [
          {
            "node": "Log Deliveries",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Snapshot Rows": {
      "main": [
        [
          {
            "node": "Update Stage Snapshot",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  }
}