AutomationFlowsAI & RAG › Manage Healthcare Resource Allocation and Conflicts with Anthropic Claude

Manage Healthcare Resource Allocation and Conflicts with Anthropic Claude

ByCheng Siong Chin @cschin on n8n.io

This workflow automates end-to-end marketing campaign management for digital marketing teams and agencies executing multi-channel strategies. It solves the complex challenge of coordinating personalized content across email, social media, and advertising platforms while…

Webhook trigger★★★★★ complexityAI-powered43 nodesAgentAnthropic ChatOutput Parser StructuredHTTP RequestAgent ToolTool Code
AI & RAG Trigger: Webhook Nodes: 43 Complexity: ★★★★★ AI nodes: yes Added:

This workflow corresponds to n8n.io template #12794 — we link there as the canonical source.

This workflow follows the Agent → Agenttool recipe pattern — see all workflows that pair these two integrations.

The workflow JSON

Copy or download the full n8n JSON below. Paste it into a new n8n workflow, add your credentials, activate. Full import guide →

Download .json
{
  "id": "e7oxIwTmsvtAoqeS",
  "name": "AI Operations Resource Allocation and Conflict Resolution Agent",
  "tags": [],
  "nodes": [
    {
      "id": "da17263e-f327-4445-8b2e-f138f6b26be7",
      "name": "Resource Request Webhook",
      "type": "n8n-nodes-base.webhook",
      "position": [
        5376,
        2096
      ],
      "parameters": {
        "path": "resource-allocation",
        "options": {},
        "httpMethod": "POST",
        "responseMode": "responseNode"
      },
      "typeVersion": 2.1
    },
    {
      "id": "1f3ba3b6-3faf-4bef-8f04-579630ace844",
      "name": "Continuous Monitoring Schedule",
      "type": "n8n-nodes-base.scheduleTrigger",
      "position": [
        5376,
        2288
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "minutes"
            }
          ]
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "0c7894db-bb7a-478b-9ab2-a6059978ea22",
      "name": "Workflow Configuration",
      "type": "n8n-nodes-base.set",
      "position": [
        5600,
        2192
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "id-1",
              "name": "priorityRules",
              "type": "object",
              "value": "{ \"highPriorityThreshold\": 0.8, \"scoringCriteria\": [\"urgency\", \"business_impact\", \"resource_availability\"] }"
            },
            {
              "id": "id-2",
              "name": "optimizationStrategy",
              "type": "string",
              "value": "maximize_utilization_minimize_conflicts"
            },
            {
              "id": "id-3",
              "name": "conflictThreshold",
              "type": "number",
              "value": 0.7
            },
            {
              "id": "id-4",
              "name": "utilizationDataSource",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Utilization API endpoint or database connection__>"
            },
            {
              "id": "id-5",
              "name": "historicalDataSource",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Historical demand API endpoint or database__>"
            },
            {
              "id": "id-6",
              "name": "eventsDataSource",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Events calendar API endpoint__>"
            },
            {
              "id": "id-7",
              "name": "humanReviewEndpoint",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Human review system webhook URL__>"
            },
            {
              "id": "id-8",
              "name": "slaDataSource",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__SLA policies API endpoint or database__>"
            },
            {
              "id": "id-9",
              "name": "auditSystemEndpoint",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Audit logging system webhook URL__>"
            },
            {
              "id": "id-10",
              "name": "stakeholderNotificationEndpoint",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Stakeholder notification API endpoint__>"
            },
            {
              "id": "id-11",
              "name": "riskScoreWeights",
              "type": "object",
              "value": "{ \"urgency\": 0.35, \"resourceAvailability\": 0.25, \"conflictSeverity\": 0.20, \"historicalDemand\": 0.15, \"slaCompliance\": 0.05 }"
            }
          ]
        },
        "includeOtherFields": true
      },
      "typeVersion": 3.4
    },
    {
      "id": "326df0fc-2f12-4ae4-b512-6dcec9c4ebf9",
      "name": "Fetch Current Utilization Data",
      "type": "n8n-nodes-base.code",
      "position": [
        5824,
        2000
      ],
      "parameters": {
        "jsCode": "// Fetch current utilization data from configured data source\n// This code retrieves real-time resource availability and occupancy information\n\nconst configData = $('Workflow Configuration').first().json;\nconst dataSourceUrl = configData.utilizationDataSourceUrl || 'https://api.example.com/utilization';\n\n// In production, this would make an actual API call to your data source\n// For now, we'll structure the expected data format\n\n// Example API call (uncomment and modify for actual implementation):\n// const response = await $http.get(dataSourceUrl);\n// const utilizationData = response.data;\n\n// Mock structured utilization data\nconst utilizationData = {\n  timestamp: new Date().toISOString(),\n  beds: {\n    total: 100,\n    occupied: 78,\n    available: 22,\n    occupancyRate: 0.78,\n    byDepartment: [\n      { department: 'ICU', total: 20, occupied: 18, available: 2 },\n      { department: 'Emergency', total: 30, occupied: 25, available: 5 },\n      { department: 'General', total: 50, occupied: 35, available: 15 }\n    ]\n  },\n  rooms: {\n    total: 80,\n    occupied: 62,\n    available: 18,\n    occupancyRate: 0.775,\n    byType: [\n      { type: 'Operating Room', total: 10, occupied: 8, available: 2 },\n      { type: 'Examination Room', total: 30, occupied: 24, available: 6 },\n      { type: 'Treatment Room', total: 40, occupied: 30, available: 10 }\n    ]\n  },\n  equipment: {\n    ventilators: { total: 25, inUse: 20, available: 5, status: 'high_demand' },\n    monitors: { total: 100, inUse: 75, available: 25, status: 'normal' },\n    infusionPumps: { total: 150, inUse: 120, available: 30, status: 'normal' },\n    wheelchairs: { total: 50, inUse: 35, available: 15, status: 'normal' }\n  },\n  staff: {\n    nurses: { scheduled: 45, present: 43, utilizationRate: 0.956 },\n    doctors: { scheduled: 20, present: 19, utilizationRate: 0.95 },\n    technicians: { scheduled: 15, present: 14, utilizationRate: 0.933 }\n  },\n  alerts: [\n    { type: 'warning', resource: 'ventilators', message: 'Ventilator availability below 25%' },\n    { type: 'info', resource: 'ICU beds', message: 'ICU approaching capacity' }\n  ]\n};\n\nreturn [{ json: utilizationData }];"
      },
      "typeVersion": 2
    },
    {
      "id": "f4374c94-99c6-4174-b038-a3211a983ee1",
      "name": "Fetch Historical Demand Trends",
      "type": "n8n-nodes-base.code",
      "position": [
        5824,
        2192
      ],
      "parameters": {
        "jsCode": "// Fetch historical demand trends from the configured data source\n// This code retrieves patterns, peak usage times, seasonal variations, and demand forecasts\n\nconst config = $('Workflow Configuration').item.json;\n\n// Simulate fetching historical demand data\n// In production, this would connect to your actual data source (database, API, etc.)\nconst historicalData = {\n  patterns: [\n    {\n      type: 'daily',\n      description: 'Higher demand during business hours (9 AM - 5 PM)',\n      confidence: 0.92\n    },\n    {\n      type: 'weekly',\n      description: 'Peak demand on Tuesdays and Wednesdays',\n      confidence: 0.85\n    },\n    {\n      type: 'monthly',\n      description: 'Increased demand at month-end for reporting',\n      confidence: 0.78\n    }\n  ],\n  peakUsageTimes: [\n    {\n      timeRange: '10:00-11:00',\n      averageUtilization: 87,\n      resourceType: 'compute'\n    },\n    {\n      timeRange: '14:00-15:00',\n      averageUtilization: 82,\n      resourceType: 'compute'\n    },\n    {\n      timeRange: '09:00-10:00',\n      averageUtilization: 75,\n      resourceType: 'storage'\n    }\n  ],\n  seasonalVariations: [\n    {\n      period: 'Q4',\n      variation: '+35%',\n      reason: 'Year-end processing and reporting'\n    },\n    {\n      period: 'Q1',\n      variation: '-15%',\n      reason: 'Post-holiday slowdown'\n    },\n    {\n      period: 'Summer months',\n      variation: '-10%',\n      reason: 'Vacation period'\n    }\n  ],\n  demandForecasts: [\n    {\n      timeframe: 'next_7_days',\n      predictedIncrease: 12,\n      confidence: 0.88,\n      drivers: ['Upcoming product launch', 'Marketing campaign']\n    },\n    {\n      timeframe: 'next_30_days',\n      predictedIncrease: 25,\n      confidence: 0.75,\n      drivers: ['Seasonal trend', 'New client onboarding']\n    },\n    {\n      timeframe: 'next_90_days',\n      predictedIncrease: 40,\n      confidence: 0.65,\n      drivers: ['Business expansion', 'Infrastructure migration']\n    }\n  ],\n  dataSource: config?.dataSource || 'historical_metrics_db',\n  lastUpdated: new Date().toISOString(),\n  analysisWindow: '90_days'\n};\n\nreturn [{ json: historicalData }];"
      },
      "typeVersion": 2
    },
    {
      "id": "62c036fa-d61a-4ce5-b1b5-6c76ce3e9c21",
      "name": "Fetch Upcoming Events",
      "type": "n8n-nodes-base.code",
      "position": [
        5824,
        2384
      ],
      "parameters": {
        "jsCode": "// Fetch upcoming events from the configured data source\n// Returns scheduled procedures, maintenance windows, expected admissions, and resource reservations\n\nconst items = $input.all();\n\n// Get configuration from Workflow Configuration node\nconst config = $('Workflow Configuration').first().json;\n\n// Simulated upcoming events data\n// In production, this would fetch from your actual data source (API, database, etc.)\nconst upcomingEvents = {\n  scheduledProcedures: [\n    {\n      id: 'PROC-001',\n      type: 'Surgery',\n      scheduledTime: new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString(), // 2 hours from now\n      estimatedDuration: 180, // minutes\n      requiredResources: ['OR-1', 'Surgeon', 'Anesthesiologist', 'Nurse-2']\n    },\n    {\n      id: 'PROC-002',\n      type: 'Imaging',\n      scheduledTime: new Date(Date.now() + 4 * 60 * 60 * 1000).toISOString(), // 4 hours from now\n      estimatedDuration: 45,\n      requiredResources: ['MRI-1', 'Radiologist', 'Technician-1']\n    }\n  ],\n  maintenanceWindows: [\n    {\n      id: 'MAINT-001',\n      equipment: 'CT-Scanner-2',\n      startTime: new Date(Date.now() + 6 * 60 * 60 * 1000).toISOString(), // 6 hours from now\n      endTime: new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString(), // 8 hours from now\n      impact: 'Equipment unavailable'\n    }\n  ],\n  expectedAdmissions: [\n    {\n      id: 'ADM-001',\n      expectedTime: new Date(Date.now() + 1 * 60 * 60 * 1000).toISOString(), // 1 hour from now\n      department: 'Emergency',\n      estimatedStayDuration: 240, // minutes\n      requiredResources: ['Bed-ER-5', 'Nurse-1', 'Physician']\n    },\n    {\n      id: 'ADM-002',\n      expectedTime: new Date(Date.now() + 3 * 60 * 60 * 1000).toISOString(), // 3 hours from now\n      department: 'ICU',\n      estimatedStayDuration: 1440, // minutes (24 hours)\n      requiredResources: ['Bed-ICU-3', 'Nurse-2', 'Intensivist']\n    }\n  ],\n  resourceReservations: [\n    {\n      id: 'RES-001',\n      resourceId: 'Conference-Room-A',\n      startTime: new Date(Date.now() + 5 * 60 * 60 * 1000).toISOString(), // 5 hours from now\n      endTime: new Date(Date.now() + 7 * 60 * 60 * 1000).toISOString(), // 7 hours from now\n      purpose: 'Staff Training',\n      reservedBy: 'HR Department'\n    }\n  ],\n  timestamp: new Date().toISOString(),\n  dataSource: config?.eventDataSource || 'simulated'\n};\n\nreturn [\n  {\n    json: upcomingEvents\n  }\n];"
      },
      "typeVersion": 2
    },
    {
      "id": "dfead5dd-c125-4b0d-9b22-a0802d24a264",
      "name": "Merge Context Data",
      "type": "n8n-nodes-base.set",
      "position": [
        6048,
        2192
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "id-1",
              "name": "currentUtilization",
              "type": "object",
              "value": "={{ $('Fetch Current Utilization Data').item.json }}"
            },
            {
              "id": "id-2",
              "name": "historicalTrends",
              "type": "object",
              "value": "={{ $('Fetch Historical Demand Trends').item.json }}"
            },
            {
              "id": "id-3",
              "name": "upcomingEvents",
              "type": "object",
              "value": "={{ $('Fetch Upcoming Events').item.json }}"
            },
            {
              "id": "id-4",
              "name": "requestDetails",
              "type": "object",
              "value": "={{ $('Workflow Configuration').item.json }}"
            },
            {
              "id": "id-5",
              "name": "timestamp",
              "type": "string",
              "value": "={{ $now.toISO() }}"
            }
          ]
        },
        "includeOtherFields": true
      },
      "typeVersion": 3.4
    },
    {
      "id": "b39acc3d-5e8c-4110-84d9-d18ac06784cc",
      "name": "Resource Allocation AI Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        7880,
        2192
      ],
      "parameters": {
        "text": "=Evaluate this resource allocation request: {{ $json.requestDetails }}. Current utilization: {{ $json.currentUtilization }}. Historical trends: {{ $json.historicalTrends }}. Upcoming events: {{ $json.upcomingEvents }}. Priority rules: {{ $json.priorityRules }}. Optimization strategy: {{ $json.optimizationStrategy }}.",
        "options": {
          "systemMessage": "You are an AI operations intelligence agent specialized in resource allocation and conflict resolution for healthcare facilities.\n\nYour responsibilities:\n1. Analyze resource requests (beds, rooms, shared equipment) against real-time utilization data\n2. Apply priority rules based on patient acuity, procedure urgency, and operational policies\n3. Evaluate historical demand trends to predict resource availability\n4. Consider upcoming events and scheduled procedures\n5. Identify conflicts and bottlenecks in resource allocation\n6. Apply optimization strategies to maximize utilization while minimizing conflicts\n7. Generate explainable decisions with reasoning and confidence scores\n8. Flag high-risk or complex scenarios for human review\n\nDecision criteria:\n- Patient safety and clinical priority always take precedence\n- Optimize for overall system efficiency\n- Balance immediate needs with predicted demand\n- Minimize resource conflicts and bottlenecks\n- Provide transparent reasoning for all decisions\n\nOutput a structured decision with: allocation status, assigned resources, conflict indicators, confidence score, reasoning, and human review flag."
        },
        "promptType": "define",
        "hasOutputParser": true
      },
      "typeVersion": 3.1
    },
    {
      "id": "60dcecf9-2a3b-4704-a705-a8fd0b302ed6",
      "name": "Anthropic Claude Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatAnthropic",
      "position": [
        7168,
        2416
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "id",
          "value": "claude-3-5-sonnet-20241022"
        },
        "options": {}
      },
      "credentials": {
        "anthropicApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "7b60d46c-3a00-49b1-b187-56fb66b5f1ca",
      "name": "Structured Decision Output",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        8480,
        2352
      ],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"allocationStatus\": {\n\t\t\t\"type\": \"string\",\n\t\t\t\"description\": \"approved, denied, or pending_review\"\n\t\t},\n\t\t\"assignedResources\": {\n\t\t\t\"type\": \"object\",\n\t\t\t\"description\": \"Details of allocated beds, rooms, or equipment\"\n\t\t},\n\t\t\"conflictIndicators\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"description\": \"List of identified conflicts or bottlenecks\"\n\t\t},\n\t\t\"confidenceScore\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"description\": \"Confidence level from 0 to 1\"\n\t\t},\n\t\t\"reasoning\": {\n\t\t\t\"type\": \"string\",\n\t\t\t\"description\": \"Detailed explanation of the decision\"\n\t\t},\n\t\t\"requiresHumanReview\": {\n\t\t\t\"type\": \"boolean\",\n\t\t\t\"description\": \"Flag indicating if human review is needed\"\n\t\t},\n\t\t\"alternativeOptions\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"description\": \"Alternative resource allocation suggestions if applicable\"\n\t\t},\n\t\t\"estimatedAvailability\": {\n\t\t\t\"type\": \"string\",\n\t\t\t\"description\": \"When resources will become available if currently unavailable\"\n\t\t}\n\t}\n}"
      },
      "typeVersion": 1.3
    },
    {
      "id": "6391e5a9-da2b-4e8a-a552-c7c0c573349b",
      "name": "Check for Conflicts",
      "type": "n8n-nodes-base.if",
      "position": [
        8688,
        2528
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "leftValue": "",
            "caseSensitive": false,
            "typeValidation": "loose"
          },
          "combinator": "or",
          "conditions": [
            {
              "id": "id-1",
              "operator": {
                "type": "boolean",
                "operation": "true"
              },
              "leftValue": "={{ $('Resource Allocation AI Agent').item.json.requiresHumanReview }}"
            },
            {
              "id": "id-2",
              "operator": {
                "type": "number",
                "operation": "lt"
              },
              "leftValue": "={{ $('Resource Allocation AI Agent').item.json.confidenceScore }}",
              "rightValue": "={{ $('Workflow Configuration').item.json.conflictThreshold }}"
            }
          ]
        }
      },
      "typeVersion": 2.3
    },
    {
      "id": "b6269646-5e43-4421-a3a5-a1e5df9ff068",
      "name": "Flag for Human Review",
      "type": "n8n-nodes-base.set",
      "position": [
        8928,
        2336
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "id-1",
              "name": "reviewStatus",
              "type": "string",
              "value": "flagged_for_human_review"
            },
            {
              "id": "id-2",
              "name": "flaggedAt",
              "type": "string",
              "value": "={{ $now.toISO() }}"
            },
            {
              "id": "id-3",
              "name": "reviewPriority",
              "type": "string",
              "value": "={{ $json.conflictSeverity === 'high' || $json.confidenceScore < 0.7 ? 'urgent' : $json.conflictSeverity === 'medium' ? 'high' : 'normal' }}"
            },
            {
              "id": "id-4",
              "name": "reviewReason",
              "type": "string",
              "value": "={{ 'Resource allocation conflict detected with ' + ($json.conflictSeverity || 'unknown') + ' severity. Confidence score: ' + ($json.confidenceScore || 'N/A') + '. Human review required for final decision.' }}"
            }
          ]
        },
        "includeOtherFields": true
      },
      "typeVersion": 3.4
    },
    {
      "id": "dafa186e-9e5d-46e7-a227-0cd408b45885",
      "name": "Send to Human Review System",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        9152,
        2416
      ],
      "parameters": {
        "url": "={{ $('Workflow Configuration').item.json.humanReviewEndpoint }}",
        "method": "POST",
        "options": {},
        "sendBody": true,
        "sendHeaders": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "decision",
              "value": "={{ $('Resource Allocation AI Agent').item.json }}"
            },
            {
              "name": "reviewFlags",
              "value": "={{ $('Flag for Human Review').item.json }}"
            },
            {
              "name": "contextData",
              "value": "={{ $('Merge Context Data').item.json }}"
            },
            {
              "name": "timestamp",
              "value": "={{ $now.toISO() }}"
            }
          ]
        },
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        }
      },
      "typeVersion": 4.3
    },
    {
      "id": "1382ebc7-0cb3-4c69-b66e-d48e729da448",
      "name": "Format Final Decision",
      "type": "n8n-nodes-base.set",
      "position": [
        10032,
        2496
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "id-1",
              "name": "decisionId",
              "type": "string",
              "value": "={{ $execution.id }}-{{ $itemIndex }}"
            },
            {
              "id": "id-2",
              "name": "processedAt",
              "type": "string",
              "value": "={{ $now.toISO() }}"
            },
            {
              "id": "id-3",
              "name": "workflowVersion",
              "type": "string",
              "value": "1.0"
            },
            {
              "id": "id-4",
              "name": "executionMode",
              "type": "string",
              "value": "={{ $('Resource Request Webhook').item.json ? 'webhook' : 'schedule' }}"
            }
          ]
        },
        "includeOtherFields": true
      },
      "typeVersion": 3.4
    },
    {
      "id": "6c901ad4-3053-43a6-9c85-b49be909641a",
      "name": "Return Decision to Caller",
      "type": "n8n-nodes-base.respondToWebhook",
      "position": [
        10720,
        2352
      ],
      "parameters": {
        "options": {},
        "respondWith": "json",
        "responseBody": "={{ $json }}"
      },
      "typeVersion": 1.5
    },
    {
      "id": "8d08255b-75ed-49f2-a5bc-087a53fe0454",
      "name": "Route by Request Type",
      "type": "n8n-nodes-base.switch",
      "position": [
        8688,
        2672
      ],
      "parameters": {
        "rules": {
          "values": [
            {
              "outputKey": "High Priority",
              "conditions": {
                "options": {
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.allocationStatus }}",
                    "rightValue": "approved"
                  },
                  {
                    "operator": {
                      "type": "number",
                      "operation": "gt"
                    },
                    "leftValue": "={{ $json.priorityScore }}",
                    "rightValue": 80
                  }
                ]
              },
              "renameOutput": true
            },
            {
              "outputKey": "Standard Priority",
              "conditions": {
                "options": {
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.allocationStatus }}",
                    "rightValue": "approved"
                  },
                  {
                    "operator": {
                      "type": "number",
                      "operation": "gte"
                    },
                    "leftValue": "={{ $json.priorityScore }}",
                    "rightValue": 50
                  },
                  {
                    "operator": {
                      "type": "number",
                      "operation": "lte"
                    },
                    "leftValue": "={{ $json.priorityScore }}",
                    "rightValue": 80
                  }
                ]
              },
              "renameOutput": true
            },
            {
              "outputKey": "Low Priority",
              "conditions": {
                "options": {
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.allocationStatus }}",
                    "rightValue": "approved"
                  },
                  {
                    "operator": {
                      "type": "number",
                      "operation": "lt"
                    },
                    "leftValue": "={{ $json.priorityScore }}",
                    "rightValue": 50
                  }
                ]
              },
              "renameOutput": true
            }
          ]
        },
        "options": {
          "fallbackOutput": "extra"
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "0b7ef9f0-40b7-4d79-a3d2-a0911e43a256",
      "name": "Capacity Forecasting Agent",
      "type": "@n8n/n8n-nodes-langchain.agentTool",
      "position": [
        7296,
        2416
      ],
      "parameters": {
        "text": "={{ $fromAI(\"forecast_parameters\") }}",
        "options": {
          "systemMessage": "You are a capacity forecasting specialist. Analyze historical demand patterns, seasonal variations, and upcoming events to predict resource availability. Provide forecasts with confidence intervals and identify potential capacity shortfalls."
        },
        "hasOutputParser": true,
        "toolDescription": "Predicts future resource capacity and availability based on historical trends and upcoming events"
      },
      "typeVersion": 3
    },
    {
      "id": "bb2cd5f4-1180-40cd-a2bb-efd37b65fd51",
      "name": "Conflict Resolution Agent",
      "type": "@n8n/n8n-nodes-langchain.agentTool",
      "position": [
        7584,
        2416
      ],
      "parameters": {
        "text": "={{ $fromAI('conflict_details') }}",
        "options": {
          "systemMessage": "You are a conflict resolution specialist. Analyze resource allocation conflicts, identify root causes, and propose optimal resolution strategies that balance competing priorities while maintaining operational efficiency."
        },
        "hasOutputParser": true,
        "toolDescription": "Analyzes resource conflicts and proposes resolution strategies"
      },
      "typeVersion": 3
    },
    {
      "id": "434dc726-69c4-4f2b-a0c0-a83e216e0686",
      "name": "Priority Scoring Agent",
      "type": "@n8n/n8n-nodes-langchain.agentTool",
      "position": [
        7872,
        2416
      ],
      "parameters": {
        "text": "={{ $fromAI(\"request_details\") }}",
        "options": {
          "systemMessage": "You are a priority scoring specialist. Evaluate resource requests based on urgency, business impact, patient safety, SLA requirements, and operational policies. Assign weighted priority scores with detailed justification."
        },
        "hasOutputParser": true,
        "toolDescription": "Calculates priority scores for resource requests based on multiple criteria"
      },
      "typeVersion": 3
    },
    {
      "id": "5ef9142a-160f-4e2b-8d3a-68145829e116",
      "name": "Forecasting Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatAnthropic",
      "position": [
        7264,
        2624
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "id",
          "value": "claude-3-5-sonnet-20241022"
        },
        "options": {}
      },
      "credentials": {
        "anthropicApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "2a3f930b-f7d4-4549-9aa7-afb4937c9e39",
      "name": "Conflict Resolution Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatAnthropic",
      "position": [
        7632,
        2624
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "id",
          "value": "claude-3-5-sonnet-20241022"
        },
        "options": {}
      },
      "credentials": {
        "anthropicApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "5fb2bcfb-7413-4bfd-a4e8-0efe062c68d4",
      "name": "Priority Scoring Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatAnthropic",
      "position": [
        7968,
        2640
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "id",
          "value": "claude-3-5-sonnet-20241022"
        },
        "options": {}
      },
      "credentials": {
        "anthropicApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "3f75d723-746c-492f-a05c-90a57eda0dfe",
      "name": "Forecasting Output Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        7456,
        2624
      ],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"forecastedCapacity\": {\n\t\t\t\"type\": \"object\",\n\t\t\t\"description\": \"Predicted resource availability over time\"\n\t\t},\n\t\t\"confidenceInterval\": {\n\t\t\t\"type\": \"object\",\n\t\t\t\"description\": \"Upper and lower bounds of forecast confidence\"\n\t\t},\n\t\t\"capacityShortfalls\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"description\": \"Identified periods of potential resource shortage\"\n\t\t},\n\t\t\"recommendations\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"description\": \"Suggested actions to address capacity issues\"\n\t\t}\n\t}\n}"
      },
      "typeVersion": 1.3
    },
    {
      "id": "3b818cbb-3cb8-4e69-bb7f-3cdaf6aaa38b",
      "name": "Conflict Resolution Output Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        7808,
        2624
      ],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"conflictType\": {\n\t\t\t\"type\": \"string\",\n\t\t\t\"description\": \"Category of resource conflict\"\n\t\t},\n\t\t\"affectedResources\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"description\": \"List of resources involved in conflict\"\n\t\t},\n\t\t\"resolutionStrategy\": {\n\t\t\t\"type\": \"string\",\n\t\t\t\"description\": \"Recommended approach to resolve conflict\"\n\t\t},\n\t\t\"tradeoffs\": {\n\t\t\t\"type\": \"object\",\n\t\t\t\"description\": \"Analysis of tradeoffs for different resolution options\"\n\t\t}\n\t}\n}"
      },
      "typeVersion": 1.3
    },
    {
      "id": "86612646-505a-4657-abd6-0b986779f963",
      "name": "Priority Scoring Output Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        8176,
        2624
      ],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"priorityScore\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"description\": \"Calculated priority score from 0 to 100\"\n\t\t},\n\t\t\"scoringBreakdown\": {\n\t\t\t\"type\": \"object\",\n\t\t\t\"description\": \"Detailed breakdown of score components\"\n\t\t},\n\t\t\"urgencyLevel\": {\n\t\t\t\"type\": \"string\",\n\t\t\t\"description\": \"Categorized urgency: critical, high, medium, low\"\n\t\t},\n\t\t\"justification\": {\n\t\t\t\"type\": \"string\",\n\t\t\t\"description\": \"Explanation of priority score reasoning\"\n\t\t}\n\t}\n}"
      },
      "typeVersion": 1.3
    },
    {
      "id": "113bc5c1-9026-4fb6-be7c-fbae2c67f4d2",
      "name": "Resource Availability Calculator",
      "type": "@n8n/n8n-nodes-langchain.toolCode",
      "position": [
        8160,
        2416
      ],
      "parameters": {
        "jsCode": "// Calculate available resources by type, considering current utilization, scheduled maintenance, and upcoming reservations\n\n// Access the query input from the AI agent\nconst resourceType = query || 'all';\n\n// Get current utilization data from the workflow context\nconst utilizationData = $fromAI('currentUtilization', 'object') || {};\nconst upcomingEvents = $fromAI('upcomingEvents', 'object') || {};\n\n// Calculate availability for different resource types\nconst calculateAvailability = (type) => {\n  const current = utilizationData[type] || {};\n  const total = current.total || 0;\n  const occupied = current.occupied || 0;\n  const available = current.available || 0;\n  \n  // Account for maintenance windows\n  const maintenanceImpact = upcomingEvents.maintenanceWindows?.filter(m => \n    m.equipment?.toLowerCase().includes(type.toLowerCase())\n  ).length || 0;\n  \n  // Account for upcoming reservations\n  const reservedCount = upcomingEvents.resourceReservations?.filter(r => \n    r.resourceId?.toLowerCase().includes(type.toLowerCase())\n  ).length || 0;\n  \n  const effectiveAvailable = Math.max(0, available - maintenanceImpact - reservedCount);\n  \n  return {\n    type: type,\n    total: total,\n    occupied: occupied,\n    available: available,\n    effectiveAvailable: effectiveAvailable,\n    utilizationRate: total > 0 ? (occupied / total) : 0,\n    maintenanceImpact: maintenanceImpact,\n    reservedCount: reservedCount\n  };\n};\n\n// Calculate for specific type or all types\nif (resourceType === 'all') {\n  const availability = {\n    beds: calculateAvailability('beds'),\n    rooms: calculateAvailability('rooms'),\n    equipment: calculateAvailability('equipment'),\n    staff: calculateAvailability('staff'),\n    timestamp: new Date().toISOString()\n  };\n  return JSON.stringify(availability, null, 2);\n} else {\n  const availability = calculateAvailability(resourceType);\n  return JSON.stringify(availability, null, 2);\n}",
        "description": "Calculates real-time resource availability considering current allocations and reservations"
      },
      "typeVersion": 1.3
    },
    {
      "id": "4083653e-8ca3-434e-9f65-97126e2408aa",
      "name": "Utilization Metrics Analyzer",
      "type": "@n8n/n8n-nodes-langchain.toolCode",
      "position": [
        8336,
        2496
      ],
      "parameters": {
        "jsCode": "// Analyzes utilization metrics and identifies optimization opportunities\n// Input: query should contain utilization data as JSON string or object\n\nlet utilizationData;\n\n// Parse the query input\nif (typeof query === 'string') {\n  try {\n    utilizationData = JSON.parse(query);\n  } catch (e) {\n    return 'Error: Invalid JSON input. Please provide utilization data as a valid JSON object.';\n  }\n} else if (typeof query === 'object') {\n  utilizationData = query;\n} else {\n  return 'Error: Please provide utilization data as a JSON object or string.';\n}\n\n// Analyze utilization patterns\nconst analysis = {\n  underutilizedResources: [],\n  bottlenecks: [],\n  efficiencyScores: {},\n  recommendations: []\n};\n\n// Identify underutilized resources (< 60% utilization)\nif (utilizationData.beds) {\n  const bedUtilization = utilizationData.beds.occupancyRate || 0;\n  if (bedUtilization < 0.6) {\n    analysis.underutilizedResources.push({\n      resource: 'beds',\n      currentUtilization: bedUtilization,\n      capacity: utilizationData.beds.total,\n      available: utilizationData.beds.available\n    });\n    analysis.recommendations.push('Consider reducing bed capacity or marketing to increase patient admissions');\n  }\n  analysis.efficiencyScores.beds = bedUtilization;\n}\n\nif (utilizationData.rooms) {\n  const roomUtilization = utilizationData.rooms.occupancyRate || 0;\n  if (roomUtilization < 0.6) {\n    analysis.underutilizedResources.push({\n      resource: 'rooms',\n      currentUtilization: roomUtilization,\n      capacity: utilizationData.rooms.total,\n      available: utilizationData.rooms.available\n    });\n    analysis.recommendations.push('Room utilization is low. Consider scheduling optimization or multi-purpose room usage');\n  }\n  analysis.efficiencyScores.rooms = roomUtilization;\n}\n\n// Detect bottlenecks (> 85% utilization)\nif (utilizationData.equipment) {\n  for (const [equipmentType, data] of Object.entries(utilizationData.equipment)) {\n    const utilization = data.inUse / data.total;\n    analysis.efficiencyScores[equipmentType] = utilization;\n    \n    if (utilization > 0.85) {\n      analysis.bottlenecks.push({\n        resource: equipmentType,\n        currentUtilization: utilization,\n        available: data.available,\n        total: data.total,\n        severity: utilization > 0.95 ? 'critical' : 'high'\n      });\n      analysis.recommendations.push(`${equipmentType} is at ${(utilization * 100).toFixed(1)}% capacity. Consider acquiring additional units or optimizing scheduling.`);\n    }\n  }\n}\n\n// Analyze staff utilization\nif (utilizationData.staff) {\n  for (const [staffType, data] of Object.entries(utilizationData.staff)) {\n    const utilization = data.utilizationRate || 0;\n    analysis.efficiencyScores[`staff_${staffType}`] = utilization;\n    \n    if (utilization > 0.9) {\n      analysis.bottlenecks.push({\n        resource: `staff_${staffType}`,\n        currentUtilization: utilization,\n        severity: 'high'\n      });\n      analysis.recommendations.push(`${staffType} utilization is ${(utilization * 100).toFixed(1)}%. Consider hiring additional staff or adjusting schedules.`);\n    } else if (utilization < 0.6) {\n      analysis.underutilizedResources.push({\n        resource: `staff_${staffType}`,\n        currentUtilization: utilization\n      });\n    }\n  }\n}\n\n// Calculate overall efficiency score\nconst efficiencyValues = Object.values(analysis.efficiencyScores);\nconst overallEfficiency = efficiencyValues.length > 0 \n  ? efficiencyValues.reduce((a, b) => a + b, 0) / efficiencyValues.length \n  : 0;\n\nanalysis.overallEfficiencyScore = overallEfficiency;\nanalysis.efficiencyRating = overallEfficiency > 0.8 ? 'Excellent' : \n                            overallEfficiency > 0.65 ? 'Good' : \n                            overallEfficiency > 0.5 ? 'Fair' : 'Poor';\n\n// Add summary\nanalysis.summary = `Overall efficiency: ${(overallEfficiency * 100).toFixed(1)}% (${analysis.efficiencyRating}). Found ${analysis.bottlenecks.length} bottleneck(s) and ${analysis.underutilizedResources.length} underutilized resource(s).`;\n\nreturn JSON.stringify(analysis, null, 2);",
        "description": "Analyzes utilization patterns and identifies optimization opportunities"
      },
      "typeVersion": 1.3
    },
    {
      "id": "6a134670-d763-42d5-babc-bf19b53d447b",
      "name": "Calculate Risk Score",
      "type": "n8n-nodes-base.code",
      "position": [
        6944,
        2264
      ],
      "parameters": {
        "jsCode": "// Calculate comprehensive risk score for resource allocation\n// Considers utilization levels, SLA violation probability, historical patterns,\n// upcoming events, and resource constraints with weighted scoring algorithm\n\nconst items = $input.all();\nconst contextData = items[0].json;\n\n// Extract relevant data\nconst currentUtilization = contextData.currentUtilization || {};\nconst historicalTrends = contextData.historicalTrends || {};\nconst upcomingEvents = contextData.upcomingEvents || {};\nconst slaData = contextData.slaData || {};\nconst requestDetails = contextData.requestDetails || {};\n\n// Define risk scoring weights (total = 1.0)\nconst weights = {\n  utilizationLevel: 0.30,\n  slaViolationProbability: 0.25,\n  historicalPatterns: 0.20,\n  upcomingEvents: 0.15,\n  resourceConstraints: 0.10\n};\n\n// 1. Calculate Utilization Level Risk (0-100)\nlet utilizationRisk = 0;\nif (currentUtilization.beds) {\n  const bedOccupancy = currentUtilization.beds.occupancyRate || 0;\n  utilizationRisk += bedOccupancy * 40; // 40% weight for beds\n}\nif (currentUtilization.rooms) {\n  const roomOccupancy = currentUtilization.rooms.occupancyRate || 0;\n  utilizationRisk += roomOccupancy * 30; // 30% weight for rooms\n}\nif (currentUtilization.equipment) {\n  const equipmentUtilization = Object.values(currentUtilization.equipment)\n    .reduce((sum, eq) => sum + (eq.inUse / eq.total), 0) / Object.keys(currentUtilization.equipment).length;\n  utilizationRisk += equipmentUtilization * 30; // 30% weight for equipment\n}\n\n// 2. Calculate SLA Violation Probability Risk (0-100)\nlet slaRisk = 0;\nconst slaThreshold = slaData.responseTimeThreshold || 30; // minutes\nconst currentResponseTime = slaData.currentResponseTime || 0;\nif (currentResponseTime > slaThreshold) {\n  slaRisk = Math.min(100, ((currentResponseTime - slaThreshold) / slaThreshold) * 100);\n} else {\n  slaRisk = (currentResponseTime / slaThreshold) * 50; // Lower risk if within threshold\n}\n\n// 3. Calculate Historical Patterns Risk (0-100)\nlet historicalRisk = 0;\nif (historicalTrends.demandForecasts && historicalTrends.demandForecasts.length > 0) {\n  const nearTermForecast = historicalTrends.demandForecasts[0];\n  const predictedIncrease = nearTermForecast.predictedIncrease || 0;\n  const confidence = nearTermForecast.confidence || 0.5;\n  historicalRisk = (predictedIncrease * confidence) * 0.8; // Scale to 0-100\n}\n\n// 4. Calculate Upcoming Events Risk (0-100)\nlet eventsRisk = 0;\nconst scheduledProcedures = upcomingEvents.scheduledProcedures || [];\nconst maintenanceWindows = upcomingEvents.maintenanceWindows || [];\nconst expectedAdmissions = upcomingEvents.expectedAdmissions || [];\n\nconst totalUpcomingEvents = scheduledProcedures.length + maintenanceWindows.length + expectedAdmissions.length;\neventsRisk = Math.min(100, totalUpcomingEvents * 15); // Each event adds 15 points, max 100\n\n// 5. Calculate Resource Constraints Risk (0-100)\nlet constraintsRisk = 0;\nif (currentUtilization.alerts && currentUtilization.alerts.length > 0) {\n  const warningAlerts = currentUtilization.alerts.filter(a => a.type === 'warning').length;\n  const criticalAlerts = currentUtilization.alerts.filter(a => a.type === 'critical').length;\n  constraintsRisk = (warningAlerts * 30) + (criticalAlerts * 50);\n  constraintsRisk = Math.min(100, constraintsRisk);\n}\n\n// Calculate weighted total risk score (0-100)\nconst totalRiskScore = \n  (utilizationRisk * weights.utilizationLevel) +\n  (slaRisk * weights.slaViolationProbability) +\n  (historicalRisk * weights.historicalPatterns) +\n  (eventsRisk * weights.upcomingEvents) +\n  (constraintsRisk * weights.resourceConstraints);\n\n// Determine risk level\nlet riskLevel = 'low';\nif (totalRiskScore >= 75) {\n  riskLevel = 'critical';\n} else if (totalRiskScore >= 50) {\n  riskLevel = 'high';\n} else if (totalRiskScore >= 25) {\n  riskLevel = 'medium';\n}\n\n// Prepare detailed risk breakdown\nconst riskBreakdown = {\n  totalRiskScore: Math.round(totalRiskScore * 100) / 100,\n  riskLevel: riskLevel,\n  components: {\n    utilizationLevel: {\n      score: Math.round(utilizationRisk * 100) / 100,\n      weight: weights.utilizationLevel,\n      contribution: Math.round(utilizationRisk * weights.utilizationLevel * 100) / 100\n    },\n    slaViolationProbability: {\n      score: Math.round(slaRisk * 100) / 100,\n      weight: weights.slaViolationProbability,\n      contribution: Math.round(slaRisk * weights.slaViolationProbability * 100) / 100\n    },\n    historicalPatterns: {\n      score: Math.round(historicalRisk * 100) / 100,\n      weight: weights.historicalPatterns,\n      contribution: Math.round(historicalRisk * weights.historicalPatterns * 100) / 100\n    },\n    upcomingEvents: {\n      score: Math.round(eventsRisk * 100) / 100,\n      weight: weights.upcomingEvents,\n      contribution: Math.round(eventsRisk * weights.upcomingEvents * 100) / 100\n    },\n    resourceConstraints: {\n      score: Math.round(constraintsRisk * 100) / 100,\n      weight: weights.resourceConstraints,\n      contribution: Math.round(constraintsRisk * weights.resourceConstraints * 100) / 100\n    }\n  },\n  recommendations: [],\n  calculatedAt: new Date().toISOString()\n};\n\n// Generate recommendations based on risk level\nif (riskLevel === 'critical' || riskLevel === 'high') {\n  riskBreakdown.recommendations.push('Immediate resource reallocation recommended');\n  riskBreakdown.recommendations.push('Consider escalating to senior management');\n}\nif (utilizationRisk > 80) {\n  riskBreakdown.recommendations.push('Critical utilization levels detected - consider capacity expansion');\n}\nif (slaRisk > 70) {\n  riskBreakdown.recommendations.push('High SLA violation risk - prioritize critical requests');\n}\nif (eventsRisk > 60) {\n  riskBreakdown.recommendations.push('Multiple upcoming events - proactive resource planning needed');\n}\n\n// Return enriched data with risk score\nreturn [{\n  json: {\n    ...contextData,\n    riskAssessment: riskBreakdown\n  }\n}];"
      },
      "typeVersion": 2
    },
    {
      "id": "b4ac0488-1fe3-4bac-85c7-7b671c65d1a0",
      "name": "Fetch SLA Policies",
      "type": "n8n-nodes-base.code",
      "position": [
        6272,
        2264
      ],
      "parameters": {
        "jsCode": "// Fetch SLA policies from configured data source\n// Returns response time requirements, priority escalation rules, and resource allocation SLAs\n\nconst config = $('Workflow Configuration').first().json;\n\n// In production, this would fetch from your actual SLA policy database or API\n// For now, we'll structure the expected SLA policy data format\n\n// Example API call (uncomment and modify for actual implementation):\n// const response = await $http.get(config.slaPolicyEndpoint);\n// const slaPolicies = response.data;\n\n// Mock SLA policies data\nconst slaPolicies = {\n  responseTimeRequirements: [\n    {\n      priority: 'critical',\n      resourceType: 'ICU bed',\n      maxResponseTime: 15, // minutes\n      escalationThreshold: 10 // minutes\n    },\n    {\n      priority: 'high',\n      resourceType: 'emergency bed',\n      maxResponseTime: 30,\n      escalationThreshold: 20\n    },\n    {\n      priority: 'medium',\n      resourceType: 'general bed',\n      maxResponseTime: 120,\n      escalationThreshold: 90\n    },\n    {\n      priority: 'low',\n      resourceType: 'elective procedure',\n      maxResponseTime: 1440, // 24 hours\n      escalationThreshold: 1080 // 18 hours\n    }\n  ],\n  priorityEscalationRules: [\n    {\n      condition: 'response_time_exceeded',\n      action: 'escalate_to_supervisor',\n      notificationChannels: ['email', 'sms', 'dashboard_alert']\n    },\n    {\n      condition: 'critical_resource_unavailable',\n      action: 'immediate_escalation',\n      notificationChannels: ['phone', 'emergency_alert']\n    },\n    {\n      condition: 'multiple_conflicts_detected',\n      action: 'trigger_human_review',\n      notificationChannels: ['email', 'dashboard_alert']\n    },\n    {\n      condition: 'capacity_threshold_reached',\n      threshold: 0.9,\n      action: 'activate_overflow_protocol',\n      notificationChannels: ['email', 'sms']\n    }\n  ],\n  resourceAllocationSLAs: [\n    {\n      resourceType: 'ICU bed',\n      guaranteedAvailability: 0.95, // 95% availability\n      maxWaitTime: 15, // minutes\n      priorityOverride: true,\n      conflictResolutionPolicy: 'clinical_priority_first'\n    },\n    {\n      resourceType: 'operating room',\n      guaranteedAvailability: 0.90,\n      maxWaitTime: 60,\n      priorityOverride: true,\n      conflictResolutionPolicy: 'scheduled_first_emergency_override'\n    },\n    {\n      resourceType: 'ventilator',\n      guaranteedAvailability: 0.85,\n      maxWaitTime: 10,\n      priorityOverride: true,\n      conflictResolutionPolicy: 'life_critical_priority'\n    },\n    {\n      resourceType: 'general bed',\n      guaranteedAvailability: 0.80,\n      maxWaitTime: 120,\n      priorityOverride: false,\n      conflictResolutionPolicy: 'first_come_first_served'\n    }\n  ],\n  complianceRequirements: [\n    {\n      regulation: 'HIPAA',\n      requirement: 'All resource allocation decisions must be logged with audit trail',\n      enforcementLevel: 'mandatory'\n    },\n    {\n      regulation: 'Joint Commission',\n      requirement: 'Critical resources must have documented allocation criteria',\n      enforcementLevel: 'mandatory'\n    },\n    {\n      regulation: 'Internal Policy',\n      requirement: 'Human review required for conflicts above threshold',\n      enforcementLevel: 'recommended'\n    }\n  ],\n  timestamp: new Date().toISOString(),\n  dataSource: config?.slaPolicySource || 'simulated',\n  version: '1.0'\n};\n\nreturn [{ json: slaPolicies }];"
      },
      "typeVersion": 2
    },
    {
      "id": "debea2eb-2ca3-45f9-91da-95f052e1e027",
      "name": "Aggregate Resource Metrics",
      "type": "n8n-nodes-base.summarize",
      "position": [
        6720,
        2264
      ],
      "parameters": {
        "options": {},
        "fieldsToSplitBy": "resourceType",
        "fieldsToSummarize": {
          "values": [
            {
              "field": "availableCapacity",
              "aggregation": "sum"
            },
            {
              "field": "occupancyRate",
              "aggregation": "average"
            },
            {
              "field": "highPriorityRequests"
            }
          ]
        }
      },
      "typeVersion": 1.1
    },
    {
      "id": "c4df6c6b-078f-4dba-b2ba-e97056d9445f",
      "name": "Enrich with SLA Data",
      "type": "n8n-nodes-base.set",
      "position": [
        6496,
        2264
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "id-1",
              "name": "slaPolicies",
              "type": "object",
              "value": "={{ $('Fetch SLA Policies').item.json }}"
            },
            {
              "id": "id-2",
              "name": "slaViolationRisk",
              "type": "string",
              "value": "={{ $('Merge Context Data').item.json.currentUtilization && $('Fetch SLA Policies').item.json.thresholds ? ($('Merge Context Data').item.json.currentUtilization.beds.occupancyRate > $('Fetch SLA Policies').item.json.thresholds.critical ? 'high' : $('Merge Context Data').item.json.currentUtilization.beds.occupancyRate > $('Fetch SLA Policies').item.json.thresholds.warning ? 'medium' : 'low') : 'unknown' }}"
            }
          ]
        },
        "includeOtherFields": true
      },
      "typeVersion": 3.4
    },
    {
      "id": "73df442e-1bdd-41c7-a14d-65cb7d10e232",
      "name": "Log Decision to Audit System",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        10256,
        2544
      ],
      "parameters": {
        "url": "={{ $('Workflow Configuration').item.json.auditSystemEndpoint }}",
        "method": "POST",
        "options": {},
        "sendBody": true,
        "sendHeaders": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "decisionId",
              "value": "={{ $('Format Final Decision').item.json.decisionId }}"
            },
            {
              "name": "allocationStatus",
              "value": "={{ $('Resource Allocation AI Agent').item.json.allocationStatus }}"
            },
            {
              "name": "assignedResources",
              "value": "={{ $('Resource Allocation AI Agent').item.json.assignedResources }}"
            },
            {
              "name": "conflictIndicators",
              "value": "={{ $('Resource Allocation AI Agent').item.json.conflictIndicators }}"
            },
            {
              "name": "confidenceScore",
              "value": "={{ $('Resource Allocation AI Agent').item.json.confidenceScore }}"
            },
            {
              "name": "reasoning",
              "value": "={{ $('Resource Allocation AI Agent').item.json.reasoning }}"
            },
            {
              "name": "requiresHumanReview",
              "value": "={{ $('Resource Allocation AI Agent').item.json.requiresHumanReview }}"
            },
            {
              "name": "processedAt",
              "value": "={{ $('Format Final Decision').item.json.processedAt }}"
            },
            {
              "name": "workflowVersion",
              "value": "={{ $('Format Final Decision').item.json.workflowVersion }}"
            },
            {
              "name": "executionMode",
              "value": "={{ $('Format Final Decision').item.json.executionMode }}"
            },
            {
              "name": "contextData",
              "value": "={{ $('Merge Context Data').item.json }}"
            },
            {
              "name": "approvalStatus",
              "value": "={{ $('Flag for Human Review').item.json.reviewStatus || 'auto_approved' }}"
            },
            {
              "name": "timestamp",
              "value": "={{ $now.toISO() }}"
            }
          ]
        },
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        }
      },
      "typeVersion": 4.3
    },
    {
      "id": "eb538e66-b5b5-4fe8-a5ca-3bd77f3a5568",
      "name": "Send Notification to Stakeholders",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        10480,
        2544
      ],
      "parameters": {
        "url": "={{ $('Workflow Configuration').item.json.stakeholderNotificationEndpoint }}",
        "method": "POST",
        "options": {},
        "sendBody": true,
        "sendHeaders": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "decisionSummary",
              "value": "={{ $('Resource Allocation AI Agent').item.json }}"
            },
            {
              "name": "affectedResources",
              "value": "={{ $('Resource Allocation AI Agent').item.json.assignedResources }}"
            },
            {
              "name": "nextSteps",
              "value": "={{ $('Resource Allocation AI Agent').item.json.requiresHumanReview ? 'Awaiting human review and approval' : 'Decision has been automatically approved and implemented' }}"
            },
            {
              "name": "timestamp",
              "value": "={{ $now.toISO() }}"
            }
          ]
        },
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        }
      },
      "typeVersion": 4.3
    },
    {
      "id": "66ac2cad-8826-4993-9776-21311a75774d",
      "name": "Wait for Human Approval",
      "type": "n8n-nodes-base.wait",
      "position": [
        9360,
        2288
      ],
      "parameters": {
        "resume": "webhook",
        "options": {},
        "resumeAmount": 24,
        "limitWaitTime": true
      },
      "typeVersion": 1.1
    },
    {
      "id": "6ab2577d-8397-48bb-a5bc-2d9aeb932125",
      "name": "Check Approval Status",
      "type": "n8n-nodes-base.if",
      "position": [
        9584,
        2336
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "leftValue": "",
            "caseSensitive": false,
            "typeValidation": "loose"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "id-1",
              "operator": {
                "type": "string",
                "operation": "equals"
              },
              "leftValue": "={{ $json.approvalStatus }}",
              "rightValue": "approved"
            }
          ]
        }
      },
      "typeVersion": 2.3
    },
    {
      "id": "ad6d2049-e25d-4662-9184-b6bbb76334e9",
      "name": "Mark as Approved",
      "type": "n8n-nodes-base.set",
      "position": [
        9824,
        2160
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "id-1",
              "name": "finalStatus",
              "type": "string",
              "value": "approved_by_human"
            },
            {
              "id": "id-2",
              "name": "approvedBy",
              "type": "string",
              "value": "={{ $('Wait for Human Approval').item.json.approver }}"
            },
            {
              "id": "id-3",
              "name": "approvedAt",
              "type": "string",
              "value": "={{ $now.toISO() }}"
            }
          ]
        },
        "includeOtherFields": true
      },
      "typeVersion": 3.4
    },
    {
      "id": "b6c78927-e980-4b3e-963f-5c0e5c5161d5",
      "name": "Mark as Rejected",
      "type": "n8n-nodes-base.set",
      "position": [
        9824,
        2352
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "id-1",
              "name": "finalStatus",
              "type": "string",
              "value": "rejected_by_human"
            },
            {
              "id": "id-2",
              "name": "rejectedBy",
              "type": "string",
              "value": "={{ $('Wait for Human Approval').item.json.reviewer }}"
            },
            {
              "id": "id-3",
              "name": "rejectedAt",
              "type": "string",
              "value": "={{ $now.toISO() }}"
            },
            {
              "id": "id-4",
              "name": "rejectionReason",
              "type": "string",
              "value": "={{ $('Wait for Human Approval').item.json.reason }}"
            }
          ]
        },
        "includeOtherFields": true
      },
      "typeVersion": 3.4
    },
    {
      "id": "bcf959b5-4b42-4006-a49c-fbcd864f8db5",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        6768,
        1408
      ],
      "parameters": {
        "color": 6,
        "width": 528,
        "height": 368,
        "content": "## Prerequisites\nMarketing automation platform access, AI service API keys, email service provider account\n## Use Cases\nProduct launch campaigns coordinating announcements across channels\n## Customization\nAdjust AI prompts for brand voice consistency, modify channel priorities based on audience preferences\n## Benefits\nReduces campaign setup time by 80%, ensures consistent messaging across all channels"
      },
      "typeVersion": 1
    },
    {
      "id": "0b48126a-6fd1-4627-83e2-f5fcacb02f60",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        6176,
        1472
      ],
      "parameters": {
        "width": 480,
        "height": 304,
        "content": "## Setup Steps\n1. Configure campaign schedule trigger or webhook integration with marketing automation platform\n2. Add AI model API credentials for content generation, personalization, and A/B testing optimization\n3. Connect email service provider with segmented audience lists and template configurations\n4. Set up social media management platform APIs for Facebook, Instagram, LinkedIn\n5. Integrate advertis

Credentials you'll need

Each integration node will prompt for credentials when you import. We strip credential IDs before publishing — you'll add your own.

Pro

For the full experience including quality scoring and batch install features for each workflow upgrade to Pro

About this workflow

This workflow automates end-to-end marketing campaign management for digital marketing teams and agencies executing multi-channel strategies. It solves the complex challenge of coordinating personalized content across email, social media, and advertising platforms while…

Source: https://n8n.io/workflows/12794/ — original creator credit. Request a take-down →

More AI & RAG workflows → · Browse all categories →

Related workflows

Workflows that share integrations, category, or trigger type with this one. All free to copy and import.

AI & RAG

Tired of grinding out YouTube content? This n8n workflow turns AI into your personal video factory—creating engaging, faceless shorts on autopilot. Perfect for creators, marketers, or side-hustlers lo

HTTP Request, Google Drive, Google Sheets +6
AI & RAG

Faceless YouTube Generator. Uses httpRequest, limit, googleDrive, googleSheets. Webhook trigger; 49 nodes.

HTTP Request, Google Drive, Google Sheets +7
AI & RAG

Automates daily project monitoring by fetching project data, analyzing tasks and team capacity with anthropic models, and generating resource optimization recommendations. Target audience: project man

HTTP Request, Agent, Anthropic Chat +3
AI & RAG

This workflow automates intelligent fleet operations management for transport operators, logistics companies, and smart mobility teams. It solves the problem of manually triaging high-volume vehicle t

Agent, OpenAI Chat, Output Parser Structured +7
AI & RAG

This workflow automates comprehensive data validation and regulatory compliance reporting through intelligent AI-driven analysis. Designed for compliance officers, data governance teams, and regulator

Agent, Agent Tool, Anthropic Chat +5