{
  "id": "qzYFj3xAFHqljhd4",
  "name": "Detect and correct claims cost leakage using AI analysis and automation",
  "tags": [],
  "nodes": [
    {
      "id": "d091a9b6-b9ea-43d7-8189-e1b6a485a01e",
      "name": "Daily Claims Analysis Schedule",
      "type": "n8n-nodes-base.scheduleTrigger",
      "position": [
        -1344,
        224
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "triggerAtHour": 2
            }
          ]
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "55c1655a-d36a-49d1-9f39-387e0cb8f1f8",
      "name": "Workflow Configuration",
      "type": "n8n-nodes-base.set",
      "position": [
        -1120,
        224
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "id-1",
              "name": "claimsApiUrl",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Claims API endpoint URL__>"
            },
            {
              "id": "id-2",
              "name": "excessivePayoutThreshold",
              "type": "number",
              "value": 10000
            },
            {
              "id": "id-3",
              "name": "reserveVarianceThreshold",
              "type": "number",
              "value": 0.25
            },
            {
              "id": "id-4",
              "name": "reportRecipients",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Email addresses for reports (comma-separated)__>"
            },
            {
              "id": "id-5",
              "name": "vendorApiUrl",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Vendor history API endpoint__>"
            },
            {
              "id": "id-6",
              "name": "policyApiUrl",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Policy rules API endpoint__>"
            },
            {
              "id": "id-7",
              "name": "auditDbConnectionString",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Audit database connection string__>"
            },
            {
              "id": "id-8",
              "name": "escalationRecipients",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Escalation alert email addresses__>"
            },
            {
              "id": "id-9",
              "name": "criticalThreshold",
              "type": "number",
              "value": 100000
            }
          ]
        },
        "includeOtherFields": true
      },
      "typeVersion": 3.4
    },
    {
      "id": "087ea2f5-c868-4e3b-8d83-d4a836098254",
      "name": "Fetch Historical Claims Data",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        -896,
        224
      ],
      "parameters": {
        "url": "={{ $('Workflow Configuration').first().json.claimsApiUrl }}",
        "options": {},
        "sendQuery": true,
        "sendHeaders": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "startDate",
              "value": "={{ $today.minus({ days: 30 }).toFormat('yyyy-MM-dd') }}"
            },
            {
              "name": "endDate",
              "value": "={{ $today.toFormat('yyyy-MM-dd') }}"
            }
          ]
        },
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        }
      },
      "typeVersion": 4.3
    },
    {
      "id": "4888393a-b542-4247-81de-9e0f4df515b8",
      "name": "Detect Cost Leakage Anomalies",
      "type": "n8n-nodes-base.code",
      "position": [
        -672,
        224
      ],
      "parameters": {
        "jsCode": "// Analyze claims data and detect cost leakage anomalies\n\n// Configuration thresholds\nconst EXCESSIVE_PAYOUT_THRESHOLD = 50000; // Flag payouts above this amount\nconst RESERVE_VARIANCE_THRESHOLD = 0.25; // 25% variance threshold\n\n// Get all input items (claims data)\nconst claims = $input.all();\n\n// Array to store detected anomalies\nconst anomalies = [];\n\n// Process each claim\nfor (const claim of claims) {\n  const claimData = claim.json;\n  const claimId = claimData.claimId || claimData.id || 'UNKNOWN';\n  \n  // 1. Check for excessive payouts\n  if (claimData.payoutAmount && claimData.payoutAmount > EXCESSIVE_PAYOUT_THRESHOLD) {\n    anomalies.push({\n      claimId: claimId,\n      leakageType: 'Excessive Payout',\n      amount: claimData.payoutAmount,\n      variancePercentage: ((claimData.payoutAmount - EXCESSIVE_PAYOUT_THRESHOLD) / EXCESSIVE_PAYOUT_THRESHOLD * 100).toFixed(2),\n      details: `Payout of $${claimData.payoutAmount} exceeds threshold of $${EXCESSIVE_PAYOUT_THRESHOLD}`,\n      severity: 'HIGH'\n    });\n  }\n  \n  // 2. Check for inconsistent reserves (variance > 25%)\n  if (claimData.reserveAmount && claimData.actualAmount) {\n    const variance = Math.abs(claimData.actualAmount - claimData.reserveAmount) / claimData.reserveAmount;\n    if (variance > RESERVE_VARIANCE_THRESHOLD) {\n      anomalies.push({\n        claimId: claimId,\n        leakageType: 'Inconsistent Reserve',\n        amount: Math.abs(claimData.actualAmount - claimData.reserveAmount),\n        variancePercentage: (variance * 100).toFixed(2),\n        details: `Reserve: $${claimData.reserveAmount}, Actual: $${claimData.actualAmount}, Variance: ${(variance * 100).toFixed(2)}%`,\n        severity: variance > 0.5 ? 'HIGH' : 'MEDIUM'\n      });\n    }\n  }\n  \n  // 3. Check for improper vendor charges (duplicates/inflated)\n  if (claimData.vendorCharges && Array.isArray(claimData.vendorCharges)) {\n    const chargeMap = {};\n    \n    for (const charge of claimData.vendorCharges) {\n      const key = `${charge.vendorId}_${charge.serviceType}_${charge.date}`;\n      \n      // Check for duplicates\n      if (chargeMap[key]) {\n        anomalies.push({\n          claimId: claimId,\n          leakageType: 'Duplicate Vendor Charge',\n          amount: charge.amount,\n          variancePercentage: 100,\n          details: `Duplicate charge from vendor ${charge.vendorId} for ${charge.serviceType} on ${charge.date}`,\n          severity: 'HIGH'\n        });\n      } else {\n        chargeMap[key] = charge;\n      }\n      \n      // Check for inflated charges (if expected amount is provided)\n      if (charge.expectedAmount && charge.amount > charge.expectedAmount * 1.25) {\n        const inflationVariance = ((charge.amount - charge.expectedAmount) / charge.expectedAmount * 100).toFixed(2);\n        anomalies.push({\n          claimId: claimId,\n          leakageType: 'Inflated Vendor Charge',\n          amount: charge.amount - charge.expectedAmount,\n          variancePercentage: inflationVariance,\n          details: `Vendor ${charge.vendorId} charged $${charge.amount} vs expected $${charge.expectedAmount}`,\n          severity: 'MEDIUM'\n        });\n      }\n    }\n  }\n}\n\n// Return results\nif (anomalies.length > 0) {\n  return {\n    json: {\n      leakageDetected: true,\n      totalAnomalies: anomalies.length,\n      totalLeakageAmount: anomalies.reduce((sum, a) => sum + (a.amount || 0), 0),\n      anomalies: anomalies,\n      analysisDate: new Date().toISOString(),\n      claimsAnalyzed: claims.length\n    }\n  };\n} else {\n  return {\n    json: {\n      leakageDetected: false,\n      totalAnomalies: 0,\n      totalLeakageAmount: 0,\n      anomalies: [],\n      analysisDate: new Date().toISOString(),\n      claimsAnalyzed: claims.length\n    }\n  };\n}"
      },
      "typeVersion": 2
    },
    {
      "id": "8520a553-f852-4dfe-b026-27a5cfe8e147",
      "name": "Check If Leakage Detected",
      "type": "n8n-nodes-base.if",
      "position": [
        -448,
        224
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "leftValue": "",
            "caseSensitive": false,
            "typeValidation": "loose"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "id-1",
              "operator": {
                "type": "boolean",
                "operation": "true"
              },
              "leftValue": "={{ $('Detect Cost Leakage Anomalies').item.json.hasLeakage }}"
            }
          ]
        }
      },
      "typeVersion": 2.3
    },
    {
      "id": "37d5efee-3348-4232-8fa8-7a1e29c8721a",
      "name": "AI Root Cause Classifier",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        512,
        80
      ],
      "parameters": {
        "text": "={{ $json.leakageDetails }}",
        "options": {
          "systemMessage": "You are an expert claims cost leakage analyst specializing in insurance fraud detection and billing accuracy.\n\nYour task is to analyze detected cost leakage anomalies and classify the root cause into one of these categories:\n\n1. EXCESSIVE_PAYOUT - Payment exceeds reasonable limits for claim type\n2. INCONSISTENT_RESERVE - Reserve amount significantly differs from actual payout\n3. DUPLICATE_BILLING - Same service/item billed multiple times\n4. INFLATED_CHARGES - Vendor charges exceed market rates\n5. CODING_ERROR - Incorrect billing codes or modifiers\n6. POLICY_VIOLATION - Payment violates policy terms or coverage limits\n7. FRAUD_SUSPECTED - Pattern indicates potential fraudulent activity\n8. ADMINISTRATIVE_ERROR - Processing or data entry mistake\n\nFor each anomaly, provide:\n- Root cause category\n- Confidence score (0-100)\n- Detailed explanation\n- Contributing factors\n- Severity level (LOW, MEDIUM, HIGH, CRITICAL)\n\nReturn your analysis in the structured JSON format defined by the output parser."
        },
        "promptType": "define",
        "hasOutputParser": true
      },
      "typeVersion": 3.1
    },
    {
      "id": "de6e73f2-b1a2-4583-903e-973f68a6b70d",
      "name": "OpenAI GPT-4",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        528,
        320
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "id",
          "value": "gpt-4o"
        },
        "options": {},
        "builtInTools": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "131708ea-911e-4355-b5cb-cd37fb77a9c5",
      "name": "Classification Output Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        832,
        336
      ],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n  \"type\": \"object\",\n  \"properties\": {\n    \"claimId\": {\n      \"type\": \"string\",\n      \"description\": \"Unique claim identifier\"\n    },\n    \"rootCause\": {\n      \"type\": \"string\",\n      \"description\": \"Root cause category from predefined list\"\n    },\n    \"confidenceScore\": {\n      \"type\": \"number\",\n      \"description\": \"Confidence score 0-100\"\n    },\n    \"explanation\": {\n      \"type\": \"string\",\n      \"description\": \"Detailed explanation of the root cause\"\n    },\n    \"contributingFactors\": {\n      \"type\": \"array\",\n      \"items\": {\n        \"type\": \"string\"\n      },\n      \"description\": \"List of contributing factors\"\n    },\n    \"severityLevel\": {\n      \"type\": \"string\",\n      \"description\": \"Severity: LOW, MEDIUM, HIGH, or CRITICAL\"\n    },\n    \"estimatedLeakageAmount\": {\n      \"type\": \"number\",\n      \"description\": \"Estimated cost leakage in dollars\"\n    }\n  }\n}"
      },
      "typeVersion": 1.3
    },
    {
      "id": "e6833c4c-51c5-40ff-962d-68fb671318ae",
      "name": "Generate Corrective Adjustments",
      "type": "n8n-nodes-base.code",
      "position": [
        912,
        80
      ],
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "// Generate corrective billing adjustments based on AI classification\nconst item = $input.item.json;\n\n// Extract AI classification results\nconst rootCause = item.root_cause || item.rootCause || 'UNKNOWN';\nconst leakageAmount = item.leakage_amount || item.leakageAmount || 0;\nconst claimId = item.claim_id || item.claimId || 'UNKNOWN';\nconst confidence = item.confidence || 0.5;\n\n// Determine adjustment type based on root cause\nlet adjustmentType;\nlet recommendedAction;\nlet priorityLevel;\n\nswitch(rootCause.toUpperCase()) {\n  case 'DUPLICATE_PAYMENT':\n  case 'OVERPAYMENT':\n    adjustmentType = 'RECOVER_OVERPAYMENT';\n    recommendedAction = 'Initiate recovery process for duplicate/overpayment';\n    priorityLevel = 'HIGH';\n    break;\n  \n  case 'INCORRECT_PRICING':\n  case 'BILLING_ERROR':\n    adjustmentType = 'REDUCE_PAYMENT';\n    recommendedAction = 'Adjust payment to correct pricing/billing amount';\n    priorityLevel = 'MEDIUM';\n    break;\n  \n  case 'RESERVE_MISCALCULATION':\n  case 'RESERVE_ERROR':\n    adjustmentType = 'CORRECT_RESERVE';\n    recommendedAction = 'Recalculate and adjust reserve allocation';\n    priorityLevel = 'MEDIUM';\n    break;\n  \n  case 'VENDOR_OVERCHARGE':\n  case 'PROVIDER_FRAUD':\n    adjustmentType = 'VENDOR_DISPUTE';\n    recommendedAction = 'Initiate vendor dispute and investigation';\n    priorityLevel = 'HIGH';\n    break;\n  \n  default:\n    adjustmentType = 'REDUCE_PAYMENT';\n    recommendedAction = 'Review and adjust payment as needed';\n    priorityLevel = 'LOW';\n}\n\n// Calculate adjustment amount (negative for reductions/recoveries)\nconst adjustmentAmount = -Math.abs(leakageAmount);\n\n// Generate justification\nconst justification = `Cost leakage detected via AI analysis. Root cause identified as ${rootCause} with ${(confidence * 100).toFixed(1)}% confidence. Recommended corrective action to recover $${Math.abs(adjustmentAmount).toFixed(2)}.`;\n\n// Return corrective adjustment object\nreturn {\n  claim_id: claimId,\n  adjustment_type: adjustmentType,\n  recommended_action: recommendedAction,\n  adjustment_amount: adjustmentAmount,\n  original_leakage_amount: leakageAmount,\n  justification: justification,\n  priority_level: priorityLevel,\n  root_cause: rootCause,\n  confidence_score: confidence,\n  generated_at: new Date().toISOString(),\n  status: 'PENDING_REVIEW'\n};"
      },
      "typeVersion": 2
    },
    {
      "id": "ca948b9c-7ce6-4e13-8965-e1cd9774f2db",
      "name": "Aggregate Findings Report",
      "type": "n8n-nodes-base.aggregate",
      "position": [
        1584,
        112
      ],
      "parameters": {
        "options": {},
        "aggregate": "aggregateAllItemData",
        "destinationFieldName": "adjustmentDetails"
      },
      "typeVersion": 1
    },
    {
      "id": "a8bb5cf9-6288-4f7a-ae03-4d37de118b20",
      "name": "Send Leakage Report",
      "type": "n8n-nodes-base.emailSend",
      "position": [
        1808,
        112
      ],
      "parameters": {
        "html": "=<h2>Claims Cost Leakage Detection Report</h2>\n<p><strong>Report Date:</strong> {{ $today.toFormat('yyyy-MM-dd') }}</p>\n\n<h3>Executive Summary</h3>\n<p>This report contains detected cost leakages, AI-powered root cause classifications, and recommended corrective adjustments.</p>\n\n<h3>Total Estimated Leakage Amount</h3>\n<p><strong>${{ $('Aggregate Findings Report').first().json.totalLeakageAmount }}</strong></p>\n\n<h3>Breakdown by Severity Level</h3>\n<ul>\n<li><strong>High Severity:</strong> {{ $('Aggregate Findings Report').first().json.highSeverityCount }} cases - ${{ $('Aggregate Findings Report').first().json.highSeverityAmount }}</li>\n<li><strong>Medium Severity:</strong> {{ $('Aggregate Findings Report').first().json.mediumSeverityCount }} cases - ${{ $('Aggregate Findings Report').first().json.mediumSeverityAmount }}</li>\n<li><strong>Low Severity:</strong> {{ $('Aggregate Findings Report').first().json.lowSeverityCount }} cases - ${{ $('Aggregate Findings Report').first().json.lowSeverityAmount }}</li>\n</ul>\n\n<h3>Detected Leakages</h3>\n<p>{{ $('Aggregate Findings Report').first().json.leakageSummary }}</p>\n\n<h3>AI Root Cause Classifications</h3>\n<p>{{ $('Aggregate Findings Report').first().json.aiClassifications }}</p>\n\n<h3>Corrective Adjustments</h3>\n<p>{{ $('Aggregate Findings Report').first().json.correctiveAdjustments }}</p>\n\n<hr>\n<p><em>This report was generated automatically by the Enterprise Claims Cost Leakage Detection system.</em></p>",
        "options": {},
        "subject": "=Claims Cost Leakage Detection Report - {{ $today.toFormat('yyyy-MM-dd') }}",
        "toEmail": "={{ $('Workflow Configuration').first().json.reportRecipients }}",
        "fromEmail": "<__PLACEHOLDER_VALUE__Sender email address__>"
      },
      "typeVersion": 2.1
    },
    {
      "id": "e3c013b5-23c3-4d93-859f-0514a8aaabf1",
      "name": "No Leakage Found",
      "type": "n8n-nodes-base.set",
      "position": [
        -224,
        416
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "id-1",
              "name": "status",
              "type": "string",
              "value": "No cost leakage detected"
            },
            {
              "id": "id-2",
              "name": "analysisDate",
              "type": "string",
              "value": "={{ $today.toFormat('yyyy-MM-dd') }}"
            },
            {
              "id": "id-3",
              "name": "message",
              "type": "string",
              "value": "All claims within acceptable parameters"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "e4b2599f-7c97-4bfa-b1c6-6c58248d7c8f",
      "name": "Split Anomalies Into Items",
      "type": "n8n-nodes-base.splitOut",
      "position": [
        -224,
        224
      ],
      "parameters": {
        "options": {},
        "fieldToSplitOut": "anomalies"
      },
      "typeVersion": 1
    },
    {
      "id": "0637d0b0-5ee3-4f9e-849d-191cf818b066",
      "name": "Fetch Vendor History",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        0,
        0
      ],
      "parameters": {
        "url": "={{ $('Workflow Configuration').first().json.vendorApiUrl }}",
        "options": {},
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "vendorId",
              "value": "={{ $json.vendorId }}"
            },
            {
              "name": "lookbackDays",
              "value": "90"
            }
          ]
        }
      },
      "typeVersion": 4.3
    },
    {
      "id": "fa82569f-2364-4d7e-afe9-fe962f4cdeda",
      "name": "Fetch Policy Rules",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        0,
        288
      ],
      "parameters": {
        "url": "={{ $('Workflow Configuration').first().json.policyApiUrl }}",
        "options": {},
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "claimType",
              "value": "={{ $json.claimType }}"
            },
            {
              "name": "policyId",
              "value": "={{ $json.policyId }}"
            }
          ]
        }
      },
      "typeVersion": 4.3
    },
    {
      "id": "f60163aa-caa5-4d91-b8da-709976295c11",
      "name": "Merge Enrichment Data",
      "type": "n8n-nodes-base.merge",
      "position": [
        224,
        80
      ],
      "parameters": {
        "mode": "combine",
        "options": {},
        "fieldsToMatchString": "claimId"
      },
      "typeVersion": 3.2
    },
    {
      "id": "253cfd89-b7d8-457c-82b9-e7f4ccad05ea",
      "name": "Route By Severity",
      "type": "n8n-nodes-base.switch",
      "position": [
        1136,
        176
      ],
      "parameters": {
        "rules": {
          "values": [
            {
              "outputKey": "CRITICAL",
              "conditions": {
                "options": {
                  "leftValue": "",
                  "caseSensitive": false,
                  "typeValidation": "loose"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.severityLevel }}",
                    "rightValue": "CRITICAL"
                  }
                ]
              },
              "renameOutput": true
            },
            {
              "outputKey": "HIGH",
              "conditions": {
                "options": {
                  "leftValue": "",
                  "caseSensitive": false,
                  "typeValidation": "loose"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.severityLevel }}",
                    "rightValue": "HIGH"
                  }
                ]
              },
              "renameOutput": true
            },
            {
              "outputKey": "MEDIUM",
              "conditions": {
                "options": {
                  "leftValue": "",
                  "caseSensitive": false,
                  "typeValidation": "loose"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.severityLevel }}",
                    "rightValue": "MEDIUM"
                  }
                ]
              },
              "renameOutput": true
            },
            {
              "outputKey": "LOW",
              "conditions": {
                "options": {
                  "leftValue": "",
                  "caseSensitive": false,
                  "typeValidation": "loose"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.severityLevel }}",
                    "rightValue": "LOW"
                  }
                ]
              },
              "renameOutput": true
            }
          ]
        },
        "options": {}
      },
      "typeVersion": 3.4
    },
    {
      "id": "46b092fd-06f4-4ece-ba02-bde5a345f210",
      "name": "Check Historical Patterns",
      "type": "n8n-nodes-base.postgres",
      "position": [
        0,
        480
      ],
      "parameters": {
        "query": "SELECT COUNT(*) as pattern_count, AVG(leakage_amount) as avg_amount FROM claim_leakage_history WHERE claim_id = $1 OR vendor_id = $2 AND detected_date > NOW() - INTERVAL '90 days'",
        "options": {
          "queryReplacement": "={{ $json.claimId }},={{ $json.vendorId }}"
        },
        "operation": "executeQuery"
      },
      "typeVersion": 2.6
    },
    {
      "id": "8f9c2004-f151-4e1f-8ca9-5aa3ae886ca6",
      "name": "Calculator Tool",
      "type": "@n8n/n8n-nodes-langchain.toolCalculator",
      "position": [
        672,
        336
      ],
      "parameters": {},
      "typeVersion": 1
    },
    {
      "id": "6b3b7464-12ae-430f-b41d-f63847dfb3d2",
      "name": "Calculate Risk Score",
      "type": "n8n-nodes-base.code",
      "position": [
        224,
        480
      ],
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "// Calculate risk score based on multiple weighted factors\nconst item = $input.item.json;\n\n// Extract input data\nconst historicalFrequency = item.historicalFrequency || item.pattern_frequency || 0;\nconst leakageAmount = item.leakageAmount || item.amount || item.adjustment_amount || 0;\nconst vendorReputation = item.vendorReputation || item.vendor_reputation_score || 50; // Default to neutral\nconst policyViolationSeverity = item.policyViolationSeverity || item.policy_violation_severity || 0;\n\n// Define weights\nconst WEIGHT_HISTORICAL = 0.3;\nconst WEIGHT_AMOUNT = 0.4;\nconst WEIGHT_VENDOR = 0.2;\nconst WEIGHT_POLICY = 0.1;\n\n// Normalize historical frequency (assume 0-10 scale, normalize to 0-100)\nconst normalizedHistorical = Math.min((historicalFrequency / 10) * 100, 100);\n\n// Normalize leakage amount (assume $0-$50000 scale, normalize to 0-100)\nconst normalizedAmount = Math.min((Math.abs(leakageAmount) / 50000) * 100, 100);\n\n// Vendor reputation is already 0-100, but invert it (lower reputation = higher risk)\nconst normalizedVendor = 100 - vendorReputation;\n\n// Policy violation severity (assume 0-10 scale, normalize to 0-100)\nconst normalizedPolicy = Math.min((policyViolationSeverity / 10) * 100, 100);\n\n// Calculate weighted risk score\nconst riskScore = Math.round(\n  (normalizedHistorical * WEIGHT_HISTORICAL) +\n  (normalizedAmount * WEIGHT_AMOUNT) +\n  (normalizedVendor * WEIGHT_VENDOR) +\n  (normalizedPolicy * WEIGHT_POLICY)\n);\n\n// Determine risk category\nlet riskCategory;\nif (riskScore >= 80) {\n  riskCategory = 'CRITICAL';\n} else if (riskScore >= 60) {\n  riskCategory = 'HIGH';\n} else if (riskScore >= 40) {\n  riskCategory = 'MEDIUM';\n} else {\n  riskCategory = 'LOW';\n}\n\n// Return enriched data with risk score and category\nreturn {\n  ...item,\n  riskScore: riskScore,\n  riskCategory: riskCategory,\n  riskFactors: {\n    historicalFrequency: normalizedHistorical,\n    leakageAmount: normalizedAmount,\n    vendorReputation: normalizedVendor,\n    policyViolation: normalizedPolicy\n  },\n  calculatedAt: new Date().toISOString()\n};"
      },
      "typeVersion": 2
    },
    {
      "id": "d9d7fae4-fae5-4ccf-882f-cbc6fa1818ef",
      "name": "Check If Requires Escalation",
      "type": "n8n-nodes-base.if",
      "position": [
        1360,
        160
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "leftValue": "",
            "caseSensitive": false,
            "typeValidation": "loose"
          },
          "combinator": "or",
          "conditions": [
            {
              "id": "id-1",
              "operator": {
                "type": "string",
                "operation": "equals"
              },
              "leftValue": "={{ $json.severityLevel }}",
              "rightValue": "CRITICAL"
            },
            {
              "id": "id-2",
              "operator": {
                "type": "number",
                "operation": "gt"
              },
              "leftValue": "={{ $json.estimatedLeakageAmount }}",
              "rightValue": "={{ $('Workflow Configuration').first().json.criticalThreshold }}"
            }
          ]
        }
      },
      "typeVersion": 2.3
    },
    {
      "id": "d522f9d0-868d-4ca6-9855-503a8f27e253",
      "name": "Send Escalation Alert",
      "type": "n8n-nodes-base.emailSend",
      "position": [
        1584,
        352
      ],
      "parameters": {
        "html": "=<h1 style=\"color: #d32f2f;\">\ud83d\udea8 URGENT: Critical Claims Leakage Alert</h1>\n\n<p><strong>Alert Generated:</strong> {{ $now.toFormat('yyyy-MM-dd HH:mm:ss') }}</p>\n\n<div style=\"background-color: #ffebee; border-left: 4px solid #d32f2f; padding: 15px; margin: 20px 0;\">\n  <h2>Critical Leakage Details</h2>\n  <ul>\n    <li><strong>Claim ID:</strong> {{ $json.claim_id }}</li>\n    <li><strong>Leakage Amount:</strong> ${{ $json.adjustment_amount }}</li>\n    <li><strong>Root Cause:</strong> {{ $json.root_cause }}</li>\n    <li><strong>Confidence Score:</strong> {{ $json.confidence_score }}%</li>\n    <li><strong>Priority Level:</strong> {{ $json.priority_level }}</li>\n  </ul>\n</div>\n\n<h3>Recommended Immediate Actions</h3>\n<ol>\n  <li>{{ $json.recommended_action }}</li>\n  <li>Review claim documentation and supporting evidence</li>\n  <li>Contact vendor/provider for clarification if applicable</li>\n  <li>Initiate corrective adjustment process</li>\n  <li>Document findings in claims management system</li>\n</ol>\n\n<h3>Justification</h3>\n<p>{{ $json.justification }}</p>\n\n<hr>\n<p style=\"color: #666; font-size: 12px;\"><em>This is an automated escalation alert. Please respond within 24 hours.</em></p>",
        "options": {},
        "subject": "URGENT: Critical Claims Leakage Detected - Immediate Action Required",
        "toEmail": "={{ $('Workflow Configuration').first().json.escalationRecipients }}",
        "fromEmail": "<__PLACEHOLDER_VALUE__Sender email address__>"
      },
      "typeVersion": 2.1
    },
    {
      "id": "bdc91095-bca4-4ab7-b0f3-a0ea82d8f832",
      "name": "Aggregate By Vendor",
      "type": "n8n-nodes-base.aggregate",
      "position": [
        1360,
        352
      ],
      "parameters": {
        "options": {},
        "fieldsToAggregate": {
          "fieldToAggregate": [
            {
              "fieldToAggregate": "vendorId"
            },
            {
              "fieldToAggregate": "leakageAmount"
            }
          ]
        }
      },
      "typeVersion": 1
    },
    {
      "id": "209304fc-26c2-48a0-841a-26925b36aff2",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1360,
        -224
      ],
      "parameters": {
        "width": 1056,
        "height": 192,
        "content": "## How It Works\nThis workflow automates enterprise claims cost leakage detection by identifying overpayments, policy deviations, and pricing inconsistencies across claims data. It supports claims operations, finance, and audit teams by providing continuous, AI-driven monitoring without manual review. Claims data is ingested through parallel HTTP requests, including claim history, policy details, pricing rules, and enrichment data. Historical claim patterns feed calculator-based risk scoring to flag potential leakage scenarios. All data streams are consolidated and analyzed using GPT-4 with structured outputs to detect anomalies, quantify leakage risk, and recommend corrective adjustments. The workflow generates claim-level findings and routes outcomes by severity: high-risk leakage triggers immediate email and Slack alerts, while lower-risk issues are compiled into periodic audit and recovery reports."
      },
      "typeVersion": 1
    },
    {
      "id": "80543095-4be8-470c-b46a-d084e7b11569",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -272,
        -224
      ],
      "parameters": {
        "width": 464,
        "height": 192,
        "content": "\n## Setup Steps\n1. Configure HTTP nodes with competitor website APIs  \n2. Add OpenAI API key to Chat Model node for AI analysis  \n3. Connect Gmail account and set leadership distribution list  \n4. Integrate Slack workspace and configure strategy team  \n5. Adjust Schedule node timing for preferred monitoring frequency  "
      },
      "typeVersion": 1
    },
    {
      "id": "3aa8ec90-a09f-4ef0-b186-7d4f672ac42a",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        240,
        -368
      ],
      "parameters": {
        "color": 6,
        "width": 656,
        "height": 336,
        "content": "## Prerequisites\nOpenAI API key, competitor data source API access, vendor monitoring service credentials \n\n## Use Cases\nSaaS companies tracking competitor feature releases and pricing changes \n\n## Customization\nModify risk scoring formulas in Calculator nodes for industry-specific metrics \n\n## Benefits\nTransforms hours of manual competitor research into automated minutes-long cycles "
      },
      "typeVersion": 1
    },
    {
      "id": "e54ea7e6-6e5d-4d68-9f17-aa33e676af6c",
      "name": "Sticky Note3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1104,
        0
      ],
      "parameters": {
        "color": 7,
        "width": 848,
        "height": 656,
        "content": "## **Severity-Based Routing**\nHigh-severity findings trigger immediate Gmail and Slack alerts "
      },
      "typeVersion": 1
    },
    {
      "id": "ed1d8f67-a00a-405e-83b5-ec4955ca251f",
      "name": "Sticky Note4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        448,
        0
      ],
      "parameters": {
        "color": 7,
        "width": 608,
        "height": 672,
        "content": "## **Conditional Risk Scoring and AI Analysis**\nHistorical checks trigger risk scoring, and all intelligence is merged for GPT-4 analysis "
      },
      "typeVersion": 1
    },
    {
      "id": "46b9a636-8fcb-4516-91f8-269cfb46b8c9",
      "name": "Sticky Note5",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1376,
        -16
      ],
      "parameters": {
        "color": 7,
        "width": 1808,
        "height": 704,
        "content": "## **Parallel Data Collection**\nHTTP nodes fetch vendor history, enrichment data, and policy rules, while batch processing detects cost anomalies across competitors."
      },
      "typeVersion": 1
    }
  ],
  "active": false,
  "settings": {
    "availableInMCP": false,
    "executionOrder": "v1"
  },
  "versionId": "aa67bbc2-cb1d-4f21-9e30-c1c51fb9d722",
  "connections": {
    "OpenAI GPT-4": {
      "ai_languageModel": [
        [
          {
            "node": "AI Root Cause Classifier",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Calculator Tool": {
      "ai_tool": [
        [
          {
            "node": "AI Root Cause Classifier",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Route By Severity": {
      "main": [
        [
          {
            "node": "Check If Requires Escalation",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Aggregate By Vendor",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Aggregate By Vendor": {
      "main": [
        [
          {
            "node": "Aggregate Findings Report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Calculate Risk Score": {
      "main": [
        [
          {
            "node": "AI Root Cause Classifier",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Vendor History": {
      "main": [
        [
          {
            "node": "Merge Enrichment Data",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Merge Enrichment Data": {
      "main": [
        [
          {
            "node": "AI Root Cause Classifier",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Workflow Configuration": {
      "main": [
        [
          {
            "node": "Fetch Historical Claims Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI Root Cause Classifier": {
      "main": [
        [
          {
            "node": "Generate Corrective Adjustments",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Aggregate Findings Report": {
      "main": [
        [
          {
            "node": "Send Leakage Report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Historical Patterns": {
      "main": [
        [
          {
            "node": "Calculate Risk Score",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check If Leakage Detected": {
      "main": [
        [
          {
            "node": "AI Root Cause Classifier",
            "type": "main",
            "index": 0
          },
          {
            "node": "Split Anomalies Into Items",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "No Leakage Found",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split Anomalies Into Items": {
      "main": [
        [
          {
            "node": "Fetch Vendor History",
            "type": "main",
            "index": 0
          },
          {
            "node": "Fetch Policy Rules",
            "type": "main",
            "index": 0
          },
          {
            "node": "Check Historical Patterns",
            "type": "main",
            "index": 0
          },
          {
            "node": "Merge Enrichment Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check If Requires Escalation": {
      "main": [
        [
          {
            "node": "Send Escalation Alert",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Aggregate Findings Report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Classification Output Parser": {
      "ai_outputParser": [
        [
          {
            "node": "AI Root Cause Classifier",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Historical Claims Data": {
      "main": [
        [
          {
            "node": "Detect Cost Leakage Anomalies",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Detect Cost Leakage Anomalies": {
      "main": [
        [
          {
            "node": "Check If Leakage Detected",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Daily Claims Analysis Schedule": {
      "main": [
        [
          {
            "node": "Workflow Configuration",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate Corrective Adjustments": {
      "main": [
        [
          {
            "node": "Aggregate Findings Report",
            "type": "main",
            "index": 0
          },
          {
            "node": "Route By Severity",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}