{
  "name": "MADIAD Hub - Đăng lại và Gỡ bài",
  "nodes": [
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "minutes",
              "minutesInterval": 10
            }
          ]
        }
      },
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        -160,
        0
      ],
      "id": "Chạy mỗi 10 phút",
      "name": "Chạy mỗi 10 phút"
    },
    {
      "parameters": {
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "list",
          "cachedResultName": "[MADIAD Template] Lịch Đăng Hub"
        },
        "sheetName": {
          "__rl": true,
          "value": "Cấu Hình",
          "mode": "name"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        60,
        0
      ],
      "id": "Đọc Cấu Hình",
      "name": "Đọc Cấu Hình"
    },
    {
      "parameters": {
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "list",
          "cachedResultName": "[MADIAD Template] Lịch Đăng Hub"
        },
        "sheetName": {
          "__rl": true,
          "value": "Lịch Đăng",
          "mode": "name"
        },
        "options": {
          "dataLocationOnSheet": {
            "values": {
              "rangeDefinition": "specifyRange",
              "headerRow": 1,
              "firstDataRow": 3
            }
          }
        }
      },
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        280,
        0
      ],
      "id": "Đọc Lịch Đăng",
      "name": "Đọc Lịch Đăng"
    },
    {
      "parameters": {
        "jsCode": "\nconst cfg = {};\nfor (const it of $('Đọc Cấu Hình').all()) {\n  const k = String(it.json['Khoá'] ?? '').trim();\n  if (k) cfg[k] = String(it.json['Giá Trị'] ?? '').trim();\n}\nif (!cfg.profile_id) throw new Error('Chưa điền profile_id ở tab Cấu Hình. Lấy trong Dashboard MADIAD Hub.');\nconst KENH = { 'Facebook': 'facebook', 'Instagram': 'instagram', 'TikTok': 'tiktok', 'YouTube': 'youtube', 'LinkedIn': 'linkedin', 'X': 'x', 'Threads': 'threads', 'Pinterest': 'pinterest', 'Reddit': 'reddit', 'Bluesky': 'bluesky', 'Google Business': 'google_business', 'Telegram': 'telegram', 'Discord': 'discord', 'Slack': 'slack', 'Mastodon': 'mastodon', 'Nostr': 'nostr', 'Lemmy': 'lemmy', 'dev.to': 'devto', 'Hashnode': 'hashnode', 'WordPress': 'wordpress', 'Whop': 'whop', 'listmonk': 'listmonk' };\nconst IMG = ['.jpg', '.jpeg', '.png', '.webp', '.gif'];\nconst VID = ['.mp4', '.mov', '.m4v', '.webm'];\nconst NEEDS_TITLE = ['youtube', 'reddit', 'pinterest'];\nconst OPEN = ['', 'Nháp', 'Chờ Đăng'];\n\nconst out = [];\nfor (const it of $input.all()) {\n  const r = it.json;\n  const act = String(r['Hành Động'] ?? '').trim();\n  const st = String(r['Trạng Thái'] ?? '').trim();\n\n  if (act === 'Đăng lại') {\n    const rid = String(r['Mã Yêu Cầu'] ?? '').trim();\n    if (!rid) { out.push({ json: { _row: r.row_number, _err: 'Đăng lại cần Mã Yêu Cầu, dòng này chưa có. Đặt Hành Động về Đăng ngay để gửi mới.' } }); continue; }\n    out.push({ json: { _row: r.row_number, _op: 'retry', _body: { request_id: rid }, _st: 'Đang Đăng' } });\n    continue;\n  }\n\n  if (act === 'Gỡ bài') {\n    if (st !== 'Đã Đăng') continue;\n    const ids = String(r['Mã Bài Đăng'] ?? '').trim();\n    if (!ids) { out.push({ json: { _row: r.row_number, _err: 'Không gỡ được: dòng này không lưu mã bài trên nền tảng. Vào thẳng nền tảng để xoá.' } }); continue; }\n    for (const pair of ids.split(';')) {\n      const [platform, postId] = pair.split('=');\n      if (!platform || !postId) continue;\n      out.push({ json: { _row: r.row_number, _op: 'unpublish', _st: 'Nháp',\n        _body: { profile_id: cfg.profile_id, platform, post_id: postId } } });\n    }\n  }\n}\nreturn out;\n"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        500,
        0
      ],
      "id": "Dựng lệnh",
      "name": "Dựng lệnh"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "version": 2
          },
          "conditions": [
            {
              "id": "c",
              "operator": {
                "type": "string",
                "operation": "notExists"
              },
              "leftValue": "={{ $json._err }}",
              "rightValue": ""
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        720,
        0
      ],
      "id": "Lệnh hợp lệ?",
      "name": "Lệnh hợp lệ?"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://api.madiad.com/v1/posts/{{ $json._op }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "X-Madiad-Source",
              "value": "tpl-retry-unpublish-v1"
            }
          ]
        },
        "options": {
          "response": {
            "response": {
              "neverError": true,
              "fullResponse": true
            }
          }
        },
        "sendBody": true,
        "contentType": "json",
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify($json._body) }}"
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [
        940,
        -120
      ],
      "id": "Gửi lệnh",
      "name": "Gửi lệnh",
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "version": 2
          },
          "conditions": [
            {
              "id": "c",
              "operator": {
                "type": "number",
                "operation": "lt"
              },
              "leftValue": "={{ $json.statusCode }}",
              "rightValue": 300
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        1160,
        -120
      ],
      "id": "Chạy được không?",
      "name": "Chạy được không?"
    },
    {
      "parameters": {
        "operation": "update",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "list",
          "cachedResultName": "[MADIAD Template] Lịch Đăng Hub"
        },
        "sheetName": {
          "__rl": true,
          "value": "Lịch Đăng",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "row_number": "={{ $('Dựng lệnh').item.json._row }}",
            "Trạng Thái": "={{ $('Dựng lệnh').item.json._st }}",
            "Hành Động": "",
            "Lỗi": ""
          },
          "matchingColumns": [
            "row_number"
          ],
          "schema": []
        },
        "options": {
          "dataLocationOnSheet": {
            "values": {
              "rangeDefinition": "specifyRange",
              "headerRow": 1,
              "firstDataRow": 3
            }
          }
        }
      },
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1380,
        -220
      ],
      "id": "Ghi xong",
      "name": "Ghi xong",
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "operation": "update",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "list",
          "cachedResultName": "[MADIAD Template] Lịch Đăng Hub"
        },
        "sheetName": {
          "__rl": true,
          "value": "Lịch Đăng",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "row_number": "={{ $('Dựng lệnh').item.json._row }}",
            "Lỗi": "={{ $json.body?.error?.message ?? ('HTTP ' + ($json.statusCode ?? '?')) }}"
          },
          "matchingColumns": [
            "row_number"
          ],
          "schema": []
        },
        "options": {
          "dataLocationOnSheet": {
            "values": {
              "rangeDefinition": "specifyRange",
              "headerRow": 1,
              "firstDataRow": 3
            }
          }
        }
      },
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1380,
        -20
      ],
      "id": "Ghi hỏng",
      "name": "Ghi hỏng",
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "operation": "update",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "list",
          "cachedResultName": "[MADIAD Template] Lịch Đăng Hub"
        },
        "sheetName": {
          "__rl": true,
          "value": "Lịch Đăng",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "row_number": "={{ $json._row }}",
            "Lỗi": "={{ $json._err }}",
            "Hành Động": ""
          },
          "matchingColumns": [
            "row_number"
          ],
          "schema": []
        },
        "options": {
          "dataLocationOnSheet": {
            "values": {
              "rangeDefinition": "specifyRange",
              "headerRow": 1,
              "firstDataRow": 3
            }
          }
        }
      },
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        940,
        140
      ],
      "id": "Ghi thiếu dữ liệu",
      "name": "Ghi thiếu dữ liệu",
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "content": "## MADIAD Hub - Đăng lại và Gỡ bài\n\n1. Chọn Google Sheet của bạn ở TẤT CẢ các node Google Sheets.\n2. Tạo credential **Header Auth** tên `MADIAD Hub`:",
        "height": 300,
        "width": 430,
        "color": 2
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -620,
        -160
      ],
      "id": "Hướng dẫn",
      "name": "Hướng dẫn"
    }
  ],
  "connections": {
    "Chạy mỗi 10 phút": {
      "main": [
        [
          {
            "node": "Đọc Cấu Hình",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Đọc Cấu Hình": {
      "main": [
        [
          {
            "node": "Đọc Lịch Đăng",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Đọc Lịch Đăng": {
      "main": [
        [
          {
            "node": "Dựng lệnh",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Dựng lệnh": {
      "main": [
        [
          {
            "node": "Lệnh hợp lệ?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Lệnh hợp lệ?": {
      "main": [
        [
          {
            "node": "Gửi lệnh",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Ghi thiếu dữ liệu",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gửi lệnh": {
      "main": [
        [
          {
            "node": "Chạy được không?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Chạy được không?": {
      "main": [
        [
          {
            "node": "Ghi xong",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Ghi hỏng",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {},
  "meta": {
    "templateCredsSetupCompleted": false
  }
}