{
  "name": "Automate authorized HubSpot sales follow-up calls with Ringee",
  "nodes": [
    {
      "parameters": {
        "errorMessage": "A service step failed. Inspect the failed execution and the source record. Reconcile any accepted Ringee call before retrying; never change its call key to bypass an ambiguous failure."
      },
      "id": "e7cf1c04-ec4f-46ad-8ff0-85bd81a47209",
      "name": "Failure requires reconciliation",
      "type": "n8n-nodes-base.stopAndError",
      "typeVersion": 1,
      "position": [
        2300,
        1700
      ]
    },
    {
      "parameters": {
        "content": "### How it works\nA CRM automation sends a due follow-up with a stable activity ID and permission evidence. The workflow retrieves the HubSpot contact, checks the intended stage and due time, then records the call result and creates a follow-up task when needed.\n\nThis template is for Sales teams and agencies operating repeatable client pipelines. An auditable follow-up activity with a next action for the sales owner. Ringee runs the voice conversation; n8n manages the surrounding records and decisions.\n\n### Setup\nInstall the verified **n8n-nodes-ringee 0.1.2** package. Create a Ringee account and a workspace Custom Integration, then select its API key in an n8n credential. Choose your already configured voice agent, keep callsEnabled false, and configure permission evidence, recipient timezones and a unique client namespace. Connect Authenticated webhook, HubSpot, Google Sheets, Slack and select every blank destination. Signed triggers also need the Signing Secret and the integration Outbound URL. Import into a new inactive workflow and test dedicated demonstration records before activation.\n\n### Customization\nStart with one authorized call per run. Change calling days and hours for your recipients; this does not establish legal compliance. No automatic redial is included. Read the companion setup guide for column names, field mappings and limitations. [Create your Ringee account](https://ringee.io/integrations/n8n?utm_source=n8n&utm_medium=template&utm_campaign=ringee_workflows&utm_content=06-crm-sales-follow-up).",
        "width": 570,
        "height": 700,
        "color": 1
      },
      "id": "c001d420-0f2f-4cb9-8b8d-ccd53c24fb2f",
      "name": "Overview",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -600,
        -320
      ]
    },
    {
      "parameters": {
        "content": "## Configure the source\nSelect credentials and destinations. Calling workflows require trusted permission evidence and an IANA timezone for each recipient.",
        "width": 1600,
        "height": 400,
        "color": 7
      },
      "id": "49fd0497-a361-4213-8beb-163fb7d37473",
      "name": "1. Configure and admit records",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        0,
        80
      ]
    },
    {
      "parameters": {
        "content": "## Control billable work\nThe model cannot grant consent. Keep persistent keys, serial processing and the one-to-five call cap. Ringee also enforces its financial, DNC and capacity gates.",
        "width": 1500,
        "height": 470,
        "color": 7
      },
      "id": "35cddd09-e69a-4e35-80d3-9f0d1dbe6f6d",
      "name": "2. One authorized call",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1650,
        80
      ]
    },
    {
      "parameters": {
        "content": "## Wait for real results\nCompletion and analysis are separate. Two bounded reads preserve pending or missing-analysis states. Failures require inspection; a result read never starts a call.",
        "width": 1400,
        "height": 470,
        "color": 7
      },
      "id": "e9a2c697-ff3f-467d-8ab4-624bc451b60e",
      "name": "3. Reconcile the result",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        3200,
        80
      ]
    },
    {
      "parameters": {
        "content": "## Update the destination\nConfigure the private results sheet and team channel. Review CRM snapshot ordering and task ownership before activation. Do not include sensitive transcripts in Slack.",
        "width": 1900,
        "height": 470,
        "color": 7
      },
      "id": "18b4e111-9f82-452b-82cd-eb86e7bb97ea",
      "name": "4. Deliver the business outcome",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        4650,
        80
      ]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "ffa2f742-631e-4c90-8a7f-a60ca1d8fb35",
              "name": "callsEnabled",
              "value": false,
              "type": "boolean"
            },
            {
              "id": "73e8715c-2e1a-4c2a-8b56-96bcca5683a9",
              "name": "clientNamespace",
              "value": "CHANGE_ME_CLIENT_NAMESPACE",
              "type": "string"
            },
            {
              "id": "ac0d5641-4e43-4b41-84c3-7b99a4a01658",
              "name": "maxCallsPerRun",
              "value": 1,
              "type": "number"
            },
            {
              "id": "a3f47fa6-054b-448a-861c-4abcbdac2bc3",
              "name": "startHour",
              "value": 9,
              "type": "number"
            },
            {
              "id": "8d42f505-5e6f-43c2-8f10-e918bdbb4e4b",
              "name": "endHour",
              "value": 17,
              "type": "number"
            },
            {
              "id": "ebf51b3f-6717-43d2-81ff-f9bc0283ac9d",
              "name": "callingDays",
              "value": "1,2,3,4,5",
              "type": "string"
            },
            {
              "id": "715ebda1-7812-4929-865e-c38e810548bc",
              "name": "eligibleStage",
              "value": "follow_up",
              "type": "string"
            }
          ]
        },
        "includeOtherFields": true,
        "options": {}
      },
      "id": "bf846bf9-6777-4c5f-839e-c6110e7e3531",
      "name": "Configuration",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.5,
      "position": [
        260,
        300
      ]
    },
    {
      "parameters": {},
      "id": "ae333dcb-9e4a-498c-83f3-5db01163bebe",
      "name": "Held for manual review",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        1800,
        700
      ]
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "ringee-06-crm-sales-follow-up",
        "authentication": "headerAuth",
        "responseMode": "onReceived",
        "options": {}
      },
      "id": "301f4a8b-2c1d-43bb-8614-f8794d63e89a",
      "name": "Authorized intake",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2.2,
      "position": [
        0,
        300
      ],
      "webhookId": "b3fc4526-5446-487e-8b39-05e2047aa54d"
    },
    {
      "parameters": {
        "authentication": "oAuth2",
        "resource": "contact",
        "operation": "get",
        "contactId": "={{ String($('Authorized intake').item.json.body.hubspotContactId || '') }}",
        "additionalFields": {
          "propertiesCollection": {
            "propertiesValues": {
              "properties": [
                "phone",
                "email",
                "firstname",
                "lastname"
              ],
              "propertyMode": "valueOnly"
            }
          }
        }
      },
      "id": "ce8ac104-b241-442c-8d02-cf6bff7fb215",
      "name": "Retrieve HubSpot contact",
      "type": "n8n-nodes-base.hubspot",
      "typeVersion": 2.3,
      "position": [
        520,
        300
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const p=$json.properties||{}; const v=x=>x&&typeof x==='object'&&'value'in x?x.value:x;\nconst policy=$('Authorized intake').item.json.body;\nreturn [{json:{...policy,phone:v(p.phone)||'',email:v(p.email)||'',name:[v(p.firstname),v(p.lastname)].filter(Boolean).join(' ')}}];"
      },
      "id": "e2088588-7eaf-4429-8d13-19d0e048cb73",
      "name": "Join CRM fields to authorized activity",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        760,
        300
      ]
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "function normalizeRecords(items, config, now, kind, sourceEvent = null) {\n\tconst yes = (v) => v === true || String(v).trim().toLowerCase() === 'true';\n\tconst no = (v) => v === false || String(v).trim().toLowerCase() === 'false';\n\tconst cleanPhone = (v) => {\n\t\tconst text = String(v ?? '').trim();\n\t\tif (!/^(?:\\+|00)[\\d\\s().-]+$/.test(text)) return '';\n\t\treturn text.replace(/^00/, '+').replace(/[\\s().-]/g, '');\n\t};\n\tconst safeId = (v) => /^[A-Za-z0-9_.:@/+~=-]{1,120}$/.test(String(v ?? ''));\n\tconst namespace = String(config.clientNamespace ?? '');\n\tconst limit = Math.max(1, Math.min(5, Math.floor(Number(config.maxCallsPerRun) || 1)));\n\tconst seen = new Set();\n\tlet accepted = 0;\n\treturn items.map((item, index) => {\n\t\tlet row = { ...(item.json.body ?? item.json) };\n\t\tlet extra = {};\n\t\tif (kind === 'appointment' && row.eventId) {\n\t\t\textra = {\n\t\t\t\teventId: row.eventId,\n\t\t\t\tappointmentStart: row.appointmentStart,\n\t\t\t\ttitle: row.title,\n\t\t\t\tinReminderWindow: Date.parse(row.appointmentStart ?? '') > now.toMillis(),\n\t\t\t};\n\t\t} else if (kind === 'appointment') {\n\t\t\tconst description = String(row.description ?? '');\n\t\t\tconst line = (key) =>\n\t\t\t\tdescription.match(new RegExp('^' + key + ':[ \\\\t]*([^\\\\r\\\\n]*)', 'im'))?.[1]?.trim() ?? '';\n\t\t\tconst startMillis = Date.parse(row.start?.dateTime ?? '');\n\t\t\tconst anchor = Date.parse(config.runStartedAt ?? '') || now.toMillis();\n\t\t\tconst minutes = (startMillis - anchor) / 60000;\n\t\t\textra = {\n\t\t\t\teventId: row.id,\n\t\t\t\tappointmentStart: row.start?.dateTime ?? '',\n\t\t\t\ttitle: row.summary ?? 'Appointment',\n\t\t\t\tinReminderWindow:\n\t\t\t\t\tNumber.isFinite(startMillis) &&\n\t\t\t\t\tminutes >= Number(config.reminderMinutes) &&\n\t\t\t\t\tminutes < Number(config.reminderMinutes) + 15 &&\n\t\t\t\t\trow.status !== 'cancelled',\n\t\t\t};\n\t\t\trow = {\n\t\t\t\trecordId: row.id,\n\t\t\t\tphone: line('Phone'),\n\t\t\t\tname: line('Name'),\n\t\t\t\ttimezone: line('Timezone'),\n\t\t\t\tconsent: line('Consent'),\n\t\t\t\tconsentRecordedAt: line('ConsentRecordedAt'),\n\t\t\t\tauthorized: line('Authorized'),\n\t\t\t\tsuppressionChecked: line('SuppressionChecked'),\n\t\t\t\tdoNotCall: line('DoNotCall'),\n\t\t\t\tattemptCount: line('AttemptCount'),\n\t\t\t\temail: line('Email'),\n\t\t\t};\n\t\t}\n\t\tif (kind === 'callback') {\n\t\t\tconst event = sourceEvent ?? {};\n\t\t\tconst data = event.data ?? {};\n\t\t\tconst timestamp = Date.parse(event.occurredAt ?? '');\n\t\t\tconst age = now.toMillis() - timestamp;\n\t\t\tconst isInboundMiss =\n\t\t\t\tevent.event === 'call.missed' &&\n\t\t\t\t(data.direction === 'inbound' || data.call?.direction === 'inbound') &&\n\t\t\t\t!data.agent &&\n\t\t\t\t!data.call?.voiceAgentCall &&\n\t\t\t\t!String(data.externalId ?? '').startsWith('ringee-callback:') &&\n\t\t\t\tage >= 0 &&\n\t\t\t\tage <= 30 * 60000;\n\t\t\textra = { eventId: event.eventId, missedCallId: data.callId, isInboundMiss };\n\t\t\trow = { ...row, recordId: data.callId, phone: data.fromNumber, name: row.name ?? 'Caller' };\n\t\t}\n\t\tconst phone = cleanPhone(row.phone);\n\t\tconst local = now.setZone(String(row.timezone ?? ''));\n\t\tconst reasons = [];\n\t\tif (!yes(config.callsEnabled)) reasons.push('calls_disabled');\n\t\tif (!/^[A-Za-z0-9_.-]{1,120}$/.test(namespace) || namespace.includes('CHANGE_ME'))\n\t\t\treasons.push('configure_client_namespace');\n\t\tif (!safeId(row.recordId)) reasons.push('missing_or_invalid_record_id');\n\t\tif (!/^\\+[1-9]\\d{7,14}$/.test(phone)) reasons.push('invalid_e164_phone');\n\t\tif (!yes(row.authorized) || !yes(row.consent)) reasons.push('authorization_or_consent_missing');\n\t\tconst consentAt = Date.parse(row.consentRecordedAt ?? '');\n\t\tif (!Number.isFinite(consentAt) || consentAt > now.toMillis())\n\t\t\treasons.push('invalid_consent_timestamp');\n\t\tif (!yes(row.suppressionChecked) || !no(row.doNotCall))\n\t\t\treasons.push('suppression_check_required');\n\t\tif (\n\t\t\t!(\n\t\t\t\trow.attemptCount === 0 ||\n\t\t\t\t(typeof row.attemptCount === 'string' && row.attemptCount.trim() === '0')\n\t\t\t)\n\t\t)\n\t\t\treasons.push('already_attempted_or_attempt_count_missing');\n\t\tconst startHour = Number(config.startHour);\n\t\tconst endHour = Number(config.endHour);\n\t\tconst days = String(config.callingDays ?? '')\n\t\t\t.split(',')\n\t\t\t.map(Number);\n\t\tif (!local.isValid || !String(row.timezone ?? '').includes('/'))\n\t\t\treasons.push('recipient_iana_timezone_required');\n\t\telse if (\n\t\t\t!Number.isInteger(startHour) ||\n\t\t\t!Number.isInteger(endHour) ||\n\t\t\tstartHour < 0 ||\n\t\t\tendHour > 24 ||\n\t\t\tstartHour >= endHour ||\n\t\t\t!days.includes(local.weekday) ||\n\t\t\tlocal.hour < startHour ||\n\t\t\tlocal.hour >= endHour\n\t\t)\n\t\t\treasons.push('outside_calling_hours');\n\t\tif (kind === 'appointment' && !extra.inReminderWindow) reasons.push('not_in_reminder_window');\n\t\tif (kind === 'callback' && !extra.isInboundMiss)\n\t\t\treasons.push('not_a_recent_human_inbound_missed_call');\n\t\tif (kind === 'followup') {\n\t\t\tconst due = Date.parse(row.followUpAt ?? '');\n\t\t\tif (!Number.isFinite(due) || due > now.toMillis() || now.toMillis() - due > 86400000)\n\t\t\t\treasons.push('followup_not_due');\n\t\t\tif (String(row.stage ?? '') !== String(config.eligibleStage ?? 'follow_up'))\n\t\t\t\treasons.push('ineligible_crm_stage');\n\t\t}\n\t\tif (kind === 'invoice') {\n\t\t\tconst due = Date.parse(row.dueAt ?? '');\n\t\t\tconst daysToDue = (due - now.toMillis()) / 86400000;\n\t\t\tif (\n\t\t\t\trow.invoiceStatus !== 'open' ||\n\t\t\t\t!(Number(row.amountDue) > 0) ||\n\t\t\t\t!Number.isFinite(due) ||\n\t\t\t\tdaysToDue > 3 ||\n\t\t\t\tdaysToDue < -30 ||\n\t\t\t\tyes(row.disputed) ||\n\t\t\t\t!no(row.disputed)\n\t\t\t)\n\t\t\t\treasons.push('invoice_not_eligible');\n\t\t}\n\t\tif (kind === 'agent' && (!yes(row.approved) || !safeId(row.authorizationId)))\n\t\t\treasons.push('human_approval_required');\n\t\tif (['qualification', 'speed', 'booking', 'sheet'].includes(kind) && row.status !== 'ready')\n\t\t\treasons.push('record_not_ready');\n\t\t// A retry must retain the missed event's recipient-local day across midnight.\n\t\tconst eventMillis = Date.parse(sourceEvent?.occurredAt ?? '');\n\t\tconst day =\n\t\t\tkind === 'callback' && local.isValid && Number.isFinite(eventMillis)\n\t\t\t\t? local.minus({ milliseconds: now.toMillis() - eventMillis }).toISODate()\n\t\t\t\t: local.isValid\n\t\t\t\t\t? local.toISODate()\n\t\t\t\t\t: now.toISODate();\n\t\tconst identity =\n\t\t\tkind === 'callback'\n\t\t\t\t? phone + ':' + day\n\t\t\t\t: kind === 'agent'\n\t\t\t\t\t? row.authorizationId\n\t\t\t\t\t: row.recordId;\n\t\tconst callKey = 'ringee-' + kind + ':' + namespace + ':' + String(identity ?? '');\n\t\tif (callKey.length > 255) reasons.push('call_key_too_long');\n\t\tif (seen.has(phone)) reasons.push('duplicate_phone_in_input');\n\t\tif (!reasons.length && accepted >= limit) reasons.push('run_call_limit_reached');\n\t\tif (!reasons.length) {\n\t\t\taccepted++;\n\t\t\tseen.add(phone);\n\t\t}\n\t\treturn {\n\t\t\tjson: {\n\t\t\t\t...row,\n\t\t\t\t...extra,\n\t\t\t\t...(kind === 'callback' ? { missedEventOccurredAt: sourceEvent?.occurredAt ?? '' } : {}),\n\t\t\t\tphone,\n\t\t\t\tcallKey,\n\t\t\t\teligible: reasons.length === 0,\n\t\t\t\tdecision: reasons.length ? 'held' : 'eligible',\n\t\t\t\tholdReasons: reasons.join(', '),\n\t\t\t\ttemplate: kind,\n\t\t\t},\n\t\t\tpairedItem: { item: index },\n\t\t};\n\t});\n}\nreturn normalizeRecords($input.all(),$('Configuration').first().json,$now,\"followup\",null);"
      },
      "id": "77731c43-024f-4e2b-84b4-cecf630cfda5",
      "name": "Normalize and check eligibility",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1280,
        300
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "cb5193b7-2392-442a-838e-b9384ab6e097",
              "leftValue": "={{ $json.eligible === true }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "adb5f248-b291-4e3b-8e0f-ee3a9ab7f77f",
      "name": "Eligible for one authorized call?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        1520,
        300
      ]
    },
    {
      "parameters": {
        "batchSize": 1,
        "options": {}
      },
      "id": "1f910bf3-5ccf-42e8-817b-67ea622e7346",
      "name": "Process one record",
      "type": "n8n-nodes-base.splitInBatches",
      "typeVersion": 3,
      "position": [
        1760,
        300
      ]
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "function normalizeRecords(items, config, now, kind, sourceEvent = null) {\n\tconst yes = (v) => v === true || String(v).trim().toLowerCase() === 'true';\n\tconst no = (v) => v === false || String(v).trim().toLowerCase() === 'false';\n\tconst cleanPhone = (v) => {\n\t\tconst text = String(v ?? '').trim();\n\t\tif (!/^(?:\\+|00)[\\d\\s().-]+$/.test(text)) return '';\n\t\treturn text.replace(/^00/, '+').replace(/[\\s().-]/g, '');\n\t};\n\tconst safeId = (v) => /^[A-Za-z0-9_.:@/+~=-]{1,120}$/.test(String(v ?? ''));\n\tconst namespace = String(config.clientNamespace ?? '');\n\tconst limit = Math.max(1, Math.min(5, Math.floor(Number(config.maxCallsPerRun) || 1)));\n\tconst seen = new Set();\n\tlet accepted = 0;\n\treturn items.map((item, index) => {\n\t\tlet row = { ...(item.json.body ?? item.json) };\n\t\tlet extra = {};\n\t\tif (kind === 'appointment' && row.eventId) {\n\t\t\textra = {\n\t\t\t\teventId: row.eventId,\n\t\t\t\tappointmentStart: row.appointmentStart,\n\t\t\t\ttitle: row.title,\n\t\t\t\tinReminderWindow: Date.parse(row.appointmentStart ?? '') > now.toMillis(),\n\t\t\t};\n\t\t} else if (kind === 'appointment') {\n\t\t\tconst description = String(row.description ?? '');\n\t\t\tconst line = (key) =>\n\t\t\t\tdescription.match(new RegExp('^' + key + ':[ \\\\t]*([^\\\\r\\\\n]*)', 'im'))?.[1]?.trim() ?? '';\n\t\t\tconst startMillis = Date.parse(row.start?.dateTime ?? '');\n\t\t\tconst anchor = Date.parse(config.runStartedAt ?? '') || now.toMillis();\n\t\t\tconst minutes = (startMillis - anchor) / 60000;\n\t\t\textra = {\n\t\t\t\teventId: row.id,\n\t\t\t\tappointmentStart: row.start?.dateTime ?? '',\n\t\t\t\ttitle: row.summary ?? 'Appointment',\n\t\t\t\tinReminderWindow:\n\t\t\t\t\tNumber.isFinite(startMillis) &&\n\t\t\t\t\tminutes >= Number(config.reminderMinutes) &&\n\t\t\t\t\tminutes < Number(config.reminderMinutes) + 15 &&\n\t\t\t\t\trow.status !== 'cancelled',\n\t\t\t};\n\t\t\trow = {\n\t\t\t\trecordId: row.id,\n\t\t\t\tphone: line('Phone'),\n\t\t\t\tname: line('Name'),\n\t\t\t\ttimezone: line('Timezone'),\n\t\t\t\tconsent: line('Consent'),\n\t\t\t\tconsentRecordedAt: line('ConsentRecordedAt'),\n\t\t\t\tauthorized: line('Authorized'),\n\t\t\t\tsuppressionChecked: line('SuppressionChecked'),\n\t\t\t\tdoNotCall: line('DoNotCall'),\n\t\t\t\tattemptCount: line('AttemptCount'),\n\t\t\t\temail: line('Email'),\n\t\t\t};\n\t\t}\n\t\tif (kind === 'callback') {\n\t\t\tconst event = sourceEvent ?? {};\n\t\t\tconst data = event.data ?? {};\n\t\t\tconst timestamp = Date.parse(event.occurredAt ?? '');\n\t\t\tconst age = now.toMillis() - timestamp;\n\t\t\tconst isInboundMiss =\n\t\t\t\tevent.event === 'call.missed' &&\n\t\t\t\t(data.direction === 'inbound' || data.call?.direction === 'inbound') &&\n\t\t\t\t!data.agent &&\n\t\t\t\t!data.call?.voiceAgentCall &&\n\t\t\t\t!String(data.externalId ?? '').startsWith('ringee-callback:') &&\n\t\t\t\tage >= 0 &&\n\t\t\t\tage <= 30 * 60000;\n\t\t\textra = { eventId: event.eventId, missedCallId: data.callId, isInboundMiss };\n\t\t\trow = { ...row, recordId: data.callId, phone: data.fromNumber, name: row.name ?? 'Caller' };\n\t\t}\n\t\tconst phone = cleanPhone(row.phone);\n\t\tconst local = now.setZone(String(row.timezone ?? ''));\n\t\tconst reasons = [];\n\t\tif (!yes(config.callsEnabled)) reasons.push('calls_disabled');\n\t\tif (!/^[A-Za-z0-9_.-]{1,120}$/.test(namespace) || namespace.includes('CHANGE_ME'))\n\t\t\treasons.push('configure_client_namespace');\n\t\tif (!safeId(row.recordId)) reasons.push('missing_or_invalid_record_id');\n\t\tif (!/^\\+[1-9]\\d{7,14}$/.test(phone)) reasons.push('invalid_e164_phone');\n\t\tif (!yes(row.authorized) || !yes(row.consent)) reasons.push('authorization_or_consent_missing');\n\t\tconst consentAt = Date.parse(row.consentRecordedAt ?? '');\n\t\tif (!Number.isFinite(consentAt) || consentAt > now.toMillis())\n\t\t\treasons.push('invalid_consent_timestamp');\n\t\tif (!yes(row.suppressionChecked) || !no(row.doNotCall))\n\t\t\treasons.push('suppression_check_required');\n\t\tif (\n\t\t\t!(\n\t\t\t\trow.attemptCount === 0 ||\n\t\t\t\t(typeof row.attemptCount === 'string' && row.attemptCount.trim() === '0')\n\t\t\t)\n\t\t)\n\t\t\treasons.push('already_attempted_or_attempt_count_missing');\n\t\tconst startHour = Number(config.startHour);\n\t\tconst endHour = Number(config.endHour);\n\t\tconst days = String(config.callingDays ?? '')\n\t\t\t.split(',')\n\t\t\t.map(Number);\n\t\tif (!local.isValid || !String(row.timezone ?? '').includes('/'))\n\t\t\treasons.push('recipient_iana_timezone_required');\n\t\telse if (\n\t\t\t!Number.isInteger(startHour) ||\n\t\t\t!Number.isInteger(endHour) ||\n\t\t\tstartHour < 0 ||\n\t\t\tendHour > 24 ||\n\t\t\tstartHour >= endHour ||\n\t\t\t!days.includes(local.weekday) ||\n\t\t\tlocal.hour < startHour ||\n\t\t\tlocal.hour >= endHour\n\t\t)\n\t\t\treasons.push('outside_calling_hours');\n\t\tif (kind === 'appointment' && !extra.inReminderWindow) reasons.push('not_in_reminder_window');\n\t\tif (kind === 'callback' && !extra.isInboundMiss)\n\t\t\treasons.push('not_a_recent_human_inbound_missed_call');\n\t\tif (kind === 'followup') {\n\t\t\tconst due = Date.parse(row.followUpAt ?? '');\n\t\t\tif (!Number.isFinite(due) || due > now.toMillis() || now.toMillis() - due > 86400000)\n\t\t\t\treasons.push('followup_not_due');\n\t\t\tif (String(row.stage ?? '') !== String(config.eligibleStage ?? 'follow_up'))\n\t\t\t\treasons.push('ineligible_crm_stage');\n\t\t}\n\t\tif (kind === 'invoice') {\n\t\t\tconst due = Date.parse(row.dueAt ?? '');\n\t\t\tconst daysToDue = (due - now.toMillis()) / 86400000;\n\t\t\tif (\n\t\t\t\trow.invoiceStatus !== 'open' ||\n\t\t\t\t!(Number(row.amountDue) > 0) ||\n\t\t\t\t!Number.isFinite(due) ||\n\t\t\t\tdaysToDue > 3 ||\n\t\t\t\tdaysToDue < -30 ||\n\t\t\t\tyes(row.disputed) ||\n\t\t\t\t!no(row.disputed)\n\t\t\t)\n\t\t\t\treasons.push('invoice_not_eligible');\n\t\t}\n\t\tif (kind === 'agent' && (!yes(row.approved) || !safeId(row.authorizationId)))\n\t\t\treasons.push('human_approval_required');\n\t\tif (['qualification', 'speed', 'booking', 'sheet'].includes(kind) && row.status !== 'ready')\n\t\t\treasons.push('record_not_ready');\n\t\t// A retry must retain the missed event's recipient-local day across midnight.\n\t\tconst eventMillis = Date.parse(sourceEvent?.occurredAt ?? '');\n\t\tconst day =\n\t\t\tkind === 'callback' && local.isValid && Number.isFinite(eventMillis)\n\t\t\t\t? local.minus({ milliseconds: now.toMillis() - eventMillis }).toISODate()\n\t\t\t\t: local.isValid\n\t\t\t\t\t? local.toISODate()\n\t\t\t\t\t: now.toISODate();\n\t\tconst identity =\n\t\t\tkind === 'callback'\n\t\t\t\t? phone + ':' + day\n\t\t\t\t: kind === 'agent'\n\t\t\t\t\t? row.authorizationId\n\t\t\t\t\t: row.recordId;\n\t\tconst callKey = 'ringee-' + kind + ':' + namespace + ':' + String(identity ?? '');\n\t\tif (callKey.length > 255) reasons.push('call_key_too_long');\n\t\tif (seen.has(phone)) reasons.push('duplicate_phone_in_input');\n\t\tif (!reasons.length && accepted >= limit) reasons.push('run_call_limit_reached');\n\t\tif (!reasons.length) {\n\t\t\taccepted++;\n\t\t\tseen.add(phone);\n\t\t}\n\t\treturn {\n\t\t\tjson: {\n\t\t\t\t...row,\n\t\t\t\t...extra,\n\t\t\t\t...(kind === 'callback' ? { missedEventOccurredAt: sourceEvent?.occurredAt ?? '' } : {}),\n\t\t\t\tphone,\n\t\t\t\tcallKey,\n\t\t\t\teligible: reasons.length === 0,\n\t\t\t\tdecision: reasons.length ? 'held' : 'eligible',\n\t\t\t\tholdReasons: reasons.join(', '),\n\t\t\t\ttemplate: kind,\n\t\t\t},\n\t\t\tpairedItem: { item: index },\n\t\t};\n\t});\n}\nreturn normalizeRecords($input.all(),$('Configuration').first().json,$now,\"followup\",null);"
      },
      "id": "dfb09b79-49d2-4ce1-8c55-3f31fb644722",
      "name": "Recheck hours before dialing",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2000,
        300
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "a4e1c0fe-4f85-4c4c-8085-465b5a8ebccd",
              "leftValue": "={{ $json.eligible === true }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "18e6bc58-96d1-4011-8ea7-f101c7c4bb05",
      "name": "Still eligible now?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        2240,
        300
      ]
    },
    {
      "parameters": {
        "resource": "contact",
        "operation": "createOrUpdate",
        "phoneNumber": "={{ $('Recheck hours before dialing').item.json.phone }}",
        "additionalFields": {
          "name": "={{ $('Recheck hours before dialing').item.json.name }}",
          "email": "={{ $('Recheck hours before dialing').item.json.email || '' }}",
          "source": "n8n 06-crm-sales-follow-up"
        }
      },
      "id": "73b97c03-040e-4140-8220-9eeb60ee2009",
      "name": "Create or update Ringee contact",
      "type": "n8n-nodes-ringee.ringee",
      "typeVersion": 1,
      "position": [
        2480,
        300
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "resource": "aiAgent",
        "operation": "startCall",
        "agentId": {
          "__rl": true,
          "value": "",
          "mode": "list"
        },
        "phoneNumber": "={{ (function phoneAtDialTime(row, config, now) {\n\tconst local = now.setZone(String(row.timezone ?? ''));\n\tconst enabled = config.callsEnabled === true || config.callsEnabled === 'true';\n\tconst days = String(config.callingDays ?? '')\n\t\t.split(',')\n\t\t.map(Number);\n\tif (\n\t\t!enabled ||\n\t\trow.eligible !== true ||\n\t\t!local.isValid ||\n\t\t!days.includes(local.weekday) ||\n\t\tlocal.hour < Number(config.startHour) ||\n\t\tlocal.hour >= Number(config.endHour)\n\t) {\n\t\tthrow new Error(\n\t\t\t'The approved calling window is no longer open. Hold this record for manual review.',\n\t\t);\n\t}\n\tif (!/^\\+[1-9]\\d{7,14}$/.test(String(row.phone ?? '')))\n\t\tthrow new Error('A valid international phone number is required.');\n\tif (row.appointmentStart && Date.parse(row.appointmentStart) <= now.toMillis())\n\t\tthrow new Error('The appointment has already started.');\n\tif (row.template === 'callback') {\n\t\tconst age = now.toMillis() - Date.parse(row.missedEventOccurredAt ?? '');\n\t\tif (!Number.isFinite(age) || age < 0 || age > 30 * 60000)\n\t\t\tthrow new Error('The missed call is no longer recent. Hold for manual review.');\n\t}\n\treturn row.phone;\n})($('Recheck hours before dialing').item.json, $('Configuration').first().json, $now) }}",
        "variables": {
          "mappingMode": "defineBelow",
          "value": {
            "first_name": "={{ String($('Recheck hours before dialing').item.json.name || 'there').split(' ')[0] }}",
            "notification": "Please follow up on the authorized customer request."
          },
          "matchingColumns": [],
          "schema": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {
          "externalId": "={{ $('Recheck hours before dialing').item.json.callKey }}",
          "idempotencyKey": "={{ $('Recheck hours before dialing').item.json.callKey }}",
          "metadata": "={{ JSON.stringify({source_record_id:$('Recheck hours before dialing').item.json.recordId,template_slug:\"06-crm-sales-follow-up\"}) }}"
        }
      },
      "id": "afd7cccb-3fa5-41f1-866b-3443a7cd8903",
      "name": "Start authorized call",
      "type": "n8n-nodes-ringee.ringee",
      "typeVersion": 1,
      "position": [
        2720,
        300
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $input.all().map((item,index)=>({json:{...$('Recheck hours before dialing').item.json,...item.json},pairedItem:{item:index}}));"
      },
      "id": "4843d93c-e1e5-4c61-877d-2c41f922dd23",
      "name": "Remember accepted call",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        3480,
        300
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "9e2b16d5-4e08-4cf5-842b-adf1ce8f8781",
              "leftValue": "={{ $json.queued === true }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "d1f03d46-e3e3-460d-8423-5d1e37c0a96a",
      "name": "Was the call queued?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        3720,
        300
      ]
    },
    {
      "parameters": {
        "resource": "aiAgent",
        "operation": "cancelCall",
        "callId": "={{ $('Remember accepted call').item.json.call_id }}"
      },
      "id": "5902b42e-dc2b-4fe9-86a3-9068031462c9",
      "name": "Withdraw queued call",
      "type": "n8n-nodes-ringee.ringee",
      "typeVersion": 1,
      "position": [
        3720,
        680
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "amount": 2,
        "unit": "minutes"
      },
      "id": "19bcadd1-14a1-4663-8167-4d2cfe77d032",
      "name": "Wait for call completion",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        3960,
        300
      ],
      "webhookId": "17fce745-24fb-4508-84d4-783efcf1f274"
    },
    {
      "parameters": {
        "resource": "aiAgent",
        "operation": "getCallResult",
        "callId": "={{ $('Remember accepted call').item.json.call_id }}"
      },
      "id": "2ade9afe-dd94-43b1-8e65-b4621c74e6ed",
      "name": "Read call result",
      "type": "n8n-nodes-ringee.ringee",
      "typeVersion": 1,
      "position": [
        4200,
        300
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "6a6988f0-6e4c-4352-8255-04e8d5150c9a",
              "leftValue": "={{ $json.finished === true && (Boolean($json.outcome || $json.summary) || ['cancelled','expired','no_answer','busy','voicemail','failed'].includes($json.status)) }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "10f727e1-adfc-4148-81e9-437a9368ed78",
      "name": "Final status and analysis?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        4440,
        300
      ]
    },
    {
      "parameters": {
        "amount": 5,
        "unit": "minutes"
      },
      "id": "65953979-f122-4691-8ae1-d0b7c860ae63",
      "name": "One final result wait",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        4440,
        680
      ],
      "webhookId": "1b374640-32d1-4599-84e9-c5508fdf22a1"
    },
    {
      "parameters": {
        "resource": "aiAgent",
        "operation": "getCallResult",
        "callId": "={{ $('Remember accepted call').item.json.call_id }}"
      },
      "id": "55238ae4-2735-44bf-8e5a-0dbfda0993e5",
      "name": "Read call result again",
      "type": "n8n-nodes-ringee.ringee",
      "typeVersion": 1,
      "position": [
        4680,
        680
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "function classifyResult(result, context, kind) {\n\tconst final = [\n\t\t'completed',\n\t\t'no_answer',\n\t\t'busy',\n\t\t'voicemail',\n\t\t'failed',\n\t\t'cancelled',\n\t\t'expired',\n\t].includes(result.status);\n\tconst analysisReady = final && Boolean(result.outcome || result.summary);\n\tlet route = 'needs_review';\n\tif (!final) route = 'pending_manual_review';\n\telse if (['cancelled', 'expired'].includes(result.status)) route = 'never_dialed';\n\telse if (['no_answer', 'busy', 'voicemail', 'failed'].includes(result.status))\n\t\troute = 'unreached';\n\telse if (!analysisReady) route = 'analysis_pending';\n\telse if (kind === 'appointment')\n\t\troute =\n\t\t\tresult.outcome === 'confirmed'\n\t\t\t\t? 'confirmed'\n\t\t\t\t: result.outcome === 'cannot_attend'\n\t\t\t\t\t? 'cancelled_by_customer'\n\t\t\t\t\t: 'follow_up';\n\telse if (['meeting_booked', 'appointment_booked'].includes(result.outcome)) route = 'sales_ready';\n\telse if (['callback_requested', 'callback_scheduled'].includes(result.outcome))\n\t\troute = 'follow_up';\n\telse if (['not_interested', 'wrong_number'].includes(result.outcome)) route = 'closed';\n\tif (kind === 'invoice' && final && analysisReady) route = 'staff_review';\n\treturn {\n\t\t...context,\n\t\tcall_id: result.call_id || context.call_id || '',\n\t\tstatus: result.status || 'unresolved',\n\t\toutcome: result.outcome ?? '',\n\t\tsummary: result.summary ?? '',\n\t\tsentiment: result.sentiment ?? '',\n\t\textracted_data: result.extracted_data ?? {},\n\t\tappointment: result.appointment ?? null,\n\t\tanalysisReady,\n\t\troute,\n\t\tneedsAttention: !['confirmed', 'sales_ready', 'closed'].includes(route),\n\t\tnotification:\n\t\t\t'Ringee ' +\n\t\t\tkind +\n\t\t\t': ' +\n\t\t\troute +\n\t\t\t'. Record ' +\n\t\t\tString(context.recordId ?? '') +\n\t\t\t'. Call ' +\n\t\t\tString(result.call_id || context.call_id || '') +\n\t\t\t'. Review the conversation in Ringee.',\n\t};\n}\nreturn $input.all().map((item,index)=>({json:classifyResult(item.json,$('Remember accepted call').item.json,\"followup\"),pairedItem:{item:index}}));"
      },
      "id": "e23c99dc-737d-4362-8644-96b9dc016518",
      "name": "Business result",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        4940,
        300
      ]
    },
    {
      "parameters": {
        "resource": "sheet",
        "operation": "appendOrUpdate",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "list"
        },
        "sheetName": {
          "__rl": true,
          "value": "",
          "mode": "list"
        },
        "options": {
          "cellFormat": "RAW",
          "useAppend": true
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "recordId": "={{ $('Business result').item.json.recordId }}",
            "callKey": "={{ $('Business result').item.json.callKey }}",
            "call_id": "={{ $('Business result').item.json.call_id }}",
            "status": "={{ $('Business result').item.json.status }}",
            "outcome": "={{ $('Business result').item.json.outcome }}",
            "summary": "={{ $('Business result').item.json.summary }}",
            "sentiment": "={{ $('Business result').item.json.sentiment }}",
            "route": "={{ $('Business result').item.json.route }}",
            "attemptCount": 1
          },
          "matchingColumns": [
            "recordId"
          ],
          "schema": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        }
      },
      "id": "a5ff481d-5cd4-4851-8a5f-7ddcf77975f1",
      "name": "Save actual call result",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        5180,
        300
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "ce846d54-db6f-47af-8184-8b7bcc1e5d40",
              "leftValue": "={{ Boolean($('Business result').item.json.hubspotContactId) }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "b24fd59d-6a2e-4d30-8c6a-3a3721d0a9f9",
      "name": "Has a CRM email?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        5420,
        300
      ]
    },
    {
      "parameters": {
        "method": "PATCH",
        "url": "={{ 'https://api.hubapi.com/crm/v3/objects/contacts/' + encodeURIComponent(String($('Business result').item.json.hubspotContactId)) }}",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "hubspotOAuth2Api",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ {\"properties\":{\"ringee_last_call_id\":$('Business result').item.json.call_id,\"ringee_last_outcome\":$('Business result').item.json.outcome,\"ringee_last_summary\":$('Business result').item.json.summary,\"ringee_last_route\":$('Business result').item.json.route}} }}",
        "options": {
          "redirect": {
            "redirect": {
              "followRedirects": false
            }
          },
          "timeout": 10000
        }
      },
      "id": "a4584dba-9a99-4005-8ac7-201374fa3723",
      "name": "Update HubSpot call properties",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.5,
      "position": [
        5660,
        180
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {},
      "id": "8459d9c0-887b-46fb-8917-b465f87df861",
      "name": "CRM result handled",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        5900,
        300
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "2b30b849-019a-43ea-886e-edbe8b6e9eee",
              "leftValue": "={{ Boolean($('Business result').item.json.needsAttention || $('Business result').item.json.needsFollowUp) }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "7821b69a-8164-414b-8434-eeb92608d840",
      "name": "Needs a follow-up task?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        6140,
        300
      ]
    },
    {
      "parameters": {
        "resource": "sheet",
        "operation": "update",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "list"
        },
        "sheetName": {
          "__rl": true,
          "value": "",
          "mode": "list"
        },
        "options": {
          "cellFormat": "RAW"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "taskId": "={{ $('Business result').item.json.call_id }}",
            "recordId": "={{ $('Business result').item.json.recordId }}",
            "reason": "={{ $('Business result').item.json.route }}",
            "call_id": "={{ $('Business result').item.json.call_id }}"
          },
          "matchingColumns": [
            "taskId"
          ],
          "schema": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        }
      },
      "id": "e9480297-3f3e-4b1f-8f04-2747e06a3333",
      "name": "Upsert follow-up task",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        6380,
        180
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {},
      "id": "1c8cc0ca-caa1-4f65-86a3-ceab2090cecd",
      "name": "Follow-up routing handled",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        6620,
        300
      ]
    },
    {
      "parameters": {
        "authentication": "oAuth2",
        "resource": "message",
        "operation": "post",
        "select": "channel",
        "channelId": {
          "__rl": true,
          "value": "",
          "mode": "list"
        },
        "text": "={{ $('Business result').item.json.notification }}",
        "otherOptions": {
          "includeLinkToWorkflow": false
        }
      },
      "id": "f016c8ed-7f90-4535-82af-b8f7c44aeb82",
      "name": "Notify the responsible team",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.7,
      "position": [
        6900,
        300
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "amount": 2,
        "unit": "seconds"
      },
      "id": "7b258317-ee52-416d-8483-84cce3b4bbc3",
      "name": "Pace the next record",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        7140,
        300
      ],
      "webhookId": "cd7b4c3f-75b2-4d71-80fc-84aa04803223"
    },
    {
      "parameters": {
        "content": "## Reconcile accepted work\nWithdraw a queued call before it drifts outside the calling window. Read delayed results with the existing call ID. Neither branch starts another call.",
        "width": 1500,
        "height": 370,
        "color": 7
      },
      "id": "bc287ab8-2f8e-4eb4-8512-53eb28138710",
      "name": "Queued and delayed results",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        3440,
        600
      ]
    },
    {
      "id": "7a7219f7-37e7-4571-8543-bd6ba1fd99ef",
      "name": "Hold this record and continue",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        520,
        2200
      ],
      "parameters": {}
    },
    {
      "id": "071f8981-aa7e-4eeb-8a80-bfa177685bab",
      "name": "Reconcile failed withdrawal",
      "type": "n8n-nodes-ringee.ringee",
      "typeVersion": 1,
      "position": [
        920,
        2200
      ],
      "parameters": {
        "resource": "aiAgent",
        "operation": "getCallStatus",
        "callId": "={{ $('Remember accepted call').item.json.call_id }}"
      },
      "onError": "continueErrorOutput"
    },
    {
      "id": "6cb4cc42-e350-4fea-8deb-f0d5d612c0cc",
      "name": "Require resolved withdrawal",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1320,
        2200
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const row=$input.first().json; if (!row.status || row.status==='queued') throw new Error('Withdrawal is unconfirmed and the original call can still dispatch. Reconcile its call ID immediately; never start another call.'); return $input.all();"
      }
    },
    {
      "id": "047e3062-0c06-4425-8bdc-46c7870badf4",
      "name": "Read Ringee queue policy",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.5,
      "position": [
        1720,
        2200
      ],
      "parameters": {
        "method": "GET",
        "url": "https://api.ringee.io/api/v1/capabilities",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "ringeeApi",
        "options": {
          "redirect": {
            "redirect": {
              "followRedirects": false
            }
          },
          "timeout": 10000
        }
      },
      "onError": "continueErrorOutput"
    },
    {
      "id": "e87656ad-5577-44bc-8c7c-df3f0dc61ff4",
      "name": "Require immediate dispatch support",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2120,
        2200
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const c=$input.first().json; if(c.apiVersion!==1 || c.capabilities?.idempotentCalls!==true || c.capabilities?.queuedCalls!==false) throw new Error('This calling template requires a queue-disabled Ringee Cloud deployment. The published node cannot enforce a recipient-window dispatch deadline. No call was submitted.'); return [{json:$('Recheck hours before dialing').item.json}];"
      }
    },
    {
      "id": "06eb8a21-9496-405e-853d-b651a1d402b9",
      "name": "Read existing follow-up task",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        520,
        2480
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "list"
        },
        "sheetName": {
          "__rl": true,
          "value": "",
          "mode": "list"
        },
        "options": {},
        "filtersUI": {
          "values": [
            {
              "lookupColumn": "taskId",
              "lookupValue": "={{ $('Business result').item.json.call_id }}"
            }
          ]
        }
      },
      "alwaysOutputData": true,
      "onError": "continueErrorOutput"
    },
    {
      "id": "3769c540-8524-4f25-8d2c-c11b5692483c",
      "name": "Keep existing task or create",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        920,
        2480
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const rows=$input.all().filter(item=>item.json.taskId); if(rows.length>1) throw new Error('The follow-up task key is ambiguous. Reconcile the task sheet.'); return [{json:{existingTask:rows.length===1}}];"
      }
    },
    {
      "id": "076782b3-9072-402d-88f8-8d7758c10c7f",
      "name": "Follow-up task already exists?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        1320,
        2480
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "ce846d54-db6f-47af-8184-8b7bcc1e5d40",
              "leftValue": "={{ $json.existingTask === true }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "3768d6d3-0c38-4dc9-89cf-10cf68000b83",
      "name": "Create new follow-up task",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1720,
        2480
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "list"
        },
        "sheetName": {
          "__rl": true,
          "value": "",
          "mode": "list"
        },
        "options": {
          "cellFormat": "RAW",
          "useAppend": true
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "taskId": "={{ $('Business result').item.json.call_id }}",
            "recordId": "={{ $('Business result').item.json.recordId }}",
            "status": "open",
            "dueAt": "={{ $now.plus({days:1}).toISO() }}",
            "reason": "={{ $('Business result').item.json.route }}",
            "call_id": "={{ $('Business result').item.json.call_id }}"
          },
          "matchingColumns": [],
          "schema": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        }
      },
      "onError": "continueErrorOutput"
    }
  ],
  "connections": {
    "Authorized intake": {
      "main": [
        [
          {
            "node": "Configuration",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Configuration": {
      "main": [
        [
          {
            "node": "Retrieve HubSpot contact",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Retrieve HubSpot contact": {
      "main": [
        [
          {
            "node": "Join CRM fields to authorized activity",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Failure requires reconciliation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Join CRM fields to authorized activity": {
      "main": [
        [
          {
            "node": "Normalize and check eligibility",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Normalize and check eligibility": {
      "main": [
        [
          {
            "node": "Eligible for one authorized call?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Eligible for one authorized call?": {
      "main": [
        [
          {
            "node": "Process one record",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Held for manual review",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Process one record": {
      "main": [
        [],
        [
          {
            "node": "Recheck hours before dialing",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Recheck hours before dialing": {
      "main": [
        [
          {
            "node": "Still eligible now?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Still eligible now?": {
      "main": [
        [
          {
            "node": "Read Ringee queue policy",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Hold this record and continue",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create or update Ringee contact": {
      "main": [
        [
          {
            "node": "Start authorized call",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Failure requires reconciliation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Start authorized call": {
      "main": [
        [
          {
            "node": "Remember accepted call",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Failure requires reconciliation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Remember accepted call": {
      "main": [
        [
          {
            "node": "Was the call queued?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Withdraw queued call": {
      "main": [
        [
          {
            "node": "Wait for call completion",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Reconcile failed withdrawal",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Was the call queued?": {
      "main": [
        [
          {
            "node": "Withdraw queued call",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Wait for call completion",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read call result": {
      "main": [
        [
          {
            "node": "Final status and analysis?",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "One final result wait",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wait for call completion": {
      "main": [
        [
          {
            "node": "Read call result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Final status and analysis?": {
      "main": [
        [
          {
            "node": "Business result",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "One final result wait",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read call result again": {
      "main": [
        [
          {
            "node": "Business result",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Failure requires reconciliation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "One final result wait": {
      "main": [
        [
          {
            "node": "Read call result again",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save actual call result": {
      "main": [
        [
          {
            "node": "Has a CRM email?",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Failure requires reconciliation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Business result": {
      "main": [
        [
          {
            "node": "Save actual call result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Has a CRM email?": {
      "main": [
        [
          {
            "node": "Update HubSpot call properties",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "CRM result handled",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Update HubSpot call properties": {
      "main": [
        [
          {
            "node": "CRM result handled",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Failure requires reconciliation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "CRM result handled": {
      "main": [
        [
          {
            "node": "Needs a follow-up task?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Upsert follow-up task": {
      "main": [
        [
          {
            "node": "Follow-up routing handled",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Failure requires reconciliation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Needs a follow-up task?": {
      "main": [
        [
          {
            "node": "Read existing follow-up task",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Follow-up routing handled",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Notify the responsible team": {
      "main": [
        [
          {
            "node": "Pace the next record",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Failure requires reconciliation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Follow-up routing handled": {
      "main": [
        [
          {
            "node": "Notify the responsible team",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pace the next record": {
      "main": [
        [
          {
            "node": "Process one record",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Hold this record and continue": {
      "main": [
        [
          {
            "node": "Process one record",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Reconcile failed withdrawal": {
      "main": [
        [
          {
            "node": "Require resolved withdrawal",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Failure requires reconciliation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Require resolved withdrawal": {
      "main": [
        [
          {
            "node": "Wait for call completion",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Ringee queue policy": {
      "main": [
        [
          {
            "node": "Require immediate dispatch support",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Failure requires reconciliation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Require immediate dispatch support": {
      "main": [
        [
          {
            "node": "Create or update Ringee contact",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read existing follow-up task": {
      "main": [
        [
          {
            "node": "Keep existing task or create",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Failure requires reconciliation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Keep existing task or create": {
      "main": [
        [
          {
            "node": "Follow-up task already exists?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Follow-up task already exists?": {
      "main": [
        [
          {
            "node": "Upsert follow-up task",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Create new follow-up task",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create new follow-up task": {
      "main": [
        [
          {
            "node": "Follow-up routing handled",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Failure requires reconciliation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "executionTimeout": 3600
  },
  "pinData": {},
  "tags": []
}
