{
  "name": "04 — Google Sheets → ربات آرتا (همگام‌سازی ۶ تب)",
  "nodes": [
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "minutes",
              "minutesInterval": 15
            }
          ]
        }
      },
      "id": "schedule-15m",
      "name": "هر ۱۵ دقیقه",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        -1700,
        0
      ],
      "notes": "سهمیهٔ Sheets رایگان ۳۰۰ درخواست در دقیقه است؛ ۱۵ دقیقه محافظه‌کارانه است.",
      "notesInFlow": true
    },
    {
      "parameters": {
        "jsCode": "\n// ── ۰) پیکربندی ──────────────────────────────────────────────────────────────\n// متغیرهای محیطی n8n (Settings → Environment Variables یا فایل .env کنار n8n):\n//   SHEET_ID              شناسهٔ فایل Google Sheets\n//   ARTA_INTERNAL_TOKEN   همان INTERNAL_TOKEN در .env ربات\n//   ARTA_BASE_URL         پیش‌فرض: http://127.0.0.1:8080\n//   SHEETS_MAX_ROWS       سقف ردیف هر تب (پیش‌فرض ۵۰۰)\n\nconst env = (k, d = '') => $env[k] || process.env[k] || d;\n\nconst cfg = {\n  sheetId: env('SHEET_ID', '1YZa4iv9x43mMc3HIx-7rYul3OuzFFN9dyPD6bUHIrPs'),\n  token:   env('ARTA_INTERNAL_TOKEN'),\n  base:    env('ARTA_BASE_URL', 'http://127.0.0.1:8080').replace(/\\/+$/, ''),\n  maxRows: Number(env('SHEETS_MAX_ROWS', '500')),\n\n  // نام نود ← نام تب. اگر تب اضافه/حذف کردید، اینجا هم به‌روز کنید.\n  tabs: [\n    { node: 'تب — ثبت روزانه',           name: 'ثبت روزانه',        gid: '786882178'  },\n    { node: 'تب — راهنما',               name: 'راهنما و فهرست‌ها', gid: '608079547'  },\n    { node: 'تب — گزارش مدیریتی',        name: 'گزارش مدیریتی',     gid: '1362518024' },\n    { node: 'تب — پیگیری وظایف',         name: 'پیگیری وظایف',      gid: '9296525'    },\n    { node: 'تب — ثبت تصمیم‌ها',          name: 'ثبت تصمیم‌ها',      gid: '125384937'  },\n    { node: 'تب — الگوی ثبت تصمیم',      name: 'الگوی ثبت تصمیم',   gid: '478066774'  },\n  ],\n};\n\nconst missing = [];\nif (!cfg.sheetId) missing.push('SHEET_ID');\nif (!cfg.token)   missing.push('ARTA_INTERNAL_TOKEN');\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": "پیکربندی",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -1480,
        0
      ]
    },
    {
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "={{ $json.sheetId }}",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "ثبت روزانه",
          "mode": "name"
        },
        "options": {
          "returnFirstRowAsHeaders": true,
          "rawData": false
        }
      },
      "id": "read-1",
      "name": "تب — ثبت روزانه",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        -1240,
        -360
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000,
      "notes": "gid=786882178 — دسترسی Viewer کافی است",
      "notesInFlow": true
    },
    {
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "={{ $json.sheetId }}",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "راهنما و فهرست‌ها",
          "mode": "name"
        },
        "options": {
          "returnFirstRowAsHeaders": true,
          "rawData": false
        }
      },
      "id": "read-2",
      "name": "تب — راهنما و فهرست‌ها",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        -1240,
        -215
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000,
      "notes": "gid=608079547 — دسترسی Viewer کافی است",
      "notesInFlow": true
    },
    {
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "={{ $json.sheetId }}",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "گزارش مدیریتی",
          "mode": "name"
        },
        "options": {
          "returnFirstRowAsHeaders": true,
          "rawData": false
        }
      },
      "id": "read-3",
      "name": "تب — گزارش مدیریتی",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        -1240,
        -70
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000,
      "notes": "gid=1362518024 — دسترسی Viewer کافی است",
      "notesInFlow": true
    },
    {
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "={{ $json.sheetId }}",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "پیگیری وظایف",
          "mode": "name"
        },
        "options": {
          "returnFirstRowAsHeaders": true,
          "rawData": false
        }
      },
      "id": "read-4",
      "name": "تب — پیگیری وظایف",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        -1240,
        75
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000,
      "notes": "gid=9296525 — دسترسی Viewer کافی است",
      "notesInFlow": true
    },
    {
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "={{ $json.sheetId }}",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "ثبت تصمیم‌ها",
          "mode": "name"
        },
        "options": {
          "returnFirstRowAsHeaders": true,
          "rawData": false
        }
      },
      "id": "read-5",
      "name": "تب — ثبت تصمیم‌ها",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        -1240,
        220
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000,
      "notes": "gid=125384937 — دسترسی Viewer کافی است",
      "notesInFlow": true
    },
    {
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "={{ $json.sheetId }}",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "الگوی ثبت تصمیم",
          "mode": "name"
        },
        "options": {
          "returnFirstRowAsHeaders": true,
          "rawData": false
        }
      },
      "id": "read-6",
      "name": "تب — الگوی ثبت تصمیم",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        -1240,
        365
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000,
      "notes": "gid=478066774 — دسترسی Viewer کافی است",
      "notesInFlow": true
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "\n// ── ۱) نرمال‌سازی شش تب به یک payload ────────────────────────────────────────\n// نکتهٔ مهم: نود Google Sheets به ازای هر ردیف یک آیتم برمی‌گرداند.\n// پس برای هر تب، خروجی نود خودش را می‌خوانیم — نه خروجی مشترک ورودی.\n// این کار از قاطی‌شدن ردیف‌های تب‌های مختلف جلوگیری می‌کند.\n\nconst cfg = $('پیکربندی').first().json;\nconst tabs = [];\n\nfor (const t of cfg.tabs) {\n  let items = [];\n  try {\n    items = $(t.node).all();\n  } catch (e) {\n    tabs.push({ name: t.name, gid: t.gid, headers: [], rows: [], rowCount: 0, error: 'نود خوانده نشد' });\n    continue;\n  }\n\n  // نود Google Sheets ممکن است خروجی را در کلید data بگذارد یا مستقیم\n  let rows = [];\n  for (const it of items) {\n    const d = it.json || {};\n    if (Array.isArray(d)) { rows.push(...d); continue; }\n    if (Array.isArray(d.data)) { rows.push(...d.data); continue; }\n    const keys = Object.keys(d).filter(k => k !== 'pairedItem' && k !== 'row_number');\n    if (keys.length) {\n      const vals = keys.map(k => d[k]);\n      if (vals.some(v => String(v ?? '').trim() !== '')) rows.push(vals);\n    }\n  }\n\n  // سرستون‌ها: از کلیدهای اولین آیتم دیکشنری‌ای\n  let headers = [];\n  const firstJson = items.length ? (items[0].json || {}) : {};\n  if (!Array.isArray(firstJson) && typeof firstJson === 'object') {\n    headers = Object.keys(firstJson).filter(k => k !== 'pairedItem' && k !== 'row_number');\n  }\n  if (!headers.length && rows.length) {\n    headers = rows[0].map((_, i) => 'ستون ' + (i + 1));\n  }\n\n  // حذف ردیف‌های کاملاً خالی و ردیف سرستون تکراری\n  rows = rows.filter(r => Array.isArray(r) && r.some(v => String(v ?? '').trim() !== ''));\n  if (rows.length && headers.length) {\n    const isHeaderRow = rows[0].every((v, i) => String(v).trim() === String(headers[i] ?? '').trim());\n    if (isHeaderRow) rows = rows.slice(1);\n  }\n\n  const limit = Number(cfg.maxRows || 500);\n  if (rows.length > limit) rows = rows.slice(0, limit);\n\n  tabs.push({ name: t.name, gid: t.gid, headers, rows, rowCount: rows.length });\n}\n\nreturn [{\n  json: {\n    base: cfg.base,\n    token: cfg.token,\n    payload: {\n      tabs,\n      synced_at: new Date().toISOString(),\n      source: 'n8n',\n    },\n    summary: tabs.map(t => t.name + '=' + t.rowCount).join(' | '),\n    totalRows: tabs.reduce((s, t) => s + t.rowCount, 0),\n  },\n}];\n"
      },
      "id": "normalize",
      "name": "نرمال‌سازی",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -980,
        0
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $json.base }}/internal/sheets/push",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "X-Internal-Token",
              "value": "={{ $json.token }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify($json.payload) }}",
        "options": {
          "timeout": 20000,
          "response": {
            "response": {
              "neverError": true
            }
          }
        }
      },
      "id": "push",
      "name": "ارسال به ربات",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        -740,
        0
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "parameters": {
        "jsCode": "\n// ── ۲) گزارش نتیجه ───────────────────────────────────────────────────────────\nconst prev = $('نرمال‌سازی').first().json;\nconst resp = $input.first().json || {};\nconst ok = resp.ok === true;\n\nconst line = ok\n  ? '✅ همگام‌سازی Sheets موفق — ' + (resp.tabs || 0) + ' تب، ' + prev.totalRows + ' ردیف'\n  : '⚠️ پاسخ ناموفق از ربات: ' + JSON.stringify(resp).slice(0, 300);\n\n// در صورت خطا، پیام قابل‌فهم فارسی\nlet hint = '';\nif (!ok) {\n  const code = resp.statusCode || (resp.error && resp.error.code);\n  if (code === 401) hint = 'توکن داخلی دو طرف یکی نیست (ARTA_INTERNAL_TOKEN ↔ INTERNAL_TOKEN).';\n  else if (code === 403) hint = 'ربات فقط از همان سرور می‌پذیرد؛ n8n را روی 127.0.0.1 اجرا کنید یا SHEETS_PUSH_ALLOW_REMOTE=true کنید.';\n  else if (code === 503) hint = 'INTERNAL_TOKEN در ربات تنظیم نشده: ./run.sh set INTERNAL_TOKEN <مقدار>';\n  else if (code === 422) hint = 'قالب payload با اندپوینت نمی‌خواند.';\n  else hint = 'لاگ ربات را ببینید: ./run.sh logs';\n}\n\nreturn [{ json: { ok, line, hint, response: resp, summary: prev.summary, at: new Date().toISOString() } }];\n"
      },
      "id": "report",
      "name": "گزارش نتیجه",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -500,
        0
      ]
    },
    {
      "parameters": {
        "content": "## همگام‌سازی Google Sheets → ربات آرتا\n\n**پیش‌نیاز**\n- Credential از نوع Google Sheets (Service Account پیشنهاد می‌شود)\n- فایل شیت به ایمیل Service Account با دسترسی **Viewer** share شده باشد\n- سه متغیر محیطی n8n:\n```\nSHEET_ID=1YZa4iv9x43mMc3HIx-7rYul3OuzFFN9dyPD6bUHIrPs\nARTA_INTERNAL_TOKEN=<همان INTERNAL_TOKEN در .env ربات>\nARTA_BASE_URL=http://127.0.0.1:8080\n```\n\n**خطاهای رایج**\n- 401 → توکن دو طرف یکی نیست\n- 403 → n8n روی سرور دیگری است؛ یا `SHEETS_PUSH_ALLOW_REMOTE=true`\n- 503 → `./run.sh set INTERNAL_TOKEN <مقدار>`\n\n**تست دستی**\n```bash\ncurl -H \"X-Internal-Token: $TOKEN\" \\\n  http://127.0.0.1:8080/internal/sheets/status\n```\n\n**شش نود خواندن عمداً جدا هستند:**\nنود Google Sheets به ازای هر ردیف یک آیتم می‌دهد؛\nخواندن موازی همهٔ تب‌ها در یک نود، ردیف‌ها را قاطی می‌کند.",
        "height": 480,
        "width": 480,
        "color": 4
      },
      "id": "note-setup",
      "name": "راهنما",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -1700,
        -420
      ]
    }
  ],
  "connections": {
    "هر ۱۵ دقیقه": {
      "main": [
        [
          {
            "node": "پیکربندی",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "پیکربندی": {
      "main": [
        [
          {
            "node": "تب — ثبت روزانه",
            "type": "main",
            "index": 0
          },
          {
            "node": "تب — راهنما و فهرست‌ها",
            "type": "main",
            "index": 0
          },
          {
            "node": "تب — گزارش مدیریتی",
            "type": "main",
            "index": 0
          },
          {
            "node": "تب — پیگیری وظایف",
            "type": "main",
            "index": 0
          },
          {
            "node": "تب — ثبت تصمیم‌ها",
            "type": "main",
            "index": 0
          },
          {
            "node": "تب — الگوی ثبت تصمیم",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "تب — ثبت روزانه": {
      "main": [
        [
          {
            "node": "نرمال‌سازی",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "تب — راهنما و فهرست‌ها": {
      "main": [
        [
          {
            "node": "نرمال‌سازی",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "تب — گزارش مدیریتی": {
      "main": [
        [
          {
            "node": "نرمال‌سازی",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "تب — پیگیری وظایف": {
      "main": [
        [
          {
            "node": "نرمال‌سازی",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "تب — ثبت تصمیم‌ها": {
      "main": [
        [
          {
            "node": "نرمال‌سازی",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "تب — الگوی ثبت تصمیم": {
      "main": [
        [
          {
            "node": "نرمال‌سازی",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "نرمال‌سازی": {
      "main": [
        [
          {
            "node": "ارسال به ربات",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "ارسال به ربات": {
      "main": [
        [
          {
            "node": "گزارش نتیجه",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1",
    "saveManualExecutions": true,
    "callerPolicy": "workflowsFromSameOwner"
  },
  "staticData": null,
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "pinData": {},
  "versionId": "arta-sheets-1.0.1",
  "active": false,
  "tags": []
}