{
  "name": "New Shopify product to sprkly",
  "nodes": [
    {
      "id": "96707fcc-92bb-413b-a0b1-fae678f9b7cc",
      "name": "Read me first",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -1640,
        -630
      ],
      "parameters": {
        "content": "## New Shopify product to sprkly\nEach new Shopify product with a photo and stock becomes a post with its photos, price and link. It waits for your OK. Skipped products get a tag and a reason.\n\n### You need\n- The sprkly node: Settings, Community nodes, install `n8n-nodes-sprkly` (self-hosted n8n)\n- A sprkly API key: https://sprkly.app/docs/api?utm_source=n8n&utm_medium=workflow&utm_campaign=shopify-to-sprkly\n- A Shopify login that can read and write products\n- A Telegram bot and your chat ID\n- A Google Sheets login and a sheet, for the log of live posts\n\n### Set it up\n1. Add your Shopify login to **New product**, **Tag the product** and **Tag as skipped**.\n2. In **Settings**, set your store domain, currency sign, accounts as platform:handle and your chat ID.\n3. Add your sprkly key to **Hold post for your OK** and your bot to the Telegram steps. Put your sheet ID in **Published log settings**.\n4. Failure alert: put your chat ID in **Write the failure alert** and your bot in **Send the failure alert**. Then in Workflow settings, set Error workflow to this workflow.\n\n### Test it\n- Add a test product with a photo and stock. A post waits for your OK, the product gets sprkly-queued and you get a message.\n- Add one with no photo. It gets sprkly-skipped and you get the reason. Delete the test post after.",
        "height": 858,
        "width": 560,
        "color": 4
      }
    },
    {
      "id": "5279373f-1f50-431a-8233-29f6449f0f53",
      "name": "Note: check",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -440,
        60
      ],
      "parameters": {
        "content": "## Check the product\nIt needs a photo, an active status and stock (turn off needStock in **Settings** to skip the stock check). A product tagged sprkly-queued or sprkly-error stops here. Remove the tag to try it again.",
        "height": 440,
        "width": 660,
        "color": 7
      }
    },
    {
      "id": "27d6a424-193f-4de4-ad3e-947f33ab3c73",
      "name": "Note: post and tag",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        240,
        60
      ],
      "parameters": {
        "content": "## Post and tag\nThe post waits for your OK. The product gets sprkly-queued, or sprkly-error when sprkly refused it. A skipped product gets sprkly-skipped and you get the reason.",
        "height": 440,
        "width": 700,
        "color": 7
      }
    },
    {
      "id": "60d3bdca-4986-4567-8c4f-db12037f46e0",
      "name": "New product",
      "type": "n8n-nodes-base.shopifyTrigger",
      "typeVersion": 1,
      "position": [
        -400,
        320
      ],
      "parameters": {
        "authentication": "accessToken",
        "topic": "products/create"
      }
    },
    {
      "id": "89c0c9a4-e3ce-4fc6-a427-b8614d66f6b1",
      "name": "Settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -180,
        320
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "f1",
              "name": "storeDomain",
              "type": "string",
              "value": "yourstore.com"
            },
            {
              "id": "f2",
              "name": "currencySign",
              "type": "string",
              "value": "$"
            },
            {
              "id": "f3",
              "name": "accounts",
              "type": "string",
              "value": "instagram:yourhandle, facebook:Your Page"
            },
            {
              "id": "f4",
              "name": "hoursFromNow",
              "type": "number",
              "value": 1
            },
            {
              "id": "f5",
              "name": "needStock",
              "type": "boolean",
              "value": true
            },
            {
              "id": "f6",
              "name": "telegramChatId",
              "type": "string",
              "value": "YOUR_CHAT_ID"
            }
          ]
        },
        "includeOtherFields": true,
        "options": {}
      }
    },
    {
      "id": "c75ee796-b051-436e-978c-9ff1f60f9810",
      "name": "Ready to post?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        40,
        320
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "c1",
              "leftValue": "={{ ($json.images || []).length > 0 && !/sprkly-(queued|error)/.test($json.tags || '') && String($json.status || 'active') === 'active' && ($json.needStock !== true || ($json.variants || []).some(v => Number(v.inventory_quantity) > 0 || v.inventory_management !== 'shopify')) }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "looseTypeValidation": true,
        "options": {}
      }
    },
    {
      "id": "443f13fa-8789-4b00-93e0-c396cac2b233",
      "name": "Hold post for your OK",
      "type": "n8n-nodes-sprkly.sprkly",
      "typeVersion": 1.1,
      "position": [
        280,
        220
      ],
      "parameters": {
        "resource": "post",
        "operation": "create",
        "accountMode": "name",
        "accountNames": "={{ $json.accounts }}",
        "caption": "={{ $json.title + '\\n' + (($json.variants || [])[0] && $json.variants[0].price ? $json.currencySign + $json.variants[0].price + '\\n' : '') + '\\nhttps://' + $json.storeDomain + '/products/' + $json.handle }}",
        "scheduledTime": "={{ $now.plus({ hours: Number($json.hoursFromNow) || 1 }).toISO() }}",
        "output": "resultRow",
        "additionalFields": {
          "mediaUrls": "={{ ($json.images || []).slice(0, 10).map(image => image.src).join(', ') }}",
          "firstComment": "={{ 'https://' + $json.storeDomain + '/products/' + $json.handle }}",
          "requiresApproval": true,
          "approvalNote": "={{ 'New product: ' + $json.title }}",
          "externalId": "={{ 'shopify-' + $json.id }}",
          "requireExternalId": true
        }
      }
    },
    {
      "id": "bdf5d393-9e27-461a-9f78-5bb96b663953",
      "name": "Tag the product",
      "type": "n8n-nodes-base.shopify",
      "typeVersion": 1,
      "position": [
        500,
        220
      ],
      "parameters": {
        "authentication": "accessToken",
        "resource": "product",
        "operation": "update",
        "productId": "={{ $json.id }}",
        "updateFields": {
          "tags": "={{ [$json.tags, $json.ok ? 'sprkly-queued' : 'sprkly-error'].filter(Boolean).join(', ') }}"
        }
      }
    },
    {
      "name": "Note: automatic published post log",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "id": "6d1b0703-4833-5e70-982b-342a6596fd2a",
      "position": [
        -1000,
        -630
      ],
      "parameters": {
        "content": "## Log posts as they go live\n\nSet **Spreadsheet ID** in **Published log settings**. Use the same Google Sheets credential in the two log steps and your sprkly API credential on **When this workflow's post goes live**.\n\nThe workflow checks each minute for its published posts. It creates **Published Posts** and its headers as needed, then writes one row per Post ID. This branch runs after publication. It leaves the scheduling and source status branches intact.",
        "height": 215,
        "width": 520,
        "color": 5
      }
    },
    {
      "name": "When this workflow's post goes live",
      "type": "n8n-nodes-sprkly.sprklyTrigger",
      "typeVersion": 1,
      "id": "b58dfbf2-b8e5-557e-aecb-ca95a3485d55",
      "position": [
        -1000,
        -380
      ],
      "parameters": {
        "pollTimes": {
          "item": [
            {
              "mode": "everyMinute"
            }
          ]
        },
        "event": "postPublished",
        "externalIdPrefix": "shopify-",
        "stripPrefix": false
      }
    },
    {
      "name": "Build published log rows",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "id": "33b15905-ed3a-5b96-b13f-90b5a82e2afb",
      "position": [
        -760,
        -380
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const prefix = \"shopify-\";\nconst text = value => typeof value === 'string' || typeof value === 'number' ? String(value).trim() : '';\nconst values = input => Array.isArray(input) ? input.map(text).filter(Boolean) : [];\nconst rows = new Map();\n\nfor (const [index, item] of $input.all().entries()) {\n  const post = item.json;\n  const id = text(post.id);\n  const externalId = text(post.externalId);\n  if (!id || post.deleted || !['posted', 'published'].includes(post.status) ||\n      !externalId.startsWith(prefix) || externalId.length === prefix.length) continue;\n\n  const platforms = values(post.platforms);\n  const accounts = values(post.profileIds);\n  const suffix = ':' + platforms[0] + ':' + accounts[0];\n  const source = platforms.length && accounts.length && externalId.endsWith(suffix)\n    ? externalId.slice(0, -suffix.length) : externalId;\n  if (source.length <= prefix.length) continue;\n  const previous = rows.get(id)?.json;\n  rows.set(id, {\n    json: {\n      'Post ID': id,\n      Status: 'Published',\n      'Published At': text(post.publishedAt) || previous?.['Published At'] || '',\n      Platform: platforms.join(', '),\n      'Account ID': accounts.join(', '),\n      'Source ID': source,\n      'External ID': externalId,\n      'Live URL': text(post.permalink) || text(post.link) || previous?.['Live URL'] || '',\n      'Sprkly URL': 'https://sprkly.app/schedule?utm_source=n8n&utm_medium=workflow&utm_campaign=shopify-to-sprkly&post=' + encodeURIComponent(id),\n    },\n    pairedItem: index,\n  });\n}\nreturn [...rows.values()];"
      }
    },
    {
      "name": "Published log settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "id": "4ca948b2-899d-51de-a2dd-131cc6fde762",
      "position": [
        -520,
        -380
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "20f3181f-a4d4-53b7-81a1-1bfdd8a6739d",
              "name": "Spreadsheet ID",
              "type": "string",
              "value": ""
            },
            {
              "id": "5ff526ee-f43b-5a2b-afc2-304030be32ce",
              "name": "Tab name",
              "type": "string",
              "value": "Published Posts"
            }
          ]
        },
        "includeOtherFields": false,
        "options": {}
      },
      "executeOnce": true
    },
    {
      "name": "Ensure published log tab",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "id": "c156f8ce-da0b-539a-b561-f4cf6420fa62",
      "position": [
        -280,
        -380
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "create",
        "documentId": {
          "__rl": true,
          "value": "={{ String($json[\"Spreadsheet ID\"]).trim() }}",
          "mode": "id"
        },
        "title": "={{ String($json[\"Tab name\"]).trim() }}",
        "options": {}
      },
      "alwaysOutputData": true,
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "name": "Restore published log rows",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "id": "702193c6-cc4f-550f-a02e-d6f3c3deaccd",
      "position": [
        -40,
        -380
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Create Sheet has one output for the setup call. Restore every publication in the trigger batch.\nreturn $('Build published log rows').all().map(({ json }) => ({ json, pairedItem: 0 }));"
      }
    },
    {
      "name": "Upsert published post log",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "id": "59b11d56-1754-5432-9619-7d72c1ca8ac5",
      "position": [
        200,
        -380
      ],
      "parameters": {
        "resource": "sheet",
        "operation": "appendOrUpdate",
        "documentId": {
          "__rl": true,
          "value": "={{ String($(\"Published log settings\").first().json[\"Spreadsheet ID\"]).trim() }}",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "={{ String($(\"Published log settings\").first().json[\"Tab name\"]).trim() }}",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "matchingColumns": [
            "Post ID"
          ],
          "schema": []
        },
        "options": {
          "cellFormat": "RAW",
          "handlingExtraData": "insertInNewColumn",
          "useAppend": true
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "id": "ee9c8288-0db8-44b4-8d50-05661aca767a",
      "name": "When this workflow fails",
      "type": "n8n-nodes-base.errorTrigger",
      "typeVersion": 1,
      "position": [
        -1600,
        308
      ],
      "parameters": {}
    },
    {
      "id": "e3c30e17-f5e3-40d0-8416-4cf99bfb37d5",
      "name": "Write the failure alert",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -1380,
        308
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "f1",
              "name": "telegramChatId",
              "type": "string",
              "value": "YOUR_TELEGRAM_CHAT_ID"
            },
            {
              "id": "f2",
              "name": "message",
              "type": "string",
              "value": "={{ 'A workflow stopped.\\n\\nWorkflow: ' + (($json.workflow || {}).name || 'unknown') + '\\nFailed step: ' + (($json.execution || {}).lastNodeExecuted || 'unknown') + '\\nWhy: ' + String((($json.execution || {}).error || {}).message || 'n8n did not give a reason.').slice(0, 300) + (($json.execution || {}).url ? '\\nOpen the run: ' + $json.execution.url : '') }}"
            }
          ]
        },
        "includeOtherFields": false,
        "options": {}
      }
    },
    {
      "id": "73e3e6c9-aa4f-4698-8fe0-6f961b0d8f5d",
      "name": "Send the failure alert",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        -1160,
        308
      ],
      "parameters": {
        "chatId": "={{ $json.telegramChatId }}",
        "text": "={{ $json.message }}",
        "additionalFields": {
          "appendAttribution": false
        }
      }
    },
    {
      "id": "d7cd00ab-bb74-40ed-a1eb-a6f78b21905a",
      "name": "Tell you the result",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        720,
        220
      ],
      "parameters": {
        "chatId": "={{ $('Settings').first().json.telegramChatId }}",
        "text": "={{ $('Hold post for your OK').item.json.ok === true ? 'Waiting for your OK: ' + $('Settings').item.json.title + '\\nOpen it in sprkly: https://sprkly.app/schedule?utm_source=n8n&utm_medium=workflow&utm_campaign=shopify-to-sprkly&post=' + encodeURIComponent(String($('Hold post for your OK').item.json.postId || '').split(',')[0].trim()) : 'Not scheduled: ' + $('Settings').item.json.title + '\\nWhy: ' + (typeof $('Hold post for your OK').item.json.error === 'string' && $('Hold post for your OK').item.json.error ? $('Hold post for your OK').item.json.error : 'sprkly did not give a reason.') }}",
        "additionalFields": {
          "appendAttribution": false
        }
      }
    },
    {
      "id": "53176fee-d156-46c0-8f10-b91fa5abd506",
      "name": "Why it was skipped",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        280,
        420
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "f1",
              "name": "reason",
              "type": "string",
              "value": "={{ !($json.images || []).length ? 'It has no photo.' : /sprkly-(queued|error)/.test($json.tags || '') ? 'It was posted before.' : String($json.status || 'active') !== 'active' ? 'It is not active in your store (' + $json.status + ').' : 'It is out of stock.' }}"
            }
          ]
        },
        "includeOtherFields": true,
        "options": {}
      }
    },
    {
      "id": "2c5d41d4-2c09-4f99-bbbb-c028ad694612",
      "name": "Tag as skipped",
      "type": "n8n-nodes-base.shopify",
      "typeVersion": 1,
      "position": [
        500,
        420
      ],
      "parameters": {
        "authentication": "accessToken",
        "resource": "product",
        "operation": "update",
        "productId": "={{ $json.id }}",
        "updateFields": {
          "tags": "={{ /sprkly-(queued|error|skipped)/.test($json.tags || '') ? $json.tags : [$json.tags, 'sprkly-skipped'].filter(Boolean).join(', ') }}"
        }
      }
    },
    {
      "id": "dcb1f47a-65de-4032-8e96-b79206163911",
      "name": "Tell you it was skipped",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        720,
        420
      ],
      "parameters": {
        "chatId": "={{ $('Settings').first().json.telegramChatId }}",
        "text": "={{ 'Not posted: ' + $('Why it was skipped').item.json.title + '\\nWhy: ' + $('Why it was skipped').item.json.reason }}",
        "additionalFields": {
          "appendAttribution": false
        }
      }
    }
  ],
  "connections": {
    "New product": {
      "main": [
        [
          {
            "node": "Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Settings": {
      "main": [
        [
          {
            "node": "Ready to post?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Hold post for your OK": {
      "main": [
        [
          {
            "node": "Tag the product",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "When this workflow's post goes live": {
      "main": [
        [
          {
            "node": "Build published log rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build published log rows": {
      "main": [
        [
          {
            "node": "Published log settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Published log settings": {
      "main": [
        [
          {
            "node": "Ensure published log tab",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Ensure published log tab": {
      "main": [
        [
          {
            "node": "Restore published log rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Restore published log rows": {
      "main": [
        [
          {
            "node": "Upsert published post log",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "When this workflow fails": {
      "main": [
        [
          {
            "node": "Write the failure alert",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Write the failure alert": {
      "main": [
        [
          {
            "node": "Send the failure alert",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Ready to post?": {
      "main": [
        [
          {
            "node": "Hold post for your OK",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Why it was skipped",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Tag the product": {
      "main": [
        [
          {
            "node": "Tell you the result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Why it was skipped": {
      "main": [
        [
          {
            "node": "Tag as skipped",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Tag as skipped": {
      "main": [
        [
          {
            "node": "Tell you it was skipped",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "active": false,
  "settings": {
    "executionOrder": "v1"
  }
}
