{
  "name": "WF-OB-1: First Call Scheduler",
  "nodes": [
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "cronExpression",
              "expression": "45 10 * * 1-5"
            },
            {
              "field": "cronExpression",
              "expression": "0 16 * * 1-5"
            },
            {
              "field": "cronExpression",
              "expression": "15 17 * * 1-5"
            },
            {
              "field": "cronExpression",
              "expression": "30 9 * * 6"
            }
          ]
        }
      },
      "id": "schedule",
      "name": "Schedule Trigger",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        0
      ]
    },
    {
      "parameters": {
        "jsCode": "var now = new Date(); var etHour = 0; var day = now.getDay(); var timezone='ET'; if(etHour>=17){timezone='PT';}else if(etHour>=15){timezone='CT';} var businessHoursOk=true; return [{ json: { timezone: timezone, maxPerBatch: 4, businessHoursOk: businessHoursOk, dayOfWeek: day } }];"
      },
      "id": "determine_tz",
      "name": "Determine Timezone Window",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        224,
        0
      ]
    },
    {
      "parameters": {
        "url": "https://api.close.com/api/v1/lead/",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBasicAuth",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "query",
              "value": "custom.cf_VFuXiSLbhAQIp4448PknymYFsHUx6P1rJpcvMimLz3j:\"VoiceSDR AI\" AND custom.cf_L6lj9vbbe1pnuRA2tAAeZs6eso00WI5MI8RNf23Bykn:1"
            },
            {
              "name": "_fields",
              "value": "id,display_name,contacts,custom,status_id"
            },
            {
              "name": "_limit",
              "value": "50"
            }
          ]
        },
        "options": {
          "response": {
            "response": {
              "neverError": true
            }
          },
          "timeout": 30000
        }
      },
      "id": "search_close",
      "name": "Search Close CRM",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        448,
        0
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "jsCode": "var response = $input.first().json; var data = response.data || []; var results = []; for (var i=0;i<data.length;i++){ var lead=data[i]; lead.callSequence=1; lead.isFollowUp=false; results.push({json:lead}); } return results;"
      },
      "id": "extract_leads",
      "name": "Extract Close Leads",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        464,
        -144
      ]
    },
    {
      "parameters": {
        "jsCode": "var coveredStates=['OH']; var items=$input.all(); var allowed=[]; for(var i=0;i<items.length;i++){ allowed.push(items[i]); } return allowed;"
      },
      "id": "filter_states",
      "name": "Filter Blocked States",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        704,
        0
      ]
    },
    {
      "parameters": {
        "jsCode": "var leads=$input.all().map(function(item){return item.json;}); return leads.map(function(lead){return {json:lead};});"
      },
      "id": "filter_tz",
      "name": "Filter by TZ + Extract",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        896,
        0
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "hl1",
              "leftValue": "={{ $json.no_leads }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "notEquals"
              }
            }
          ]
        },
        "options": {}
      },
      "id": "has_leads",
      "name": "Has Leads?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        960,
        -160
      ]
    },
    {
      "parameters": {
        "options": {}
      },
      "id": "batch",
      "name": "SplitInBatches",
      "type": "n8n-nodes-base.splitInBatches",
      "typeVersion": 3,
      "position": [
        1264,
        0
      ]
    },
    {
      "parameters": {
        "jsCode": "var items=$input.all(); var results=[]; var agentId='YOUR_RETELL_AGENT_ID'; for(var idx=0;idx<items.length;idx++){ var lead=items[idx].json; var phone=''; var firstName='there'; var fromNumber='+15555550100'; results.push({json:{ closeLeadId:lead.id, toNumber:phone, fromNumber:fromNumber, agentId:agentId, retellPayload:{ from_number:fromNumber, to_number:phone, override_agent_id:agentId, retell_llm_dynamic_variables:{ firstName:firstName, callDirection:'outbound' } } }}); } return results;"
      },
      "id": "build_retell",
      "name": "Build Retell Payload",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1568,
        0
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.retellai.com/v2/create-phone-call",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer YOUR_RETELL_API_KEY"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify($json.retellPayload) }}",
        "options": {}
      },
      "id": "call_retell",
      "name": "Call Retell API",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1792,
        0
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://YOUR_CONVEX_DEPLOYMENT/outbound-call-log",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ retellCallId: $json.call_id || '', closeLeadId: $('Build Retell Payload').first().json.closeLeadId, callStatus: 'initiated' }) }}",
        "options": {}
      },
      "id": "log_convex",
      "name": "Log Call to Convex",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2016,
        0
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "method": "PUT",
        "url": "=https://api.close.com/api/v1/lead/{{ $('Build Retell Payload').first().json.closeLeadId }}/",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBasicAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ 'custom.cf_L6lj9vbbe1pnuRA2tAAeZs6eso00WI5MI8RNf23Bykn': 2 }) }}",
        "options": {
          "response": {
            "response": {
              "neverError": true
            }
          },
          "timeout": 30000
        }
      },
      "id": "update_close",
      "name": "Update Close Call Fields",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2240,
        0
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "jsCode": "return $input.all();"
      },
      "id": "wait_1s",
      "name": "Wait 1s",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2464,
        0
      ]
    },
    {
      "parameters": {
        "select": "channel",
        "channelId": {
          "__rl": true,
          "value": "C0ABWBR67JL",
          "mode": "list",
          "cachedResultName": "test"
        },
        "text": "=*WF-OB-1 First Call Batch*\n:phone: *Timezone*: {{ $('Determine Timezone Window').first().json.timezone }}\n:busts_in_silhouette: *Batch Complete*",
        "otherOptions": {}
      },
      "id": "slack_summary",
      "name": "Slack Summary",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.2,
      "position": [
        1792,
        -224
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "content": "## WF-OB-1: First Call Scheduler\n\n**Purpose**: Fire FIRST Retell AI call for new leads. VoiceSDR AI. Owner. Source: Close CRM search."
      },
      "id": "sticky_overview",
      "name": "WF-OB-1 Overview",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -208,
        -352
      ]
    },
    {
      "parameters": {
        "maxItems": 10
      },
      "type": "n8n-nodes-base.limit",
      "typeVersion": 1,
      "position": [
        752,
        -160
      ],
      "id": "cd10db62-4262-4b83-b45e-38b66d3102bb",
      "name": "Limit"
    },
    {
      "parameters": {
        "jsCode": "return [{ json: { id: 'lead_bUgffcA1Ew4MzishfkVICz6D46N8VCTTgdbxrszD3My', display_name: 'Test caller', callSequence: 1, contacts: [{ id: 'cont_rtDRjEpvuYqoWgEiFhXQqwRt1Vfoc6XOvXhDeSnkmex', name: 'Test Caller', phones: [{ phone: '+15555550100', type: 'office' }], emails: [{ email: '', type: 'office' }] }] } }];"
      },
      "id": "test_data",
      "name": "TEST - Inject Test Lead",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        736,
        -368
      ]
    }
  ],
  "connections": {
    "Schedule Trigger": {
      "main": [
        [
          {
            "node": "Determine Timezone Window",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Determine Timezone Window": {
      "main": [
        [
          {
            "node": "Search Close CRM",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Search Close CRM": {
      "main": [
        [
          {
            "node": "Extract Close Leads",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract Close Leads": {
      "main": [
        [
          {
            "node": "Filter Blocked States",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Filter Blocked States": {
      "main": [
        [
          {
            "node": "Filter by TZ + Extract",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Filter by TZ + Extract": {
      "main": [
        [
          {
            "node": "Limit",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Limit": {
      "main": [
        [
          {
            "node": "Has Leads?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Has Leads?": {
      "main": [
        [
          {
            "node": "SplitInBatches",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "SplitInBatches",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "SplitInBatches": {
      "main": [
        [
          {
            "node": "Slack Summary",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Build Retell Payload",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Retell Payload": {
      "main": [
        [
          {
            "node": "Call Retell API",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Call Retell API": {
      "main": [
        [
          {
            "node": "Log Call to Convex",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log Call to Convex": {
      "main": [
        [
          {
            "node": "Update Close Call Fields",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Update Close Call Fields": {
      "main": [
        [
          {
            "node": "Wait 1s",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wait 1s": {
      "main": [
        [
          {
            "node": "SplitInBatches",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "TEST - Inject Test Lead": {
      "main": [
        []
      ]
    }
  },
  "settings": {
    "executionOrder": "v1",
    "timezone": "America/New_York"
  },
  "active": false
}