{
  "name": "Rejection Reason Recalibrator",
  "nodes": [
    {
      "id": "4094c99a-e115-4453-a58b-479b8207f3e4",
      "name": "Monthly Scoring Review",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        100,
        300
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "cronExpression",
              "expression": "30 8 1 * *"
            }
          ]
        }
      }
    },
    {
      "id": "1b1b772d-d1d5-4d02-b0f5-fc03d81b8b38",
      "name": "Get Scoring Model",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        300,
        300
      ],
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "C4S8GUDRWtQzQRuI",
          "cachedResultName": "MQL Scoring Model"
        },
        "returnAll": true
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "966053f6-c769-4901-b1f8-2e6331177a33",
      "name": "Get MQL Outcomes",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        500,
        300
      ],
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "Ra6sqc8cJbU78a1B",
          "cachedResultName": "MQL Outcomes"
        },
        "returnAll": true
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "547664c5-1986-4202-97a6-2d31e2d4b6fe",
      "name": "Get Customers",
      "type": "n8n-nodes-base.salesforce",
      "typeVersion": 1.1,
      "position": [
        700,
        300
      ],
      "parameters": {
        "resource": "search",
        "operation": "query",
        "query": "SELECT Account.Name FROM Opportunity WHERE IsWon = true"
      },
      "credentials": {
        "salesforceOAuth2Api": {
          "id": "553Tae1kPe5Wpthq",
          "name": "Salesforce account"
        }
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "66ff8305-4052-49c3-8665-593633904197",
      "name": "Analyze Scores",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        900,
        300
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Re-score every MQL from the last 60 days with the current model, then test weight changes on the same leads.\n// A change is only proposed if no accepted lead would fall below the MQL threshold; the search is greedy, one\n// component at a time, up to three changes, always taking the change that pushes the most rejected leads below the line.\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 model = $('Get Scoring Model').all().map(i => i.json).filter(m => m.component);\nconst threshold = Number((model[0] || {}).threshold) || 60;\nconst label = {}; for (const m of model) label[m.component] = m.label;\nconst W0 = {}; for (const m of model) W0[m.component] = Number(m.points);\nconst mqls = $('Get MQL Outcomes').all().map(i => i.json).filter(m => m.mqlId && days(m.mqlOn, runDate) <= 60)\n  .map(m => ({ ...m, parts: String(m.components || '').split(';').map(s => s.trim()).filter(Boolean) }));\nconst score = (m, W) => m.parts.reduce((s, c) => s + (W[c] || 0), 0);\nconst rej = mqls.filter(m => m.salesDecision === 'rejected'), acc = mqls.filter(m => m.salesDecision === 'accepted');\nconst fires = c => ({ rejected: rej.filter(m => m.parts.includes(c)).length, accepted: acc.filter(m => m.parts.includes(c)).length });\nconst stats = model.map(m => ({ component: m.component, label: m.label, points: W0[m.component], ...fires(m.component) }));\nconst W = { ...W0 }, changes = [];\nconst above = (list, w) => list.filter(m => score(m, w) >= threshold);\nfor (let step = 0; step < 3; step++) {\n  let best = null;\n  for (const c of Object.keys(W).filter(c => W[c] > 0)) for (let v = W[c] - 5; v >= 0; v -= 5) {\n    const t = { ...W, [c]: v };\n    if (above(acc, t).length < acc.length) break;\n    const dropped = above(rej, W).length - above(rej, t).length;\n    if (dropped > 0 && (!best || dropped > best.dropped || (dropped === best.dropped && W[c] - v < best.from - best.to))) best = { component: c, label: label[c], from: W[c], to: v, dropped };\n  }\n  if (!best) break;\n  best.droppedLeads = above(rej, W).filter(m => score(m, { ...W, [best.component]: best.to }) < threshold).map(m => m.company);\n  W[best.component] = best.to; changes.push(best);\n}\nconst stillOver = above(rej, W).map(m => m.mqlId);\nconst rows = mqls.map(m => ({ mqlId: m.mqlId, company: m.company, title: m.title, decision: m.salesDecision, rep: m.rep, note: m.rejectionNote || '', before: score(m, W0), after: score(m, W), parts: m.parts }));\nreturn [{ json: { runDate, threshold, stats, changes, newWeights: W, stillOver, rows, totals: { mqls: mqls.length, rejected: rej.length, accepted: acc.length, afterMqls: above(mqls, W).length, afterAccepted: above(acc, W).length },\n  forClaude: rej.map(m => ({ mqlId: m.mqlId, title: m.title, company: m.company, note: m.rejectionNote || '' })) } }];\n"
      },
      "executeOnce": true
    },
    {
      "id": "fbb3cedd-53b3-4c8f-937b-6c72084085ce",
      "name": "Reason 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 why sales reps rejected marketing-qualified leads (MQLs) at Fortavault, Inc. (a fictional data protection company). For each rejected lead you get its title, company and the rep's note.\n\nReturn mqlId, reason and quote. reason must be exactly one of: Student or researcher, Consultant or partner, Competitor, Too small, No budget or timing, Wrong persona, Existing customer, Bad contact data, Unclear.\n- Wrong persona: the person has no role in buying security or IT tools (for example they downloaded content for an unrelated job).\n- Unclear: the note does not state a reason.\nquote: the exact words from the note that give the reason, copied word for word (a short phrase is fine). Never paraphrase. Use an empty quote only with Unclear. Judge only from the note, not from the title or company.\nReturn one entry per lead."
        }
      },
      "executeOnce": true,
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000
    },
    {
      "id": "87a2a459-e35a-440b-a361-108919d23cba",
      "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": "33dd44fb-86ff-4e2e-9d20-bc12ab2fd87c",
      "name": "Reason 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\":{\"mqlId\":{\"type\":\"string\"},\"reason\":{\"type\":\"string\",\"enum\":[\"Student or researcher\",\"Consultant or partner\",\"Competitor\",\"Too small\",\"No budget or timing\",\"Wrong persona\",\"Existing customer\",\"Bad contact data\",\"Unclear\"]},\"quote\":{\"type\":\"string\"}},\"required\":[\"mqlId\",\"reason\",\"quote\"]}}},\"required\":[\"leads\"]}"
      }
    },
    {
      "id": "bd610294-95b3-4c97-98e1-253029e0afc2",
      "name": "Build Recalibration",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        500,
        450
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Keep each rejection reason only if its quote is word for word in the rep's note, and confirm \"existing customer\"\n// against Closed Won accounts in Salesforce. Reasons that weights can't fix become rules; weight changes come from the simulation.\nconst a = $('Analyze Scores').first().json;\nconst out = $('Reason 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 customers = new Set($('Get Customers').all().map(i => i.json).filter(o => o.Account && o.Account.Name).map(o => norm(o.Account.Name)));\nconst REASONS = ['Student or researcher', 'Consultant or partner', 'Competitor', 'Too small', 'No budget or timing', 'Wrong persona', 'Existing customer', 'Bad contact data', 'Unclear'];\nconst read = {}; for (const r of (out.leads || [])) read[r.mqlId] = r;\nlet dropped = 0;\nconst rejected = a.rows.filter(r => r.decision === 'rejected').map(r => {\n  const c = read[r.mqlId] || {};\n  let reason = REASONS.includes(c.reason) ? c.reason : 'Unclear', quote = '';\n  if (reason !== 'Unclear') { if (c.quote && norm(r.note).includes(norm(c.quote))) quote = c.quote.trim(); else { reason = 'Unclear'; dropped++; } }\n  const isCustomer = customers.has(norm(r.company));\n  return { ...r, reason, quote, isCustomer };\n});\nconst count = {}; for (const r of rejected) count[r.reason] = (count[r.reason] || 0) + 1;\nconst RULE = {\n  'Student or researcher': 'exclude student and researcher titles and .edu domains before scoring',\n  'Wrong persona': 'subtract points for job functions outside IT and security (marketing, HR, office staff)',\n  'Competitor': 'add competitor domains to a do-not-score list',\n  'Existing customer': 'suppress Closed Won accounts from MQL scoring and route them to customer success',\n  'Consultant or partner': 'route consultants and MSPs to the partner team instead of sales',\n  'Too small': 'require a size signal before a lead can become an MQL',\n  'Bad contact data': 'verify email and phone before a lead can become an MQL',\n  'No budget or timing': 'not a scoring problem; recycle to nurture with a check-back date'\n};\nconst pct = (n, d) => Math.round(100 * n / Math.max(d, 1)) + '%';\nconst t = a.totals;\nconst reasonsLine = Object.entries(count).sort((x, y) => y[1] - x[1]).map(([k, v]) => k + ' ' + v).join(' · ');\nconst custConfirmed = rejected.filter(r => r.isCustomer);\nlet text = ':dart: *Rejection Reason Recalibrator* (' + a.runDate + '): ' + t.mqls + ' MQLs in the last 60 days; sales rejected ' + t.rejected + ' (' + pct(t.rejected, t.mqls) + '). MQL threshold ' + a.threshold + ' points.\\n' +\n  '\\n*Why sales said no* (from the reps’ notes): ' + reasonsLine + '\\n' +\n  rejected.filter(r => r.quote).slice(0, 5).map(r => '      ' + r.company + ' (' + r.reason + '): _“' + safe(r.quote) + '”_').join('\\n') + '\\n' +\n  '\\n*What scored the rejected leads* (fired on rejected vs accepted MQLs)\\n' + a.stats.filter(s => s.points > 0).sort((x, y) => (y.rejected / t.rejected - y.accepted / t.accepted) - (x.rejected / t.rejected - x.accepted / t.accepted)).slice(0, 4)\n    .map(s => '      ' + s.label + ' (+' + s.points + '): ' + s.rejected + ' of ' + t.rejected + ' rejected vs ' + s.accepted + ' of ' + t.accepted + ' accepted').join('\\n') + '\\n' +\n  '\\n*Proposed weight changes* (simulated on these ' + t.mqls + ' MQLs)\\n' + (a.changes.length ? a.changes.map(c => '• ' + c.label + ': +' + c.from + ' → +' + c.to + '. ' + c.dropped + ' rejected lead' + (c.dropped > 1 ? 's fall' : ' falls') + ' below ' + a.threshold + '; no accepted lead is lost').join('\\n') +\n    '\\nResult: ' + (t.rejected - a.stillOver.length) + ' of ' + t.rejected + ' rejected leads stop qualifying and all ' + t.afterAccepted + ' accepted leads still qualify. MQL volume ' + t.mqls + ' → ' + t.afterMqls + '; acceptance ' + pct(t.accepted, t.mqls) + ' → ' + pct(t.afterAccepted, t.afterMqls) + '.' : 'No weight change pushes rejected leads out without losing an accepted one.') + '\\n' +\n  '\\n*Rules weights can’t fix*\\n' + Object.keys(count).filter(k => RULE[k] && k !== 'Unclear').map(k => '• ' + k + ' (' + count[k] + '): ' + RULE[k] + (k === 'Existing customer' ? (custConfirmed.length ? '. Confirmed in Salesforce: ' + custConfirmed.map(r => r.company).join(', ') + ' is a Closed Won account.' : '. Not found among Closed Won accounts in Salesforce; check the note.') : '')).join('\\n') +\n  (count.Unclear ? '\\n_' + count.Unclear + ' rejection(s) had no usable reason in the note; ask reps to pick a reason code._' : '') +\n  (dropped ? '\\n_' + dropped + ' reason(s) dropped: quote not found in the note._' : '') +\n  '\\n_' + t.mqls + ' MQLs is a small sample: review before changing the live model, and re-run monthly._';\nif (text.length > 2900) text = text.slice(0, 2850).slice(0, text.slice(0, 2850).lastIndexOf('\\n')) + '\\n_…cut to fit Slack; details are in the Scoring Recalibration Log._';\nconst now = $now.toISO();\nconst logs = rejected.map(r => ({ runDate: a.runDate, kind: 'rejection', mqlId: r.mqlId, company: r.company, reason: r.reason, quote: r.quote, component: '', fromPoints: r.before, toPoints: r.after, effect: r.after < a.threshold ? 'below threshold after changes' : 'still qualifies', loggedAt: now }))\n  .concat(a.changes.map(c => ({ runDate: a.runDate, kind: 'proposal', mqlId: '', company: '', reason: '', quote: '', component: c.component, fromPoints: c.from, toPoints: c.to, effect: c.dropped + ' rejected below threshold: ' + c.droppedLeads.join(', '), loggedAt: now })));\nreturn [{ json: { recalText: text, logs, check: { reasons: rejected.map(r => [r.mqlId, r.reason]), changes: a.changes.map(c => [c.component, c.from, c.to, c.dropped]), stillOver: a.stillOver }, dropped } }];\n"
      },
      "executeOnce": true
    },
    {
      "id": "6ae74b2c-7343-46fe-bdb9-9cd1cd60b5c5",
      "name": "Post Recalibration",
      "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.recalText }}",
        "otherOptions": {
          "includeLinkToWorkflow": false
        }
      },
      "credentials": {
        "slackApi": {
          "id": "mv7TIi8kucFPqPg6",
          "name": "Slack account"
        }
      }
    },
    {
      "id": "7af4973d-6572-4155-b68c-454100cab9e8",
      "name": "Split Log Rows",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        700,
        600
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $('Build Recalibration').first().json.logs.map(json => ({ json }));"
      }
    },
    {
      "id": "16e77f8d-b3b3-4398-b349-7a469c4d455e",
      "name": "Log Recalibration",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        900,
        600
      ],
      "parameters": {
        "resource": "row",
        "operation": "insert",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "f1IBaPaYfPbF9c1X",
          "cachedResultName": "Scoring Recalibration Log"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {}
        }
      }
    }
  ],
  "connections": {
    "Monthly Scoring Review": {
      "main": [
        [
          {
            "node": "Get Scoring Model",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Scoring Model": {
      "main": [
        [
          {
            "node": "Get MQL Outcomes",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get MQL Outcomes": {
      "main": [
        [
          {
            "node": "Get Customers",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Customers": {
      "main": [
        [
          {
            "node": "Analyze Scores",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Analyze Scores": {
      "main": [
        [
          {
            "node": "Reason Reader",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Reason Reader": {
      "main": [
        [
          {
            "node": "Build Recalibration",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Claude Sonnet": {
      "ai_languageModel": [
        [
          {
            "node": "Reason Reader",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Reason Parser": {
      "ai_outputParser": [
        [
          {
            "node": "Reason Reader",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Build Recalibration": {
      "main": [
        [
          {
            "node": "Post Recalibration",
            "type": "main",
            "index": 0
          },
          {
            "node": "Split Log Rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split Log Rows": {
      "main": [
        [
          {
            "node": "Log Recalibration",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  }
}