{
  "name": "Mallary - Check all saved platform jobs",
  "nodes": [
    {
      "parameters": {},
      "id": "0c97ceb6-62f4-5b42-a2b2-270ff3085851",
      "name": "Run manually",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        280
      ]
    },
    {
      "parameters": {
        "mode": "manual",
        "assignments": {
          "assignments": [
            {
              "id": "spreadsheet-id",
              "name": "spreadsheet_id",
              "value": "REPLACE_WITH_YOUR_SPREADSHEET_ID",
              "type": "string"
            },
            {
              "id": "sheet-name",
              "name": "sheet_name",
              "value": "Posts",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "d4d3b898-a4eb-593b-8f11-13c0f6f8d116",
      "name": "Sheet settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        240,
        280
      ]
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const config = $input.first().json;\nconst spreadsheetId = String(config.spreadsheet_id ?? '').trim();\nconst sheetName = String(config.sheet_name ?? '').trim();\nif (!/^[A-Za-z0-9_-]{20,}$/.test(spreadsheetId) || /REPLACE|YOUR_|PASTE_/i.test(spreadsheetId)) {\n  throw new Error('Open Sheet settings and paste your spreadsheet ID. Use the ID between /d/ and /edit in its URL.');\n}\nif (!sheetName || /[\\[\\]:*?\\/\\\\]/.test(sheetName)) {\n  throw new Error('Open Sheet settings and enter your sheet tab name, such as Posts.');\n}\nreturn [{ json: { spreadsheet_id: spreadsheetId, sheet_name: sheetName }, pairedItem: { item: 0 } }];"
      },
      "id": "421cb3a1-fcf6-5f52-954a-1c433a7bfbad",
      "name": "Check sheet settings",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        480,
        280
      ]
    },
    {
      "parameters": {
        "authentication": "oAuth2",
        "resource": "sheet",
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "={{ $('Check sheet settings').first().json.spreadsheet_id }}",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "={{ $('Check sheet settings').first().json.sheet_name }}",
          "mode": "name"
        },
        "options": {
          "returnFirstMatch": false
        }
      },
      "id": "7205cad0-2507-51e9-9bb3-bc7ab08cb859",
      "name": "Read all sheet rows",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        720,
        280
      ]
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const items = $input.all();\nconst text = (value) => String(value ?? '').trim();\nconst seen = new Set();\nfor (const item of items) {\n  const row = item.json;\n  const hasContent = ['content_id', 'caption', 'image_url', 'status', 'job_ids'].some((key) => text(row[key]));\n  if (!hasContent) continue;\n  const id = text(row.content_id);\n  if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,79}$/.test(id) || String(row.content_id) !== id) {\n    throw new Error('Each nonempty row needs a content_id with only letters, numbers, dashes, or underscores, and no surrounding spaces.');\n  }\n  if (seen.has(id)) throw new Error('Duplicate content_id: ' + id + '. Give every row its own ID before running this workflow.');\n  seen.add(id);\n}\nconst allJobIds = new Set();\nreturn items.flatMap((item, index) => {\n  const row = item.json;\n  if (text(row.status) !== 'submitted') return [];\n  let jobs;\n  try { jobs = JSON.parse(text(row.job_ids)); } catch { throw new Error('Submitted row ' + text(row.content_id) + ' needs the job_ids JSON from the publisher.'); }\n  if (!Array.isArray(jobs) || jobs.length === 0) throw new Error('Submitted row ' + text(row.content_id) + ' has no saved jobs.');\n  const supported = ['facebook', 'instagram', 'linkedin'];\n  return jobs.map((job) => {\n    const platform = text(job?.platform);\n    const rawJobId = job?.job_id ?? job?.jobId;\n    const jobId = text(rawJobId);\n    if (job?.job_id != null && job?.jobId != null && text(job.job_id) !== text(job.jobId)) {\n      throw new Error('Conflicting job_id and jobId in row ' + text(row.content_id) + '. Restore the complete original jobs array.');\n    }\n    if (!supported.includes(platform) || !/^[A-Za-z0-9_-]{1,128}$/.test(jobId) || (typeof rawJobId === 'number' && !Number.isSafeInteger(rawJobId)) || allJobIds.has(jobId)) {\n      throw new Error('Invalid or repeated saved job in row ' + text(row.content_id) + '. Restore the original job_ids from the publish execution.');\n    }\n    allJobIds.add(jobId);\n    return { json: { content_id: text(row.content_id), platform, job_id: jobId, job_ids: text(row.job_ids), expected_jobs: jobs.length }, pairedItem: { item: index } };\n  });\n});"
      },
      "id": "518e83d0-bff7-555c-bfb3-008f663c60ed",
      "name": "Choose submitted jobs",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        960,
        280
      ]
    },
    {
      "parameters": {
        "method": "GET",
        "url": "={{ 'https://mallary.ai/api/v1/jobs/' + encodeURIComponent($json.job_id) }}",
        "authentication": "genericCredentialType",
        "options": {
          "timeout": 60000,
          "response": {
            "response": {
              "responseFormat": "json"
            }
          },
          "redirect": {
            "redirect": {
              "followRedirects": false
            }
          },
          "batching": {
            "batch": {
              "batchSize": 1,
              "batchInterval": 200
            }
          }
        },
        "genericAuthType": "httpHeaderAuth"
      },
      "id": "79dde8a4-a771-546a-a0dc-42fd9dc56ebd",
      "name": "Get Mallary job",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1200,
        280
      ],
      "retryOnFail": false,
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "if ($input.all().length !== $('Choose submitted jobs').all().length) {\n  throw new Error('Not every saved job returned a result. Keep the rows submitted and run the checker again.');\n}\nconst groups = new Map();\n$input.all().forEach((item, index) => {\n  const saved = $('Choose submitted jobs').itemMatching(index).json;\n  if (!groups.has(saved.content_id)) groups.set(saved.content_id, { saved, results: [], inputIndexes: [] });\n  const group = groups.get(saved.content_id);\n  const job = item.json?.data?.job;\n  let state = 'unknown';\n  let error = '';\n  let postUrl = '';\n  if (!job || typeof job.status !== 'string') {\n    const problem = item.json?.error;\n    error = typeof problem === 'string' ? problem : (problem?.message || 'Could not read this job. Check the saved ID and credential, then run this checker again.');\n  } else {\n    state = job.status.toLowerCase();\n    if (['failed', 'action_required'].includes(state)) {\n      const problem = job.error || job.failedReason || (state === 'action_required' ? 'This post needs your attention in Mallary.' : 'Mallary reported that this post failed.');\n      error = typeof problem === 'string' ? problem : JSON.stringify(problem);\n    }\n    if (state === 'completed' && typeof job.platform_post_url === 'string' && /^https?:\\/\\//.test(job.platform_post_url)) postUrl = job.platform_post_url;\n  }\n  group.results.push({ platform: saved.platform, job_id: saved.job_id, state, error, postUrl });\n  group.inputIndexes.push(index);\n});\nreturn [...groups.values()].map(({ saved, results, inputIndexes }) => {\n  if (results.length !== saved.expected_jobs || new Set(results.map((job) => job.job_id)).size !== saved.expected_jobs) {\n    throw new Error('Some saved jobs were not checked for ' + saved.content_id + '. Keep the row submitted and run the checker again.');\n  }\n  const pending = results.some((job) => !['completed', 'failed', 'action_required'].includes(job.state));\n  const completed = results.filter((job) => job.state === 'completed').length;\n  const status = pending ? 'submitted' : (completed === results.length ? 'live' : (completed === 0 ? 'failed' : 'partial'));\n  const label = (job) => job.platform + ' (' + job.job_id + ')';\n  return { json: { content_id: saved.content_id, status, job_ids: saved.job_ids,\n    post_urls: results.filter((job) => job.postUrl).map((job) => label(job) + ': ' + job.postUrl).join('\\n'),\n    platform_status: results.map((job) => label(job) + ': ' + job.state).join('\\n'),\n    error: results.filter((job) => job.error).map((job) => label(job) + ': ' + job.error).join('\\n')\n  }, pairedItem: inputIndexes.map((item) => ({ item })) };\n});"
      },
      "id": "b6cd5a57-5f0b-57d6-8b8d-571e5772d848",
      "name": "Prepare sheet results",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1440,
        280
      ]
    },
    {
      "parameters": {
        "authentication": "oAuth2",
        "resource": "sheet",
        "operation": "update",
        "documentId": {
          "__rl": true,
          "value": "={{ $('Check sheet settings').first().json.spreadsheet_id }}",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "={{ $('Check sheet settings').first().json.sheet_name }}",
          "mode": "name"
        },
        "options": {
          "cellFormat": "RAW"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "content_id": "={{ $json.content_id }}",
            "status": "={{ $json.status }}",
            "job_ids": "={{ $json.job_ids }}",
            "post_urls": "={{ $json.post_urls }}",
            "platform_status": "={{ $json.platform_status }}",
            "error": "={{ $json.error }}"
          },
          "matchingColumns": [
            "content_id"
          ],
          "schema": [
            {
              "id": "content_id",
              "displayName": "content_id",
              "required": false,
              "defaultMatch": true,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "status",
              "displayName": "status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "job_ids",
              "displayName": "job_ids",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "post_urls",
              "displayName": "post_urls",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "platform_status",
              "displayName": "platform_status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "error",
              "displayName": "error",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        }
      },
      "id": "713a55bc-11e1-5a31-b269-4919a6b8aeac",
      "name": "Save post results",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1680,
        280
      ]
    },
    {
      "parameters": {
        "content": "## Set up in n8n Cloud or self-hosted n8n\nThese files use built-in nodes. No community node is needed.\n1. Import content-queue.csv into a Google Sheet. Name the tab Posts. Keep all eight headers. Format content_id and job_ids as Plain text.\n2. In Sheet settings, replace spreadsheet_id with the ID between /d/ and /edit in your Sheet URL. Change sheet_name only if needed.\n3. Select your Google Sheets OAuth credential in each green Sheets node.\n4. Create one Header Auth credential: Name = Authorization; Value = Bearer followed by a space and your Mallary API key. Select it only in Get Mallary upload URL, Create social posts, and Get Mallary job.\nNever add that credential to Download image or Upload image to storage. No credentials are included in these files.",
        "height": 350,
        "width": 780
      },
      "id": "479027e1-e7e9-56e2-b8b2-c5e0e57a736a",
      "name": "Start here",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        0,
        -90
      ]
    },
    {
      "parameters": {
        "content": "## Check every saved platform job\nUse the same spreadsheet_id and sheet_name as the publisher. Select Google Sheets OAuth on both Sheets nodes and Header Auth on Get Mallary job.\nRun the whole workflow. Each submitted row expands into its saved job_ids, every job is checked, and results are grouped back to its content_id. Multiple jobs on the same platform keep their own IDs and results. This workflow never uploads or creates posts.\nRow status stays submitted while any job is pending or unreadable. When all jobs finish: live = all completed; failed = none completed; partial = some completed and some failed or need action.\nRead platform_status and error for details even while submitted. post_urls includes any successful links returned. A completed job may have no public link. Never reapprove partial, failed, or sending rows without checking Mallary first.",
        "height": 350,
        "width": 1050
      },
      "id": "c8a0277c-6bde-5035-ae39-26a6c946aadb",
      "name": "Check results",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        850,
        -90
      ]
    }
  ],
  "connections": {
    "Run manually": {
      "main": [
        [
          {
            "node": "Sheet settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Sheet settings": {
      "main": [
        [
          {
            "node": "Check sheet settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check sheet settings": {
      "main": [
        [
          {
            "node": "Read all sheet rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read all sheet rows": {
      "main": [
        [
          {
            "node": "Choose submitted jobs",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Choose submitted jobs": {
      "main": [
        [
          {
            "node": "Get Mallary job",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Mallary job": {
      "main": [
        [
          {
            "node": "Prepare sheet results",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare sheet results": {
      "main": [
        [
          {
            "node": "Save post results",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "saveManualExecutions": true
  },
  "pinData": {},
  "tags": []
}
