{
  "name": "03 — منشن ایجنت → وظیفه در Notion",
  "nodes": [
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "seconds",
              "secondsInterval": 15
            }
          ]
        }
      },
      "id": "schedule-trigger",
      "name": "Schedule Trigger",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        -1400,
        0
      ],
      "notes": "هر ۱۵ ثانیه پیام‌های جدید را می‌خواند",
      "notesInFlow": true
    },
    {
      "parameters": {
        "jsCode": "\n// ── ۰) بررسی پیکربندی ────────────────────────────────────────────────────────\n// همهٔ مقادیر از Environment Variables در n8n خوانده می‌شوند.\n// در n8n → Settings → Environment Variables (یا فایل .env کنار n8n).\n\nconst env = (k, d = '') => $env[k] || process.env[k] || d;\n\nconst cfg = {\n  tgToken:      env('TELEGRAM_BOT_TOKEN'),\n  notionKey:    env('NOTION_API_KEY'),\n  tasksDb:      env('NOTION_TASKS_DB'),\n  notionVer:    env('NOTION_API_VERSION', '2022-06-28'),\n  openaiKey:    env('OPENAI_API_KEY'),\n  model:        env('OPENAI_MODEL', 'gpt-4o'),\n\n  // نام پراپرتی‌ها در دیتابیس شما — با tools/notion_map.py پیدا کنید\n  pTitle:       env('NOTION_TASK_TITLE_PROP', 'Name'),\n  pAssignee:    env('NOTION_TASK_ASSIGNEE_PROP', 'Assignee'),\n  pStatus:      env('NOTION_TASK_STATUS_PROP', 'Status'),\n  pDescription: env('NOTION_TASK_DESCRIPTION_PROP', 'Description'),\n  pResult:      env('NOTION_TASK_RESULT_PROP', 'Result'),\n  pRequester:   env('NOTION_TASK_REQUESTER_PROP', 'Requester'),\n  pSource:      env('NOTION_TASK_SOURCE_PROP', 'Source'),\n  pChatId:      env('NOTION_TASK_CHATID_PROP', 'ChatID'),\n  pTrace:       env('NOTION_TASK_TRACE_PROP', 'TraceID'),\n\n  // مقدار وضعیت «برای انجام»\n  statusTodo:   env('NOTION_TASK_STATUS_TODO', 'برای انجام'),\n  statusDoing:  env('NOTION_TASK_STATUS_DOING', 'در حال انجام'),\n  statusDone:   env('NOTION_TASK_STATUS_DONE', 'انجام شد'),\n\n  // فیلترها\n  minChars:     Number(env('MENTION_TASK_MIN_CHARS', '12')),\n  allowBots:    env('MENTION_TASK_ALLOW_BOTS', 'false') === 'true',\n\n  agents: ['AG01','AG02','AG03','AG04','AG05','AG06','AG07','AG08','AG09'],\n};\n\nconst missing = [];\nif (!cfg.tgToken) missing.push('TELEGRAM_BOT_TOKEN');\nif (!cfg.notionKey) missing.push('NOTION_API_KEY');\nif (!cfg.tasksDb) missing.push('NOTION_TASKS_DB');\n\nif (missing.length) {\n  throw new Error(\n    'متغیرهای محیطی غایب: ' + missing.join(', ') +\n    ' — در n8n → Settings → Environment Variables تنظیم کنید.'\n  );\n}\n\nreturn [{ json: cfg }];\n"
      },
      "id": "config",
      "name": "Config",
      "type": "n8n-nodes-base.code",
      "typeVersion": 1,
      "position": [
        -1200,
        0
      ],
      "notes": "خواندن کلیدها از Environment Variables",
      "notesInFlow": true
    },
    {
      "parameters": {
        "jsCode": "\n// ── ۱) getUpdates از تلگرام ──────────────────────────────────────────────────\n// offset در staticData ذخیره می‌شود تا بین اجراها گم نشود.\nconst cfg = $('Config').first().json;\nconst staticData = $getWorkflowStaticData('global');\nconst offset = staticData.tgOffset || 0;\n\nconst resp = await this.helpers.httpRequest({\n  method: 'GET',\n  url: `https://api.telegram.org/bot${cfg.tgToken}/getUpdates`,\n  qs: { offset, timeout: 0, allowed_updates: JSON.stringify(['message']) },\n  json: true,\n});\n\nif (!resp.ok) {\n  throw new Error('getUpdates ناموفق: ' + JSON.stringify(resp).slice(0, 200));\n}\n\nconst updates = resp.result || [];\nif (updates.length) {\n  staticData.tgOffset = updates[updates.length - 1].update_id + 1;\n}\n\nreturn updates.map(u => ({ json: u }));\n"
      },
      "id": "telegram-getupdates",
      "name": "Telegram getUpdates",
      "type": "n8n-nodes-base.code",
      "typeVersion": 1,
      "position": [
        -1000,
        0
      ],
      "notes": "getUpdates با ذخیرهٔ offset",
      "notesInFlow": true
    },
    {
      "parameters": {
        "jsCode": "\n// ── ۲) استخراج پیام و منشن‌ها ────────────────────────────────────────────────\nconst cfg = $('Config').first().json;\nconst update = $json;\nconst msg = update.message || update.edited_message || update.channel_post;\nif (!msg) return [];\n\nconst chat = msg.chat || {};\nconst user = msg.from || {};\nconst text = msg.text || msg.caption || '';\n\n// ۱) پیام ربات‌ها → نادیده (جلوگیری از حلقه)\nif (user.is_bot && !cfg.allowBots) return [];\n\n// ۲) پیام خصوصی را به پایتون بسپار (ویزارد)\nif (chat.type === 'private') return [];\n\n// ۳) جست‌وجوی منشن‌ها — پشتیبانی @ag01 و @ag1 و @AG01\nconst found = [];\nfor (const ag of cfg.agents) {\n  const short = 'ag' + ag.replace(/^AG0?/, '');\n  const re = new RegExp(`@(${ag}|${short})\\\\b`, 'i');\n  if (re.test(text)) found.push(ag);\n}\n\nif (!found.length) return [];   // منشنی نیست → کاری نکن\n\n// ۴) طول متن بدون منشن\nlet body = text;\nfor (const ag of found) {\n  body = body.replace(new RegExp(`@${ag}\\\\b`, 'gi'), '');\n  body = body.replace(new RegExp(`@ag0?${Number(ag.slice(2))}\\\\b`, 'gi'), '');\n}\nbody = body.replace(/\\s+/g, ' ').trim().replace(/^[-—:,،]+|[-—:,،]+$/g, '');\n\n// ۵) ریپلای — قبل از سنجش طول، چون «@ag09 وظیفه» روی یک پیام بلند معتبر است\nconst rt = msg.reply_to_message;\nconst replyText = rt ? (rt.text || rt.caption || '') : '';\nconst replyAuthor = rt && rt.from ? (rt.from.username || rt.from.first_name || '') : '';\n\n// طول مؤثر = متن دستور + متن پیام ریپلای‌شده\nconst effectiveLen = body.length + (replyText ? Math.min(replyText.length, cfg.minChars) : 0);\nif (effectiveLen < cfg.minChars) return [];   // «@ag01؟» را وظیفه نکن\n\n// یک آیتم به ازای هر ایجنت منشن‌شده\nreturn found.map(ag => ({\n  json: {\n    agent_id: ag,\n    text: body,\n    raw_text: text,\n    chat_id: chat.id,\n    chat_title: chat.title || 'خصوصی',\n    chat_type: chat.type,\n    message_id: msg.message_id,\n    user_id: user.id || null,\n    username: user.username || user.first_name || 'unknown',\n    date: msg.date || Math.floor(Date.now() / 1000),\n    reply_text: replyText,\n    reply_author: replyAuthor,\n  },\n}));\n"
      },
      "id": "detect-mentions",
      "name": "Detect Mentions",
      "type": "n8n-nodes-base.code",
      "typeVersion": 1,
      "position": [
        -800,
        0
      ],
      "notes": "استخراج @ag01..@ag09 + فیلتر طول/ربات/پیوی",
      "notesInFlow": true
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "c1",
              "leftValue": "={{ $json.agent_id }}",
              "rightValue": "",
              "operator": {
                "type": "string",
                "operation": "notEmpty",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "has-mention?",
      "name": "Has Mention?",
      "type": "n8n-nodes-base.filter",
      "typeVersion": 1,
      "position": [
        -600,
        0
      ],
      "notes": "بدون منشن → توقف",
      "notesInFlow": true
    },
    {
      "parameters": {
        "jsCode": "\n// ── ۳) ساخت payload برای Notion ──────────────────────────────────────────────\nconst cfg = $('Config').first().json;\nconst d = $json;\n\n// عنوان: خط اول پیام ریپلای‌شده، یا خود متن\nconst firstLine = (d.reply_text.split('\\n')[0] || d.text.split('\\n')[0] || 'وظیفه').trim();\nconst title = firstLine.slice(0, 200);\n\nconst description = d.reply_text\n  ? `متن پیام ریپلای‌شده (از ${d.reply_author || 'ناشناس'}):\\n${d.reply_text}` +\n    (d.text ? `\\n\\nدرخواست از منشن:\\n${d.text}` : '')\n  : d.text;\n\n// شناسهٔ کوتاه برای پیگیری بین Notion و تلگرام\nconst trace = `${d.chat_id}:${d.message_id}:${d.agent_id}`;\n\nconst properties = {\n  [cfg.pTitle]: {\n    title: [{ text: { content: title } }],\n  },\n  [cfg.pAssignee]: {\n    select: { name: d.agent_id },\n  },\n  [cfg.pStatus]: {\n    status: { name: cfg.statusTodo },\n  },\n  [cfg.pDescription]: {\n    rich_text: [{ text: { content: description.slice(0, 1900) } }],\n  },\n  [cfg.pRequester]: {\n    rich_text: [{ text: { content: d.username } }],\n  },\n  [cfg.pSource]: {\n    rich_text: [{ text: { content: 'telegram' } }],\n  },\n  [cfg.pChatId]: {\n    rich_text: [{ text: { content: String(d.chat_id) } }],\n  },\n  [cfg.pTrace]: {\n    rich_text: [{ text: { content: trace } }],\n  },\n};\n\nreturn [{\n  json: {\n    ...d,\n    title,\n    description,\n    trace,\n    properties,\n    notionUrl: `https://api.notion.com/v1/pages`,\n  },\n}];\n"
      },
      "id": "build-notion-props",
      "name": "Build Notion Props",
      "type": "n8n-nodes-base.code",
      "typeVersion": 1,
      "position": [
        -400,
        0
      ],
      "notes": "نگاشت به پراپرتی‌های دیتابیس شما",
      "notesInFlow": true
    },
    {
      "parameters": {
        "jsCode": "\n// بدنهٔ درخواست Notion (برای HTTP Request node)\nconst cfg = $('Config').first().json;\nconst d = $json;\n\nreturn [{\n  json: {\n    parent: { database_id: cfg.tasksDb },\n    properties: d.properties,\n  },\n}];\n"
      },
      "id": "notion-payload",
      "name": "Notion Payload",
      "type": "n8n-nodes-base.code",
      "typeVersion": 1,
      "position": [
        -200,
        0
      ],
      "notes": "بدنهٔ درخواست ساخت صفحه",
      "notesInFlow": true
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.notion.com/v1/pages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Notion-Version",
              "value": "={{ $('Config').first().json.notionVer }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify($json) }}",
        "options": {}
      },
      "id": "create-notion-task",
      "name": "Create Notion Task",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        0,
        0
      ],
      "notes": "ساخت رکورد وظیفه در Notion (Credential: Notion API)",
      "notesInFlow": true
    },
    {
      "parameters": {
        "jsCode": "\n// ── ۵) پاسخ به گروه: «وظیفه ثبت شد» ─────────────────────────────────────────\nconst cfg = $('Config').first().json;\nconst prev = $('Build Notion Props').first().json;\nconst page = $json;   // پاسخ Notion\n\nconst pageId = page.id || '';\nconst pageUrl = page.url || '';\n\n// ساخت لینک کوتاه Notion (حذف https://www.notion.so/)\nconst shortUrl = pageUrl.replace('https://www.notion.so/', '') || pageId;\n\nconst text =\n  `🧩 <b>وظیفه ثبت شد</b> → ${prev.agent_id}\\n` +\n  `<b>عنوان:</b> ${prev.title}\\n` +\n  (prev.reply_text ? `<b>منبع:</b> ریپلای روی پیام ${prev.reply_author || 'ناشناس'}\\n` : '') +\n  `<a href=\"${pageUrl}\">مشاهده در Notion</a>\\n` +\n  `<code>${prev.trace}</code>`;\n\nreturn [{\n  json: {\n    chat_id: prev.chat_id,\n    reply_to_message_id: prev.message_id,\n    text,\n    agent_id: prev.agent_id,\n    page_id: pageId,\n    page_url: pageUrl,\n  },\n}];\n"
      },
      "id": "format-confirmation",
      "name": "Format Confirmation",
      "type": "n8n-nodes-base.code",
      "typeVersion": 1,
      "position": [
        200,
        0
      ],
      "notes": "ساخت پیام «وظیفه ثبت شد»",
      "notesInFlow": true
    },
    {
      "parameters": {
        "chatId": "={{ $json.chat_id }}",
        "text": "={{ $json.text }}",
        "additionalFields": {
          "parse_mode": "HTML",
          "reply_to_message_id": "={{ $json.reply_to_message_id }}"
        }
      },
      "id": "send-confirmation",
      "name": "Send Confirmation",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        400,
        0
      ],
      "notes": "تأیید ثبت در گروه",
      "notesInFlow": true,
      "credentials": {
        "telegramApi": {
          "id": "telegram",
          "name": "Telegram"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "\n// ── ۶) ساخت پرامپت ایجنت برای اجرای فوری ────────────────────────────────────\n// توجه: اگر ربات پایتونی polling می‌کند، این بخش را حذف کنید؛\n//       پولر پایتون خودش وظیفه را می‌گیرد و اجرا می‌کند.\nconst cfg = $('Config').first().json;\nconst d = $('Build Notion Props').first().json;\n\nconst missions = {\n  AG01: 'تحلیل بازار و رقبا. هر ادعا باید شاهد داشته باشد.',\n  AG02: 'نوشتن کپی و متن تبلیغاتی.',\n  AG03: 'تولید محتوا و تقویم انتشار.',\n  AG04: 'طراحی گرافیک و هویت بصری.',\n  AG05: 'توسعه وب و لندینگ.',\n  AG06: 'سئو و کلمات کلیدی.',\n  AG07: 'تحلیل داده و گزارش.',\n  AG08: 'مدیریت کمپین و بودجه.',\n  AG09: 'مشاور نهایی: وظیفه را به زیرکارها می‌شکند.',\n};\n\nconst common = [\n  'قواعد مشترک:',\n  '۱) حدس نزن. اگر داده نداری بگو «نیازمند تأیید».',\n  '۲) هر ادعا باید شاهد داشته باشد (عدد، لینک، یا نقل‌قول).',\n  '۳) خانهٔ خالی را صفر یا تأیید حساب نکن.',\n  '۴) تصمیم نهایی با مدیر پروژه است.',\n  'پاسخ حداکثر ۱۵۰۰ کاراکتر، فارسی، بدون مقدمه.',\n].join('\\n');\n\nconst system = `تو ${d.agent_id} هستی.\\nمأموریت: ${missions[d.agent_id] || ''}\\n\\n${common}`;\n\nreturn [{\n  json: {\n    system,\n    user: d.description,\n    agent_id: d.agent_id,\n    ...d,\n  },\n}];\n"
      },
      "id": "build-prompt",
      "name": "Build Prompt",
      "type": "n8n-nodes-base.code",
      "typeVersion": 1,
      "position": [
        200,
        200
      ],
      "notes": "پرامپت ایجنت — اگر ربات پایتونی دارید این مسیر را غیرفعال کنید",
      "notesInFlow": true,
      "disabled": true
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.openai.com/v1/chat/completions",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({model: $('Config').first().json.model, messages: [{role:'system',content:$json.system},{role:'user',content:$json.user}], temperature: 0.4, max_tokens: 1200}) }}",
        "options": {}
      },
      "id": "openai-chat",
      "name": "OpenAI Chat",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        400,
        200
      ],
      "notes": "فراخوانی مدل",
      "notesInFlow": true,
      "disabled": true
    },
    {
      "parameters": {
        "jsCode": "\n// ── ۷) خودبازبینی: ادعای بدون شاهد → «نیازمند تأیید» ───────────────────────\nconst prev = $('Build Prompt').first().json;\nconst content = ($json.choices?.[0]?.message?.content || '').trim();\n\nif (!content) {\n  return [{ json: { ...prev, answer: '⚠️ پاسخ خالی از مدل — دوباره تلاش کنید.' } }];\n}\n\n// اگر هیچ عددی/لینکی/نقل‌قولی نیست و ادعای قطعی دارد → علامت‌گذاری\nconst hasEvidence = /(\\d|https?:\\/\\/|«|»|منبع|شاهد|طبق|بر اساس)/.test(content);\nconst isAssertive = /(است\\.|هست\\.|خواهد شد|تأیید می‌شود)/.test(content);\n\nlet answer = content;\nif (isAssertive && !hasEvidence) {\n  answer += '\\n\\n⚠️ <b>نیازمند تأیید</b> — این پاسخ شاهد مشخصی ندارد.';\n}\n\nreturn [{ json: { ...prev, answer, hasEvidence } }];\n"
      },
      "id": "self-check",
      "name": "Self Check",
      "type": "n8n-nodes-base.code",
      "typeVersion": 1,
      "position": [
        600,
        200
      ],
      "notes": "ادعای بدون شاهد → «نیازمند تأیید»",
      "notesInFlow": true,
      "disabled": true
    },
    {
      "parameters": {
        "method": "PATCH",
        "url": "=https://api.notion.com/v1/pages/{{ $json.page_id }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Notion-Version",
              "value": "={{ $('Config').first().json.notionVer }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify($json.body) }}",
        "options": {}
      },
      "id": "write-result",
      "name": "Write Result",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        800,
        200
      ],
      "notes": "نوشتن پاسخ + تغییر وضعیت به «انجام شد»",
      "notesInFlow": true,
      "disabled": true
    },
    {
      "parameters": {
        "chatId": "={{ $json.chat_id }}",
        "text": "={{ $json.text }}",
        "additionalFields": {
          "parse_mode": "HTML",
          "reply_to_message_id": "={{ $json.reply_to_message_id }}"
        }
      },
      "id": "send-answer",
      "name": "Send Answer",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        1000,
        200
      ],
      "notes": "ارسال پاسخ ایجنت در گروه",
      "notesInFlow": true,
      "disabled": true,
      "credentials": {
        "telegramApi": {
          "id": "telegram",
          "name": "Telegram"
        }
      }
    }
  ],
  "connections": {
    "Schedule Trigger": {
      "main": [
        [
          {
            "node": "Config",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Config": {
      "main": [
        [
          {
            "node": "Telegram getUpdates",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Telegram getUpdates": {
      "main": [
        [
          {
            "node": "Detect Mentions",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Detect Mentions": {
      "main": [
        [
          {
            "node": "Has Mention?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Has Mention?": {
      "main": [
        [
          {
            "node": "Build Notion Props",
            "type": "main",
            "index": 0
          }
        ],
        []
      ]
    },
    "Build Notion Props": {
      "main": [
        [
          {
            "node": "Notion Payload",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Notion Payload": {
      "main": [
        [
          {
            "node": "Create Notion Task",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Notion Task": {
      "main": [
        [
          {
            "node": "Format Confirmation",
            "type": "main",
            "index": 0
          },
          {
            "node": "Build Prompt",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Format Confirmation": {
      "main": [
        [
          {
            "node": "Send Confirmation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Prompt": {
      "main": [
        [
          {
            "node": "OpenAI Chat",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Chat": {
      "main": [
        [
          {
            "node": "Self Check",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Self Check": {
      "main": [
        [
          {
            "node": "Write Result",
            "type": "main",
            "index": 0
          },
          {
            "node": "Send Answer",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "saveManualExecutions": true,
    "callerPolicy": "workflowsFromSameOwner"
  },
  "staticData": null,
  "pinData": {},
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "tags": [
    {
      "name": "agents"
    },
    {
      "name": "notion"
    }
  ]
}
