{
  "id": "sjlmtePgbFjeBF9c",
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "name": "Qualify and Route Sales Leads with Mistral-Saba AI and MCDM Scoring",
  "tags": [],
  "nodes": [
    {
      "id": "2410ac7c-3026-41a2-b63b-591612723de4",
      "name": "Schedule Trigger",
      "type": "n8n-nodes-base.scheduleTrigger",
      "position": [
        -3872,
        304
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "hours"
            }
          ]
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "91d73e7a-46e3-4e85-a63b-0a7dc347bd99",
      "name": "Workflow Configuration",
      "type": "n8n-nodes-base.set",
      "position": [
        -3616,
        160
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "id-1",
              "name": "demographicApiUrl",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Demographic Data API Endpoint__>"
            },
            {
              "id": "id-2",
              "name": "behavioralApiUrl",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Behavioral Data API Endpoint__>"
            },
            {
              "id": "id-3",
              "name": "transactionalApiUrl",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Transactional Data API Endpoint__>"
            },
            {
              "id": "id-4",
              "name": "crmApiUrl",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__CRM API Endpoint__>"
            },
            {
              "id": "id-5",
              "name": "analyticsApiUrl",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Analytics Dashboard API Endpoint__>"
            },
            {
              "id": "id-6",
              "name": "enterpriseThreshold",
              "type": "number",
              "value": 85
            },
            {
              "id": "id-7",
              "name": "midMarketThreshold",
              "type": "number",
              "value": 70
            },
            {
              "id": "id-8",
              "name": "smbThreshold",
              "type": "number",
              "value": 50
            },
            {
              "id": "id-9",
              "name": "ahpWeights",
              "type": "object",
              "value": "{\"demographic\": 0.3, \"behavioral\": 0.4, \"transactional\": 0.3}"
            }
          ]
        },
        "includeOtherFields": true
      },
      "typeVersion": 3.4
    },
    {
      "id": "5ca10112-7824-47f6-ba15-9729dac1e58a",
      "name": "Fetch Demographic Data",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        -3376,
        16
      ],
      "parameters": {
        "url": "={{ $('Workflow Configuration').first().json.demographicApiUrl }}",
        "options": {},
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        }
      },
      "typeVersion": 4.3
    },
    {
      "id": "3a596f6b-8d56-4093-9310-575a7a338cbd",
      "name": "Fetch Behavioral Data",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        -3392,
        160
      ],
      "parameters": {
        "url": "={{ $('Workflow Configuration').first().json.behavioralApiUrl }}",
        "options": {},
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        }
      },
      "typeVersion": 4.3
    },
    {
      "id": "434bff0d-e1d6-4c94-a0c4-4685f0ab7f52",
      "name": "Fetch Transactional Data",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        -3392,
        352
      ],
      "parameters": {
        "url": "={{ $('Workflow Configuration').first().json.transactionalApiUrl }}",
        "options": {},
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        }
      },
      "typeVersion": 4.3
    },
    {
      "id": "850c94fe-646c-40a5-8dd5-7f34ce0cd279",
      "name": "Merge Lead Data Sources",
      "type": "n8n-nodes-base.aggregate",
      "position": [
        -3184,
        64
      ],
      "parameters": {
        "options": {},
        "aggregate": "aggregateAllItemData",
        "destinationFieldName": "leadData"
      },
      "typeVersion": 1
    },
    {
      "id": "6c0328d2-0b4d-43f0-92f2-88e1e422870b",
      "name": "MCDM Scoring Engine (AHP-TOPSIS)",
      "type": "n8n-nodes-base.code",
      "position": [
        -2944,
        64
      ],
      "parameters": {
        "jsCode": "// MCDM Scoring Engine: AHP-TOPSIS Implementation\n// Multi-Criteria Decision Making for Lead Scoring\n\n// Get input items (merged lead data)\nconst leads = $input.all();\n\n// Get configuration from Workflow Configuration node\nconst config = $('Workflow Configuration').first().json;\n\n// Default criteria weights (AHP-derived) if not in config\nconst criteriaWeights = config.criteriaWeights || {\n  companySize: 0.25,\n  budget: 0.30,\n  engagement: 0.20,\n  fitScore: 0.15,\n  urgency: 0.10\n};\n\n// Extract criteria values from leads\nconst criteria = ['companySize', 'budget', 'engagement', 'fitScore', 'urgency'];\n\n// Step 1: Build decision matrix\nconst decisionMatrix = leads.map(lead => {\n  return {\n    leadId: lead.json.leadId || lead.json.id,\n    values: criteria.map(criterion => parseFloat(lead.json[criterion]) || 0),\n    originalData: lead.json\n  };\n});\n\n// Step 2: Normalize the decision matrix (vector normalization)\nconst normalizedMatrix = [];\nfor (let j = 0; j < criteria.length; j++) {\n  const columnSum = Math.sqrt(\n    decisionMatrix.reduce((sum, row) => sum + Math.pow(row.values[j], 2), 0)\n  );\n  \n  decisionMatrix.forEach((row, i) => {\n    if (!normalizedMatrix[i]) normalizedMatrix[i] = [];\n    normalizedMatrix[i][j] = columnSum > 0 ? row.values[j] / columnSum : 0;\n  });\n}\n\n// Step 3: Apply weights to normalized matrix\nconst weightedMatrix = normalizedMatrix.map(row => \n  row.map((value, j) => value * criteriaWeights[criteria[j]])\n);\n\n// Step 4: Determine ideal best (A+) and ideal worst (A-) solutions\nconst idealBest = [];\nconst idealWorst = [];\n\nfor (let j = 0; j < criteria.length; j++) {\n  const column = weightedMatrix.map(row => row[j]);\n  idealBest[j] = Math.max(...column);\n  idealWorst[j] = Math.min(...column);\n}\n\n// Step 5: Calculate separation measures\nconst separations = weightedMatrix.map(row => {\n  const distanceToBest = Math.sqrt(\n    row.reduce((sum, value, j) => sum + Math.pow(value - idealBest[j], 2), 0)\n  );\n  \n  const distanceToWorst = Math.sqrt(\n    row.reduce((sum, value, j) => sum + Math.pow(value - idealWorst[j], 2), 0)\n  );\n  \n  return { distanceToBest, distanceToWorst };\n});\n\n// Step 6: Calculate closeness coefficient (TOPSIS score)\nconst scoredLeads = decisionMatrix.map((lead, i) => {\n  const { distanceToBest, distanceToWorst } = separations[i];\n  const closenessCoefficient = distanceToWorst / (distanceToBest + distanceToWorst) || 0;\n  \n  return {\n    json: {\n      ...lead.originalData,\n      leadId: lead.leadId,\n      mcdmScore: Math.round(closenessCoefficient * 100) / 100,\n      normalizedScore: Math.round(closenessCoefficient * 100), // 0-100 scale\n      criteriaBreakdown: {\n        companySize: lead.values[0],\n        budget: lead.values[1],\n        engagement: lead.values[2],\n        fitScore: lead.values[3],\n        urgency: lead.values[4]\n      },\n      weightedScores: {\n        companySize: weightedMatrix[i][0],\n        budget: weightedMatrix[i][1],\n        engagement: weightedMatrix[i][2],\n        fitScore: weightedMatrix[i][3],\n        urgency: weightedMatrix[i][4]\n      },\n      distanceToBest: Math.round(separations[i].distanceToBest * 1000) / 1000,\n      distanceToWorst: Math.round(separations[i].distanceToWorst * 1000) / 1000,\n      scoringMethod: 'AHP-TOPSIS',\n      scoredAt: new Date().toISOString()\n    }\n  };\n});\n\n// Step 7: Rank leads by MCDM score (descending)\nscoredLeads.sort((a, b) => b.json.mcdmScore - a.json.mcdmScore);\n\n// Add rank to each lead\nscoredLeads.forEach((lead, index) => {\n  lead.json.rank = index + 1;\n  lead.json.percentile = Math.round((1 - index / scoredLeads.length) * 100);\n});\n\nconsole.log(`MCDM Scoring Complete: ${scoredLeads.length} leads scored and ranked`);\nconsole.log(`Top Lead Score: ${scoredLeads[0]?.json.mcdmScore}`);\nconsole.log(`Criteria Weights Used:`, criteriaWeights);\n\nreturn scoredLeads;"
      },
      "typeVersion": 2
    },
    {
      "id": "ee6ed16c-eb18-4b8d-acfc-a541a599b997",
      "name": "AI Lead Qualification Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        -2784,
        160
      ],
      "parameters": {
        "text": "You are an expert lead qualification analyst. Analyze the provided lead data with MCDM scores and provide a comprehensive qualification assessment. Consider demographic fit, behavioral engagement, transactional history, and overall score. Provide actionable insights for sales teams including key strengths, potential objections, recommended approach, and priority level. Use the enrichLeadData tool to gather additional context.",
        "options": {},
        "promptType": "define"
      },
      "typeVersion": 3
    },
    {
      "id": "f575333e-9a96-4e0a-814f-fd60f3bf4e1d",
      "name": "Lead Enrichment Tool",
      "type": "@n8n/n8n-nodes-langchain.toolCode",
      "position": [
        -2592,
        352
      ],
      "parameters": {
        "jsCode": "// Extract lead information from the query\nconst leadData = typeof query === 'string' ? JSON.parse(query) : query;\n\n// Analyze MCDM scores and patterns\nconst mcdmScore = leadData.mcdmScore || 0;\nconst ahpScore = leadData.ahpScore || 0;\nconst topsisScore = leadData.topsisScore || 0;\n\n// Determine lead quality tier\nlet qualityTier = 'Low';\nlet qualificationInsights = [];\n\nif (mcdmScore >= 0.8) {\n  qualityTier = 'Enterprise';\n  qualificationInsights.push('High MCDM score indicates strong fit for enterprise sales');\n} else if (mcdmScore >= 0.6) {\n  qualityTier = 'Mid-Market';\n  qualificationInsights.push('Moderate MCDM score suitable for mid-market engagement');\n} else if (mcdmScore >= 0.4) {\n  qualityTier = 'SMB';\n  qualificationInsights.push('MCDM score indicates SMB potential');\n} else {\n  qualityTier = 'Nurture';\n  qualificationInsights.push('Low MCDM score - recommend nurture campaign');\n}\n\n// Analyze behavioral patterns\nif (leadData.engagementScore && leadData.engagementScore > 0.7) {\n  qualificationInsights.push('High engagement score indicates active interest');\n}\n\nif (leadData.companySize && leadData.companySize > 500) {\n  qualificationInsights.push('Large company size increases enterprise potential');\n}\n\nif (leadData.budget && leadData.budget > 100000) {\n  qualificationInsights.push('Significant budget allocation detected');\n}\n\n// Create enriched lead profile\nconst enrichedData = {\n  ...leadData,\n  qualityTier,\n  qualificationInsights,\n  enrichmentTimestamp: new Date().toISOString(),\n  recommendedAction: qualityTier === 'Nurture' ? 'Add to nurture campaign' : `Route to ${qualityTier} sales team`,\n  priorityScore: mcdmScore,\n  confidenceLevel: (ahpScore + topsisScore) / 2\n};\n\n// Return enriched data as JSON string\nreturn JSON.stringify(enrichedData, null, 2);",
        "description": "Enriches lead data with additional context and insights based on MCDM scores"
      },
      "typeVersion": 1.3
    },
    {
      "id": "c508c747-30e9-4bb2-9033-daa74adaf07e",
      "name": "Prepare Lead Scores",
      "type": "n8n-nodes-base.set",
      "position": [
        -2496,
        160
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "id-1",
              "name": "leadScore",
              "type": "number",
              "value": "={{ $json.mcdmScore }}"
            },
            {
              "id": "id-2",
              "name": "leadTier",
              "type": "string",
              "value": "={{ $json.tier }}"
            },
            {
              "id": "id-3",
              "name": "aiInsights",
              "type": "string",
              "value": "={{ $json.output }}"
            },
            {
              "id": "id-4",
              "name": "routingDecision",
              "type": "string",
              "value": "={{ $json.routingDecision }}"
            }
          ]
        },
        "includeOtherFields": true
      },
      "typeVersion": 3.4
    },
    {
      "id": "9218e955-5d21-43c7-9409-4c9d8a39e3cf",
      "name": "Route by Lead Quality",
      "type": "n8n-nodes-base.switch",
      "position": [
        -2320,
        224
      ],
      "parameters": {
        "rules": {
          "values": [
            {
              "outputKey": "Enterprise",
              "conditions": {
                "options": {
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "operator": {
                      "type": "number",
                      "operation": "gte"
                    },
                    "leftValue": "={{ $json.leadScore }}",
                    "rightValue": "={{ $('Workflow Configuration').first().json.enterpriseThreshold }}"
                  }
                ]
              },
              "renameOutput": true
            },
            {
              "outputKey": "Mid-Market",
              "conditions": {
                "options": {
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "operator": {
                      "type": "number",
                      "operation": "gte"
                    },
                    "leftValue": "={{ $json.leadScore }}",
                    "rightValue": "={{ $('Workflow Configuration').first().json.midMarketThreshold }}"
                  }
                ]
              },
              "renameOutput": true
            },
            {
              "outputKey": "SMB",
              "conditions": {
                "options": {
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "operator": {
                      "type": "number",
                      "operation": "gte"
                    },
                    "leftValue": "={{ $json.leadScore }}",
                    "rightValue": "={{ $('Workflow Configuration').first().json.smbThreshold }}"
                  }
                ]
              },
              "renameOutput": true
            },
            {
              "outputKey": "Nurture",
              "conditions": {
                "options": {
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "operator": {
                      "type": "number",
                      "operation": "lt"
                    },
                    "leftValue": "={{ $json.leadScore }}",
                    "rightValue": "={{ $('Workflow Configuration').first().json.smbThreshold }}"
                  }
                ]
              },
              "renameOutput": true
            }
          ]
        },
        "options": {}
      },
      "typeVersion": 3.3
    },
    {
      "id": "e9345b1d-b546-4098-8f87-55228bab52dc",
      "name": "Assign to Enterprise Sales Team",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        -2064,
        80
      ],
      "parameters": {
        "url": "<__PLACEHOLDER_VALUE__Enterprise Sales Team Assignment API__>",
        "method": "POST",
        "options": {},
        "sendBody": true,
        "sendHeaders": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "leadId",
              "value": "={{ $json.leadId }}"
            },
            {
              "name": "leadData",
              "value": "={{ $json.leadData }}"
            },
            {
              "name": "score",
              "value": "={{ $json.score }}"
            },
            {
              "name": "tier",
              "value": "={{ $json.tier }}"
            },
            {
              "name": "aiInsights",
              "value": "={{ $json.aiInsights }}"
            }
          ]
        },
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        }
      },
      "typeVersion": 4.3
    },
    {
      "id": "baab50d2-df84-4256-a5e7-ab11bb6f31ad",
      "name": "Assign to Mid-Market Team",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        -2096,
        256
      ],
      "parameters": {
        "url": "<__PLACEHOLDER_VALUE__Mid-Market Team Assignment API__>",
        "method": "POST",
        "options": {},
        "sendBody": true,
        "sendHeaders": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "lead_data",
              "value": "={{ $json.lead_data }}"
            },
            {
              "name": "score",
              "value": "={{ $json.score }}"
            },
            {
              "name": "tier",
              "value": "={{ $json.tier }}"
            },
            {
              "name": "ai_insights",
              "value": "={{ $json.ai_insights }}"
            }
          ]
        },
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        }
      },
      "typeVersion": 4.3
    },
    {
      "id": "b09653ea-5fea-4487-a6ae-a7e66f5b5463",
      "name": "Assign to SMB Team",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        -2096,
        448
      ],
      "parameters": {
        "url": "<__PLACEHOLDER_VALUE__SMB Team Assignment API__>",
        "method": "POST",
        "options": {},
        "sendBody": true,
        "sendHeaders": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "lead_id",
              "value": "={{ $json.lead_id }}"
            },
            {
              "name": "lead_data",
              "value": "={{ $json.lead_data }}"
            },
            {
              "name": "score",
              "value": "={{ $json.score }}"
            },
            {
              "name": "tier",
              "value": "={{ $json.tier }}"
            },
            {
              "name": "ai_insights",
              "value": "={{ $json.ai_insights }}"
            }
          ]
        },
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        }
      },
      "typeVersion": 4.3
    },
    {
      "id": "67fb8eef-ceac-4ca8-8e71-cc270d2838c2",
      "name": "Send to Nurture Campaign",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        -2096,
        640
      ],
      "parameters": {
        "url": "<__PLACEHOLDER_VALUE__Nurture Campaign API__>",
        "method": "POST",
        "options": {},
        "jsonBody": "={{ {\n  \"leadId\": $json.leadId,\n  \"email\": $json.email,\n  \"name\": $json.name,\n  \"score\": $json.score,\n  \"qualificationStatus\": $json.qualificationStatus,\n  \"nurtureRecommendations\": $json.nurtureRecommendations,\n  \"assignedCampaign\": \"nurture\",\n  \"timestamp\": $now\n} }}",
        "sendBody": true,
        "sendHeaders": true,
        "specifyBody": "json",
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        }
      },
      "typeVersion": 4.3
    },
    {
      "id": "e2cff35d-64d8-43b8-962e-5d34aa722fe1",
      "name": "Collect Routing Results",
      "type": "n8n-nodes-base.aggregate",
      "position": [
        -1792,
        144
      ],
      "parameters": {
        "options": {},
        "aggregate": "aggregateAllItemData",
        "destinationFieldName": "routingResults"
      },
      "typeVersion": 1
    },
    {
      "id": "9fff038a-72fd-4860-a620-594e9aa79b3d",
      "name": "Update CRM with Lead Scores",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        -1616,
        144
      ],
      "parameters": {
        "url": "={{ $('Workflow Configuration').first().json.crmApiUrl }}",
        "method": "POST",
        "options": {},
        "jsonBody": "={{ {\n  \"leadId\": $json.leadId,\n  \"leadScore\": $json.leadScore,\n  \"tier\": $json.tier,\n  \"routingDecision\": $json.routingDecision,\n  \"assignedTeam\": $json.assignedTeam,\n  \"aiInsights\": $json.aiInsights,\n  \"demographicScore\": $json.demographicScore,\n  \"behavioralScore\": $json.behavioralScore,\n  \"transactionalScore\": $json.transactionalScore,\n  \"qualificationTimestamp\": $now.toISO()\n} }}",
        "sendBody": true,
        "sendHeaders": true,
        "specifyBody": "json",
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        }
      },
      "typeVersion": 4.3
    },
    {
      "id": "f69e1819-7713-4dac-87cf-f2256b8860cb",
      "name": "Calculate Performance KPIs",
      "type": "n8n-nodes-base.code",
      "position": [
        -1376,
        128
      ],
      "parameters": {
        "jsCode": "// Calculate Performance KPIs for Lead Qualification System\n\nconst items = $input.all();\n\n// Initialize counters and metrics\nconst tierCounts = {\n  enterprise: 0,\n  midMarket: 0,\n  smb: 0,\n  nurture: 0\n};\n\nconst tierScores = {\n  enterprise: [],\n  midMarket: [],\n  smb: [],\n  nurture: []\n};\n\nconst tierConversions = {\n  enterprise: 0,\n  midMarket: 0,\n  smb: 0,\n  nurture: 0\n};\n\nconst responseTimes = [];\nconst processingTimes = [];\nlet totalLeads = items.length;\nlet accurateQualifications = 0;\n\n// Process each lead\nfor (const item of items) {\n  const json = item.json;\n  \n  // Determine tier from routing or score\n  let tier = 'nurture';\n  const score = json.leadScore || json.score || 0;\n  \n  if (json.tier) {\n    tier = json.tier.toLowerCase();\n  } else if (score >= 80) {\n    tier = 'enterprise';\n  } else if (score >= 60) {\n    tier = 'midMarket';\n  } else if (score >= 40) {\n    tier = 'smb';\n  }\n  \n  // Count leads by tier\n  tierCounts[tier]++;\n  \n  // Collect scores by tier\n  tierScores[tier].push(score);\n  \n  // Track conversions (if conversion data exists)\n  if (json.converted === true || json.status === 'converted') {\n    tierConversions[tier]++;\n  }\n  \n  // Collect response times (if available)\n  if (json.responseTime) {\n    responseTimes.push(json.responseTime);\n  }\n  \n  // Collect processing times (if available)\n  if (json.processingTime) {\n    processingTimes.push(json.processingTime);\n  }\n  \n  // Track model accuracy (if validation data exists)\n  if (json.actualQuality && json.predictedQuality) {\n    if (json.actualQuality === json.predictedQuality) {\n      accurateQualifications++;\n    }\n  }\n}\n\n// Calculate average scores by tier\nconst avgScoresByTier = {};\nfor (const [tier, scores] of Object.entries(tierScores)) {\n  if (scores.length > 0) {\n    avgScoresByTier[tier] = scores.reduce((a, b) => a + b, 0) / scores.length;\n  } else {\n    avgScoresByTier[tier] = 0;\n  }\n}\n\n// Calculate conversion rates by tier\nconst conversionRatesByTier = {};\nfor (const [tier, count] of Object.entries(tierCounts)) {\n  if (count > 0) {\n    conversionRatesByTier[tier] = (tierConversions[tier] / count) * 100;\n  } else {\n    conversionRatesByTier[tier] = 0;\n  }\n}\n\n// Calculate average response time\nconst avgResponseTime = responseTimes.length > 0\n  ? responseTimes.reduce((a, b) => a + b, 0) / responseTimes.length\n  : 0;\n\n// Calculate average processing time\nconst avgProcessingTime = processingTimes.length > 0\n  ? processingTimes.reduce((a, b) => a + b, 0) / processingTimes.length\n  : 0;\n\n// Calculate model accuracy\nconst modelAccuracy = totalLeads > 0\n  ? (accurateQualifications / totalLeads) * 100\n  : 0;\n\n// Calculate lead distribution percentages\nconst leadDistribution = {};\nfor (const [tier, count] of Object.entries(tierCounts)) {\n  leadDistribution[tier] = totalLeads > 0 ? (count / totalLeads) * 100 : 0;\n}\n\n// Compile KPIs\nconst kpis = {\n  timestamp: new Date().toISOString(),\n  totalLeadsProcessed: totalLeads,\n  \n  conversionRates: {\n    enterprise: conversionRatesByTier.enterprise.toFixed(2) + '%',\n    midMarket: conversionRatesByTier.midMarket.toFixed(2) + '%',\n    smb: conversionRatesByTier.smb.toFixed(2) + '%',\n    nurture: conversionRatesByTier.nurture.toFixed(2) + '%',\n    overall: ((Object.values(tierConversions).reduce((a, b) => a + b, 0) / totalLeads) * 100).toFixed(2) + '%'\n  },\n  \n  averageLeadScores: {\n    enterprise: avgScoresByTier.enterprise.toFixed(2),\n    midMarket: avgScoresByTier.midMarket.toFixed(2),\n    smb: avgScoresByTier.smb.toFixed(2),\n    nurture: avgScoresByTier.nurture.toFixed(2)\n  },\n  \n  leadDistribution: {\n    enterprise: leadDistribution.enterprise.toFixed(2) + '%',\n    midMarket: leadDistribution.midMarket.toFixed(2) + '%',\n    smb: leadDistribution.smb.toFixed(2) + '%',\n    nurture: leadDistribution.nurture.toFixed(2) + '%'\n  },\n  \n  leadCounts: tierCounts,\n  \n  performanceMetrics: {\n    averageResponseTime: avgResponseTime.toFixed(2) + ' ms',\n    averageProcessingTime: avgProcessingTime.toFixed(2) + ' ms',\n    modelAccuracy: modelAccuracy.toFixed(2) + '%'\n  }\n};\n\nreturn [{ json: kpis }];"
      },
      "typeVersion": 2
    },
    {
      "id": "4642b3cf-8ef8-431b-980a-dc66214e95d3",
      "name": "Log KPIs to Analytics Dashboard",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        -1200,
        128
      ],
      "parameters": {
        "url": "={{ $('Workflow Configuration').first().json.analyticsApiUrl }}",
        "method": "POST",
        "options": {},
        "jsonBody": "={{ {\n  \"kpis\": $json,\n  \"timestamp\": $now\n} }}",
        "sendBody": true,
        "sendHeaders": true,
        "specifyBody": "json",
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        }
      },
      "typeVersion": 4.3
    },
    {
      "id": "755a24b3-ce8d-4f19-a7b8-acc30c2f1001",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -3920,
        -256
      ],
      "parameters": {
        "width": 656,
        "height": 192,
        "content": "## How It Works\nThe workflow starts with a scheduled trigger that activates at set intervals. Behavioral data from multiple sources is parsed and sent to the MCDN routing engine, which intelligently assigns leads to the right teams based on predefined rules. AI-powered scoring evaluates each prospect\u2019s potential, ensuring high-quality leads are prioritized. The results are synced to the CRM, and updates are reflected on an analytics dashboard for real-time visibility.\n\n"
      },
      "typeVersion": 1
    },
    {
      "id": "1453438a-89f0-493a-87d7-859de1060ad3",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -3248,
        -256
      ],
      "parameters": {
        "width": 576,
        "height": 192,
        "content": "## Setup Steps\n1. **Trigger:** Define schedule frequency.\n2. **Data Fetch:** Configure APIs for all behavioral data sources.\n3. **MCDN Router:** Set routing rules, thresholds, and team assignments.\n4. **AI Models:** Connect OpenAI/NVIDIA APIs and configure scoring prompts.\n5. **CRM Integration:** Enter credentials for Salesforce, HubSpot, or other CRMs.\n6. **Dashboard:** Link to analytics tools like Tableau or Google Sheets for reporting.\n"
      },
      "typeVersion": 1
    },
    {
      "id": "e2219910-ab39-4b05-8219-98b1c1d284d3",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -2640,
        -256
      ],
      "parameters": {
        "color": 4,
        "width": 672,
        "content": "## Prerequisites\nAPI credentials: NVIDIA AI, OpenAI, CRM platform; data sources; spreadsheet/analytics access\n\n## Use Cases\nLead prioritization for sales teams; customer segmentation; automated routing; "
      },
      "typeVersion": 1
    },
    {
      "id": "fca6d1b5-68f8-4d5a-82ef-9f16454fa202",
      "name": "Sticky Note3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1936,
        -272
      ],
      "parameters": {
        "color": 3,
        "content": "## Customization\nAdjust routing rules, add custom scoring models, modify team assignments, expand data sources "
      },
      "typeVersion": 1
    },
    {
      "id": "52914015-7d55-4ef4-824b-fab34ef818b5",
      "name": "Sticky Note4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1648,
        -272
      ],
      "parameters": {
        "color": 6,
        "width": 336,
        "height": 128,
        "content": "## Benefits\nReduces manual lead routing 90%; improves scoring accuracy; accelerates sales cycle "
      },
      "typeVersion": 1
    },
    {
      "id": "95272b07-2b31-4895-a068-8682d009c3ad",
      "name": "OpenRouter Chat Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenRouter",
      "position": [
        -2768,
        352
      ],
      "parameters": {
        "model": "mistralai/mistral-saba",
        "options": {}
      },
      "credentials": {
        "openRouterApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "8a3a9dd6-44bc-4f46-91c4-17621f32f851",
      "name": "Sticky Note5",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -3920,
        -48
      ],
      "parameters": {
        "color": 7,
        "height": 512,
        "content": "## Schedule Lead Processing\nTriggers workflow at defined intervals to process batches of incoming leads\nWhy: Consistent cadence ensures leads don't sit unqualified; "
      },
      "typeVersion": 1
    },
    {
      "id": "f3a3bac6-e7bd-4fa2-8e81-1a809d3fb196",
      "name": "Sticky Note6",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -3664,
        -48
      ],
      "parameters": {
        "color": 7,
        "width": 416,
        "height": 720,
        "content": "## Fetch Behavioral Data\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nRetrieves multi-source lead information: form submissions, website interactions, email engagement, past purchase signals\nWhy: Rich behavioral data reveals intent "
      },
      "typeVersion": 1
    },
    {
      "id": "d1cc1263-e929-4114-ba26-fdcd1c2fbf32",
      "name": "Sticky Note7",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -3232,
        -48
      ],
      "parameters": {
        "color": 7,
        "height": 608,
        "content": "## Parse Multi-Format Inputs\n\n\n\n\n\n\n\n\n\n\n\n\n\nStandardizes data from different sources (APIs, spreadsheets, webhooks, forms) into consistent structure\nWhy: email parsing ensures AI and routing engine work with clean, normalized information  "
      },
      "typeVersion": 1
    },
    {
      "id": "b6d4d290-7d4a-495e-b8cd-29fb3174961a",
      "name": "Sticky Note8",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -2976,
        -48
      ],
      "parameters": {
        "color": 7,
        "width": 160,
        "height": 608,
        "content": "## MCDN Route\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nRoutes leads to the right sales teams using account size, industry, region, product interests.\n**Why:** Ensures reps focus on the right opportunities "
      },
      "typeVersion": 1
    },
    {
      "id": "7489c24d-2b64-4905-9411-39ab65d72244",
      "name": "Sticky Note9",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -2800,
        -48
      ],
      "parameters": {
        "color": 7,
        "width": 416,
        "height": 608,
        "content": "## AI Scores Lead Quality\nAnalyzes behavioral, transactional, and firmographic data to rank leads by conversion probability\nWhy: AI scoring reveals which prospects are sales-ready "
      },
      "typeVersion": 1
    },
    {
      "id": "c6b6a7be-0f1c-4010-8284-26cf782e9d27",
      "name": "Sticky Note10",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -2368,
        -80
      ],
      "parameters": {
        "color": 7,
        "width": 496,
        "height": 880,
        "content": "## Assign to Specialized Team\nRoutes qualified lead to the right team: enterprise, mid-market, SMB, or vertical specialist based on scoring and routing rules\nWhy:  proper assignment cuts sales cycle time and improves close rates"
      },
      "typeVersion": 1
    },
    {
      "id": "a87da9c7-d2e0-419b-8879-9b4e7a7f140b",
      "name": "Sticky Note11",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1856,
        -80
      ],
      "parameters": {
        "color": 7,
        "width": 384,
        "height": 400,
        "content": "## Sync Assignment Metadata\nCaptures which team received the lead, reasoning for routing, and AI confidence score in CRM fields\nWhy: Understand why a lead went to team A instead of B, and refine rules based on outcomes"
      },
      "typeVersion": 1
    },
    {
      "id": "765bc70b-5101-498c-843f-6d34b1c20241",
      "name": "Sticky Note12",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1456,
        -80
      ],
      "parameters": {
        "color": 7,
        "width": 448,
        "height": 368,
        "content": "## Generate Performance Dashboard & Log\nCompiles metrics: leads processed, quality distribution, routing accuracy, team assignment rates, conversion tracking\nWhy: Transforms individual routing decisions into strategic visibility "
      },
      "typeVersion": 1
    }
  ],
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "70da3d90-a427-422a-8641-822ee81af49e",
  "connections": {
    "Schedule Trigger": {
      "main": [
        [
          {
            "node": "Workflow Configuration",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Assign to SMB Team": {
      "main": [
        [
          {
            "node": "Collect Routing Results",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare Lead Scores": {
      "main": [
        [
          {
            "node": "Route by Lead Quality",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Lead Enrichment Tool": {
      "ai_tool": [
        [
          {
            "node": "AI Lead Qualification Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Behavioral Data": {
      "main": [
        [
          {
            "node": "Merge Lead Data Sources",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenRouter Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "AI Lead Qualification Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Route by Lead Quality": {
      "main": [
        [
          {
            "node": "Assign to Enterprise Sales Team",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Assign to Mid-Market Team",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Assign to SMB Team",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Send to Nurture Campaign",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Demographic Data": {
      "main": [
        [
          {
            "node": "Merge Lead Data Sources",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Workflow Configuration": {
      "main": [
        [
          {
            "node": "Fetch Demographic Data",
            "type": "main",
            "index": 0
          },
          {
            "node": "Fetch Behavioral Data",
            "type": "main",
            "index": 0
          },
          {
            "node": "Fetch Transactional Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Collect Routing Results": {
      "main": [
        [
          {
            "node": "Update CRM with Lead Scores",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Merge Lead Data Sources": {
      "main": [
        [
          {
            "node": "MCDM Scoring Engine (AHP-TOPSIS)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Transactional Data": {
      "main": [
        [
          {
            "node": "Merge Lead Data Sources",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send to Nurture Campaign": {
      "main": [
        [
          {
            "node": "Collect Routing Results",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Assign to Mid-Market Team": {
      "main": [
        [
          {
            "node": "Collect Routing Results",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Calculate Performance KPIs": {
      "main": [
        [
          {
            "node": "Log KPIs to Analytics Dashboard",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI Lead Qualification Agent": {
      "main": [
        [
          {
            "node": "Prepare Lead Scores",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Update CRM with Lead Scores": {
      "main": [
        [
          {
            "node": "Calculate Performance KPIs",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Assign to Enterprise Sales Team": {
      "main": [
        [
          {
            "node": "Collect Routing Results",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "MCDM Scoring Engine (AHP-TOPSIS)": {
      "main": [
        [
          {
            "node": "AI Lead Qualification Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}