{
  "name": "Delivery Route Optimization & Driver Dispatch",
  "nodes": [
    {
      "parameters": {
        "content": "## Airtable\nCreate an Airtable base with these tables/fields, then select it in the Airtable nodes:\n- **Route & Load Optimization → Orders**: `Order ID`, `Status`\n- **Route & Load Optimization → Fleet**: `Truck ID`, `Availability`\n- **Route & Load Optimization → RoutesOutput**: `Order ID`, `Route ID`, `Date`, `Truck ID`, `Driver Name`, `Driver Phone`, `Total Weight kg`, `Total Stops`, `Est Total km`, `Est Total Time Min`, `Weather Summary`, `Route Link`",
        "height": 112
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -208,
        672
      ],
      "id": "e482ecc9-a4bc-4eb2-b3dc-848f67cc80b4",
      "name": "Sticky Note"
    },
    {
      "parameters": {
        "jsCode": "const orders = $input.all().map(i => i.json);\n\n// ===== CONFIG =====\nconst MAX_CAPACITY = 1000; // truck capacity (kg)\nconst TIME_FLEXIBILITY_HOURS = 2; // allow ±2 hour grouping\n\n// ===== HELPER: Convert time to minutes =====\nfunction timeToMinutes(timeStr) {\n  if (!timeStr) return 0;\n  const [h, m] = timeStr.split(\":\").map(Number);\n  return h * 60 + m;\n}\n\n// ===== STEP 1: GROUP BY CITY =====\nconst cityGroups = {};\n\nfor (const order of orders) {\n  const city = order.City || \"Unknown\";\n\n  if (!cityGroups[city]) {\n    cityGroups[city] = [];\n  }\n\n  cityGroups[city].push(order);\n}\n\n// ===== STEP 2: SORT ORDERS BY TIME =====\nfor (const city in cityGroups) {\n  cityGroups[city].sort((a, b) => {\n    return timeToMinutes(a[\"Window Start\"]) - timeToMinutes(b[\"Window Start\"]);\n  });\n}\n\n// ===== STEP 3: CREATE ROUTES =====\nlet routes = [];\n\nfor (const city in cityGroups) {\n  const groupOrders = cityGroups[city];\n\n  let currentRoute = [];\n  let currentWeight = 0;\n  let baseTime = null;\n\n  for (const order of groupOrders) {\n    const weight = Number(order[\"Weight kg\"] || 0);\n    const orderTime = timeToMinutes(order[\"Window Start\"]);\n\n    // first order in route\n    if (currentRoute.length === 0) {\n      currentRoute.push(order);\n      currentWeight += weight;\n      baseTime = orderTime;\n      continue;\n    }\n\n    const timeDiff = Math.abs(orderTime - baseTime);\n\n    // ===== CONDITIONS =====\n    const withinCapacity = (currentWeight + weight) <= MAX_CAPACITY;\n    const withinTime = timeDiff <= (TIME_FLEXIBILITY_HOURS * 60);\n\n    if (withinCapacity && withinTime) {\n      currentRoute.push(order);\n      currentWeight += weight;\n    } else {\n      // push current route\n      routes.push(currentRoute);\n\n      // start new route\n      currentRoute = [order];\n      currentWeight = weight;\n      baseTime = orderTime;\n    }\n  }\n\n  // push last route\n  if (currentRoute.length > 0) {\n    routes.push(currentRoute);\n  }\n}\n\n// ===== STEP 4: FORMAT OUTPUT =====\nreturn routes.map(route => ({\n  json: {\n    stops: route,\n    totalWeight: route.reduce((sum, o) => sum + Number(o[\"Weight kg\"] || 0), 0),\n    totalStops: route.length,\n    city: route[0]?.City || \"Unknown\"\n  }\n}));"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        272,
        832
      ],
      "id": "67d7af44-1669-41d7-8b19-4b6b8206621f",
      "name": "Grouped Route"
    },
    {
      "parameters": {
        "jsCode": "const stops = $('Generate Formula').first().json.stops;\n\nreturn stops.map((stop, index) => ({\n  json: {\n    stopNo: index + 1,\n    orderId: stop[\"Order ID\"],\n    name: stop[\"Customer Name\"],\n    phone: stop[\"Customer Phone\"],\n    address: stop[\"Address\"],\n    city: stop[\"City\"],\n    zipCode: stop[\"ZIP Code\"],\n    deliveryDate: stop[\"Delivery Date\"],\n    windowStart: stop[\"Window Start\"],\n    windowEnd: stop[\"Window End\"],\n    weight: stop[\"Weight kg\"],\n    type: stop[\"Special Type\"]\n  }\n}));\n"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1152,
        768
      ],
      "id": "1058f694-2c0d-4791-8c71-a769fa2c3ffc",
      "name": "Get Route Details"
    },
    {
      "parameters": {
        "jsCode": "const orderIds = $input.first().json.fields[\"Order ID\"]\n  .split(\",\")\n  .map(id => id.trim());\n\nreturn orderIds.map(id => ({\n  json: {\n    \"Order ID\": id,\n    \"Status\": \"Out for Delivery\"\n  }\n}));"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2960,
        768
      ],
      "id": "226b890b-86f3-4a86-84a7-36a4531d552e",
      "name": "Split Order IDs"
    },
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "hours"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.3,
      "position": [
        -64,
        832
      ],
      "id": "f386eeaf-5ee8-42cd-980d-f08942f0b6ea",
      "name": "Schedule Trigger"
    },
    {
      "parameters": {
        "operation": "search",
        "base": {
          "__rl": true,
          "value": "appllYarQHA4ecVUd",
          "mode": "list",
          "cachedResultName": "Route & Load Optimization"
        },
        "table": {
          "__rl": true,
          "value": "tblohVlKvjbkbJc3K",
          "mode": "list",
          "cachedResultName": "Orders"
        },
        "filterByFormula": "=AND(\n  {Status}=\"Ready\",\n  {Delivery Date}=TODAY()\n)",
        "options": {
          "fields": [
            "Order ID",
            "Customer Name",
            "Customer Phone",
            "Address",
            "City",
            "ZIP Code",
            "Delivery Date",
            "Window Start",
            "Window End",
            "Weight kg",
            "Special Type"
          ]
        }
      },
      "type": "n8n-nodes-base.airtable",
      "typeVersion": 2.1,
      "position": [
        112,
        832
      ],
      "id": "df214d11-0e4a-4c05-8dda-771ed3112c51",
      "name": "Get Today Ready For Delivery Records",
      "credentials": {
        "airtableTokenApi": {
          "id": "0lstEdikXtvhmDPJ",
          "name": "Airtable account"
        }
      }
    },
    {
      "parameters": {
        "options": {}
      },
      "type": "n8n-nodes-base.splitInBatches",
      "typeVersion": 3,
      "position": [
        432,
        832
      ],
      "id": "848c4a17-cbac-4ea7-9d4c-0ea35f67b23c",
      "name": "Loop Over Delivery Records"
    },
    {
      "parameters": {
        "jsCode": "const route = $json;\nconst stops = route.stops || [];\n\n// 👉 Take TOTAL weight (important)\nconst totalWeight = route.totalWeight || 0;\n\n// --- Tolerance ---\nconst tolerance = 5;\n\n// --- Range ---\nconst minWeight = totalWeight - tolerance;\nconst maxWeight = totalWeight + tolerance;\n\n// --- Airtable Formula ---\nconst formula = `AND(\n  {Active}=TRUE(),\n  {Availability}=\"Available\",\n  {Max Weight kg} >= ${minWeight}\n)`;\n\n// (no need maxWeight check in real-world)\n\nreturn [{\n  json: {\n    totalWeight,\n    minWeight,\n    maxWeight,\n    formula,\n    stops\n  }\n}];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        640,
        848
      ],
      "id": "d7887e01-44fe-4153-96f2-638ddfb55ae0",
      "name": "Generate Formula"
    },
    {
      "parameters": {
        "operation": "search",
        "base": {
          "__rl": true,
          "value": "appllYarQHA4ecVUd",
          "mode": "list",
          "cachedResultName": "Route & Load Optimization"
        },
        "table": {
          "__rl": true,
          "value": "tblrgPvARzBzlriXK",
          "mode": "list",
          "cachedResultName": "Fleet"
        },
        "filterByFormula": "={{ $json.formula }}",
        "returnAll": false,
        "options": {
          "fields": [
            "Truck ID",
            "Driver Name",
            "Driver Phone",
            "Max Weight kg"
          ]
        }
      },
      "type": "n8n-nodes-base.airtable",
      "typeVersion": 2.1,
      "position": [
        800,
        848
      ],
      "id": "9ace74ac-a25a-4a8f-a7f2-f2bfa8f56c1d",
      "name": "Get Available Truck",
      "alwaysOutputData": true,
      "credentials": {
        "airtableTokenApi": {
          "id": "0lstEdikXtvhmDPJ",
          "name": "Airtable account"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 3
          },
          "conditions": [
            {
              "id": "3571f119-2c10-4957-a903-64544ab172db",
              "leftValue": "={{ $json[\"Truck ID\"] }}",
              "rightValue": "",
              "operator": {
                "type": "dateTime",
                "operation": "notEmpty",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        960,
        848
      ],
      "id": "6735b729-b53f-41f7-b0ec-c69445cbbbea",
      "name": "If Check Truck Availability"
    },
    {
      "parameters": {
        "authentication": "oAuth2",
        "select": "channel",
        "channelId": {
          "__rl": true,
          "value": "C090F70N52M",
          "mode": "list",
          "cachedResultName": "website-uptime"
        },
        "text": "=🚨 *TRUCK NOT AVAILABLE ALERT*\n\n📦 Order ID: *{{ $('Loop Over Delivery Records').item.json[\"Order ID\"] }}*\n👤 Customer: *{{ $('Loop Over Delivery Records').item.json[\"Customer Name\"] }}*\n📍 Delivery Location: {{ $('Loop Over Delivery Records').item.json[\"Address\"] }}, {{ $('Loop Over Delivery Records').item.json[\"City\"] }} - {{ $('Loop Over Delivery Records').item.json[\"ZIP Code\"] }}\n📅 Delivery Date: {{ $('Loop Over Delivery Records').item.json[\"Delivery Date\"] }}\n⏰ Delivery Window: {{ $('Loop Over Delivery Records').item.json[\"Window Start\"] }} - {{ $('Loop Over Delivery Records').item.json[\"Window End\"] }}\n⚖️ Load Weight: {{ $('Loop Over Delivery Records').item.json[\"Weight kg\"] }} kg\n\n❌ No available truck found for this order.\n\n👉 Action Required:\n• Assign another truck manually\n• Or reschedule delivery",
        "otherOptions": {}
      },
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.4,
      "position": [
        1152,
        928
      ],
      "id": "787ed3fa-3bce-4789-a100-360fcca57713",
      "name": "Alert to Team for truck not available",
      "webhookId": "ec8ffc59-4d61-4705-8673-5c44fa4e2b7d",
      "credentials": {
        "slackOAuth2Api": {
          "id": "TF3jowThH6PoCk5Q",
          "name": "Slack account"
        }
      }
    },
    {
      "parameters": {
        "url": "https://nominatim.openstreetmap.org/search",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "format",
              "value": "json"
            },
            {
              "name": "q",
              "value": "={{ $json.address }}"
            },
            {
              "name": "limit",
              "value": "1"
            }
          ]
        },
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "User-Agent",
              "value": "n8n-logistics-bot/1.0 (contact: team@forgentsystems.com)"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        1328,
        768
      ],
      "id": "9fc28f7d-e13a-422f-a821-291539ba1347",
      "name": "Get Google Maps Route"
    },
    {
      "parameters": {
        "url": "=https://router.project-osrm.org/route/v1/driving/72.5197538,23.0451784;{{$json.lon}},{{$json.lat}}?overview=false",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        1504,
        768
      ],
      "id": "643fd9a2-4147-4e05-a5dc-cb7f0a93fb73",
      "name": "Find a Distance & Duration"
    },
    {
      "parameters": {
        "jsCode": "\n// const origin = \"500 Industrial Pkwy, Columbus, OH 43215\";\n\n// const nominatim = $('Get Google Maps Route').first().json;\n// const lat = nominatim.lat;\n// const lon = nominatim.lon;\n\n// const destination = `${lat},${lon}`;\n\n// const routeLink =\n//   `https://www.google.com/maps/dir/?api=1&origin=${encodeURIComponent(origin)}&destination=${encodeURIComponent(destination)}`;\n\n// const osrm = $json;\n// const route = osrm.routes?.[0];\n\n// let estKm = null;\n// let estMin = null;\n\n// if (route) {\n//   estKm = +(route.distance / 1000).toFixed(2);\n\n//   // OSRM base time (no traffic)\n//   const baseMin = route.duration / 60;\n\n//   // Traffic buffer (adjust this)\n//   const trafficMultiplier = 2.1;\n\n//   estMin = Math.ceil(baseMin * trafficMultiplier);\n// }\n\n// return [{\n//   json: {\n//     ...nominatim,\n//     routeLink,\n//     \"Est Total km\": estKm,\n//     \"Est Total Time Min\": estMin\n//   }\n// }];\n\n\nconst origin = \"500 Industrial Pkwy, Columbus, OH 43215\";\nconst nominatim = $('Get Google Maps Route').all();\n\nconst allItems = $input.all();\n\n// Extract all destination points\nconst locations = allItems.map(item => {\n  const wp = item.json.waypoints?.[1];\n  return wp ? `${wp.location[1]},${wp.location[0]}` : null;\n}).filter(Boolean);\n\nif (locations.length === 0) {\n  return [];\n}\n\n// Last = destination, rest = waypoints\nconst destination = locations[locations.length - 1];\nconst waypoints = locations.slice(0, -1).join('|');\n\n// Build route link\nconst routeLink =\n  `https://www.google.com/maps/dir/?api=1` +\n  `&origin=${encodeURIComponent(origin)}` +\n  `&destination=${encodeURIComponent(destination)}` +\n  (waypoints ? `&waypoints=${encodeURIComponent(waypoints)}` : '');\n\n// Optional: total distance + time (sum all routes)\nlet totalKm = 0;\nlet totalMin = 0;\n\nfor (const item of allItems) {\n  const route = item.json.routes?.[0];\n  if (route) {\n    totalKm += route.distance || 0;\n    totalMin += route.duration || 0;\n  }\n}\n\ntotalKm = +(totalKm / 1000).toFixed(2);\ntotalMin = Math.ceil((totalMin / 60) * 2.1);\n\n// ✅ RETURN SINGLE ITEM ARRAY\nreturn [\n  {\n    json: {\n      ...nominatim,\n      routeLink,\n      \"Est Total km\": totalKm,\n      \"Est Total Time Min\": totalMin\n    }\n  }\n];\n"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1680,
        768
      ],
      "id": "663e9949-caac-4dfb-b3b9-1d8bff26ccca",
      "name": "Generate Route Link"
    },
    {
      "parameters": {
        "format": "imperial",
        "cityName": "={{ $('Loop Over Delivery Records').first().json.stops[0].City }}",
        "language": "en"
      },
      "type": "n8n-nodes-base.openWeatherMap",
      "typeVersion": 1,
      "position": [
        1856,
        768
      ],
      "id": "c0bcefeb-beaf-4319-b5db-2812ff88463f",
      "name": "Search Route Weather",
      "credentials": {
        "openWeatherMapApi": {
          "id": "jW0HChuNcAMDq4Ta",
          "name": "OpenWeatherMap account"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "const w = $json;\n\nconst city = w.name || \"Unknown\";\nconst desc = w.weather?.[0]?.description || \"N/A\";\n\nconst temp = w.main?.temp;\nconst humidity = w.main?.humidity;\nconst windSpeed = w.wind?.speed;\nconst visibility = w.visibility;\n\nlet risk = \"Low\";\nlet note = \"No major weather risk.\";\n\nif (visibility && visibility < 2000) {\n  risk = \"Medium\";\n  note = \"Low visibility due to haze/fog. Drive carefully.\";\n}\n\nconst summary = `${desc.toUpperCase()} in ${city} | ${temp}°C | Humidity ${humidity}% | Wind ${windSpeed} m/s | Visibility ${(visibility/1000).toFixed(1)} km | Weather ${risk} risk`;\n\nreturn [{\n  json: {\n    weather_summary: summary,\n    weather_risk: risk,\n    weather_note: note\n  }\n}];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2032,
        768
      ],
      "id": "1f48c957-c268-4e8d-bd4f-556edbbce338",
      "name": "Generate Weather Summary"
    },
    {
      "parameters": {
        "jsCode": "// // ===== GET DATA FROM PREVIOUS NODES =====\n// const order = $('Loop Over Delivery Records').first().json;\n// const truck = $('Get Available Truck').first().json;\n\n// const routeData = $('Generate Route Link').first().json; \n// // contains: routeLink, \"Est Total km\", \"Est Total Time Min\"\n\n// const weather = $('Generate Weather Summary').first().json;\n// // contains: weather_summary, weather_risk, weather_note\n\n// // ===== BASIC VALUES =====\n// const orderId = order[\"Order ID\"];\n// const customerName = order[\"Customer Name\"];\n// const customerPhone = order[\"Customer Phone\"];\n// const address = order[\"Address\"];\n// const city = order[\"City\"];\n// const zipCode = order[\"ZIP Code\"];\n// const deliveryDate = order[\"Delivery Date\"];\n// const windowStart = order[\"Window Start\"];\n// const windowEnd = order[\"Window End\"];\n// const weightKg = order[\"Weight kg\"];\n\n// const truckId = truck[\"Truck ID\"];\n// const driverName = truck[\"Driver Name\"];\n// const driverPhone = truck[\"Driver Phone\"];\n\n// const estKm = routeData[\"Est Total km\"];\n// const estMin = routeData[\"Est Total Time Min\"];\n// const routeLink = routeData.routeLink;\n\n// const weatherSummary = weather.weather_summary;\n\n// // ===== CREATE ROUTE ID =====\n// const dateStr = (deliveryDate || new Date().toISOString().slice(0, 10)).replaceAll(\"-\", \"\");\n\n// const now = new Date();\n// const hh = String(now.getHours()).padStart(2, \"0\");\n// const min = String(now.getMinutes()).padStart(2, \"0\");\n// // Take the last part of the Order ID (example: ORD-1001 -> 1001)\n// const orderShort = String(orderId || \"\").split(\"-\").pop() || \"X\";\n// const routeId = `R-${dateStr}-${truckId}-${hh}${min}-${orderShort}`;\n\n// // ===== DRIVER WHATSAPP MESSAGE =====\n// const driverMessage =\n// `🚚 *New Delivery Assigned*\n\n// Hello ${driverName},\n// You have been assigned a new delivery.\n\n// 📦 *Customer Details*\n// Name: ${customerName}\n// Phone: ${customerPhone}\n\n// 📍 *Delivery Address*\n// ${address}, ${city} - ${zipCode}\n\n// 📅 *Delivery Date:* ${deliveryDate}\n// ⏰ *Time Window:* ${windowStart} - ${windowEnd}\n\n// ⚖️ *Load:* ${weightKg} kg\n// 🛣️ *Estimated Distance:* ${estKm} km\n// ⏱️ *Estimated Time:* ${estMin} min\n\n// 🌦️ *Weather Update:* ${weatherSummary}\n\n// 📍 *Route Link:*\n// ${routeLink}\n\n// Reply *DONE* after delivery completion.`;\n\n// // ===== SUPPLIER / DISPATCH SLACK MESSAGE =====\n// const supplierSlackMessage =\n// `📌 *New Delivery Assigned*\n// • Route ID: *${routeId}*\n// • Order ID: *${orderId}*\n// • Truck: *${truckId}*\n// • Driver: *${driverName}* (${driverPhone})\n// • Address: ${address}, ${city} - ${zipCode}\n// • Window: ${windowStart} - ${windowEnd}\n// • Load: ${weightKg} kg\n// • Est: ${estKm} km | ${estMin} min\n// • Weather: ${weatherSummary}\n// • Route: ${routeLink}`;\n\n// // ===== AIRTABLE ROUTESOUTPUT PAYLOAD =====\n// const airtablePayload = {\n//   \"Order ID\": orderId,\n//   \"Route ID\": routeId,\n//   \"Date\": deliveryDate,\n//   \"Truck ID\": truckId,\n//   \"Driver Name\": driverName,\n//   \"Driver Phone\": driverPhone,\n//   \"Total Stops\": 1,\n//   \"Total Weight kg\": weightKg,\n//   \"Est Total km\": estKm,\n//   \"Est Total Time Min\": estMin,\n//   \"Weather Summary\": weatherSummary,\n//   \"Route Link\": routeLink\n// };\n\n// // ===== RETURN =====\n// return [{\n//   json: {\n//     driverMessage,\n//     supplierSlackMessage,\n//     airtablePayload\n//   }\n// }];\n\n\n\n// ===== GET DATA =====\nconst routeGroup = $('Loop Over Delivery Records').first().json;\nconst truck = $('Get Available Truck').first().json;\nconst routeData = $('Generate Route Link').first().json;\nconst weather = $('Generate Weather Summary').first().json;\n\n// ===== STOPS =====\nconst stops = routeGroup.stops || [];\n\n// First stop (for primary display)\nconst firstStop = stops[0] || {};\n\n// ===== BASIC VALUES =====\nconst orderId = stops.map(s => s[\"Order ID\"]).join(\", \");\nconst customerName = firstStop[\"Customer Name\"];\nconst customerPhone = firstStop[\"Customer Phone\"];\nconst city = firstStop[\"City\"];\nconst zipCode = firstStop[\"ZIP Code\"];\nconst deliveryDate = firstStop[\"Delivery Date\"];\n\nconst windowStart = firstStop[\"Window Start\"];\nconst windowEnd = firstStop[\"Window End\"];\n\n// Combine all addresses\nconst allAddresses = stops\n  .map((s, i) => `${i + 1}. ${s[\"Address\"]}`)\n  .join(\"\\n\");\n\n// Total weight\nconst weightKg = stops.reduce((sum, s) => sum + Number(s[\"Weight kg\"] || 0), 0);\n\n// ===== TRUCK =====\nconst truckId = truck[\"Truck ID\"];\nconst driverName = truck[\"Driver Name\"];\nconst driverPhone = truck[\"Driver Phone\"];\n\n// ===== ROUTE =====\nconst estKm = routeData[\"Est Total km\"];\nconst estMin = routeData[\"Est Total Time Min\"];\nconst routeLink = routeData.routeLink;\n\n// ===== WEATHER =====\nconst weatherSummary = weather.weather_summary;\n\n// ===== ROUTE ID =====\nconst dateStr = (deliveryDate || new Date().toISOString().slice(0, 10)).replaceAll(\"-\", \"\");\nconst now = new Date();\nconst hh = String(now.getHours()).padStart(2, \"0\");\nconst min = String(now.getMinutes()).padStart(2, \"0\");\n\nconst routeId = `R-${dateStr}-${truckId}-${hh}${min}`;\n\n// ===== DRIVER MESSAGE =====\nconst driverMessage =\n`🚚 *New Delivery Assigned*\n\nHello ${driverName},\nYou have been assigned a delivery route.\n\n📦 *Total Stops (${stops.length})*\n${allAddresses}\n\n📅 *Delivery Date:* ${deliveryDate}\n⏰ *Time Window:* ${windowStart} - ${windowEnd}\n\n⚖️ *Total Load:* ${weightKg} kg\n🛣️ *Estimated Distance:* ${estKm} km\n⏱️ *Estimated Time:* ${estMin} min\n\n🌦️ *Weather:* ${weatherSummary}\n\n📍 *Route Link:*\n${routeLink}\n\nDrive carefully.`;\n\n// ===== SLACK MESSAGE =====\nconst supplierSlackMessage =\n`📌 *New Delivery Route*\n• Route ID: *${routeId}*\n• Orders: *${orderId}*\n• Truck: *${truckId}*\n• Driver: *${driverName}* (${driverPhone})\n• Stops: ${stops.length}\n• Load: ${weightKg} kg\n• Est: ${estKm} km | ${estMin} min\n• Weather: ${weatherSummary}\n• Route: ${routeLink}`;\n\n// ===== AIRTABLE =====\nconst airtablePayload = {\n  \"Order ID\": orderId,\n  \"Route ID\": routeId,\n  \"Date\": deliveryDate,\n  \"Truck ID\": truckId,\n  \"Driver Name\": driverName,\n  \"Driver Phone\": driverPhone,\n  \"Total Stops\": stops.length,\n  \"Total Weight kg\": weightKg,\n  \"Est Total km\": estKm,\n  \"Est Total Time Min\": estMin,\n  \"Weather Summary\": weatherSummary,\n  \"Route Link\": routeLink\n};\n\n// ===== RETURN =====\nreturn [\n  {\n    json: {\n      driverMessage,\n      supplierSlackMessage,\n      airtablePayload,\n      driverPhone\n    }\n  }\n];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2208,
        768
      ],
      "id": "f3568804-b2fd-4926-b747-4d49d3f6794f",
      "name": "Generate Whatsapp Message & Payload"
    },
    {
      "parameters": {
        "from": "+14155238886",
        "to": "=+{{ $json.driverPhone }}",
        "toWhatsapp": true,
        "message": "={{ $json.driverMessage }}",
        "options": {}
      },
      "type": "n8n-nodes-base.twilio",
      "typeVersion": 1,
      "position": [
        2400,
        768
      ],
      "id": "41ee7d8f-ea00-4f95-b7fd-07eba1259fc3",
      "name": "Send WhatsApp to Driver Notify",
      "credentials": {
        "twilioApi": {
          "id": "xmQ7NblKKLEiOZwC",
          "name": "Twilio account"
        }
      }
    },
    {
      "parameters": {
        "authentication": "oAuth2",
        "select": "channel",
        "channelId": {
          "__rl": true,
          "value": "C090F70N52M",
          "mode": "list",
          "cachedResultName": "website-uptime"
        },
        "text": "={{ $('Generate Whatsapp Message & Payload').item.json.supplierSlackMessage }}",
        "otherOptions": {}
      },
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.4,
      "position": [
        2608,
        768
      ],
      "id": "84561a4a-63d0-4dc1-8487-8d472605d52c",
      "name": "Notify to Supplier Team",
      "webhookId": "b8d4fcc3-397d-4681-a0a8-68d8d0c4e6af",
      "credentials": {
        "slackOAuth2Api": {
          "id": "TF3jowThH6PoCk5Q",
          "name": "Slack account"
        }
      }
    },
    {
      "parameters": {
        "operation": "create",
        "base": {
          "__rl": true,
          "value": "appllYarQHA4ecVUd",
          "mode": "list",
          "cachedResultName": "Route & Load Optimization"
        },
        "table": {
          "__rl": true,
          "value": "tbl8RnCN0P3W9HDvO",
          "mode": "list",
          "cachedResultName": "RoutesOutput"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Order ID": "={{ $('Generate Whatsapp Message & Payload').item.json.airtablePayload[\"Order ID\"] }}",
            "Route ID": "={{ $('Generate Whatsapp Message & Payload').item.json.airtablePayload[\"Route ID\"] }}",
            "Date": "={{ $('Generate Whatsapp Message & Payload').item.json.airtablePayload.Date }}",
            "Truck ID": "={{ $('Generate Whatsapp Message & Payload').item.json.airtablePayload[\"Truck ID\"] }}",
            "Driver Name": "={{ $('Generate Whatsapp Message & Payload').item.json.airtablePayload[\"Driver Name\"] }}",
            "Driver Phone": "={{ $('Generate Whatsapp Message & Payload').item.json.airtablePayload[\"Driver Phone\"] }}",
            "Total Weight kg": "={{ $('Generate Whatsapp Message & Payload').item.json.airtablePayload[\"Total Weight kg\"] }}",
            "Est Total km": "={{ $('Generate Whatsapp Message & Payload').item.json.airtablePayload[\"Est Total km\"] }}",
            "Est Total Time Min": "={{ $('Generate Whatsapp Message & Payload').item.json.airtablePayload[\"Est Total Time Min\"] }}",
            "Weather Summary": "={{ $('Generate Whatsapp Message & Payload').item.json.airtablePayload[\"Weather Summary\"] }}",
            "Route Link": "={{ $('Generate Whatsapp Message & Payload').item.json.airtablePayload[\"Route Link\"] }}",
            "Total Stops": "={{ $('Generate Whatsapp Message & Payload').item.json.airtablePayload[\"Total Stops\"] }}"
          },
          "matchingColumns": [],
          "schema": [
            {
              "id": "Order ID",
              "displayName": "Order ID",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Route ID",
              "displayName": "Route ID",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Date",
              "displayName": "Date",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Truck ID",
              "displayName": "Truck ID",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Driver Name",
              "displayName": "Driver Name",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Driver Phone",
              "displayName": "Driver Phone",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Total Weight kg",
              "displayName": "Total Weight kg",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Total Stops",
              "displayName": "Total Stops",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Est Total km",
              "displayName": "Est Total km",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Est Total Time Min",
              "displayName": "Est Total Time Min",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Weather Summary",
              "displayName": "Weather Summary",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Route Link",
              "displayName": "Route Link",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "type": "n8n-nodes-base.airtable",
      "typeVersion": 2.1,
      "position": [
        2800,
        768
      ],
      "id": "d4df2624-4dc1-45b8-b9e0-7e43fd5f9098",
      "name": "Append Payload Data",
      "credentials": {
        "airtableTokenApi": {
          "id": "0lstEdikXtvhmDPJ",
          "name": "Airtable account"
        }
      }
    },
    {
      "parameters": {
        "operation": "update",
        "base": {
          "__rl": true,
          "value": "appllYarQHA4ecVUd",
          "mode": "list",
          "cachedResultName": "Route & Load Optimization"
        },
        "table": {
          "__rl": true,
          "value": "tblohVlKvjbkbJc3K",
          "mode": "list",
          "cachedResultName": "Orders"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Status": "Out for Delivery",
            "Order ID": "={{ $json[\"Order ID\"] }}"
          },
          "matchingColumns": [
            "Order ID"
          ],
          "schema": [
            {
              "id": "id",
              "displayName": "id",
              "required": false,
              "defaultMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": true
            },
            {
              "id": "Order ID",
              "displayName": "Order ID",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Customer Name",
              "displayName": "Customer Name",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": true
            },
            {
              "id": "Customer Phone",
              "displayName": "Customer Phone",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": true
            },
            {
              "id": "Address",
              "displayName": "Address",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": true
            },
            {
              "id": "City",
              "displayName": "City",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": true
            },
            {
              "id": "ZIP Code",
              "displayName": "ZIP Code",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": true
            },
            {
              "id": "Delivery Date",
              "displayName": "Delivery Date",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "dateTime",
              "readOnly": false,
              "removed": true
            },
            {
              "id": "Window Start",
              "displayName": "Window Start",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": true
            },
            {
              "id": "Window End",
              "displayName": "Window End",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": true
            },
            {
              "id": "Weight kg",
              "displayName": "Weight kg",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": true
            },
            {
              "id": "Special Type",
              "displayName": "Special Type",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "Normal",
                  "value": "Normal"
                },
                {
                  "name": "Fragile",
                  "value": "Fragile"
                },
                {
                  "name": "Heavy",
                  "value": "Heavy"
                }
              ],
              "readOnly": false,
              "removed": true
            },
            {
              "id": "Status",
              "displayName": "Status",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "Ready",
                  "value": "Ready"
                },
                {
                  "name": "Delivered",
                  "value": "Delivered"
                },
                {
                  "name": "Out for Delivery",
                  "value": "Out for Delivery"
                }
              ],
              "readOnly": false,
              "removed": false
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "type": "n8n-nodes-base.airtable",
      "typeVersion": 2.1,
      "position": [
        3120,
        768
      ],
      "id": "893ef462-248c-46f9-a128-05afb9172a33",
      "name": "Update Order Status",
      "credentials": {
        "airtableTokenApi": {
          "id": "0lstEdikXtvhmDPJ",
          "name": "Airtable account"
        }
      }
    },
    {
      "parameters": {
        "operation": "update",
        "base": {
          "__rl": true,
          "value": "appllYarQHA4ecVUd",
          "mode": "list",
          "cachedResultName": "Route & Load Optimization"
        },
        "table": {
          "__rl": true,
          "value": "tblrgPvARzBzlriXK",
          "mode": "list",
          "cachedResultName": "Fleet"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Availability": "Not Available",
            "Truck ID": "={{ $('Generate Whatsapp Message & Payload').item.json.airtablePayload[\"Truck ID\"] }}"
          },
          "matchingColumns": [
            "Truck ID"
          ],
          "schema": [
            {
              "id": "id",
              "displayName": "id",
              "required": false,
              "defaultMatch": true,
              "display": true,
              "type": "string",
              "readOnly": true,
              "removed": true
            },
            {
              "id": "Truck ID",
              "displayName": "Truck ID",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Driver Name",
              "displayName": "Driver Name",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": true
            },
            {
              "id": "Driver Phone",
              "displayName": "Driver Phone",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": true
            },
            {
              "id": "Max Weight kg",
              "displayName": "Max Weight kg",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "number",
              "readOnly": false,
              "removed": true
            },
            {
              "id": "Availability",
              "displayName": "Availability",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "options",
              "options": [
                {
                  "name": "Available",
                  "value": "Available"
                },
                {
                  "name": "Not Available",
                  "value": "Not Available"
                }
              ],
              "readOnly": false,
              "removed": false
            },
            {
              "id": "Active",
              "displayName": "Active",
              "required": false,
              "defaultMatch": false,
              "canBeUsedToMatch": true,
              "display": true,
              "type": "boolean",
              "readOnly": false,
              "removed": true
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "type": "n8n-nodes-base.airtable",
      "typeVersion": 2.1,
      "position": [
        3312,
        912
      ],
      "id": "907d6fa7-bc63-4ae6-b9aa-b11edd96a1dd",
      "name": "Update Truck Status",
      "credentials": {
        "airtableTokenApi": {
          "id": "0lstEdikXtvhmDPJ",
          "name": "Airtable account"
        }
      }
    }
  ],
  "pinData": {},
  "connections": {
    "Grouped Route": {
      "main": [
        [
          {
            "node": "Loop Over Delivery Records",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Route Details": {
      "main": [
        [
          {
            "node": "Get Google Maps Route",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split Order IDs": {
      "main": [
        [
          {
            "node": "Update Order Status",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Schedule Trigger": {
      "main": [
        [
          {
            "node": "Get Today Ready For Delivery Records",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Today Ready For Delivery Records": {
      "main": [
        [
          {
            "node": "Grouped Route",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Loop Over Delivery Records": {
      "main": [
        [],
        [
          {
            "node": "Generate Formula",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate Formula": {
      "main": [
        [
          {
            "node": "Get Available Truck",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Available Truck": {
      "main": [
        [
          {
            "node": "If Check Truck Availability",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "If Check Truck Availability": {
      "main": [
        [
          {
            "node": "Get Route Details",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Alert to Team for truck not available",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Alert to Team for truck not available": {
      "main": [
        [
          {
            "node": "Loop Over Delivery Records",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Google Maps Route": {
      "main": [
        [
          {
            "node": "Find a Distance & Duration",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Find a Distance & Duration": {
      "main": [
        [
          {
            "node": "Generate Route Link",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate Route Link": {
      "main": [
        [
          {
            "node": "Search Route Weather",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Search Route Weather": {
      "main": [
        [
          {
            "node": "Generate Weather Summary",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate Weather Summary": {
      "main": [
        [
          {
            "node": "Generate Whatsapp Message & Payload",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate Whatsapp Message & Payload": {
      "main": [
        [
          {
            "node": "Send WhatsApp to Driver Notify",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send WhatsApp to Driver Notify": {
      "main": [
        [
          {
            "node": "Notify to Supplier Team",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Notify to Supplier Team": {
      "main": [
        [
          {
            "node": "Append Payload Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Append Payload Data": {
      "main": [
        [
          {
            "node": "Split Order IDs",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Update Order Status": {
      "main": [
        [
          {
            "node": "Update Truck Status",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Update Truck Status": {
      "main": [
        [
          {
            "node": "Loop Over Delivery Records",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "2e9b67f5-f18f-4f6d-8943-bc266a19f758",
  "meta": {
    "templateCredsSetupCompleted": true,
    "instanceId": "f1c26778ec36097a9722a22c47c5e9c01f00b8862dadd0121ec118026a370fa6"
  },
  "id": "aNvFR4y77M86G5e2",
  "tags": []
}