{
  "name": "[HUB] \u0416\u043e\u0440\u0430 Action",
  "description": null,
  "nodes": [
    {
      "id": "action-trigger",
      "name": "When Called by \u0416\u043e\u0440\u0430",
      "type": "n8n-nodes-base.executeWorkflowTrigger",
      "typeVersion": 1.1,
      "position": [
        -800,
        0
      ],
      "parameters": {
        "inputSource": "passthrough"
      }
    },
    {
      "id": "<uuid>",
      "name": "Switch by Intent",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.2,
      "position": [
        -600,
        0
      ],
      "parameters": {
        "rules": {
          "values": [
            {
              "outputKey": "new_task",
              "conditions": {
                "options": {
                  "version": 2,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "new-task-check",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.output.intent }}",
                    "rightValue": "new_task"
                  }
                ]
              },
              "renameOutput": true
            },
            {
              "outputKey": "task_update",
              "conditions": {
                "options": {
                  "version": 2,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "task-update-check",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.output.intent }}",
                    "rightValue": "task_update"
                  }
                ]
              },
              "renameOutput": true
            },
            {
              "outputKey": "dialogue",
              "conditions": {
                "options": {
                  "version": 2,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "dialogue-check",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.output.intent }}",
                    "rightValue": "dialogue"
                  }
                ]
              },
              "renameOutput": true
            }
          ]
        },
        "options": {
          "fallbackOutput": "none"
        }
      }
    },
    {
      "id": "<uuid>",
      "name": "Prepare New Task Data",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -400,
        -200
      ],
      "parameters": {
        "jsCode": "const decision = $input.first().json.output;\nconst originalData = $('When Called by \u0416\u043e\u0440\u0430').first().json.original_data;\nconst context = originalData.context;\n\nlet sourceData = null;\n\n// ============================================\n// \u041f\u0420\u0418\u041e\u0420\u0418\u0422\u0415\u0422 #1-4: Context-based source_data\n// ============================================\n\nif (context && context.context_type) {\n  \n  // \u041f\u0440\u0438\u043e\u0440\u0438\u0442\u0435\u0442 1: Reply \u043d\u0430 longread\n  if (context.context_type === 'longread') {\n    sourceData = {\n      type: 'longread',\n      news_list: context.content.news_list,\n      user_instruction: decision.user_request\n    };\n  }\n  \n  // \u041f\u0440\u0438\u043e\u0440\u0438\u0442\u0435\u0442 2: Forwarded message\n  else if (context.context_type === 'forwarded') {\n    sourceData = {\n      type: 'forwarded_message',\n      text: context.forwarded_content.text,\n      forwarded_date: context.forwarded_content.forwarded_date\n    };\n  }\n  \n  // \u041f\u0440\u0438\u043e\u0440\u0438\u0442\u0435\u0442 3: Photo\n  else if (context.context_type === 'photo') {\n    sourceData = {\n      type: 'photo',\n      photo_file_id: context.photo_file_id\n    };\n  }\n  \n  // \u041f\u0440\u0438\u043e\u0440\u0438\u0442\u0435\u0442 3.5: Post (reply \u043d\u0430 \u043f\u043e\u0441\u0442)\n  else if (context.context_type === 'post') {\n    sourceData = {\n      type: 'post',\n      task_id: context.task_id,\n      post_text: context.content?.post_text || '',\n      photo_file_id: context.content?.photo_file_id || null,\n      version: context.content?.version || 1,\n      sources: context.content?.sources || []\n    };\n    console.log('[PREPARE NEW TASK] Post source_data from reply, text length:', sourceData.post_text.length);\n  }\n  \n  // \u041f\u0440\u0438\u043e\u0440\u0438\u0442\u0435\u0442 4: Task (\u043e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u0438\u0435)\n  else if (context.context_type === 'task') {\n    sourceData = null;\n  }\n  \n  // \u041f\u0440\u0438\u043e\u0440\u0438\u0442\u0435\u0442 5: Research\n  else if (context.context_type === 'research') {\n    sourceData = {\n      type: 'research',\n      content: context.content?.content || null,\n      sources: context.content?.sources || []\n    };\n  }\n  \n  else {\n    sourceData = null;\n  }\n}\n\n// \u041f\u0420\u0418\u041e\u0420\u0418\u0422\u0415\u0422 #5: \u041d\u0435\u044f\u0432\u043d\u044b\u0435 \u0441\u0441\u044b\u043b\u043a\u0438 \u043d\u0430 completed tasks\nif (!sourceData && decision.user_request) {\n  const implicitReferences = [\n    '\u0434\u043b\u044f \u044d\u0442\u043e\u0433\u043e \u043f\u043e\u0441\u0442\u0430',\n    '\u043a \u044d\u0442\u043e\u043c\u0443 \u043f\u043e\u0441\u0442\u0443', \n    '\u043f\u0440\u043e \u044d\u0442\u043e\u0442 \u043f\u043e\u0441\u0442',\n    '\u0434\u043b\u044f \u0442\u043e\u0433\u043e \u043f\u043e\u0441\u0442\u0430',\n    '\u043a \u0442\u043e\u0439 \u043d\u043e\u0432\u043e\u0441\u0442\u0438',\n    '\u043f\u0440\u043e \u0442\u0443 \u043d\u043e\u0432\u043e\u0441\u0442\u044c',\n    '\u0434\u043b\u044f \u044d\u0442\u043e\u0439 \u043d\u043e\u0432\u043e\u0441\u0442\u0438',\n    '\u043a \u044d\u0442\u043e\u0439 \u043d\u043e\u0432\u043e\u0441\u0442\u0438'\n  ];\n  \n  const requestLower = decision.user_request.toLowerCase();\n  const hasImplicitReference = implicitReferences.some(phrase => \n    requestLower.includes(phrase)\n  );\n  \n  if (hasImplicitReference && originalData.completed_tasks?.length > 0) {\n    const lastCopywritingTask = originalData.completed_tasks\n      .filter(t => t.department === 'copywriting')\n      .sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at))[0];\n    \n    if (lastCopywritingTask) {\n      sourceData = {\n        reference_task_id: lastCopywritingTask.id,  // \u2705 \u0422\u043e\u043b\u044c\u043a\u043e ID\n        reference_type: 'post',                     // \u2705 \u0422\u0438\u043f \u0438\u0441\u0442\u043e\u0447\u043d\u0438\u043a\u0430\n        user_request: decision.user_request         // \u2705 \u0417\u0430\u043f\u0440\u043e\u0441\n      };\n      \n      console.log('[PREPARE NEW TASK] Implicit reference detected, reference_task_id:', lastCopywritingTask.id);\n    }\n  }\n}\n// ============================================\n// \u0424\u041e\u0420\u041c\u0418\u0420\u0423\u0415\u041c \u0418\u0422\u041e\u0413\u041e\u0412\u042b\u0419 \u041e\u0411\u042a\u0415\u041a\u0422\n// ============================================\n\nreturn {\n  json: {\n    chat_id: originalData.chat_id,\n    user_id: originalData.user_id,\n    department: decision.department,\n    status: 'created',\n    initial_prompt: decision.user_request,\n    source_data: sourceData,\n    agent_output: {\n      current_version: 1,\n      versions: []\n    },\n    _trigger: {\n      intent: 'new_task',\n      chat_id: originalData.chat_id,\n      reply_to_message_id: originalData.reply_to_message_id,\n      user_request: decision.user_request,\n      department: decision.department\n    }\n  }\n};"
      }
    },
    {
      "id": "<uuid>",
      "name": "Create Task in Supabase",
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        -200,
        -200
      ],
      "parameters": {
        "schema": "smm_army",
        "tableId": "tasks",
        "fieldsUi": {
          "fieldValues": [
            {
              "fieldId": "chat_id",
              "fieldValue": "={{ $json.chat_id }}"
            },
            {
              "fieldId": "user_id",
              "fieldValue": "={{ $json.user_id }}"
            },
            {
              "fieldId": "department",
              "fieldValue": "={{ $json.department }}"
            },
            {
              "fieldId": "status",
              "fieldValue": "={{ $json.status }}"
            },
            {
              "fieldId": "initial_prompt",
              "fieldValue": "={{ $json.initial_prompt }}"
            },
            {
              "fieldId": "agent_output",
              "fieldValue": "={{ $json.agent_output }}"
            },
            {
              "fieldId": "source_data",
              "fieldValue": "={{ $json.source_data }}"
            },
            {
              "fieldId": "version",
              "fieldValue": "1"
            }
          ]
        },
        "useCustomSchema": true
      },
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "id": "<uuid>",
      "name": "Prepare Update Task Data",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -400,
        0
      ],
      "parameters": {
        "jsCode": "const decision = $input.first().json.output;\nconst originalData = $('When Called by \u0416\u043e\u0440\u0430').first().json.original_data;\nconst context = originalData.context;\n\nlet taskId = null;\nlet taskData = null;\nlet fullAgentOutput = null;\n\n// \u0417\u0430\u0433\u0440\u0443\u0437\u043a\u0430 completed tasks\nlet completedTasks = [];\ntry {\n  completedTasks = originalData.completed_tasks || [];\n} catch (e) {\n  console.log('[Prepare Update Task Data] Failed to load completed tasks:', e);\n  completedTasks = [];\n}\n\n// \u041f\u0420\u0418\u041e\u0420\u0418\u0422\u0415\u0422 #1: target_task_id \u043e\u0442 AI Agent\nif (decision.target_task_id) {\n  const targetTask = completedTasks.find(task => task.id === decision.target_task_id);\n  \n  if (targetTask) {\n    taskId = targetTask.id;\n    taskData = {\n      current_version: targetTask.agent_output?.current_version || 0,\n      department: targetTask.department\n    };\n    fullAgentOutput = targetTask.agent_output;\n  } else {\n    throw new Error(`Task ${decision.target_task_id} not found in completed tasks`);\n  }\n}\n\n// \u041f\u0420\u0418\u041e\u0420\u0418\u0422\u0415\u0422 #2: REPLY \u043a\u043e\u043d\u0442\u0435\u043a\u0441\u0442\nelse if (context.task_id) {\n  taskId = context.task_id;\n  const targetTask = completedTasks.find(task => task.id === context.task_id);\n  \n  if (targetTask) {\n    taskData = {\n      current_version: targetTask.agent_output?.current_version || 0,\n      department: targetTask.department\n    };\n    fullAgentOutput = targetTask.agent_output;\n  } else {\n    taskData = {\n      current_version: 0,\n      department: decision.department\n    };\n    fullAgentOutput = { current_version: 0, versions: [] };\n  }\n}\n\n// \u041f\u0420\u0418\u041e\u0420\u0418\u0422\u0415\u0422 #3: \u041f\u043e\u0441\u043b\u0435\u0434\u043d\u044f\u044f \u0437\u0430\u0434\u0430\u0447\u0430 \u0441 matching department\nelse if (completedTasks.length > 0 && decision.department) {\n  const tasksInDepartment = completedTasks.filter(\n    task => task.department === decision.department\n  );\n  \n  if (tasksInDepartment.length > 0) {\n    const targetTask = tasksInDepartment[0];\n    taskId = targetTask.id;\n    taskData = {\n      current_version: targetTask.agent_output?.current_version || 0,\n      department: targetTask.department\n    };\n    fullAgentOutput = targetTask.agent_output;\n  }\n}\n\n// FALLBACK: \u0437\u0430\u0434\u0430\u0447\u0438 \u043d\u0435 \u043d\u0430\u0448\u043b\u0438\nif (!taskId) {\n  const hint = decision.department && completedTasks.length > 0\n    ? `No ${decision.department} tasks found in recent history. Reply to a specific task message or create a new task.`\n    : 'No recent completed tasks found. Reply to a task message or create a new task.';\n  \n  throw new Error(hint);\n}\n\n// \u0424\u043e\u0440\u043c\u0438\u0440\u0443\u0435\u043c \u043e\u0431\u043d\u043e\u0432\u043b\u0451\u043d\u043d\u044b\u0439 agent_output\nif (typeof fullAgentOutput === 'string') {\n  try {\n    fullAgentOutput = JSON.parse(fullAgentOutput);\n  } catch (e) {\n    fullAgentOutput = { current_version: 0, versions: [] };\n  }\n}\n\nlet versions = fullAgentOutput?.versions || [];\n\n// \u0421\u043e\u0437\u0434\u0430\u0451\u043c \u043d\u043e\u0432\u0443\u044e \u0432\u0435\u0440\u0441\u0438\u044e\nconst newVersion = {\n  version: (fullAgentOutput?.current_version || 0) + 1,\n  user_request: decision.user_request,\n  agent_response: null,\n  timestamp: new Date().toISOString()\n};\n\n// \u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430 \u0431\u0435\u0437\u043e\u043f\u0430\u0441\u043d\u043e\u0441\u0442\u0438 (\u043b\u043e\u0433\u0438\u0440\u0443\u0435\u043c, \u043d\u0435 \u0431\u043b\u043e\u043a\u0438\u0440\u0443\u0435\u043c)\nif (versions.length > 0) {\n  const lastVersion = versions[versions.length - 1];\n  if (lastVersion.version && lastVersion.version !== newVersion.version - 1) {\n    console.warn(`[PREPARE UPDATE] Version sequence warning: last=${lastVersion.version}, new=${newVersion.version}`);\n  }\n}\n\nversions.push(newVersion);\n\nconst updatedAgentOutput = {\n  versions: versions,\n  current_version: newVersion.version\n};\n\nreturn {\n  json: {\n    task_id: taskId,\n    agent_output: updatedAgentOutput,\n    status: 'in_progress',\n    department: taskData?.department || decision.department,\n    reply_to_message_id: originalData.reply_to_message_id,\n    _trigger: {\n      intent: 'task_update',\n      chat_id: originalData.chat_id,\n      reply_to_message_id: originalData.reply_to_message_id,\n      user_request: decision.user_request,\n      department: taskData?.department || decision.department\n    }\n  }\n};"
      }
    },
    {
      "id": "<uuid>",
      "name": "Update Task in Supabase",
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        -200,
        0
      ],
      "parameters": {
        "schema": "smm_army",
        "filters": {
          "conditions": [
            {
              "keyName": "id",
              "keyValue": "={{ $json.task_id }}",
              "condition": "eq"
            }
          ]
        },
        "tableId": "tasks",
        "fieldsUi": {
          "fieldValues": [
            {
              "fieldId": "status",
              "fieldValue": "in_progress"
            }
          ]
        },
        "matchType": "allFilters",
        "operation": "update",
        "useCustomSchema": true
      },
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "id": "<uuid>",
      "name": "Send Clarification",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        0,
        200
      ],
      "parameters": {
        "text": "={{ $json.message }}",
        "chatId": "={{ $json.chat_id }}",
        "resource": "message",
        "operation": "sendMessage",
        "additionalFields": {
          "parse_mode": "Markdown",
          "appendAttribution": false
        }
      },
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "id": "<uuid>",
      "name": "Merge All Routes",
      "type": "n8n-nodes-base.merge",
      "typeVersion": 3.2,
      "position": [
        0,
        -100
      ],
      "parameters": {}
    },
    {
      "id": "<uuid>",
      "name": "Prepare Success Message",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        200,
        -100
      ],
      "parameters": {
        "jsCode": "const taskData = $input.first().json;\nconst trg = taskData._trigger || {};\nconst intent = trg.intent || 'new_task';\nconst department = taskData.department || trg.department;\n\nconst newTaskPhrases = [\n  '\u0421\u043e\u0437\u0434\u0430\u043b \u0437\u0430\u0434\u0430\u0447\u0443 \u2705',\n  '\u0412 \u0440\u0430\u0431\u043e\u0442\u0435 \ud83d\ude80',\n  '\u0421\u0443\u0435\u0447\u0443\u0441\u044c \u2728',\n  '\u0423\u0436\u0435 \u0434\u0435\u043b\u0430\u044e \u26a1',\n  '\u0423\u0436\u0435 \u043d\u0430\u0447\u0430\u043b \ud83d\udc4c',\n  '\u0414\u0435\u043b\u0430\u044e \u26a1'\n];\n\nconst updateTaskPhrases = [\n  '\u041e\u0431\u043d\u043e\u0432\u043b\u044f\u044e \ud83d\udd04',\n  '\u041f\u0440\u0430\u0432\u043b\u044e  \ud83d\udee0',\n  '\u041d\u0435 \u0432\u043e\u043f\u0440\u043e\u0441 \ud83d\udee0',\n  '\u041c\u043e\u043c\u0435\u043d\u0442\u0438\u043a \u2699\ufe0f',\n  '\u0429\u0430 \u0431\u0443\u0434\u0435\u0442 \ud83d\udd04'\n];\n\nlet message = '';\n\nif (intent === 'new_task') {\n  message = newTaskPhrases[Math.floor(Math.random() * newTaskPhrases.length)];\n} else if (intent === 'task_update') {\n  message = updateTaskPhrases[Math.floor(Math.random() * updateTaskPhrases.length)];\n} else {\n  message = '\u0413\u043e\u0442\u043e\u0432\u043e!';\n}\n\nlet effectiveUserRequest = taskData.initial_prompt;\nif (intent === 'task_update') {\n  effectiveUserRequest = trg.user_request || taskData.initial_prompt;\n}\n\nreturn {\n  json: {\n    ...taskData,\n    telegram_message: message,\n    chat_id: trg.chat_id || taskData.chat_id,\n    department: department,\n    effective_user_request: effectiveUserRequest,\n    reply_to_message_id: trg.reply_to_message_id || taskData.reply_to_message_id || null\n  }\n};"
      }
    },
    {
      "id": "<uuid>",
      "name": "Send Confirmation",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        400,
        100
      ],
      "parameters": {
        "text": "={{ $json.telegram_message }}",
        "chatId": "={{ $json.chat_id }}",
        "resource": "message",
        "operation": "sendMessage",
        "additionalFields": {
          "appendAttribution": false
        }
      },
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "id": "e3216da4-7c17-4581-a7b4-95f<TG_USER_ID>e",
      "name": "Execute Copywriting",
      "type": "n8n-nodes-base.executeWorkflow",
      "typeVersion": 1.3,
      "position": [
        600,
        -300
      ],
      "parameters": {
        "options": {
          "waitForSubWorkflow": false
        },
        "workflowId": {
          "__rl": true,
          "mode": "list",
          "value": "ms4UpiiPsGF8GRpZ",
          "cachedResultUrl": "/workflow/7eCTCPZ2fFhMqhKd",
          "cachedResultName": ""
        },
        "workflowInputs": {
          "value": {},
          "schema": [],
          "mappingMode": "defineBelow",
          "matchingColumns": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": true
        }
      }
    },
    {
      "id": "<uuid>",
      "name": "Execute Research",
      "type": "n8n-nodes-base.executeWorkflow",
      "typeVersion": 1.3,
      "position": [
        600,
        300
      ],
      "parameters": {
        "options": {
          "waitForSubWorkflow": false
        },
        "workflowId": {
          "__rl": true,
          "mode": "list",
          "value": "w2J2Nvqf9w3T8G2I",
          "cachedResultUrl": "/workflow/YWVgcNTa3YG2rvJA",
          "cachedResultName": "[SMM] Research Agent"
        },
        "workflowInputs": {
          "value": {},
          "schema": [],
          "mappingMode": "defineBelow",
          "matchingColumns": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": true
        }
      }
    },
    {
      "id": "<uuid>",
      "name": "Execute Image Gen",
      "type": "n8n-nodes-base.executeWorkflow",
      "typeVersion": 1.3,
      "position": [
        600,
        -200
      ],
      "parameters": {
        "options": {
          "waitForSubWorkflow": false
        },
        "workflowId": {
          "__rl": true,
          "mode": "list",
          "value": "RLNAMdc1C9krPt7o",
          "cachedResultUrl": "/workflow/WHvXosyNwhLB6OOp",
          "cachedResultName": ""
        },
        "workflowInputs": {
          "value": {},
          "schema": [],
          "mappingMode": "defineBelow",
          "matchingColumns": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": true
        }
      }
    },
    {
      "id": "<uuid>",
      "name": "Execute Image Edit",
      "type": "n8n-nodes-base.executeWorkflow",
      "typeVersion": 1.3,
      "position": [
        600,
        -100
      ],
      "parameters": {
        "options": {
          "waitForSubWorkflow": false
        },
        "workflowId": {
          "__rl": true,
          "mode": "list",
          "value": "yrdBxd3PxAosMSGg",
          "cachedResultUrl": "/workflow/UpcjQTagDBhV8ChU",
          "cachedResultName": ""
        },
        "workflowInputs": {
          "value": {},
          "schema": [],
          "mappingMode": "defineBelow",
          "matchingColumns": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": true
        }
      }
    },
    {
      "id": "<uuid>",
      "name": "Switch Department",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.3,
      "position": [
        400,
        -100
      ],
      "parameters": {
        "rules": {
          "values": [
            {
              "outputKey": "copywriting",
              "conditions": {
                "options": {
                  "version": 2,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "<uuid>",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.department }}",
                    "rightValue": "copywriting"
                  }
                ]
              },
              "renameOutput": true
            },
            {
              "outputKey": "image_gen",
              "conditions": {
                "options": {
                  "version": 2,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "<uuid>",
                    "operator": {
                      "name": "filter.operator.equals",
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.department }}",
                    "rightValue": "image_gen"
                  }
                ]
              },
              "renameOutput": true
            },
            {
              "outputKey": "image_edit",
              "conditions": {
                "options": {
                  "version": 2,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "<uuid>",
                    "operator": {
                      "name": "filter.operator.equals",
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.department }}",
                    "rightValue": "image_edit"
                  }
                ]
              },
              "renameOutput": true
            },
            {
              "outputKey": "research",
              "conditions": {
                "options": {
                  "version": 2,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "<uuid>",
                    "operator": {
                      "name": "filter.operator.equals",
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.department }}",
                    "rightValue": "research"
                  }
                ]
              },
              "renameOutput": true
            },
            {
              "outputKey": "longwriter",
              "conditions": {
                "options": {
                  "version": 2,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "longwriter-case-001",
                    "operator": {
                      "name": "filter.operator.equals",
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.department }}",
                    "rightValue": "longwriter"
                  }
                ]
              },
              "renameOutput": true
            },
            {
              "outputKey": "reels_ideas",
              "conditions": {
                "options": {
                  "version": 2,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "reels-ideas-case-001",
                    "operator": {
                      "name": "filter.operator.equals",
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.department }}",
                    "rightValue": "reels_ideas"
                  }
                ]
              },
              "renameOutput": true
            }
          ]
        },
        "options": {}
      }
    },
    {
      "id": "<uuid>",
      "name": "Execute Longwriter",
      "type": "n8n-nodes-base.executeWorkflow",
      "typeVersion": 1.3,
      "position": [
        600,
        0
      ],
      "parameters": {
        "options": {
          "waitForSubWorkflow": false
        },
        "workflowId": {
          "__rl": true,
          "mode": "list",
          "value": "UPFcgobNesc5H0do",
          "cachedResultUrl": "/workflow/7eCTCPZ2fFhMqhKd",
          "cachedResultName": "Secretary: Longwriter"
        },
        "workflowInputs": {
          "value": {},
          "schema": [],
          "mappingMode": "defineBelow",
          "matchingColumns": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": true
        }
      }
    },
    {
      "id": "<uuid>",
      "name": "Execute Reels Ideas",
      "type": "n8n-nodes-base.executeWorkflow",
      "typeVersion": 1.3,
      "position": [
        600,
        100
      ],
      "parameters": {
        "options": {
          "waitForSubWorkflow": false
        },
        "workflowId": {
          "__rl": true,
          "mode": "list",
          "value": "oVbxXDb6knuvR9MJ",
          "cachedResultUrl": "/workflow/7eCTCPZ2fFhMqhKd",
          "cachedResultName": "Reels Collector Bot"
        },
        "workflowInputs": {
          "value": {},
          "schema": [],
          "mappingMode": "defineBelow",
          "matchingColumns": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": true
        }
      }
    },
    {
      "id": "gen-options-001",
      "name": "Generate Options",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        -400,
        200
      ],
      "parameters": {
        "url": "https://api.openai.com/v1/chat/completions",
        "method": "POST",
        "options": {
          "timeout": 30000
        },
        "jsonBody": "={\n  \"model\": \"gpt-4o\",\n  \"messages\": [\n    {\"role\": \"system\", \"content\": \"\u0422\u044b \u2014 \u043a\u0432\u0430\u043b\u0438\u0444\u0438\u043a\u0430\u0442\u043e\u0440 \u0437\u0430\u043f\u0440\u043e\u0441\u043e\u0432 Boss (n8n \u0430\u0432\u0442\u043e\u043c\u0430\u0442\u0438\u0437\u0430\u0442\u043e\u0440 \u0438\u0437 Da Nang). \u041d\u0430 \u0432\u0445\u043e\u0434 \u2014 \u043d\u0435\u044f\u0441\u043d\u044b\u0439 \u0437\u0430\u043f\u0440\u043e\u0441. \u041f\u0440\u0435\u0434\u043b\u043e\u0436\u0438 \u0420\u041e\u0412\u041d\u041e 3 \u0432\u0430\u0440\u0438\u0430\u043d\u0442\u0430 \u0447\u0442\u043e Boss \u043c\u043e\u0433 \u0438\u043c\u0435\u0442\u044c \u0432 \u0432\u0438\u0434\u0443. \u041a\u0430\u0436\u0434\u044b\u0439 \u0432\u0430\u0440\u0438\u0430\u043d\u0442 = \u043a\u043e\u043d\u043a\u0440\u0435\u0442\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430 \u0434\u043b\u044f department: copywriting (\u043a\u043e\u0440\u043e\u0442\u043a\u0438\u0439 \u043f\u043e\u0441\u0442 100-400 \u0441\u043b\u043e\u0432) | research (\u0440\u0438\u0441\u0451\u0440\u0447 \u0442\u0435\u043c\u044b) | longwriter (\u043b\u043e\u043d\u0433\u0440\u0438\u0434 1500-3500 \u0437\u043d\u0430\u043a\u043e\u0432) | image_gen (\u043a\u0430\u0440\u0442\u0438\u043d\u043a\u0430) | image_edit (\u0440\u0435\u0434\u0430\u043a\u0442 \u0444\u043e\u0442\u043e) | reels_ideas (\u0430\u043d\u0430\u043b\u0438\u0437 TikTok/YT/IG \u0441\u0441\u044b\u043b\u043a\u0438). \u0412\u0435\u0440\u043d\u0438 \u0421\u0422\u0420\u041e\u0413\u041e JSON \u0431\u0435\u0437 markdown: {\\\"options\\\":[{\\\"num\\\":1,\\\"emoji\\\":\\\"\ud83d\udcdd\\\",\\\"title\\\":\\\"\u043a\u043e\u0440\u043e\u0442\u043a\u043e\u0435 \u043e\u043f\u0438\u0441\u0430\u043d\u0438\u0435 \u0432 \u0438\u043c\u043f\u0435\u0440\u0430\u0442\u0438\u0432\u0435\\\",\\\"intent\\\":\\\"new_task\\\",\\\"department\\\":\\\"copywriting\\\",\\\"request\\\":\\\"\u043f\u043e\u043b\u043d\u0430\u044f \u0444\u0440\u0430\u0437\u0430 \u0434\u043b\u044f \u0430\u0433\u0435\u043d\u0442\u0430 department\\\"},...]}\"},\n    {\"role\": \"user\", \"content\": {{ JSON.stringify($json.output.user_request) }}}\n  ],\n  \"response_format\": {\"type\": \"json_object\"},\n  \"temperature\": 0.5\n}",
        "sendBody": true,
        "specifyBody": "json",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "openAiApi"
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000
    },
    {
      "id": "format-options-001",
      "name": "Format Options & Save",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -200,
        200
      ],
      "parameters": {
        "jsCode": "const raw = $json.choices[0].message.content;\nconst parsed = JSON.parse(raw);\nconst state = $getWorkflowStaticData('global');\nconst chatId = $('When Called by \u0416\u043e\u0440\u0430').first().json.original_data.chat_id;\n\nstate[`options_${chatId}`] = {\n  options: parsed.options,\n  expires: Date.now() + 300000\n};\n\nconst text = `\ud83e\udd14 \u0423\u0442\u043e\u0447\u043d\u0438 \u0447\u0442\u043e \u043d\u0443\u0436\u043d\u043e:\\n\\n${parsed.options.map(o => `${o.num}. ${o.emoji} ${o.title}`).join('\\n')}\\n\\n\u041e\u0442\u0432\u0435\u0442\u044c \u0446\u0438\u0444\u0440\u043e\u0439 (1\u20133) \u0438\u043b\u0438 \u043d\u0430\u043f\u0438\u0448\u0438 \u0437\u0430\u043d\u043e\u0432\u043e.`;\n\nreturn [{ json: { message: text, chat_id: chatId } }];"
      }
    }
  ],
  "connections": {
    "When Called by \u0416\u043e\u0440\u0430": {
      "main": [
        [
          {
            "node": "Switch by Intent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Switch by Intent": {
      "main": [
        [
          {
            "node": "Prepare New Task Data",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Prepare Update Task Data",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Generate Options",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare New Task Data": {
      "main": [
        [
          {
            "node": "Create Task in Supabase",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Task in Supabase": {
      "main": [
        [
          {
            "node": "Merge All Routes",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare Update Task Data": {
      "main": [
        [
          {
            "node": "Update Task in Supabase",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Update Task in Supabase": {
      "main": [
        [
          {
            "node": "Merge All Routes",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Merge All Routes": {
      "main": [
        [
          {
            "node": "Prepare Success Message",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare Success Message": {
      "main": [
        [
          {
            "node": "Switch Department",
            "type": "main",
            "index": 0
          },
          {
            "node": "Send Confirmation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Switch Department": {
      "main": [
        [
          {
            "node": "Execute Copywriting",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Execute Image Gen",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Execute Image Edit",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Execute Research",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Execute Longwriter",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Execute Reels Ideas",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate Options": {
      "main": [
        [
          {
            "node": "Format Options & Save",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Format Options & Save": {
      "main": [
        [
          {
            "node": "Send Clarification",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1",
    "timezone": "Asia/Ho_Chi_Minh",
    "errorWorkflow": "O6BjG1ublqWZ1KWk",
    "callerPolicy": "workflowsFromSameOwner",
    "availableInMCP": false
  },
  "staticData": {
    "global": {
      "options_undefined": {
        "options": [
          {
            "num": 1,
            "emoji": "\ud83d\udd0d",
            "title": "\u043f\u0440\u043e\u0430\u043d\u0430\u043b\u0438\u0437\u0438\u0440\u043e\u0432\u0430\u0442\u044c \u0432\u0430\u0448\u0438 TikTok \u0441\u0441\u044b\u043b\u043a\u0438",
            "intent": "analyze_links",
            "department": "reels_ideas",
            "request": "\u043f\u0440\u043e\u0430\u043d\u0430\u043b\u0438\u0437\u0438\u0440\u0443\u0439\u0442\u0435 \u0432\u0441\u0435 TikTok \u0441\u0441\u044b\u043b\u043a\u0438, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044c \u043f\u0440\u0435\u0434\u043e\u0441\u0442\u0430\u0432\u043b\u044f\u043b, \u0438 \u0441\u043e\u0441\u0442\u0430\u0432\u044c\u0442\u0435 \u043f\u043e\u043b\u043d\u044b\u0439 \u0441\u043f\u0438\u0441\u043e\u043a \u0441 \u0434\u0430\u0442\u0430\u043c\u0438 \u0438 \u0430\u0432\u0442\u043e\u0440\u0430\u043c\u0438"
          },
          {
            "num": 2,
            "emoji": "\ud83d\udcdd",
            "title": "\u0441\u043e\u0437\u0434\u0430\u0442\u044c \u043f\u043e\u0441\u0442 \u043e \u0432\u0430\u0448\u0438\u0445 TikTok \u043f\u0440\u0435\u0434\u043f\u043e\u0447\u0442\u0435\u043d\u0438\u044f\u0445",
            "intent": "create_post",
            "department": "copywriting",
            "request": "\u043d\u0430\u043f\u0438\u0448\u0438\u0442\u0435 \u043a\u043e\u0440\u043e\u0442\u043a\u0438\u0439 \u043f\u043e\u0441\u0442 \u043e \u043f\u0440\u0435\u0434\u043f\u043e\u0447\u0442\u0435\u043d\u0438\u044f\u0445 \u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044f \u0432 TikTok \u043d\u0430 \u043e\u0441\u043d\u043e\u0432\u0435 \u043f\u0440\u0435\u0434\u043e\u0441\u0442\u0430\u0432\u043b\u0435\u043d\u043d\u044b\u0445 \u0441\u0441\u044b\u043b\u043e\u043a, \u0432\u043a\u043b\u044e\u0447\u0430\u044f \u0434\u0430\u0442\u044b \u0438 \u0430\u0432\u0442\u043e\u0440\u043e\u0432"
          },
          {
            "num": 3,
            "emoji": "\ud83d\udcca",
            "title": "\u0438\u0441\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u044c \u043f\u043e\u043f\u0443\u043b\u044f\u0440\u043d\u044b\u0435 TikTok \u0442\u0440\u0435\u043d\u0434\u044b",
            "intent": "research_trends",
            "department": "research",
            "request": "\u0438\u0441\u0441\u043b\u0435\u0434\u0443\u0439\u0442\u0435 \u043f\u043e\u043f\u0443\u043b\u044f\u0440\u043d\u044b\u0435 \u0442\u0440\u0435\u043d\u0434\u044b \u0432 TikTok, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u043c\u043e\u0433\u043b\u0438 \u0431\u044b \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043e\u0432\u0430\u0442\u044c \u0438\u043d\u0442\u0435\u0440\u0435\u0441\u0430\u043c \u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044f \u043d\u0430 \u043e\u0441\u043d\u043e\u0432\u0435 \u043f\u0440\u0435\u0434\u043e\u0441\u0442\u0430\u0432\u043b\u0435\u043d\u043d\u044b\u0445 \u0441\u0441\u044b\u043b\u043e\u043a"
          }
        ],
        "expires": 1776843865710
      }
    }
  }
}