{
  "name": "Klaviyo Update List For Campain",
  "nodes": [
    {
      "parameters": {
        "url": "=https://a.klaviyo.com/api/lists/{{ $json.klaviyo_list_id_main }}/relationships/profiles",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "page[size]",
              "value": "1000"
            }
          ]
        },
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "revision",
              "value": "2026-04-15"
            },
            {
              "name": "accept",
              "value": "application/vnd.api+json"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        -736,
        160
      ],
      "id": "8556a8dd-e942-4e18-806a-425fa66b81f6",
      "name": "Get Current Main List Profiles",
      "credentials": {
        "httpHeaderAuth": {
          "id": "bn8eoxIfVyshqKit",
          "name": "Klaviyo Update List"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "const items = $input.all();\n\nlet currentProfiles = [];\nfor (const item of items) {\n  const raw = item.json.data;\n  const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw;\n  const pageData = parsed.data || [];\n  currentProfiles = currentProfiles.concat(pageData);\n}\n\nconst seen = new Set();\ncurrentProfiles = currentProfiles.filter(p => {\n  if (seen.has(p.id)) return false;\n  seen.add(p.id);\n  return true;\n});\n\n\nconst currentCount = currentProfiles.length === 0 ? 30 : currentProfiles.length;\nconst growthRate = 1.04 + Math.random() * 0.03; // 4%–7%\nconst newCount = Math.round(currentCount * growthRate);\n\nconst totalInSource = $('Get & Shuffle Source Profiles').first().json.total_profiles_in_source;\nconst cappedCount = Math.min(newCount, totalInSource);\n\n\nconst listIdMain = $('Get & Shuffle Source Profiles').first().json.klaviyo_list_id_main;\n\nconst deleteData = currentProfiles.map(p => ({\n  type: 'profile',\n  id: p.id\n}));\n\nreturn [{\n  json: {\n    klaviyo_list_id_main: listIdMain,\n    delete_body: { data: deleteData },\n    has_profiles_to_delete: deleteData.length > 0,\n    new_count: cappedCount,\n    growth_rate_applied: `${((growthRate - 1) * 100).toFixed(1)}%`\n  }\n}];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -512,
        160
      ],
      "id": "55c7627a-419a-4c3b-8366-2a4b48f95d60",
      "name": "Build Delete Payload"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "leftValue": "={{ $json.has_profiles_to_delete }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true"
              },
              "id": "65936130-b3b5-4f34-9ab9-af53a475799f"
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        -224,
        160
      ],
      "id": "48d2b1c9-76fc-4ad8-b6cf-0a5820bee628",
      "name": "Has Profiles to Delete?"
    },
    {
      "parameters": {
        "jsCode": "const selectedProfileIds = $('Get & Shuffle Source Profiles').first().json.selected_profile_ids;\nconst listIdMain = $('Build Delete Payload').first().json.klaviyo_list_id_main;\nconst newCount = $('Build Delete Payload').first().json.new_count;\n\nconst slicedIds = selectedProfileIds.slice(0, newCount);\n\nconst addData = slicedIds.map(id => ({\n  type: 'profile',\n  id: id\n}));\n\nreturn [{\n  json: {\n    klaviyo_list_id_main: listIdMain,\n    add_body: { data: addData },\n    profiles_added: slicedIds.length,\n    growth_rate_applied: $('Build Delete Payload').first().json.growth_rate_applied\n  }\n}];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        240,
        176
      ],
      "id": "ed9040c3-bd01-41bd-a2c1-e0538302203a",
      "name": "Build Add Payload"
    },
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "triggerAtHour": 8
            }
          ]
        }
      },
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.3,
      "position": [
        -1696,
        160
      ],
      "id": "ea43b828-b2f0-4df6-8be9-6920e80b2859",
      "name": "Schedule Trigger1"
    },
    {
      "parameters": {
        "mode": "raw",
        "jsonOutput": "{\n  \"klaviyo_list_info\": [\n    {\n      \"klaviyo_list_id_main\": \"list_id\",\n      \"klaviyo_list_id_source\": \"list_id\"\n    }\n  ]\n}",
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -1440,
        160
      ],
      "id": "2f55b4d4-8641-420c-a5ae-1a29d86b6f54",
      "name": "Set Workflow Global Variables"
    },
    {
      "parameters": {
        "method": "DELETE",
        "url": "={{ \"https://a.klaviyo.com/api/lists/\" + $json.klaviyo_list_id_main + \"/relationships/profiles\" }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "revision",
              "value": "2026-04-15"
            },
            {
              "name": "content-type",
              "value": "application/vnd.api+json"
            },
            {
              "name": "accept",
              "value": "application/vnd.api+json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ $json.delete_body }}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        0,
        0
      ],
      "id": "f8b75bb8-560e-4509-bc8d-ccd626c2aee3",
      "name": "Remove All Profiles from Main List",
      "credentials": {
        "httpHeaderAuth": {
          "id": "5lg0nOKmOhtOlA06",
          "name": "Klaviyo Auth"
        }
      }
    },
    {
      "parameters": {
        "url": "={{ \"https://a.klaviyo.com/api/lists/\" + $('Set Workflow Global Variables').first().json.klaviyo_list_info[0].klaviyo_list_id_source + \"/relationships/profiles\" }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "page[size]",
              "value": "1000"
            }
          ]
        },
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "revision",
              "value": "2026-04-15"
            },
            {
              "name": "accept",
              "value": "application/vnd.api+json"
            }
          ]
        },
        "options": {
          "response": {
            "response": {
              "responseFormat": "json"
            }
          },
          "pagination": {
            "pagination": {
              "parameters": {
                "parameters": [
                  {
                    "name": "page[cursor]",
                    "value": "={{ decodeURIComponent($response.body.links.next)?.match(/page\\[cursor\\]=([^&]+)/)?.[1] }}"
                  }
                ]
              },
              "paginationCompleteWhen": "other",
              "completeExpression": "={{ !$response.body?.links?.next }}",
              "requestInterval": 1000
            }
          }
        }
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        -1216,
        160
      ],
      "id": "eaee4d9d-dc40-4ea7-8d1e-7f886d9b4de8",
      "name": "Get Source List Profiles",
      "credentials": {
        "httpHeaderAuth": {
          "id": "5lg0nOKmOhtOlA06",
          "name": "Klaviyo Auth"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "const items = $input.all();\n\nlet profiles = [];\nfor (const item of items) {\n  const pageData = item.json.data || [];\n  profiles = profiles.concat(pageData);\n}\n\n// Deduplicate by id\nconst seen = new Set();\nprofiles = profiles.filter(p => {\n  if (seen.has(p.id)) return false;\n  seen.add(p.id);\n  return true;\n});\n\nconsole.log('Total pages received:', items.length);\nconsole.log('Total profiles after dedup:', profiles.length);\n\n// Shuffle using Fisher-Yates\nfor (let i = profiles.length - 1; i > 0; i--) {\n  const j = Math.floor(Math.random() * (i + 1));\n  [profiles[i], profiles[j]] = [profiles[j], profiles[i]];\n}\n\n// Pass ALL shuffled profiles — slicing happens later in Build Add Payload\nreturn [{\n  json: {\n    total_profiles_in_source: profiles.length,\n    total_pages: items.length,\n    selected_profile_ids: profiles.map(p => p.id),\n    klaviyo_list_id_main: $('Set Workflow Global Variables').first().json.klaviyo_list_info[0].klaviyo_list_id_main,\n    klaviyo_list_id_source: $('Set Workflow Global Variables').first().json.klaviyo_list_info[0].klaviyo_list_id_source\n  }\n}];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -992,
        160
      ],
      "id": "a1e2c181-2c57-40c9-a0b7-2c53ada11cfc",
      "name": "Get & Shuffle Source Profiles"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://a.klaviyo.com/api/lists/{{ $json.klaviyo_list_id_main }}/relationships/profiles",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "revision",
              "value": "2026-04-15"
            },
            {
              "name": "content-type",
              "value": "application/vnd.api+json"
            },
            {
              "name": "accept",
              "value": "application/vnd.api+json"
            }
          ]
        },
        "sendBody": true,
        "contentType": "raw",
        "rawContentType": "application/vnd.api+json",
        "body": "={{ JSON.stringify($json.add_body) }}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        496,
        176
      ],
      "id": "9cf44e20-2d8c-4f18-9d25-8d521240fb42",
      "name": "Add Random Profiles to Main List",
      "credentials": {
        "httpHeaderAuth": {
          "id": "bn8eoxIfVyshqKit",
          "name": "Klaviyo Update List"
        }
      }
    }
  ],
  "pinData": {},
  "connections": {
    "Get Current Main List Profiles": {
      "main": [
        [
          {
            "node": "Build Delete Payload",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Delete Payload": {
      "main": [
        [
          {
            "node": "Has Profiles to Delete?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Has Profiles to Delete?": {
      "main": [
        [
          {
            "node": "Remove All Profiles from Main List",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Build Add Payload",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Add Payload": {
      "main": [
        [
          {
            "node": "Add Random Profiles to Main List",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Schedule Trigger1": {
      "main": [
        [
          {
            "node": "Set Workflow Global Variables",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set Workflow Global Variables": {
      "main": [
        [
          {
            "node": "Get Source List Profiles",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Remove All Profiles from Main List": {
      "main": [
        [
          {
            "node": "Build Add Payload",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Source List Profiles": {
      "main": [
        [
          {
            "node": "Get & Shuffle Source Profiles",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get & Shuffle Source Profiles": {
      "main": [
        [
          {
            "node": "Get Current Main List Profiles",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "binaryMode": "separate"
  },
  "versionId": "49b890c4-64b9-4c99-8a6c-0b65d8642050",
  "meta": {
    "instanceId": "6f57e464250a9fd092024d89a5e7f85582364ce6c7ac3677734aa0fb1770e696"
  },
  "id": "jyFdcKkfkBSZAaIl",
  "tags": []
}