{
  "name": "Voicely phone agent (SIP): know the caller at ring, file the ticket after the call (DemoMart demo)",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "voicely-demomart-phone",
        "responseMode": "responseNode",
        "options": {
          "rawBody": true
        }
      },
      "id": "bee90909-a6c6-46ec-b965-290c2e604c29",
      "name": "Voicely Phone Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2.1,
      "position": [
        -400,
        0
      ],
      "webhookId": "de425cc3-d3d2-422a-8c12-9684d15b0b89"
    },
    {
      "parameters": {
        "mode": "raw",
        "jsonOutput": "{\n  \"voicelyPolicy\": {\n    \"storage\": \"both\",\n    \"ordersTableId\": \"SELECT_DEMOMART_ORDERS_TABLE_ID\",\n    \"ticketsTableId\": \"SELECT_DEMOMART_TICKETS_TABLE_ID\",\n    \"callsTableId\": \"SELECT_DEMOMART_CALLS_TABLE_ID\",\n    \"sheets\": {\n      \"documentId\": \"SELECT_GOOGLE_SPREADSHEET_ID\",\n      \"ordersSheet\": \"orders\",\n      \"ticketsSheet\": \"tickets\",\n      \"callsSheet\": \"calls\"\n    },\n    \"windowMs\": 300000,\n    \"bodyBytes\": 262144,\n    \"depth\": 32,\n    \"ticketBase\": 5000,\n    \"contextBytes\": 480,\n    \"expectedAccountId\": \"SET_YOUR_VOICELY_ACCOUNT_ID\",\n    \"lookupFields\": {\n      \"found\": \"boolean\",\n      \"order_id\": \"string\",\n      \"status\": \"string\",\n      \"expected_delivery\": \"string\",\n      \"revised_delivery\": \"string\",\n      \"delivered_on\": \"string\"\n    }\n  }\n}",
        "includeOtherFields": true,
        "options": {
          "stripBinary": false
        }
      },
      "id": "8a0632ff-7f3a-4573-9755-a24a37548c97",
      "name": "DemoMart Policy",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -170,
        0
      ]
    },
    {
      "parameters": {
        "jsCode": "return await (async function prepareSignedRequest(){\n const items=$input.all();if(items.length!==1)throw Error('voicely_webhook_item_invalid');\n const item=items[0],policy=item.json.voicelyPolicy;\n for(const name of ['windowMs','bodyBytes','depth'])if(!Number.isSafeInteger(policy?.[name])||policy[name]<=0)throw Error('voicely_webhook_policy_required');\n const headers=item.json.headers,id=headers?.['x-voicely-event-id'],stamp=headers?.['x-voicely-timestamp'],signature=headers?.['x-voicely-signature'];\n if(typeof id!=='string'||!id||typeof stamp!=='string'||!/^\\d+$/.test(stamp)||!Number.isSafeInteger(Number(stamp))||typeof signature!=='string'||!/^v1=[a-f0-9]{64}$/.test(signature)||Math.abs(Date.now()-Number(stamp))>policy.windowMs)throw Error('voicely_webhook_unauthorized');\n const raw=await this.helpers.getBinaryDataBuffer(0,'data');if(!Buffer.isBuffer(raw)||raw.length>policy.bodyBytes)throw Error('voicely_webhook_body_refused');\n const prefix=Buffer.from(JSON.stringify([1,Number(stamp),id])+'\\n'),frame=Buffer.concat([prefix,raw]);\n return [{json:{voicelyPolicy:policy,voicelyId:id,voicelyStamp:stamp,voicelySignature:signature,voicelyRaw:raw.toString('base64')},binary:{voicelySigned:{data:frame.toString('base64'),mimeType:'application/octet-stream'}}}];\n}).call(this);"
      },
      "id": "e2637e94-3e1f-46d6-9c82-c82a53bb5478",
      "name": "Prepare Voicely Signature",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        60,
        0
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "jsCode": "// >>> PASTE your Voicely webhook signing secret (whsec_...) between the quotes. Kept only here, never in execution data. <<<\nconst SIGNING_SECRET='PASTE_YOUR_WHSEC_SIGNING_SECRET_HERE';\n// VERIFY VOICELY SIGNATURE (replaces the Crypto node). Voicely's key is the part of the endpoint secret after \"whsec_\",\n// base64url-decoded (see Voicely > API access > Webhooks > \"How to verify a webhook\"). Pure JavaScript HMAC-SHA256:\n// no credential, no built-in module, so it runs the same on self-hosted n8n and n8n Cloud.\nreturn await (async function verifyVoicely(){\n const items=$input.all();if(items.length!==1)throw Error('voicely_webhook_item_invalid');\n const item=items[0],secret=SIGNING_SECRET;\n if(typeof secret!=='string'||!/^whsec_[A-Za-z0-9_-]{43,}$/.test(secret))throw Error('voicely_signing_secret_not_configured');\n const fromB64url=s=>{const t=s.replace(/-/g,'+').replace(/_/g,'/');return Uint8Array.from(Buffer.from(t+'='.repeat((4-t.length%4)%4),'base64'));};\n const K=new Uint32Array([0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2]);\n const sha256=msg=>{const l=msg.length,n=((l+9+63)>>6)<<6,b=new Uint8Array(n);b.set(msg);b[l]=0x80;const bits=l*8;\n  for(let i=0;i<8;i++)b[n-1-i]=Math.floor(bits/2**(8*i))&255;\n  const H=new Uint32Array([0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19]),W=new Uint32Array(64);\n  const r=(x,s)=>(x>>>s)|(x<<(32-s));\n  for(let o=0;o<n;o+=64){for(let i=0;i<16;i++)W[i]=(b[o+4*i]<<24)|(b[o+4*i+1]<<16)|(b[o+4*i+2]<<8)|b[o+4*i+3];\n   for(let i=16;i<64;i++){const s0=r(W[i-15],7)^r(W[i-15],18)^(W[i-15]>>>3),s1=r(W[i-2],17)^r(W[i-2],19)^(W[i-2]>>>10);W[i]=(W[i-16]+s0+W[i-7]+s1)>>>0;}\n   let [a,bb,c,d,e,f,g,h]=H;\n   for(let i=0;i<64;i++){const S1=r(e,6)^r(e,11)^r(e,25),ch=(e&f)^(~e&g),t1=(h+S1+ch+K[i]+W[i])>>>0,S0=r(a,2)^r(a,13)^r(a,22),mj=(a&bb)^(a&c)^(bb&c),t2=(S0+mj)>>>0;\n    h=g;g=f;f=e;e=(d+t1)>>>0;d=c;c=bb;bb=a;a=(t1+t2)>>>0;}\n   H[0]+=a;H[1]+=bb;H[2]+=c;H[3]+=d;H[4]+=e;H[5]+=f;H[6]+=g;H[7]+=h;}\n  const out=new Uint8Array(32);for(let i=0;i<8;i++){out[4*i]=H[i]>>>24;out[4*i+1]=(H[i]>>>16)&255;out[4*i+2]=(H[i]>>>8)&255;out[4*i+3]=H[i]&255;}return out;};\n const hmac=(key,msg)=>{let k=key.length>64?sha256(key):key;const kp=new Uint8Array(64);kp.set(k);const ip=new Uint8Array(64+msg.length),op=new Uint8Array(96);\n  for(let i=0;i<64;i++){ip[i]=kp[i]^0x36;op[i]=kp[i]^0x5c;}ip.set(msg,64);op.set(sha256(ip),64);return sha256(op);};\n const frame=Uint8Array.from(Buffer.from(item.binary.voicelySigned.data,'base64'));\n const expectedSignature=Array.from(hmac(fromB64url(secret.slice(6)),frame),x=>x.toString(16).padStart(2,'0')).join('');\n const json={...item.json,expectedSignature};return [{json}];\n})();\n"
      },
      "id": "70f611e5-0b2d-4aed-82d4-2862e037aa8c",
      "name": "Verify Voicely HMAC",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        290,
        0
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Voicely webhook envelope (signed with this endpoint's secret): {id, type, created_at, account_id, api_version, data}.\nreturn await (function acceptEvent(){\n const items=$input.all();if(items.length!==1)throw Error('voicely_webhook_item_invalid');const j=items[0].json,p=j.voicelyPolicy;\n if(typeof j.expectedSignature!=='string'||!/^[a-f0-9]{64}$/.test(j.expectedSignature)||typeof j.voicelySignature!=='string'||!/^v1=[a-f0-9]{64}$/.test(j.voicelySignature))throw Error('voicely_webhook_unauthorized');\n let mismatch=0;for(let i=0;i<64;i++)mismatch|=j.expectedSignature.charCodeAt(i)^j.voicelySignature.charCodeAt(i+3);\n if(mismatch||Math.abs(Date.now()-Number(j.voicelyStamp))>p.windowMs)throw Error('voicely_webhook_unauthorized');\n const raw=Buffer.from(j.voicelyRaw,'base64');if(raw.length>p.bodyBytes)throw Error('voicely_webhook_body_refused');\n let body;try{body=JSON.parse(raw.toString('utf8'));}catch{throw Error('voicely_webhook_body_refused');}\n const types=['telephony.call.start','telephony.call.lookup','calling.call.completed','telephony.recording.ready','telephony.call.started','telephony.call.ended','telephony.call.failed','webhook.test'];\n if(!body||body.id!==j.voicelyId||!types.includes(body.type)||!body.data||typeof body.data!=='object'||Array.isArray(body.data))throw Error('voicely_webhook_contract_invalid');\n // Tenant binding: this workflow serves ONE Voicely business account. Any other account's event is refused, never processed.\n if(typeof p.expectedAccountId!=='string'||!p.expectedAccountId||p.expectedAccountId.startsWith('SET_'))throw Error('demomart_account_not_configured');\n if(String(body.account_id)!==p.expectedAccountId)throw Error('voicely_webhook_account_refused');\n return [{json:{event:body}}];\n})();"
      },
      "id": "a8054768-57ac-4893-9155-59259d5feee5",
      "name": "Accept Voicely Event",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        520,
        0
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return [{json:{httpStatus:401,reply:{error:'webhook_authentication_refused'}}}];"
      },
      "id": "385675ef-fe60-44d6-9e63-3fa977735fd9",
      "name": "Authentication Refused",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        520,
        240
      ],
      "onError": "stopWorkflow"
    },
    {
      "parameters": {
        "respondWith": "text",
        "responseBody": "={{ JSON.stringify($json.reply) }}",
        "options": {
          "responseCode": "={{ $json.httpStatus }}",
          "responseHeaders": {
            "entries": [
              {
                "name": "content-type",
                "value": "application/json"
              }
            ]
          }
        }
      },
      "id": "128270bb-a0cf-42b1-ae3b-ca41f69d21fe",
      "name": "Reply to Voicely",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.4,
      "position": [
        3820,
        0
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "328e9670-d8c7-4bbc-9b38-0f7893208a41",
              "leftValue": "={{ $('Accept Voicely Event').first().json.event.type }}",
              "rightValue": "telephony.call.start",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "1949b2ed-cc51-45fa-8dbd-3670fdc340ac",
      "name": "Is call start (ring)?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        800,
        -1000
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "e583e965-a692-464b-92ac-1ab3650f54ff",
              "leftValue": "={{ $('Accept Voicely Event').first().json.event.type }}",
              "rightValue": "calling.call.completed",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "65d43914-7e06-43a7-94f2-dd0f66dc5ddd",
      "name": "Is call completed (lead)?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        800,
        0
      ]
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Pass-through so the next read can reach these rows by node name.\nreturn $input.all();"
      },
      "id": "8babdda6-e536-4f3d-b64b-24bb68578d6b",
      "name": "Collect Orders",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1520,
        -1000
      ],
      "onError": "stopWorkflow"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "f9ca8377-8b9e-40da-93f1-dfaafb3e54ec",
              "leftValue": "={{ $('DemoMart Policy').first().json.voicelyPolicy.storage !== 'sheets' }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "e783bb1a-a95f-459f-9d6c-ef530c517902",
      "name": "Read Orders at Ring: Data Table?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1060,
        -1000
      ]
    },
    {
      "parameters": {
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.ordersTableId }}",
          "mode": "id"
        },
        "matchType": "allConditions",
        "filters": {
          "conditions": []
        },
        "limit": 5000
      },
      "id": "97ee8853-6232-43c0-b439-77be0751b281",
      "name": "Read Orders at Ring (Data Table)",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        1290,
        -1090
      ],
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.sheets.documentId }}",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.sheets.ordersSheet }}",
          "mode": "name"
        },
        "options": {}
      },
      "id": "a53c3436-ab59-488d-b510-8a588d651995",
      "name": "Read Orders at Ring (Sheet)",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        1290,
        -910
      ],
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "560f15fa-191a-40e1-b132-c4d45fb2fafc",
              "leftValue": "={{ $('DemoMart Policy').first().json.voicelyPolicy.storage !== 'sheets' }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "2295d41e-ea45-4428-be83-81adfe73e686",
      "name": "Read Tickets at Ring: Data Table?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1750,
        -1000
      ]
    },
    {
      "parameters": {
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.ticketsTableId }}",
          "mode": "id"
        },
        "matchType": "allConditions",
        "filters": {
          "conditions": []
        },
        "limit": 5000
      },
      "id": "fc1f4afb-a20d-48d1-ae2b-9a585fa8e11d",
      "name": "Read Tickets at Ring (Data Table)",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        1980,
        -1090
      ],
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.sheets.documentId }}",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.sheets.ticketsSheet }}",
          "mode": "name"
        },
        "options": {}
      },
      "id": "79834be8-009c-41b4-bb95-66746a704bfe",
      "name": "Read Tickets at Ring (Sheet)",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        1980,
        -910
      ],
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const ev=$('Accept Voicely Event').first().json.event,pol=$('DemoMart Policy').first().json.voicelyPolicy;\nconst S=v=>v===undefined||v===null?'':String(v).trim();\nconst digits=v=>S(v).replace(/[^0-9*]/g,'');\nconst nextTicket=rows=>rows.reduce((m,t)=>{const n=Number((/^CS-(\\d+)$/.exec(S(t.ticket_id))||[])[1]);return Number.isSafeInteger(n)&&n>m?n:m;},pol.ticketBase)+1;\n// Full sync happens HERE (n8n is the buffer): all orders were read, then filtered to THIS caller's number.\n// Only the caller's own orders reach the agent (Voicely injects 'variables' into this call's instructions, max ~500 bytes).\nconst orders=$('Collect Orders').all().map(i=>i.json).filter(o=>o&&S(o.order_id));\nconst tickets=$input.all().map(i=>i.json).filter(t=>t&&S(t.ticket_id));\nconst caller=digits(ev.data.caller_number),masked=caller.includes('*');\nconst key=n=>n.replace(/\\D/g,'').slice(-10);\nconst mine=!caller||masked?[]:orders.filter(o=>key(S(o.phone))&&key(S(o.phone))===key(caller));\nconst reference='CS-'+nextTicket(tickets);\nconst label={processing:'processing',pending_verification:'pending verification',out_for_delivery:'out for delivery',delivered:'delivered',delayed:'delayed'};\nconst fmt=o=>[S(o.order_id),label[S(o.status)]||S(o.status),S(o.delivered_on)?'delivered '+S(o.delivered_on):S(o.revised_delivery)?'new date '+S(o.revised_delivery):S(o.expected_delivery)?'expected '+S(o.expected_delivery):(S(o.status)==='delayed'?'no new date yet':'')].filter(Boolean).join(', ');\nconst v={reserved_reference:reference};\nif(mine.length){v.customer_name=S(mine[0].customer_name)||'customer';v.orders_on_this_number=mine.map(fmt).join(' | ');}\nelse v.orders_on_this_number=masked?'unavailable (number hidden)':'none found for this number';\nv.rule='These are this caller\\'s own orders. For any other order number, use the order lookup when it is available; otherwise take the details for the team.';\n// Keep within contextBytes: drop orders from the end until it fits (Voicely drops context that is too large).\nconst size=o=>Object.entries(o).reduce((n,[k,x])=>n+Buffer.byteLength(k+': '+x)+1,0);\n// Never silent: orders that do not fit are COUNTED for the agent (it can pull them mid-call if the business enabled lookup).\nlet kept=mine.length;const all=v.orders_on_this_number;\nwhile(size(v)>pol.contextBytes&&v.orders_on_this_number.includes(' | ')){v.orders_on_this_number=v.orders_on_this_number.split(' | ').slice(0,-1).join(' | ');kept--;v.more_orders_not_listed=String(mine.length-kept);}\nreturn [{json:{httpStatus:200,reply:{variables:v},reservation:{ticket_id:reference,operation_id:'',call_id:'',channel:'sip',caller_number:masked?'':caller,caller_name:S(v.customer_name),\n  category:'',order_id:'',order_status:'',summary:'',priority:'normal',requested_deadline:'',contact_email:'',verification:'caller_id',status:'reserved',created_at:new Date().toISOString()}}}];"
      },
      "id": "ffbbf729-250c-40dc-9393-d236bc8da118",
      "name": "Build Call Context",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2210,
        -1000
      ],
      "onError": "stopWorkflow"
    },
    {
      "parameters": {
        "respondWith": "text",
        "responseBody": "={{ JSON.stringify($json.reply) }}",
        "options": {
          "responseCode": "={{ $json.httpStatus }}",
          "responseHeaders": {
            "entries": [
              {
                "name": "content-type",
                "value": "application/json"
              }
            ]
          }
        }
      },
      "id": "31101b6b-8ee2-4e1f-a4b3-756b27a17e76",
      "name": "Reply at Ring",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.4,
      "position": [
        2440,
        -1000
      ]
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// After the caller is already connected: the reserved CS reference is now in the tickets store (status reserved).\nreturn [{json:{reserved:$('Build Call Context').first().json.reservation.ticket_id}}];"
      },
      "id": "47264f50-3f75-40c7-aa78-45e74be2af16",
      "name": "Reservation Saved",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        3590,
        -1000
      ],
      "onError": "stopWorkflow"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "3f35fb55-4677-43ad-99e2-4fee8ad0d331",
              "leftValue": "={{ $('DemoMart Policy').first().json.voicelyPolicy.storage !== 'sheets' }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "b551d1da-b9c8-4765-b44c-ca5d105e1327",
      "name": "Reserve Reference: Data Table?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        2670,
        -1000
      ]
    },
    {
      "parameters": {
        "operation": "insert",
        "dataTableId": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.ticketsTableId }}",
          "mode": "id"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "ticket_id": "={{ $('Build Call Context').first().json.reservation.ticket_id }}",
            "operation_id": "={{ $('Build Call Context').first().json.reservation.operation_id }}",
            "call_id": "={{ $('Build Call Context').first().json.reservation.call_id }}",
            "channel": "={{ $('Build Call Context').first().json.reservation.channel }}",
            "caller_number": "={{ $('Build Call Context').first().json.reservation.caller_number }}",
            "caller_name": "={{ $('Build Call Context').first().json.reservation.caller_name }}",
            "category": "={{ $('Build Call Context').first().json.reservation.category }}",
            "order_id": "={{ $('Build Call Context').first().json.reservation.order_id }}",
            "order_status": "={{ $('Build Call Context').first().json.reservation.order_status }}",
            "summary": "={{ $('Build Call Context').first().json.reservation.summary }}",
            "priority": "={{ $('Build Call Context').first().json.reservation.priority }}",
            "requested_deadline": "={{ $('Build Call Context').first().json.reservation.requested_deadline }}",
            "contact_email": "={{ $('Build Call Context').first().json.reservation.contact_email }}",
            "verification": "={{ $('Build Call Context').first().json.reservation.verification }}",
            "status": "={{ $('Build Call Context').first().json.reservation.status }}",
            "created_at": "={{ $('Build Call Context').first().json.reservation.created_at }}"
          },
          "matchingColumns": [],
          "schema": [
            {
              "id": "ticket_id",
              "displayName": "ticket_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "operation_id",
              "displayName": "operation_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "call_id",
              "displayName": "call_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "channel",
              "displayName": "channel",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "caller_number",
              "displayName": "caller_number",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "caller_name",
              "displayName": "caller_name",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "category",
              "displayName": "category",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "order_id",
              "displayName": "order_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "order_status",
              "displayName": "order_status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "summary",
              "displayName": "summary",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "priority",
              "displayName": "priority",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "requested_deadline",
              "displayName": "requested_deadline",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "contact_email",
              "displayName": "contact_email",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "verification",
              "displayName": "verification",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "status",
              "displayName": "status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "created_at",
              "displayName": "created_at",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "id": "af1986c8-5400-4de3-9965-52c757112844",
      "name": "Reserve Reference (Data Table)",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        2900,
        -1090
      ],
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "6b9cb7f0-5735-4dea-b9c7-f2dfbbfa164a",
              "leftValue": "={{ $('DemoMart Policy').first().json.voicelyPolicy.storage === 'both' }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "c668a280-34f9-4b8c-9d1f-3ce4d25550bb",
      "name": "Reserve Reference: mirror to Sheet?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        3130,
        -1090
      ]
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.sheets.documentId }}",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.sheets.ticketsSheet }}",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "ticket_id": "={{ $('Build Call Context').first().json.reservation.ticket_id }}",
            "operation_id": "={{ $('Build Call Context').first().json.reservation.operation_id }}",
            "call_id": "={{ $('Build Call Context').first().json.reservation.call_id }}",
            "channel": "={{ $('Build Call Context').first().json.reservation.channel }}",
            "caller_number": "={{ $('Build Call Context').first().json.reservation.caller_number }}",
            "caller_name": "={{ $('Build Call Context').first().json.reservation.caller_name }}",
            "category": "={{ $('Build Call Context').first().json.reservation.category }}",
            "order_id": "={{ $('Build Call Context').first().json.reservation.order_id }}",
            "order_status": "={{ $('Build Call Context').first().json.reservation.order_status }}",
            "summary": "={{ $('Build Call Context').first().json.reservation.summary }}",
            "priority": "={{ $('Build Call Context').first().json.reservation.priority }}",
            "requested_deadline": "={{ $('Build Call Context').first().json.reservation.requested_deadline }}",
            "contact_email": "={{ $('Build Call Context').first().json.reservation.contact_email }}",
            "verification": "={{ $('Build Call Context').first().json.reservation.verification }}",
            "status": "={{ $('Build Call Context').first().json.reservation.status }}",
            "created_at": "={{ $('Build Call Context').first().json.reservation.created_at }}"
          },
          "matchingColumns": [],
          "schema": [
            {
              "id": "ticket_id",
              "displayName": "ticket_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "operation_id",
              "displayName": "operation_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "call_id",
              "displayName": "call_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "channel",
              "displayName": "channel",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "caller_number",
              "displayName": "caller_number",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "caller_name",
              "displayName": "caller_name",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "category",
              "displayName": "category",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "order_id",
              "displayName": "order_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "order_status",
              "displayName": "order_status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "summary",
              "displayName": "summary",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "priority",
              "displayName": "priority",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "requested_deadline",
              "displayName": "requested_deadline",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "contact_email",
              "displayName": "contact_email",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "verification",
              "displayName": "verification",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "status",
              "displayName": "status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "created_at",
              "displayName": "created_at",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "id": "0fa38b06-3bfe-46f6-b15e-c29b2d9b4840",
      "name": "Reserve Reference (Sheet)",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        3360,
        -910
      ],
      "alwaysOutputData": true,
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $input.all();"
      },
      "id": "ce6fc2f0-4a7e-4ee7-b21a-ebaa3780275b",
      "name": "Collect Tickets",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1520,
        0
      ],
      "onError": "stopWorkflow"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "ee4f50ed-2b4d-4757-8c1e-4d19dbd57fde",
              "leftValue": "={{ $('DemoMart Policy').first().json.voicelyPolicy.storage !== 'sheets' }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "2998762b-d6ae-463e-9ad5-4f14177220c4",
      "name": "Read Tickets after Call: Data Table?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1060,
        0
      ]
    },
    {
      "parameters": {
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.ticketsTableId }}",
          "mode": "id"
        },
        "matchType": "allConditions",
        "filters": {
          "conditions": []
        },
        "limit": 5000
      },
      "id": "50b2e598-8b77-4306-8e1e-36aa6464a2cc",
      "name": "Read Tickets after Call (Data Table)",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        1290,
        -90
      ],
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.sheets.documentId }}",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.sheets.ticketsSheet }}",
          "mode": "name"
        },
        "options": {}
      },
      "id": "cf56957b-871f-4ddb-8b2d-f92571296c60",
      "name": "Read Tickets after Call (Sheet)",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        1290,
        90
      ],
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "e4406d2d-1169-4c1e-9f2c-b939eac68be8",
              "leftValue": "={{ $('DemoMart Policy').first().json.voicelyPolicy.storage !== 'sheets' }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "89eaa1c7-3412-4477-9c60-62cab1c865a8",
      "name": "Read Orders after Call: Data Table?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1750,
        0
      ]
    },
    {
      "parameters": {
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.ordersTableId }}",
          "mode": "id"
        },
        "matchType": "allConditions",
        "filters": {
          "conditions": []
        },
        "limit": 5000
      },
      "id": "3d906ab2-f879-4485-a0b5-9c7f52bf59ad",
      "name": "Read Orders after Call (Data Table)",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        1980,
        -90
      ],
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.sheets.documentId }}",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.sheets.ordersSheet }}",
          "mode": "name"
        },
        "options": {}
      },
      "id": "b8713466-9c4e-4f3c-89ed-c5ba90adb8a1",
      "name": "Read Orders after Call (Sheet)",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        1980,
        90
      ],
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const ev=$('Accept Voicely Event').first().json.event,pol=$('DemoMart Policy').first().json.voicelyPolicy;\nconst S=v=>v===undefined||v===null?'':String(v).trim();\nconst digits=v=>S(v).replace(/[^0-9*]/g,'');\nconst nextTicket=rows=>rows.reduce((m,t)=>{const n=Number((/^CS-(\\d+)$/.exec(S(t.ticket_id))||[])[1]);return Number.isSafeInteger(n)&&n>m?n:m;},pol.ticketBase)+1;\n// Voicely extracted the agent's lead_fields after the call. The ticket carries the order's CURRENT status from the store.\nconst tickets=$('Collect Tickets').all().map(i=>i.json).filter(t=>t&&S(t.ticket_id));\nconst orders=$input.all().map(i=>i.json).filter(o=>o&&S(o.order_id));\nif(tickets.some(t=>S(t.operation_id)===ev.id))return [{json:{httpStatus:200,reply:{received:true,replay:true},action:'none'}}];\nconst lead=ev.data.lead||{},d=lead.data||{},f=k=>S(d[k]);\n// The caller hears \"CS fifty hundred nine\"; the lead may carry CS5009, CS 5009 or cs-5009. All mean CS-5009.\nconst refRaw=f('reference').toUpperCase().replace(/[\\s_.\\-]+/g,''),refM=/^CS(\\d{4,})$/.exec(refRaw),ref=refM?'CS-'+refM[1]:f('reference').toUpperCase(),reserved=tickets.find(t=>S(t.ticket_id)===ref&&S(t.status)==='reserved');\nconst oidRaw=f('order_id').toUpperCase().replace(/[\\s_.\\-]+/g,''),oidM=/^(?:DM)?(\\d{4})$/.exec(oidRaw),oid=oidM?'DM-'+oidM[1]:f('order_id').toUpperCase(),order=orders.find(o=>S(o.order_id)===oid);\nconst cats=['delivery_status_inquiry','delivered_not_received','verification_assistance','delivery_overdue','missing_order_payment','general_support'];\nconst category=cats.includes(f('issue_category'))?f('issue_category'):'general_support';\nconst ticket={ticket_id:reserved?S(reserved.ticket_id):'CS-'+nextTicket(tickets),operation_id:ev.id,call_id:S(ev.data.call_id),channel:'sip',\n  caller_number:reserved?S(reserved.caller_number):'',caller_name:f('caller_name')||(reserved?S(reserved.caller_name):''),category,order_id:oid,\n  order_status:order?S(order.status):(oid?'not_found':''),summary:f('issue_summary')||f('next_step')||'Phone call: see recording',\n  priority:['delivered_not_received','delivery_overdue','missing_order_payment'].includes(category)?'high':'normal',requested_deadline:f('requested_deadline'),\n  contact_email:/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(f('contact_email'))?f('contact_email'):'',verification:reserved?'caller_id':'none',status:'open',created_at:reserved?S(reserved.created_at):new Date().toISOString()};\nreturn [{json:{action:reserved?'update':'insert',ticket,httpStatus:200,reply:{received:true,ticket_id:ticket.ticket_id}}}];"
      },
      "id": "2592750c-3114-4de2-84d9-bbf12ec389c5",
      "name": "Build Ticket from Lead",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2210,
        0
      ],
      "onError": "stopWorkflow"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "182fcc43-6645-4835-9336-5a6d63e2a6f6",
              "leftValue": "={{ $json.action }}",
              "rightValue": "update",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "b9e3381d-98e9-4889-aaf3-001c7ec1876b",
      "name": "Complete reserved ticket?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        2440,
        0
      ]
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Delivery is acknowledged only after the primary store write finished (Voicely retries a non-2xx).\nreturn [{json:$('Build Ticket from Lead').first().json}];"
      },
      "id": "474a80ed-504a-48ca-a542-1062921f8433",
      "name": "Ticket Filed",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        3590,
        0
      ],
      "onError": "stopWorkflow"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "5487e22c-00d6-4a6b-a7eb-a52fe7adf6ac",
              "leftValue": "={{ $('DemoMart Policy').first().json.voicelyPolicy.storage !== 'sheets' }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "0fc7a38c-c3f4-48cc-b5fa-c78c9a600b91",
      "name": "Complete Ticket: Data Table?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        2670,
        -150
      ]
    },
    {
      "parameters": {
        "operation": "update",
        "dataTableId": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.ticketsTableId }}",
          "mode": "id"
        },
        "matchType": "allConditions",
        "filters": {
          "conditions": [
            {
              "keyName": "ticket_id",
              "keyValue": "={{ $('Build Ticket from Lead').first().json.ticket.ticket_id }}"
            }
          ]
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "operation_id": "={{ $('Build Ticket from Lead').first().json.ticket.operation_id }}",
            "call_id": "={{ $('Build Ticket from Lead').first().json.ticket.call_id }}",
            "channel": "={{ $('Build Ticket from Lead').first().json.ticket.channel }}",
            "caller_number": "={{ $('Build Ticket from Lead').first().json.ticket.caller_number }}",
            "caller_name": "={{ $('Build Ticket from Lead').first().json.ticket.caller_name }}",
            "category": "={{ $('Build Ticket from Lead').first().json.ticket.category }}",
            "order_id": "={{ $('Build Ticket from Lead').first().json.ticket.order_id }}",
            "order_status": "={{ $('Build Ticket from Lead').first().json.ticket.order_status }}",
            "summary": "={{ $('Build Ticket from Lead').first().json.ticket.summary }}",
            "priority": "={{ $('Build Ticket from Lead').first().json.ticket.priority }}",
            "requested_deadline": "={{ $('Build Ticket from Lead').first().json.ticket.requested_deadline }}",
            "contact_email": "={{ $('Build Ticket from Lead').first().json.ticket.contact_email }}",
            "verification": "={{ $('Build Ticket from Lead').first().json.ticket.verification }}",
            "status": "={{ $('Build Ticket from Lead').first().json.ticket.status }}",
            "created_at": "={{ $('Build Ticket from Lead').first().json.ticket.created_at }}"
          },
          "matchingColumns": [],
          "schema": [
            {
              "id": "ticket_id",
              "displayName": "ticket_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": true
            },
            {
              "id": "operation_id",
              "displayName": "operation_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "call_id",
              "displayName": "call_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "channel",
              "displayName": "channel",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "caller_number",
              "displayName": "caller_number",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "caller_name",
              "displayName": "caller_name",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "category",
              "displayName": "category",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "order_id",
              "displayName": "order_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "order_status",
              "displayName": "order_status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "summary",
              "displayName": "summary",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "priority",
              "displayName": "priority",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "requested_deadline",
              "displayName": "requested_deadline",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "contact_email",
              "displayName": "contact_email",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "verification",
              "displayName": "verification",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "status",
              "displayName": "status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "created_at",
              "displayName": "created_at",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "id": "9e4f92d9-6e14-40a8-a8d2-369981e41f74",
      "name": "Complete Ticket (Data Table)",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        2900,
        -230
      ],
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "cf44f4a9-4b50-4ac9-a0db-5f154bde340c",
              "leftValue": "={{ $('DemoMart Policy').first().json.voicelyPolicy.storage === 'both' }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "fdbbc979-00e2-49e6-b2c4-268e5a80251f",
      "name": "Complete Ticket: mirror to Sheet?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        3130,
        -230
      ]
    },
    {
      "parameters": {
        "operation": "update",
        "documentId": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.sheets.documentId }}",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.sheets.ticketsSheet }}",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "ticket_id": "={{ $('Build Ticket from Lead').first().json.ticket.ticket_id }}",
            "operation_id": "={{ $('Build Ticket from Lead').first().json.ticket.operation_id }}",
            "call_id": "={{ $('Build Ticket from Lead').first().json.ticket.call_id }}",
            "channel": "={{ $('Build Ticket from Lead').first().json.ticket.channel }}",
            "caller_number": "={{ $('Build Ticket from Lead').first().json.ticket.caller_number }}",
            "caller_name": "={{ $('Build Ticket from Lead').first().json.ticket.caller_name }}",
            "category": "={{ $('Build Ticket from Lead').first().json.ticket.category }}",
            "order_id": "={{ $('Build Ticket from Lead').first().json.ticket.order_id }}",
            "order_status": "={{ $('Build Ticket from Lead').first().json.ticket.order_status }}",
            "summary": "={{ $('Build Ticket from Lead').first().json.ticket.summary }}",
            "priority": "={{ $('Build Ticket from Lead').first().json.ticket.priority }}",
            "requested_deadline": "={{ $('Build Ticket from Lead').first().json.ticket.requested_deadline }}",
            "contact_email": "={{ $('Build Ticket from Lead').first().json.ticket.contact_email }}",
            "verification": "={{ $('Build Ticket from Lead').first().json.ticket.verification }}",
            "status": "={{ $('Build Ticket from Lead').first().json.ticket.status }}",
            "created_at": "={{ $('Build Ticket from Lead').first().json.ticket.created_at }}"
          },
          "matchingColumns": [
            "ticket_id"
          ],
          "schema": [
            {
              "id": "ticket_id",
              "displayName": "ticket_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "operation_id",
              "displayName": "operation_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "call_id",
              "displayName": "call_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "channel",
              "displayName": "channel",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "caller_number",
              "displayName": "caller_number",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "caller_name",
              "displayName": "caller_name",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "category",
              "displayName": "category",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "order_id",
              "displayName": "order_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "order_status",
              "displayName": "order_status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "summary",
              "displayName": "summary",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "priority",
              "displayName": "priority",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "requested_deadline",
              "displayName": "requested_deadline",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "contact_email",
              "displayName": "contact_email",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "verification",
              "displayName": "verification",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "status",
              "displayName": "status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "created_at",
              "displayName": "created_at",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "id": "6de0d18a-ea99-4e80-9a89-ab25a1e659c3",
      "name": "Complete Ticket (Sheet)",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        3360,
        -90
      ],
      "alwaysOutputData": true,
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "5360c4bf-ed31-4740-8369-e2782696d261",
              "leftValue": "={{ $json.action }}",
              "rightValue": "insert",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "99ceadef-f54c-422e-9af6-4ebaf6ddbf88",
      "name": "New ticket needed?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        2670,
        150
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "3c4814e2-8fd2-4538-bbb0-8c6e71283eaa",
              "leftValue": "={{ $('DemoMart Policy').first().json.voicelyPolicy.storage !== 'sheets' }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "674e49c7-5432-4779-b0a0-19a4b6994580",
      "name": "Create Ticket: Data Table?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        2900,
        150
      ]
    },
    {
      "parameters": {
        "operation": "insert",
        "dataTableId": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.ticketsTableId }}",
          "mode": "id"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "ticket_id": "={{ $('Build Ticket from Lead').first().json.ticket.ticket_id }}",
            "operation_id": "={{ $('Build Ticket from Lead').first().json.ticket.operation_id }}",
            "call_id": "={{ $('Build Ticket from Lead').first().json.ticket.call_id }}",
            "channel": "={{ $('Build Ticket from Lead').first().json.ticket.channel }}",
            "caller_number": "={{ $('Build Ticket from Lead').first().json.ticket.caller_number }}",
            "caller_name": "={{ $('Build Ticket from Lead').first().json.ticket.caller_name }}",
            "category": "={{ $('Build Ticket from Lead').first().json.ticket.category }}",
            "order_id": "={{ $('Build Ticket from Lead').first().json.ticket.order_id }}",
            "order_status": "={{ $('Build Ticket from Lead').first().json.ticket.order_status }}",
            "summary": "={{ $('Build Ticket from Lead').first().json.ticket.summary }}",
            "priority": "={{ $('Build Ticket from Lead').first().json.ticket.priority }}",
            "requested_deadline": "={{ $('Build Ticket from Lead').first().json.ticket.requested_deadline }}",
            "contact_email": "={{ $('Build Ticket from Lead').first().json.ticket.contact_email }}",
            "verification": "={{ $('Build Ticket from Lead').first().json.ticket.verification }}",
            "status": "={{ $('Build Ticket from Lead').first().json.ticket.status }}",
            "created_at": "={{ $('Build Ticket from Lead').first().json.ticket.created_at }}"
          },
          "matchingColumns": [],
          "schema": [
            {
              "id": "ticket_id",
              "displayName": "ticket_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "operation_id",
              "displayName": "operation_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "call_id",
              "displayName": "call_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "channel",
              "displayName": "channel",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "caller_number",
              "displayName": "caller_number",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "caller_name",
              "displayName": "caller_name",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "category",
              "displayName": "category",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "order_id",
              "displayName": "order_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "order_status",
              "displayName": "order_status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "summary",
              "displayName": "summary",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "priority",
              "displayName": "priority",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "requested_deadline",
              "displayName": "requested_deadline",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "contact_email",
              "displayName": "contact_email",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "verification",
              "displayName": "verification",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "status",
              "displayName": "status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "created_at",
              "displayName": "created_at",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "id": "16338760-ca81-4aa0-a90e-43849ddc78ca",
      "name": "Create Ticket (Data Table)",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        3130,
        70
      ],
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "c616aaaa-c26f-4a23-96e5-e2aea5ea514a",
              "leftValue": "={{ $('DemoMart Policy').first().json.voicelyPolicy.storage === 'both' }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "5f8ea48e-bb8c-42ad-8aeb-c6da7abbd265",
      "name": "Create Ticket: mirror to Sheet?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        3360,
        70
      ]
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.sheets.documentId }}",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.sheets.ticketsSheet }}",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "ticket_id": "={{ $('Build Ticket from Lead').first().json.ticket.ticket_id }}",
            "operation_id": "={{ $('Build Ticket from Lead').first().json.ticket.operation_id }}",
            "call_id": "={{ $('Build Ticket from Lead').first().json.ticket.call_id }}",
            "channel": "={{ $('Build Ticket from Lead').first().json.ticket.channel }}",
            "caller_number": "={{ $('Build Ticket from Lead').first().json.ticket.caller_number }}",
            "caller_name": "={{ $('Build Ticket from Lead').first().json.ticket.caller_name }}",
            "category": "={{ $('Build Ticket from Lead').first().json.ticket.category }}",
            "order_id": "={{ $('Build Ticket from Lead').first().json.ticket.order_id }}",
            "order_status": "={{ $('Build Ticket from Lead').first().json.ticket.order_status }}",
            "summary": "={{ $('Build Ticket from Lead').first().json.ticket.summary }}",
            "priority": "={{ $('Build Ticket from Lead').first().json.ticket.priority }}",
            "requested_deadline": "={{ $('Build Ticket from Lead').first().json.ticket.requested_deadline }}",
            "contact_email": "={{ $('Build Ticket from Lead').first().json.ticket.contact_email }}",
            "verification": "={{ $('Build Ticket from Lead').first().json.ticket.verification }}",
            "status": "={{ $('Build Ticket from Lead').first().json.ticket.status }}",
            "created_at": "={{ $('Build Ticket from Lead').first().json.ticket.created_at }}"
          },
          "matchingColumns": [],
          "schema": [
            {
              "id": "ticket_id",
              "displayName": "ticket_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "operation_id",
              "displayName": "operation_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "call_id",
              "displayName": "call_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "channel",
              "displayName": "channel",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "caller_number",
              "displayName": "caller_number",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "caller_name",
              "displayName": "caller_name",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "category",
              "displayName": "category",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "order_id",
              "displayName": "order_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "order_status",
              "displayName": "order_status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "summary",
              "displayName": "summary",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "priority",
              "displayName": "priority",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "requested_deadline",
              "displayName": "requested_deadline",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "contact_email",
              "displayName": "contact_email",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "verification",
              "displayName": "verification",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "status",
              "displayName": "status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "created_at",
              "displayName": "created_at",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "id": "13744732-2893-4100-b289-0e62f54fe04a",
      "name": "Create Ticket (Sheet)",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        3360,
        230
      ],
      "alwaysOutputData": true,
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const ev=$('Accept Voicely Event').first().json.event,pol=$('DemoMart Policy').first().json.voicelyPolicy;\nconst S=v=>v===undefined||v===null?'':String(v).trim();\nconst digits=v=>S(v).replace(/[^0-9*]/g,'');\nconst nextTicket=rows=>rows.reduce((m,t)=>{const n=Number((/^CS-(\\d+)$/.exec(S(t.ticket_id))||[])[1]);return Number.isSafeInteger(n)&&n>m?n:m;},pol.ticketBase)+1;\n// One log row per event. Only the signed recording LINK is kept (it expires per your retention); transcript text is not copied.\nconst d=ev.data,rec=d.recording||{};\nconst url=S(rec.caller_url||rec.recording_url||rec.url||'');\nreturn [{json:{row:{event_id:ev.id,event_type:ev.type,call_id:S(d.call_id),agent_id:S(d.agent_id),direction:S(d.direction),status:S(d.status),\n  duration_ms:S(d.duration_ms),recording_url:url,transcript_included:String(d.transcript_included===true),received_at:new Date().toISOString()},httpStatus:200,reply:{received:true}}}];"
      },
      "id": "37ec3aae-88c5-4824-b847-34f47111a3f2",
      "name": "Build Call Log Row",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1060,
        600
      ],
      "onError": "stopWorkflow"
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return [{json:$('Build Call Log Row').first().json}];"
      },
      "id": "2a01b934-4635-4b65-9c5b-4d39e2d64b79",
      "name": "Call Logged",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2210,
        600
      ],
      "onError": "stopWorkflow"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "e71c7277-a436-414a-a430-92b9b05cd908",
              "leftValue": "={{ $('DemoMart Policy').first().json.voicelyPolicy.storage !== 'sheets' }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "be55462e-1e8e-42a2-bc17-e6b3521820e5",
      "name": "Log Call Event: Data Table?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1290,
        600
      ]
    },
    {
      "parameters": {
        "operation": "insert",
        "dataTableId": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.callsTableId }}",
          "mode": "id"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "event_id": "={{ $('Build Call Log Row').first().json.row.event_id }}",
            "event_type": "={{ $('Build Call Log Row').first().json.row.event_type }}",
            "call_id": "={{ $('Build Call Log Row').first().json.row.call_id }}",
            "agent_id": "={{ $('Build Call Log Row').first().json.row.agent_id }}",
            "direction": "={{ $('Build Call Log Row').first().json.row.direction }}",
            "status": "={{ $('Build Call Log Row').first().json.row.status }}",
            "duration_ms": "={{ $('Build Call Log Row').first().json.row.duration_ms }}",
            "recording_url": "={{ $('Build Call Log Row').first().json.row.recording_url }}",
            "transcript_included": "={{ $('Build Call Log Row').first().json.row.transcript_included }}",
            "received_at": "={{ $('Build Call Log Row').first().json.row.received_at }}"
          },
          "matchingColumns": [],
          "schema": [
            {
              "id": "event_id",
              "displayName": "event_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "event_type",
              "displayName": "event_type",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "call_id",
              "displayName": "call_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "agent_id",
              "displayName": "agent_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "direction",
              "displayName": "direction",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "status",
              "displayName": "status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "duration_ms",
              "displayName": "duration_ms",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "recording_url",
              "displayName": "recording_url",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "transcript_included",
              "displayName": "transcript_included",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "received_at",
              "displayName": "received_at",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "id": "df617e02-3eff-4727-a08c-64dca7eacad5",
      "name": "Log Call Event (Data Table)",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        1520,
        510
      ],
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "61c67b9f-56ab-4b53-96c1-0bf39a7c52c5",
              "leftValue": "={{ $('DemoMart Policy').first().json.voicelyPolicy.storage === 'both' }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "ecf5d74d-e56e-475e-9805-dcf2bc2ae842",
      "name": "Log Call Event: mirror to Sheet?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1750,
        510
      ]
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.sheets.documentId }}",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.sheets.callsSheet }}",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "event_id": "={{ $('Build Call Log Row').first().json.row.event_id }}",
            "event_type": "={{ $('Build Call Log Row').first().json.row.event_type }}",
            "call_id": "={{ $('Build Call Log Row').first().json.row.call_id }}",
            "agent_id": "={{ $('Build Call Log Row').first().json.row.agent_id }}",
            "direction": "={{ $('Build Call Log Row').first().json.row.direction }}",
            "status": "={{ $('Build Call Log Row').first().json.row.status }}",
            "duration_ms": "={{ $('Build Call Log Row').first().json.row.duration_ms }}",
            "recording_url": "={{ $('Build Call Log Row').first().json.row.recording_url }}",
            "transcript_included": "={{ $('Build Call Log Row').first().json.row.transcript_included }}",
            "received_at": "={{ $('Build Call Log Row').first().json.row.received_at }}"
          },
          "matchingColumns": [],
          "schema": [
            {
              "id": "event_id",
              "displayName": "event_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "event_type",
              "displayName": "event_type",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "call_id",
              "displayName": "call_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "agent_id",
              "displayName": "agent_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "direction",
              "displayName": "direction",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "status",
              "displayName": "status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "duration_ms",
              "displayName": "duration_ms",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "recording_url",
              "displayName": "recording_url",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "transcript_included",
              "displayName": "transcript_included",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "received_at",
              "displayName": "received_at",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "id": "4924f808-870b-4bbe-8f9e-bdcc81aa9596",
      "name": "Log Call Event (Sheet)",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        1980,
        690
      ],
      "alwaysOutputData": true,
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "content": "## DemoMart phone agent (SIP) + n8n + Google Sheets\nYour own phone number (BYOC SIP trunk/PBX) answered by a Voicely AI agent that **knows the caller before saying hello**, and **files the follow-up after the call**.\n\n**One webhook, three moments:**\n1. **Ring** (`telephony.call.start`): n8n reads all orders, keeps only the ones on the caller's number, reserves the next CS reference and answers within the call-start timeout with `variables` → Voicely adds them to this call's instructions.\n2. **After the call** (`calling.call.completed`): Voicely's extracted lead completes the reserved ticket with the order's current status.\n3. **Recording ready / call ended / failed**: one row in the calls log with the signed recording link.\n\n**Setup:**\n1. Storage in **DemoMart Policy**: `datatable`, `sheets` or `both` (Data Table record + Sheet mirror). Tables `demomart_orders`, `demomart_tickets`, `demomart_calls` and/or tabs `orders`, `tickets`, `calls`.\n2. **Verify Voicely HMAC** (Code node): paste your Voicely **webhook signing secret** (`whsec_...`) into `SIGNING_SECRET` on its first line. No credential needed. Then **Publish** (Save alone does not update the live webhook).\n3. Voicely → Webhooks: create an endpoint with this Production URL (public https), events `calling.call.completed`, `telephony.recording.ready`, `telephony.call.ended`, `telephony.call.failed`, and **Include phone numbers ON** (needed to match the caller).\n4. SIP agent → **Call start webhook** = that endpoint. lead_fields: `reference, caller_name, order_id, issue_category, issue_summary, contact_email, next_step`.\n\nFictional demo data only.\n\n**Data Tables only?** If `storage` is `datatable`, select all the `(Sheet)` nodes and disable them (press D) before **Publish**. n8n refuses to publish a workflow whose Google Sheets nodes have no credential, even when they never run. For `sheets` or `both`, keep them enabled and select your Google Sheets credential.",
        "height": 1190,
        "width": 1100,
        "color": 7
      },
      "id": "c2244316-552a-4b6a-90d4-94baf416db87",
      "name": "Note: Start here",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -480,
        -1290
      ]
    },
    {
      "parameters": {
        "content": "### Ring: personal context before hello, no mid-call waiting\nVoicely calls this before the agent speaks and waits at most the configured timeout. If n8n is late or down, the call continues **without** context. The reply goes out **before** the reservation is written, so the write never delays the caller.\n\nPrivacy: only the caller's own orders are sent (matched on the last 10 digits). A hidden number gets no orders. The agent discusses an order only after the caller names it. Caller ID can be spoofed: context is status-level only (no PINs, no addresses, no payment data), and no order is changed on a phone call.",
        "height": 480,
        "width": 2810,
        "color": 4
      },
      "id": "fe5c6c42-31df-4d94-93ea-50c4ee2698e9",
      "name": "Note: Ring",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1000,
        -1290
      ]
    },
    {
      "parameters": {
        "content": "### After the call: ticket with the same reference\nIdempotent on the Voicely event id (a retried delivery updates nothing twice). A missing or unknown reference creates the next CS number. Voicely only treats the event as delivered after this workflow answers 2xx.",
        "height": 710,
        "width": 3040,
        "color": 6
      },
      "id": "321e6f80-4d33-48bc-87f6-a0a34c55df14",
      "name": "Note: After call",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1000,
        -330
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "a4625da5-01e1-4f23-9c8f-afec84a65eec",
              "leftValue": "={{ $('Accept Voicely Event').first().json.event.type }}",
              "rightValue": "telephony.call.lookup",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "6c58c3e2-66ec-4975-8684-409f3f1f5ff4",
      "name": "Is call lookup (mid-call)?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        800,
        -550
      ]
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// The order the caller said, normalized. Invalid references never reach your data source.\n// Callers say \"4107\", \"DM 4107\", \"dm-4107\"... all mean DM-4107 (DemoMart references are DM- + 4 digits).\n// Current agents send the spoken reference as data.reference; older classic agents also send data.order_id.\nconst data=$('Accept Voicely Event').first().json.event.data||{};\nconst raw=String(data.reference??data.order_id??'').trim().toUpperCase().replace(/[\\s_.\\-]+/g,'');\nconst m=/^(?:DM)?(\\d{4})$/.exec(raw);\nreturn [{json:{order_id:m?'DM-'+m[1]:'__invalid__'}}];"
      },
      "id": "ac9d7e53-f783-497f-a4e7-c8f87dc94509",
      "name": "Normalize Order Reference",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1060,
        -550
      ],
      "onError": "stopWorkflow"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "f745b630-ef77-45c4-90ad-90058e94524f",
              "leftValue": "={{ $('DemoMart Policy').first().json.voicelyPolicy.storage !== 'sheets' }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "e7cd9f78-4b71-479c-a998-1f999b270d82",
      "name": "Lookup Order: Data Table?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1290,
        -550
      ]
    },
    {
      "parameters": {
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.ordersTableId }}",
          "mode": "id"
        },
        "matchType": "allConditions",
        "filters": {
          "conditions": [
            {
              "keyName": "order_id",
              "keyValue": "={{ $('Normalize Order Reference').first().json.order_id }}"
            }
          ]
        },
        "limit": 2
      },
      "id": "1c9a4f49-affd-44fd-a6df-1e1a14061f68",
      "name": "Lookup Order (Data Table)",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        1520,
        -640
      ],
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.sheets.documentId }}",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.sheets.ordersSheet }}",
          "mode": "name"
        },
        "filtersUI": {
          "values": [
            {
              "lookupColumn": "order_id",
              "lookupValue": "={{ $('Normalize Order Reference').first().json.order_id }}"
            }
          ]
        },
        "options": {}
      },
      "id": "7ad7384a-02f8-4133-93d2-24ea847ea7c6",
      "name": "Lookup Order (Sheet)",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        1520,
        -460
      ],
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// FORMAT FOR VOICELY (the only node to keep if you swap the data source above for Airtable, Postgres, Shopify, a CRM...).\n// Explicit caller-safe projection: ONLY the allowlisted fields, each with its declared type. Everything else (PIN hash,\n// order date, phone, address, payment) is never returned. Voicely projects again with the Admin allowlist.\nconst pol=$('DemoMart Policy').first().json.voicelyPolicy,want=$('Normalize Order Reference').first().json.order_id;\nconst S=v=>v===undefined||v===null?'':String(v).trim();\nconst rows=$input.all().map(i=>i.json).filter(o=>o&&S(o.order_id)===want);\n// More than one row for the same order is a DATA error in your store: the caller still hears \"not found\" (never a guess\n// between rows), and the branch below writes a \"lookup.data_error\" row to your calls log so you can fix the data.\nif(rows.length>1)return [{json:{httpStatus:200,reply:{result:{found:false,order_id:want}},data_error:'duplicate_order_rows',order_id:want,duplicate_rows:rows.length}}];\nif(rows.length!==1)return [{json:{httpStatus:200,reply:{result:{found:false,order_id:want==='__invalid__'?'':want}}}}];\nconst o=rows[0],result={found:true};\nfor(const [k,type] of Object.entries(pol.lookupFields)){if(k==='found')continue;const v=S(o[k]);if(!v)continue;\n if(type==='string')result[k]=v;else if(type==='number'&&Number.isFinite(Number(v)))result[k]=Number(v);else if(type==='boolean')result[k]=v==='true';}\nreturn [{json:{httpStatus:200,reply:{result}}}];"
      },
      "id": "3e2cf100-a9e1-46c0-8d69-b64e8059e9fb",
      "name": "Format for Voicely (lookup)",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1750,
        -550
      ],
      "onError": "stopWorkflow"
    },
    {
      "parameters": {
        "content": "### Mid-call order lookup (only if the business turned it on)\nVoicely sends `telephony.call.lookup` when the caller names an order not in the ring context; the agent first says a short holding line. Answer within the Admin timeout with `{\"result\":{...}}`. **Format for Voicely** is the contract: swap the read nodes for any data source, keep that node. Read-only; tickets stay after the call.\n\n**Size:** Voicely's Admin limit (`maxResultBytes`) counts the WHOLE reply, `{\"result\":…}` included. Replies are sent as compact JSON (`JSON.stringify`, no spaces); empty fields are left out, never `null`.\n\n**Data errors:** if your store has the same order twice, the caller hears \"not found\" (never a guess) and a `lookup.data_error` row lands in your calls log: fix the duplicate rows.",
        "height": 470,
        "width": 2580,
        "color": 5
      },
      "id": "0f12f14e-4207-466d-9085-1ec5cffc4e2f",
      "name": "Note: Mid-call lookup",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1000,
        -810
      ]
    },
    {
      "parameters": {
        "width": 1220,
        "height": 560,
        "color": 1,
        "content": "### Every request: verify, then route\nVoicely signs every event with your endpoint secret (`whsec_…`). **Verify Voicely HMAC** checks it (paste the secret on its first line), **Accept** checks freshness, event type and that it is YOUR account (`expectedAccountId`). Anything else → **401**, nothing is read or written.\n\nThen the three routers send the event to its lane: **ring**, **mid-call lookup**, **after the call**, and everything else to the **call log**."
      },
      "id": "4cbbae47-e072-46ec-be99-eddd9abe9ce2",
      "name": "Note: Security",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -480,
        -160
      ]
    },
    {
      "parameters": {
        "width": 1430,
        "height": 440,
        "color": 3,
        "content": "### Call log (started, ended, failed, recording ready)\nOne row per event in `demomart_calls` (and the Sheet when storage is `both`). Recording links are signed and expire; transcripts are not copied."
      },
      "id": "7c208a1d-eb79-4e05-bde5-a30ecd9beeab",
      "name": "Note: Call log",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1000,
        380
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "66cd3c41-9f4e-4522-8ff4-28227ec02419",
              "leftValue": "={{ $json.data_error === 'duplicate_order_rows' }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "ec4355f2-3461-4660-bb62-7a268b829dac",
      "name": "Lookup data error?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1980,
        -550
      ]
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// One calls-log row for a lookup data error (no caller data; the order id is your own key so you can fix the rows).\nconst ev=$('Accept Voicely Event').first().json.event,j=$input.first().json,S=v=>v===undefined||v===null?'':String(v).trim();\nreturn [{json:{row:{event_id:ev.id+':data_error',event_type:'lookup.data_error',call_id:S(ev.data.call_id),agent_id:S(ev.data.agent_id),direction:'',\n  status:'duplicate_order_rows '+S(j.order_id)+' x'+S(j.duplicate_rows),duration_ms:'',recording_url:'',transcript_included:'false',received_at:new Date().toISOString()}}}];"
      },
      "id": "9e85cb9d-9516-4c87-bf41-6d7230952330",
      "name": "Build Data Error Row",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2210,
        -550
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "582d371a-31db-4c70-9d08-12fa090fbdd9",
              "leftValue": "={{ $('DemoMart Policy').first().json.voicelyPolicy.storage !== 'sheets' }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "e674d5aa-102f-4f99-af4f-4da54f25de4b",
      "name": "Log Data Error: Data Table?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        2440,
        -550
      ]
    },
    {
      "parameters": {
        "operation": "insert",
        "dataTableId": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.callsTableId }}",
          "mode": "id"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "event_id": "={{ $('Build Data Error Row').first().json.row.event_id }}",
            "event_type": "={{ $('Build Data Error Row').first().json.row.event_type }}",
            "call_id": "={{ $('Build Data Error Row').first().json.row.call_id }}",
            "agent_id": "={{ $('Build Data Error Row').first().json.row.agent_id }}",
            "direction": "={{ $('Build Data Error Row').first().json.row.direction }}",
            "status": "={{ $('Build Data Error Row').first().json.row.status }}",
            "duration_ms": "={{ $('Build Data Error Row').first().json.row.duration_ms }}",
            "recording_url": "={{ $('Build Data Error Row').first().json.row.recording_url }}",
            "transcript_included": "={{ $('Build Data Error Row').first().json.row.transcript_included }}",
            "received_at": "={{ $('Build Data Error Row').first().json.row.received_at }}"
          },
          "matchingColumns": [],
          "schema": [
            {
              "id": "event_id",
              "displayName": "event_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "event_type",
              "displayName": "event_type",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "call_id",
              "displayName": "call_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "agent_id",
              "displayName": "agent_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "direction",
              "displayName": "direction",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "status",
              "displayName": "status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "duration_ms",
              "displayName": "duration_ms",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "recording_url",
              "displayName": "recording_url",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "transcript_included",
              "displayName": "transcript_included",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "received_at",
              "displayName": "received_at",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "id": "fd601344-1e97-43fc-a2e3-ddd116d02f11",
      "name": "Log Data Error (Data Table)",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        2670,
        -640
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "c5d434cb-8cb3-4c3a-90fc-9400e85e8d30",
              "leftValue": "={{ $('DemoMart Policy').first().json.voicelyPolicy.storage === 'both' }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "a6f762ae-1de8-48c6-afd6-f39f6489ea0f",
      "name": "Log Data Error: mirror to Sheet?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        2900,
        -640
      ]
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.sheets.documentId }}",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "={{ $('DemoMart Policy').first().json.voicelyPolicy.sheets.callsSheet }}",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "event_id": "={{ $('Build Data Error Row').first().json.row.event_id }}",
            "event_type": "={{ $('Build Data Error Row').first().json.row.event_type }}",
            "call_id": "={{ $('Build Data Error Row').first().json.row.call_id }}",
            "agent_id": "={{ $('Build Data Error Row').first().json.row.agent_id }}",
            "direction": "={{ $('Build Data Error Row').first().json.row.direction }}",
            "status": "={{ $('Build Data Error Row').first().json.row.status }}",
            "duration_ms": "={{ $('Build Data Error Row').first().json.row.duration_ms }}",
            "recording_url": "={{ $('Build Data Error Row').first().json.row.recording_url }}",
            "transcript_included": "={{ $('Build Data Error Row').first().json.row.transcript_included }}",
            "received_at": "={{ $('Build Data Error Row').first().json.row.received_at }}"
          },
          "matchingColumns": [],
          "schema": [
            {
              "id": "event_id",
              "displayName": "event_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "event_type",
              "displayName": "event_type",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "call_id",
              "displayName": "call_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "agent_id",
              "displayName": "agent_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "direction",
              "displayName": "direction",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "status",
              "displayName": "status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "duration_ms",
              "displayName": "duration_ms",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "recording_url",
              "displayName": "recording_url",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "transcript_included",
              "displayName": "transcript_included",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            },
            {
              "id": "received_at",
              "displayName": "received_at",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "readOnly": false,
              "removed": false
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "id": "ff1910c7-55e8-42f0-a4b8-a07178f1104e",
      "name": "Log Data Error (Sheet)",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        3130,
        -460
      ]
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return [{json:{logged:true}}];"
      },
      "id": "a64b9e89-ac30-4407-bbed-755cec941275",
      "name": "Data Error Logged",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        3360,
        -550
      ]
    }
  ],
  "connections": {
    "Voicely Phone Webhook": {
      "main": [
        [
          {
            "node": "DemoMart Policy",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "DemoMart Policy": {
      "main": [
        [
          {
            "node": "Prepare Voicely Signature",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare Voicely Signature": {
      "main": [
        [
          {
            "node": "Verify Voicely HMAC",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Authentication Refused",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Verify Voicely HMAC": {
      "main": [
        [
          {
            "node": "Accept Voicely Event",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Authentication Refused",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Accept Voicely Event": {
      "main": [
        [
          {
            "node": "Is call start (ring)?",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Authentication Refused",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Authentication Refused": {
      "main": [
        [
          {
            "node": "Reply to Voicely",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Is call start (ring)?": {
      "main": [
        [
          {
            "node": "Read Orders at Ring: Data Table?",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Is call lookup (mid-call)?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Orders at Ring: Data Table?": {
      "main": [
        [
          {
            "node": "Read Orders at Ring (Data Table)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Read Orders at Ring (Sheet)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Orders at Ring (Data Table)": {
      "main": [
        [
          {
            "node": "Collect Orders",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Orders at Ring (Sheet)": {
      "main": [
        [
          {
            "node": "Collect Orders",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Tickets at Ring: Data Table?": {
      "main": [
        [
          {
            "node": "Read Tickets at Ring (Data Table)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Read Tickets at Ring (Sheet)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Tickets at Ring (Data Table)": {
      "main": [
        [
          {
            "node": "Build Call Context",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Tickets at Ring (Sheet)": {
      "main": [
        [
          {
            "node": "Build Call Context",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Collect Orders": {
      "main": [
        [
          {
            "node": "Read Tickets at Ring: Data Table?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Call Context": {
      "main": [
        [
          {
            "node": "Reply at Ring",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Reserve Reference: Data Table?": {
      "main": [
        [
          {
            "node": "Reserve Reference (Data Table)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Reserve Reference (Sheet)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Reserve Reference (Data Table)": {
      "main": [
        [
          {
            "node": "Reserve Reference: mirror to Sheet?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Reserve Reference: mirror to Sheet?": {
      "main": [
        [
          {
            "node": "Reserve Reference (Sheet)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Reservation Saved",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Reserve Reference (Sheet)": {
      "main": [
        [
          {
            "node": "Reservation Saved",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Reply at Ring": {
      "main": [
        [
          {
            "node": "Reserve Reference: Data Table?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Tickets after Call: Data Table?": {
      "main": [
        [
          {
            "node": "Read Tickets after Call (Data Table)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Read Tickets after Call (Sheet)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Tickets after Call (Data Table)": {
      "main": [
        [
          {
            "node": "Collect Tickets",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Tickets after Call (Sheet)": {
      "main": [
        [
          {
            "node": "Collect Tickets",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Is call completed (lead)?": {
      "main": [
        [
          {
            "node": "Read Tickets after Call: Data Table?",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Build Call Log Row",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Orders after Call: Data Table?": {
      "main": [
        [
          {
            "node": "Read Orders after Call (Data Table)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Read Orders after Call (Sheet)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Orders after Call (Data Table)": {
      "main": [
        [
          {
            "node": "Build Ticket from Lead",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Orders after Call (Sheet)": {
      "main": [
        [
          {
            "node": "Build Ticket from Lead",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Collect Tickets": {
      "main": [
        [
          {
            "node": "Read Orders after Call: Data Table?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Ticket Filed": {
      "main": [
        [
          {
            "node": "Reply to Voicely",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Complete Ticket: Data Table?": {
      "main": [
        [
          {
            "node": "Complete Ticket (Data Table)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Complete Ticket (Sheet)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Complete Ticket (Data Table)": {
      "main": [
        [
          {
            "node": "Complete Ticket: mirror to Sheet?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Complete Ticket: mirror to Sheet?": {
      "main": [
        [
          {
            "node": "Complete Ticket (Sheet)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Ticket Filed",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Complete Ticket (Sheet)": {
      "main": [
        [
          {
            "node": "Ticket Filed",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Ticket: Data Table?": {
      "main": [
        [
          {
            "node": "Create Ticket (Data Table)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Create Ticket (Sheet)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Ticket (Data Table)": {
      "main": [
        [
          {
            "node": "Create Ticket: mirror to Sheet?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Ticket: mirror to Sheet?": {
      "main": [
        [
          {
            "node": "Create Ticket (Sheet)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Ticket Filed",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Ticket (Sheet)": {
      "main": [
        [
          {
            "node": "Ticket Filed",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Complete reserved ticket?": {
      "main": [
        [
          {
            "node": "Complete Ticket: Data Table?",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "New ticket needed?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "New ticket needed?": {
      "main": [
        [
          {
            "node": "Create Ticket: Data Table?",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Reply to Voicely",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Call Logged": {
      "main": [
        [
          {
            "node": "Reply to Voicely",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log Call Event: Data Table?": {
      "main": [
        [
          {
            "node": "Log Call Event (Data Table)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Log Call Event (Sheet)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log Call Event (Data Table)": {
      "main": [
        [
          {
            "node": "Log Call Event: mirror to Sheet?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log Call Event: mirror to Sheet?": {
      "main": [
        [
          {
            "node": "Log Call Event (Sheet)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Call Logged",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log Call Event (Sheet)": {
      "main": [
        [
          {
            "node": "Call Logged",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Call Log Row": {
      "main": [
        [
          {
            "node": "Log Call Event: Data Table?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Is call lookup (mid-call)?": {
      "main": [
        [
          {
            "node": "Normalize Order Reference",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Is call completed (lead)?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Normalize Order Reference": {
      "main": [
        [
          {
            "node": "Lookup Order: Data Table?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Lookup Order: Data Table?": {
      "main": [
        [
          {
            "node": "Lookup Order (Data Table)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Lookup Order (Sheet)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Lookup Order (Data Table)": {
      "main": [
        [
          {
            "node": "Format for Voicely (lookup)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Lookup Order (Sheet)": {
      "main": [
        [
          {
            "node": "Format for Voicely (lookup)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Format for Voicely (lookup)": {
      "main": [
        [
          {
            "node": "Reply to Voicely",
            "type": "main",
            "index": 0
          },
          {
            "node": "Lookup data error?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Ticket from Lead": {
      "main": [
        [
          {
            "node": "Complete reserved ticket?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Lookup data error?": {
      "main": [
        [
          {
            "node": "Build Data Error Row",
            "type": "main",
            "index": 0
          }
        ],
        []
      ]
    },
    "Build Data Error Row": {
      "main": [
        [
          {
            "node": "Log Data Error: Data Table?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log Data Error: Data Table?": {
      "main": [
        [
          {
            "node": "Log Data Error (Data Table)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Log Data Error (Sheet)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log Data Error (Data Table)": {
      "main": [
        [
          {
            "node": "Log Data Error: mirror to Sheet?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log Data Error: mirror to Sheet?": {
      "main": [
        [
          {
            "node": "Log Data Error (Sheet)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Data Error Logged",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log Data Error (Sheet)": {
      "main": [
        [
          {
            "node": "Data Error Logged",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {},
  "tags": []
}
