{
  "name": "Lead Black-Hole Finder",
  "nodes": [
    {
      "id": "cd4956fa-b80d-4b01-815b-bf0591b1039c",
      "name": "Daily Lead Sweep",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        100,
        300
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "cronExpression",
              "expression": "20 8 * * 1-5"
            }
          ]
        }
      }
    },
    {
      "id": "8b5d068f-be45-4f68-849a-2cacbce698f0",
      "name": "Get Open Leads",
      "type": "n8n-nodes-base.salesforce",
      "typeVersion": 1.1,
      "position": [
        300,
        300
      ],
      "parameters": {
        "resource": "search",
        "operation": "query",
        "query": "SELECT Id, Name, Company, Title, Status, State, Country, CreatedDate FROM Lead WHERE IsConverted = false"
      },
      "credentials": {
        "salesforceOAuth2Api": {
          "id": "553Tae1kPe5Wpthq",
          "name": "Salesforce account"
        }
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "464f72f2-21bd-4b2f-98ba-10159dbaecd2",
      "name": "Get Assignments",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        500,
        300
      ],
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "GYh67xv7uwS8dH3U",
          "cachedResultName": "Seeded Lead Assignments"
        },
        "returnAll": true
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "932cd851-f1e2-4f87-bfe8-ee351f6bf445",
      "name": "Get Roster",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        700,
        300
      ],
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "lsI8wXYizWE02rgw",
          "cachedResultName": "Lead Owner Roster"
        },
        "returnAll": true
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "50fc652f-bae2-446d-b8ad-081a073f1032",
      "name": "Find Black Holes",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        900,
        300
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Find leads that are sitting where nobody will work them. Owners come from the assignment overlay and the rep roster;\n// lead status, company and location are the real Salesforce lead. Rules, in order:\n//   owner left the company -> reassign; owner on leave and no touch for 7+ days -> reassign;\n//   'Open - Not Contacted' more than 2 business days after assignment -> nudge the owner (first-touch SLA);\n//   'Working' with no touch for 21+ days -> stale, and Claude checks the last note for a follow-up date the buyer set.\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 bizDays = (a, b) => { let n = 0; for (let t = Date.parse(a + 'T00:00:00Z') + 86400000; t <= Date.parse(b + 'T00:00:00Z'); t += 86400000) { const d = new Date(t).getUTCDay(); if (d && d < 6) n++; } return n; };\nconst EAST = ['FL', 'VA', 'MD', 'NC', 'SC', 'GA', 'CT', 'PA', 'MA', 'AL', 'NY', 'NJ', 'ME', 'NH', 'VT', 'RI', 'DE', 'WV', 'DC', 'TN', 'KY'];\nconst WEST = ['CA', 'OR', 'WA', 'NV', 'AZ', 'UT', 'CO', 'ID', 'MT', 'WY', 'NM', 'AK', 'HI'];\nconst region = l => (!/^(usa|us|united states)$/i.test(String(l.Country || '').trim()) ? 'International' : EAST.includes(l.State) ? 'East' : WEST.includes(l.State) ? 'West' : 'Central');\nconst roster = {}; for (const r of $('Get Roster').all().map(i => i.json).filter(r => r.rep)) roster[r.rep] = r;\nconst asg = {}; for (const a of $('Get Assignments').all().map(i => i.json).filter(a => a.leadId)) asg[a.leadId] = a;\nconst leads = $('Get Open Leads').all().map(i => i.json).filter(l => l.Id && !/^closed/i.test(l.Status || ''));\nconst load = {}; for (const l of leads) { const a = asg[l.Id]; if (a && a.owner) load[a.owner] = (load[a.owner] || 0) + 1; }\nconst rows = leads.map(l => {\n  const a = asg[l.Id] || {}, owner = a.owner || '', rep = roster[owner] || {};\n  const sinceTouch = a.lastTouchOn ? days(a.lastTouchOn, runDate) : null;\n  let finding = 'ok', detail = '';\n  if (!owner || !rep.rep) { finding = 'reassign'; detail = 'no active owner on record'; }\n  else if (rep.status === 'left') { finding = 'reassign'; detail = owner + ' left on ' + rep.statusSince + (a.lastTouchOn ? '; last touch ' + a.lastTouchOn : '; never touched'); }\n  else if (rep.status === 'on leave' && (sinceTouch === null || sinceTouch >= 7)) { finding = 'reassign'; detail = owner + ' is on leave until ' + rep.returnsOn + '; last touch ' + (a.lastTouchOn || 'never') + (sinceTouch !== null ? ' (' + sinceTouch + ' days)' : ''); }\n  else if (/not contacted/i.test(l.Status || '') && !a.lastTouchOn && bizDays(a.assignedOn, runDate) > 2) { finding = 'nudge'; detail = 'assigned ' + a.assignedOn + ', not contacted after ' + bizDays(a.assignedOn, runDate) + ' business days (SLA is 2)'; }\n  else if (sinceTouch !== null && sinceTouch >= 21) { finding = 'stale'; detail = 'no touch for ' + sinceTouch + ' days (last ' + a.lastTouchOn + ')'; }\n  return { leadId: l.Id, leadName: l.Name, company: l.Company, title: l.Title, status: l.Status, region: region(l), location: [l.State, l.Country].filter(Boolean).join(', '),\n    owner, ownerStatus: rep.status || 'unknown', assignedOn: a.assignedOn || '', lastTouchOn: a.lastTouchOn || '', lastNote: a.lastNote || '', finding, detail };\n});\nconst forClaude = rows.filter(r => r.finding === 'stale').map(r => ({ leadId: r.leadId, lastTouchOn: r.lastTouchOn, note: r.lastNote }));\nreturn [{ json: { runDate, rows, load, roster: Object.values(roster), forClaude } }];\n"
      },
      "executeOnce": true
    },
    {
      "id": "2fb12f35-75b3-4382-96ec-ed74bda33215",
      "name": "Follow-up 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 read the last activity note on sales leads for Fortavault, Inc. (a fictional data protection company) that nobody has touched in three weeks or more. For each lead decide whether the buyer asked to be contacted again on or after a specific date.\n\nReturn leadId, followUpDate and quote. followUpDate is the calendar date (YYYY-MM-DD) the note says to follow up or call back, or the date of the event the follow-up waits for. If the note names only a month, use the last day of that month. If the note gives no year, use the first such date on or after lastTouchOn. quote is the exact words from the note that state it, copied word for word. If the note gives no date or event to wait for (a voicemail, no reply, general interest), return an empty followUpDate and an empty quote. Do not judge whether the date has passed; just report it."
        }
      },
      "executeOnce": true,
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000
    },
    {
      "id": "1c15378f-518d-4469-a7d5-c99cc6c6d2db",
      "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": "9e9693f1-c11e-48b2-b2be-ee8d5f50f6fc",
      "name": "Follow-up Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "typeVersion": 1.3,
      "position": [
        100,
        600
      ],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\"type\":\"object\",\"properties\":{\"leads\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"leadId\":{\"type\":\"string\"},\"followUpDate\":{\"type\":\"string\"},\"quote\":{\"type\":\"string\"}},\"required\":[\"leadId\",\"followUpDate\",\"quote\"]}}},\"required\":[\"leads\"]}"
      }
    },
    {
      "id": "25399509-b077-482b-adb0-13610b25cdce",
      "name": "Build Proposals",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        500,
        450
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// A stale lead is parked, not lost, only if Claude's quote is word for word in its note and the follow-up date is still\n// ahead. Every reassignment goes to the active rep in the lead's region with the most room under capacity.\nconst f = $('Find Black Holes').first().json;\nconst out = $('Follow-up 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 read = {}; for (const r of (out.leads || [])) read[r.leadId] = r;\nconst load = { ...f.load };\nconst rows = f.rows.map(r => {\n  if (r.finding !== 'stale') return r;\n  const c = read[r.leadId] || {};\n  const ok = c.quote && /^\\d{4}-\\d{2}-\\d{2}$/.test(c.followUpDate || '') && norm(r.lastNote).includes(norm(c.quote));\n  if (ok && c.followUpDate > f.runDate) return { ...r, finding: 'parked', detail: 'buyer set a follow-up for ' + c.followUpDate, quote: c.quote.trim() };\n  return { ...r, finding: 'going cold', detail: r.detail + (ok ? '; the follow-up date in the note (' + c.followUpDate + ') has passed' : '; no follow-up date in the note'), quote: ok ? c.quote.trim() : '' };\n});\nfor (const r of rows.filter(r => r.finding === 'reassign')) {\n  const pick = f.roster.filter(p => p.region === r.region && p.status === 'active' && p.rep !== r.owner && (load[p.rep] || 0) < p.capacity)\n    .sort((a, b) => (a.capacity - (load[a.rep] || 0) > b.capacity - (load[b.rep] || 0) ? -1 : 1))[0];\n  r.proposedOwner = pick ? pick.rep : '';\n  if (pick) load[pick.rep] = (load[pick.rep] || 0) + 1;\n}\nconst line = r => '*' + r.leadName + '*, ' + r.title + ' at ' + r.company + ' (' + r.location + ', ' + r.status + ')';\nconst re = rows.filter(r => r.finding === 'reassign'), nudge = rows.filter(r => r.finding === 'nudge'), cold = rows.filter(r => r.finding === 'going cold'), parked = rows.filter(r => r.finding === 'parked'), ok = rows.filter(r => r.finding === 'ok');\nlet text = ':hole: *Lead Black-Hole Finder* (' + f.runDate + '): ' + rows.length + ' open Salesforce leads checked against the rep roster.\\n' +\n  (re.length ? '\\n*Reassign* (' + re.length + '): approving moves these leads and logs a task on each lead in Salesforce\\n' + re.map(r => '• ' + line(r) + '\\n      ' + r.detail + ' → ' + (r.proposedOwner ? '*' + r.proposedOwner + '* (' + r.region + ')' : '_no ' + r.region + ' rep has room; needs a manager_')).join('\\n') + '\\n' : '') +\n  (nudge.length ? '\\n*Nudge the owner* (' + nudge.length + ')\\n' + nudge.map(r => '• ' + line(r) + ': ' + r.owner + ', ' + r.detail).join('\\n') + '\\n' : '') +\n  (cold.length ? '\\n*Going cold* (' + cold.length + ')\\n' + cold.map(r => '• ' + line(r) + ': ' + r.owner + ', ' + r.detail + (r.lastNote ? '. Last note: _“' + safe(r.lastNote) + '”_' : '')).join('\\n') + '\\n' : '') +\n  (parked.length ? '\\n*Parked on purpose, left alone* (' + parked.length + '): ' + parked.map(r => r.leadName + ' (' + r.owner + ', ' + r.detail + ': _“' + safe(r.quote) + '”_)').join('; ') + '\\n' : '') +\n  '\\n_Healthy: ' + ok.length + ' leads touched recently by an active owner._';\nif (text.length > 2900) text = text.slice(0, 2850).slice(0, text.slice(0, 2850).lastIndexOf('\\n')) + '\\n_…cut to fit Slack._';\nreturn [{ json: { approvalText: text, rows, reassign: re.filter(r => r.proposedOwner) } }];\n"
      },
      "executeOnce": true
    },
    {
      "id": "c8c69e8a-cbd0-4167-aea1-aaf08d77089d",
      "name": "Ask Approval in Slack",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.3,
      "position": [
        700,
        450
      ],
      "parameters": {
        "resource": "message",
        "operation": "sendAndWait",
        "select": "channel",
        "channelId": {
          "__rl": true,
          "mode": "id",
          "value": "C0BQ3G96HL6",
          "cachedResultName": "general"
        },
        "message": "={{ $json.approvalText }}",
        "responseType": "approval",
        "approvalOptions": {
          "values": {
            "approvalType": "double",
            "approveLabel": "Reassign leads",
            "disapproveLabel": "Decline"
          }
        },
        "options": {
          "limitWaitTime": {
            "values": {
              "limitType": "afterTimeInterval",
              "resumeAmount": 48,
              "resumeUnit": "hours"
            }
          },
          "appendAttribution": false
        }
      },
      "credentials": {
        "slackApi": {
          "id": "mv7TIi8kucFPqPg6",
          "name": "Slack account"
        }
      }
    },
    {
      "id": "2a51bf33-a0a5-4768-9e85-b7bde8a90dfd",
      "name": "Apply Decision",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        900,
        450
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Apply only what a person approved in Slack. Approved: move each lead to its proposed owner in the assignment\n// overlay and log a Salesforce task on the lead so the history shows why it moved. Declined: change nothing.\nconst p = $('Build Proposals').first().json;\nconst approved = !!(($('Ask Approval in Slack').first().json.data || {}).approved);\nconst runDate = $('Find Black Holes').first().json.runDate;\nconst now = $now.toISO();\nconst moves = approved ? p.reassign : [];\nconst updates = moves.map(r => ({ leadId: r.leadId, owner: r.proposedOwner, assignedOn: runDate, lastTouchOn: r.lastTouchOn, lastNote: r.lastNote }));\nconst tasks = moves.map(r => ({ whoId: r.leadId, subject: 'Lead reassigned to ' + r.proposedOwner + ' by the Lead Black-Hole Finder',\n  description: 'Moved from ' + r.owner + ' to ' + r.proposedOwner + ' on ' + runDate + ': ' + r.detail + '. Approved in Slack.' }));\nconst logs = p.rows.filter(r => r.finding !== 'ok').map(r => ({ runDate, leadId: r.leadId, leadName: r.leadName, company: r.company, finding: r.finding, owner: r.owner,\n  proposedOwner: r.proposedOwner || '', detail: r.detail, decision: r.finding === 'reassign' ? (approved ? 'approved' : 'declined') : 'report only', salesforceTaskId: '', loggedAt: now }));\nconst resultText = approved\n  ? ':white_check_mark: Reassigned ' + moves.length + ' lead' + (moves.length === 1 ? '' : 's') + ': ' + moves.map(r => r.leadName + ' → ' + r.proposedOwner).join(', ') + '. A task explaining each move is logged on the lead in Salesforce.'\n  : ':no_entry_sign: Declined. No leads were moved; the findings are in the Lead Black-Hole Log.';\nreturn [{ json: { approved, updates, tasks, logs, resultText } }];\n"
      },
      "executeOnce": true
    },
    {
      "id": "17b89f8e-cb25-4746-8f37-58a333eb00dd",
      "name": "Post Result to Slack",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.7,
      "position": [
        1100,
        450
      ],
      "parameters": {
        "resource": "message",
        "operation": "post",
        "select": "channel",
        "channelId": {
          "__rl": true,
          "mode": "id",
          "value": "C0BQ3G96HL6",
          "cachedResultName": "general"
        },
        "text": "={{ $json.resultText }}",
        "otherOptions": {
          "includeLinkToWorkflow": false
        }
      },
      "credentials": {
        "slackApi": {
          "id": "mv7TIi8kucFPqPg6",
          "name": "Slack account"
        }
      }
    },
    {
      "id": "3ace7250-ba13-4cc3-b180-bf04ee2de235",
      "name": "Split Reassignments",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1100,
        600
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $('Apply Decision').first().json.updates.map(json => ({ json }));"
      }
    },
    {
      "id": "e7fd01fe-5641-46e4-8478-958f2821ec92",
      "name": "Move Lead Owner",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        1300,
        600
      ],
      "parameters": {
        "resource": "row",
        "operation": "upsert",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "GYh67xv7uwS8dH3U",
          "cachedResultName": "Seeded Lead Assignments"
        },
        "matchType": "allConditions",
        "filters": {
          "conditions": [
            {
              "keyName": "leadId",
              "condition": "eq",
              "keyValue": "={{ $json.leadId }}"
            }
          ]
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {}
        }
      }
    },
    {
      "id": "825f261c-da09-4dd7-b382-d633ad902bab",
      "name": "Split Tasks",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1100,
        750
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $('Apply Decision').first().json.tasks.map(json => ({ json }));"
      }
    },
    {
      "id": "03446970-445f-49cd-8ff8-15f9a6120500",
      "name": "Log Task on Lead",
      "type": "n8n-nodes-base.salesforce",
      "typeVersion": 1.1,
      "position": [
        1300,
        750
      ],
      "parameters": {
        "resource": "task",
        "operation": "create",
        "status": "Completed",
        "additionalFields": {
          "subject": "={{ $json.subject }}",
          "description": "={{ $json.description }}",
          "whoId": "={{ $json.whoId }}"
        }
      },
      "credentials": {
        "salesforceOAuth2Api": {
          "id": "553Tae1kPe5Wpthq",
          "name": "Salesforce account"
        }
      }
    },
    {
      "id": "ccc537fc-deca-4529-b7c5-718efae482ed",
      "name": "Split Log Rows",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1100,
        900
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $('Apply Decision').first().json.logs.map(json => ({ json }));"
      }
    },
    {
      "id": "fa70b035-44cd-4b3e-a393-2ededbdbfd9f",
      "name": "Log Findings",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        1300,
        900
      ],
      "parameters": {
        "resource": "row",
        "operation": "insert",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "Z9eviHooYpqkCX3z",
          "cachedResultName": "Lead Black-Hole Log"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {}
        }
      }
    }
  ],
  "connections": {
    "Daily Lead Sweep": {
      "main": [
        [
          {
            "node": "Get Open Leads",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Open Leads": {
      "main": [
        [
          {
            "node": "Get Assignments",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Assignments": {
      "main": [
        [
          {
            "node": "Get Roster",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Roster": {
      "main": [
        [
          {
            "node": "Find Black Holes",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Find Black Holes": {
      "main": [
        [
          {
            "node": "Follow-up Reader",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Follow-up Reader": {
      "main": [
        [
          {
            "node": "Build Proposals",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Claude Sonnet": {
      "ai_languageModel": [
        [
          {
            "node": "Follow-up Reader",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Follow-up Parser": {
      "ai_outputParser": [
        [
          {
            "node": "Follow-up Reader",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Build Proposals": {
      "main": [
        [
          {
            "node": "Ask Approval in Slack",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Ask Approval in Slack": {
      "main": [
        [
          {
            "node": "Apply Decision",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Apply Decision": {
      "main": [
        [
          {
            "node": "Post Result to Slack",
            "type": "main",
            "index": 0
          },
          {
            "node": "Split Reassignments",
            "type": "main",
            "index": 0
          },
          {
            "node": "Split Tasks",
            "type": "main",
            "index": 0
          },
          {
            "node": "Split Log Rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split Reassignments": {
      "main": [
        [
          {
            "node": "Move Lead Owner",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split Tasks": {
      "main": [
        [
          {
            "node": "Log Task on Lead",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split Log Rows": {
      "main": [
        [
          {
            "node": "Log Findings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  }
}