{
  "name": "Automatically confirm Google Calendar appointments with Ringee AI phone calls",
  "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": "3612c4ff-5971-46b3-8f5c-ccbb83ce421a",
      "name": "Failure requires reconciliation",
      "type": "n8n-nodes-base.stopAndError",
      "typeVersion": 1,
      "position": [
        2300,
        1700
      ]
    },
    {
      "parameters": {
        "content": "### How it works\nA schedule reads timed Google Calendar events in a configurable reminder window. Eligible guests receive one reminder call; supported confirmed/cannot_attend outcomes color the existing event, and unresolved conversations go to the team.\n\nThis template is for Clinics, consultants, real estate teams, appointment businesses and automation agencies. A customer confirmation, a cancellation signal or a clear manual follow-up record. 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 Google Calendar, 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=01-appointment-confirmation).",
        "width": 570,
        "height": 700,
        "color": 1
      },
      "id": "70e702ee-3133-4b6f-836a-5a272c61d5c2",
      "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": "ed6f28f7-6362-404b-85e3-ce68c6f014ae",
      "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": "27701f07-6db0-43d5-84fd-32c8f9bdff84",
      "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": "1fcbfd92-439e-4703-8dfd-5cd4c96e51a5",
      "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. CRM properties are overwritten by call ID; tasks use an upsert key. Do not include sensitive transcripts in Slack.",
        "width": 1900,
        "height": 470,
        "color": 7
      },
      "id": "939c184c-b400-43d8-8453-f3d6f842a480",
      "name": "4. Deliver the business outcome",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        4650,
        80
      ]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "d8880648-c2b7-4ff5-8311-22d612671914",
              "name": "callsEnabled",
              "value": false,
              "type": "boolean"
            },
            {
              "id": "25c7775a-9bb4-4439-8faf-28a11775d160",
              "name": "clientNamespace",
              "value": "CHANGE_ME_CLIENT_NAMESPACE",
              "type": "string"
            },
            {
              "id": "8814b132-d7d6-49d6-88df-55b30a40cd34",
              "name": "maxCallsPerRun",
              "value": 1,
              "type": "number"
            },
            {
              "id": "05458a57-4456-423f-845a-ea9c1c519ecc",
              "name": "startHour",
              "value": 9,
              "type": "number"
            },
            {
              "id": "4b2922fb-74fb-401a-81d2-98b283c5f0a8",
              "name": "endHour",
              "value": 17,
              "type": "number"
            },
            {
              "id": "190a6883-0021-4afb-89ac-f5f9be4421d5",
              "name": "callingDays",
              "value": "1,2,3,4,5",
              "type": "string"
            },
            {
              "id": "13a7f68b-8fe7-46b3-897e-905d0f193649",
              "name": "reminderMinutes",
              "value": 60,
              "type": "number"
            },
            {
              "id": "dc449e86-4799-422a-89a0-320a234da06e",
              "name": "runStartedAt",
              "value": "={{ $now.startOf(\"minute\").toISO() }}",
              "type": "string"
            }
          ]
        },
        "includeOtherFields": true,
        "options": {}
      },
      "id": "0eac3d45-ab86-4ce3-8789-06ec2dca720b",
      "name": "Configuration",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.5,
      "position": [
        260,
        300
      ]
    },
    {
      "parameters": {},
      "id": "17f00df7-a39a-4d60-8688-188eb4a647d9",
      "name": "Held for manual review",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        1800,
        700
      ]
    },
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "minutes",
              "minutesInterval": 15
            }
          ]
        }
      },
      "id": "453be7c2-98a7-40a5-84a1-bdf52775e9d3",
      "name": "Run on schedule",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.3,
      "position": [
        0,
        300
      ]
    },
    {
      "parameters": {
        "resource": "event",
        "operation": "getAll",
        "calendar": {
          "__rl": true,
          "value": "",
          "mode": "list"
        },
        "returnAll": true,
        "timeMin": "={{ DateTime.fromISO($('Configuration').first().json.runStartedAt).plus({minutes:Number($('Configuration').first().json.reminderMinutes)}).toISO() }}",
        "timeMax": "={{ DateTime.fromISO($('Configuration').first().json.runStartedAt).plus({minutes:Number($('Configuration').first().json.reminderMinutes)+15}).toISO() }}",
        "options": {
          "recurringEventHandling": "expand",
          "orderBy": "startTime"
        }
      },
      "id": "fee10dcb-ba2f-42c4-87ce-fa9352c04025",
      "name": "Find upcoming appointments",
      "type": "n8n-nodes-base.googleCalendar",
      "typeVersion": 1.3,
      "position": [
        520,
        300
      ],
      "onError": "continueErrorOutput"
    },
    {
      "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 (!safeId(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 (row.attemptCount === '' || row.attemptCount === undefined || Number(row.attemptCount) !== 0)\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\tconst day = local.isValid ? local.toISODate() : 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\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,\"appointment\",null);"
      },
      "id": "6b8cc199-6a0d-46e8-8250-54238ad670fb",
      "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": "6eb383c5-66ee-414e-891e-8502a1ed7188",
              "leftValue": "={{ $json.eligible === true }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "a424bb83-1f0d-47a7-8cbb-b6c62b966ac3",
      "name": "Eligible for one authorized call?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        1520,
        300
      ]
    },
    {
      "parameters": {
        "batchSize": 1,
        "options": {}
      },
      "id": "a1329991-7162-43cc-8376-1304237381d9",
      "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 (!safeId(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 (row.attemptCount === '' || row.attemptCount === undefined || Number(row.attemptCount) !== 0)\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\tconst day = local.isValid ? local.toISODate() : 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\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,\"appointment\",null);"
      },
      "id": "955723fc-f529-49bc-8970-0cced7aca4f7",
      "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": "8b32763b-f794-454e-8e23-d77448b9e346",
              "leftValue": "={{ $json.eligible === true }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "4fc7b038-b0c5-4184-8c4f-26189237ce01",
      "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 01-appointment-confirmation"
        }
      },
      "id": "069266a2-aa79-4590-8865-bc9c45a204da",
      "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\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": "={{ $('Recheck hours before dialing').item.json.title }}"
          },
          "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:\"01-appointment-confirmation\"}) }}"
        }
      },
      "id": "a81d092f-fefe-4782-8b38-4efcb9ce0e3e",
      "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": "13bca791-cc4c-47cf-8a44-14a16daa9cb0",
      "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": "93dd8509-8f9d-4ba3-8e27-de9354d2100b",
              "leftValue": "={{ $json.queued === true }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "13888025-4b7d-49b0-8352-7bac365a9e49",
      "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": "3fe58e83-04d1-479d-8df8-398ff1a5dc53",
      "name": "Withdraw queued call",
      "type": "n8n-nodes-ringee.ringee",
      "typeVersion": 1,
      "position": [
        3720,
        680
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "amount": 2,
        "unit": "minutes"
      },
      "id": "09c526f6-a33c-4865-82e7-8a5fcb54e2e2",
      "name": "Wait for call completion",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        3960,
        300
      ],
      "webhookId": "3f3af728-a06b-41c4-8370-4e2779d7d3ba"
    },
    {
      "parameters": {
        "resource": "aiAgent",
        "operation": "getCallResult",
        "callId": "={{ $('Remember accepted call').item.json.call_id }}"
      },
      "id": "883b3043-e0ad-41c0-8c7f-d5f1357a4a59",
      "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": "1e4cd6a1-e080-4938-85e9-d01b57b5c218",
              "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": "9e146fab-618e-4464-8dae-98acd3efa462",
      "name": "Final status and analysis?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        4440,
        300
      ]
    },
    {
      "parameters": {
        "amount": 5,
        "unit": "minutes"
      },
      "id": "eab78606-0e95-4671-83ee-6bb4e76b8a16",
      "name": "One final result wait",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        4440,
        680
      ],
      "webhookId": "6b043001-a4b4-439e-8e4a-a886a54b51a5"
    },
    {
      "parameters": {
        "resource": "aiAgent",
        "operation": "getCallResult",
        "callId": "={{ $('Remember accepted call').item.json.call_id }}"
      },
      "id": "cfcd3ba9-01d0-48a8-8fae-5b438b79f3c8",
      "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,\"appointment\"),pairedItem:{item:index}}));"
      },
      "id": "57836173-e45d-45a7-88b8-bece971ee34e",
      "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": {},
        "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": "af034a32-6484-484c-88ac-cb71393b0b1e",
      "name": "Save actual call result",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        5180,
        300
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "resource": "event",
        "operation": "update",
        "calendar": {
          "__rl": true,
          "value": "",
          "mode": "list"
        },
        "eventId": "={{ $('Business result').item.json.eventId }}",
        "useDefaultReminders": true,
        "updateFields": {
          "color": "={{ ({'confirmed':'10','cancelled_by_customer':'11'})[$('Business result').item.json.route] || '5' }}"
        }
      },
      "id": "06077fb0-d26c-49f3-8028-799c5561d457",
      "name": "Color the existing appointment",
      "type": "n8n-nodes-base.googleCalendar",
      "typeVersion": 1.3,
      "position": [
        5420,
        300
      ],
      "onError": "continueErrorOutput"
    },
    {
      "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": "a65c51df-444c-4923-8cb4-233045c04d33",
      "name": "Notify the responsible team",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.7,
      "position": [
        6900,
        300
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "amount": 2,
        "unit": "seconds"
      },
      "id": "07357b6a-0b0d-491b-801d-07f68b750a85",
      "name": "Pace the next record",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        7140,
        300
      ],
      "webhookId": "69bd73bf-a253-4096-8194-60d684799466"
    },
    {
      "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": "2ec58eba-4846-493a-8121-98898b8c8135",
      "name": "Queued and delayed results",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        3440,
        600
      ]
    }
  ],
  "connections": {
    "Run on schedule": {
      "main": [
        [
          {
            "node": "Configuration",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Configuration": {
      "main": [
        [
          {
            "node": "Find upcoming appointments",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Find upcoming appointments": {
      "main": [
        [
          {
            "node": "Normalize and check eligibility",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Failure requires reconciliation",
            "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": "Create or update Ringee contact",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Held for manual review",
            "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": "Wait for call completion",
            "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": "Color the existing appointment",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Failure requires reconciliation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Business result": {
      "main": [
        [
          {
            "node": "Save actual call result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Color the existing appointment": {
      "main": [
        [
          {
            "node": "Notify the responsible team",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Failure requires reconciliation",
            "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
          }
        ]
      ]
    },
    "Pace the next record": {
      "main": [
        [
          {
            "node": "Process one record",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "executionTimeout": 3600
  },
  "pinData": {},
  "tags": []
}
