{
  "name": "Vexqo · Shopify variant price drops and restocks",
  "nodes": [
    {
      "id": "start-here",
      "name": "Start here",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "parameters": {
        "content": "### How it works\nFor shoppers watching a specific size or color: a manual run or daily schedule extracts known Shopify products and compares exact variant IDs. After the first live run saves a quiet baseline, a lower known price or confirmed restock produces a Telegram CSV. Comparisons require the same product, variant and currency. Missing values are unknown and reset that field’s comparison baseline.\n\n### Setup\nTested with n8n 2.49.7. Import inactive and run manually with demoMode: true. Demo result uses labeled synthetic data; it makes no requests, spends no credits, saves no state and sends nothing.\n\n1. Create an n8n Data Table with two String columns: key and state. Leave it empty and set tableId in Settings.\n2. Get a Vexqo API key. Create a Header Auth credential named X-API-Key, with the key as its value, and select it in each Collect node. Live requests use credits.\n3. In Settings, replace product URLs and exact variant IDs and choose a unique watchId.\n4. Connect a Telegram bot credential, start a chat with your bot, and set chatId.\n5. Set demoMode: false, run manually, inspect the result and destination, then publish the schedule.\n\n### Customization\nAdjust the schedule and targets. Changing target/filter settings resets the whole watch. Run one execution at a time. Pause after failures and retry the saved execution before new checks; retries may repeat delivered rows. See the section notes and [setup guide](https://vexqo.dev/n8n-workflows/#setup).",
        "height": 760,
        "width": 720,
        "color": 1
      },
      "position": [
        -600,
        -1000
      ]
    },
    {
      "id": "manual-trigger",
      "name": "Manual Trigger",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "parameters": {},
      "position": [
        -560,
        100
      ]
    },
    {
      "id": "daily-schedule",
      "name": "Daily schedule",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "days",
              "daysInterval": 1,
              "triggerAtHour": 9,
              "triggerAtMinute": 15
            }
          ]
        }
      },
      "position": [
        -560,
        300
      ]
    },
    {
      "id": "settings",
      "name": "Settings",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "jsCode": "// Edit only this object. Keep API keys in n8n credentials, never here.\nconst config = {\n  \"demoMode\": true,\n  \"kind\": \"shopify-price-alerts\",\n  \"watchId\": \"shopify-price-alerts-1\",\n  \"tableId\": \"\",\n  \"chatId\": \"\",\n  \"products\": [\n    {\n      \"url\": \"https://store.example/products/headphones\",\n      \"variantId\": \"200000000001\"\n    }\n  ]\n};\n\nfunction prepareConfig(config) {\n  if (typeof config.demoMode !== 'boolean') throw new Error('demoMode must be true or false.');\n  if (!config.watchId?.trim()) throw new Error('Give this watch a unique watchId.');\n  if (!config.demoMode && !config.tableId?.trim()) throw new Error('Set tableId to your n8n Data Table ID.');\n  const watch = { kind: config.kind, watchId: config.watchId };\n  if (config.kind === 'meta-ad-swipe-file') {\n    if (!config.demoMode && !config.spreadsheetId?.trim()) throw new Error('Set spreadsheetId to your Google spreadsheet ID.');\n    if (!Array.isArray(config.advertisers) || !config.advertisers.length || config.advertisers.some(a => !/^\\d+$/.test(a.pageId))) {\n      throw new Error('Set each advertiser pageId to its numeric Meta Page ID.');\n    }\n    if (!Number.isInteger(config.limit) || config.limit < 1 || config.limit > 100) throw new Error('Meta limit must be 1–100.');\n    Object.assign(watch, { advertisers: config.advertisers, country: config.country, limit: config.limit });\n  } else if (config.kind === 'shopify-price-alerts') {\n    if (!Array.isArray(config.products) || !config.products.length) throw new Error('Add at least one product.');\n    for (const product of config.products) {\n      if (!/^https:\\/\\/[^/]+\\/(?:[^/?#]+\\/)*products\\/[^/?#]+(?:\\?[^#]*)?$/.test(product.url) || !/^\\d+$/.test(product.variantId)) {\n        throw new Error('Each Shopify watch needs an HTTPS product URL and exact numeric variantId.');\n      }\n    }\n    Object.assign(watch, { products: config.products });\n  } else {\n    if (typeof config.query !== 'string' || !config.query.trim() || config.query.length > 300) throw new Error('Set an eBay query of 1–300 characters.');\n    if (!Array.isArray(config.excludeTerms) || !Array.isArray(config.blockedSellers)) throw new Error('Use arrays for excludeTerms and blockedSellers.');\n    if (config.kind !== 'ebay-seller-digest' && config.blockedSellers.length) throw new Error('Use the seller digest workflow to filter by seller username.');\n    Object.assign(watch, { query: config.query, excludeTerms: config.excludeTerms, blockedSellers: config.blockedSellers,\n      maxPrice: config.maxPrice, currency: config.currency, buyingFormat: config.buyingFormat, condition: config.condition });\n  }\n  if (!config.demoMode && config.kind !== 'meta-ad-swipe-file' && !config.chatId?.trim()) throw new Error('Set chatId to your Telegram destination.');\n  return { ...config, stateKey: JSON.stringify(watch) };\n}\nreturn [{json: prepareConfig(config)}];"
      },
      "position": [
        -300,
        100
      ]
    },
    {
      "id": "demo-",
      "name": "Demo?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "condition",
              "leftValue": "={{ $json.demoMode }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "position": [
        -60,
        100
      ]
    },
    {
      "id": "demo-result",
      "name": "Demo result",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "jsCode": "function processShopify(responses, previous, config, now) {\n  const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);\n  const identifier = value => typeof value === 'string' && value.trim() ? value.trim()\n    : Number.isSafeInteger(value) && value >= 0 ? String(value) : null;\n  const text = value => typeof value === 'string' ? value : '';\n  const price = value => {\n    if (typeof value !== 'string' && typeof value !== 'number') return null;\n    const result = String(value).trim();\n    return /^\\d+(?:\\.\\d+)?$/.test(result) && Number.isFinite(Number(result)) ? result : null;\n  };\n  const address = (value, productPath = true) => {\n    // n8n's Code sandbox does not expose URL. Accept only unambiguous web\n    // addresses; never normalize credentials, dot segments or escaped slashes.\n    if (typeof value !== 'string' || /[\\s\\\\\\u0000-\\u001f\\u007f]/.test(value)) return null;\n    const parts = /^(https?):\\/\\/([^/?#]+)(\\/[^?#]*)?(\\?[^#]*)?(#.*)?$/i.exec(value);\n    if (!parts) return null;\n    const authority = /^([a-z0-9.-]+)(?::(\\d+))?$/i.exec(parts[2]);\n    if (!authority) return null;\n    const hostname = authority[1].toLowerCase();\n    if (hostname.length > 253 || !hostname.includes('.') || !hostname.split('.').every(label => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label))) return null;\n    if (authority[2] && authority[2] !== (parts[1].toLowerCase() === 'https' ? '443' : '80')) return null;\n    let path = (parts[3] || '/').replace(/\\/$/, '');\n    if (productPath) {\n      const product = /^(\\/[a-zA-Z]{2}(?:-[a-zA-Z]{2})?)?(?:\\/collections\\/([^/]+))?\\/products\\/([^/]+)$/.exec(path);\n      if (!product) return null;\n      try {\n        for (const component of [product[2], product[3]].filter(Boolean)) {\n          const slug = decodeURIComponent(component);\n          if (slug === '.' || slug === '..' || /[\\s\\\\/?#\\u0000-\\u001f\\u007f]/.test(slug)) return null;\n        }\n      } catch { return null; }\n      path = `${product[1] || ''}/products/${product[3]}`;\n    } else if (path || parts[4] || parts[5]) return null;\n    return { host: hostname.replace(/^www\\./, ''), path };\n  };\n  if (!object(config) || !Array.isArray(config.products) || !config.products.length) {\n    throw new Error('Shopify config needs at least one product URL and variantId.');\n  }\n  if (!Array.isArray(responses) || responses.length !== config.products.length) {\n    throw new Error('Shopify responses must contain one response for each configured product, in the same order.');\n  }\n  if (previous !== null && previous !== undefined && (!object(previous) || previous.version !== 1 || previous.kind !== 'shopify-price-alerts' || !object(previous.products))) {\n    throw new Error('Unsupported Shopify state. Keep the saved state or reset it deliberately.');\n  }\n  const state = previous ? JSON.parse(JSON.stringify(previous)) : { version: 1, kind: 'shopify-price-alerts', products: {} };\n  const rows = [];\n  const warnings = [];\n  let observed = 0;\n  let seeded = 0;\n\n  responses.forEach((response, index) => {\n    if (!object(response) || response.error || !object(response.product)) {\n      throw new Error(`Invalid Shopify response for product ${index + 1}: expected a successful product object.`);\n    }\n    const watched = config.products[index];\n    const requested = address(watched?.url);\n    const variantId = identifier(watched?.variantId);\n    if (!requested || !variantId) {\n      warnings.push(`Product ${index + 1}: configure a product URL and an exact variantId before enabling alerts.`);\n      return;\n    }\n    const product = response.product;\n    const returned = address(product.url);\n    const suppliedDomain = product.store?.domain;\n    const domain = typeof suppliedDomain === 'string'\n      ? address(/^https?:\\/\\//i.test(suppliedDomain) ? suppliedDomain : `https://${suppliedDomain}`, false)?.host : null;\n    if (!returned || returned.host !== requested.host || returned.path !== requested.path || (suppliedDomain != null && (!domain || domain !== requested.host))) {\n      warnings.push(`${watched.url}: returned product URL or storefront does not match; baseline retained.`);\n      return;\n    }\n    const productId = identifier(product.id);\n    if (!productId) {\n      warnings.push(`${watched.url}: product identity is missing; baseline retained.`);\n      return;\n    }\n    const variants = Array.isArray(product.variants) ? product.variants.filter(object) : [];\n    const matching = variants.filter(variant => identifier(variant.id) === variantId);\n    if (matching.length !== 1 || product.selected_variant_found === false\n      || (identifier(product.selected_variant_id) && identifier(product.selected_variant_id) !== variantId)) {\n      warnings.push(`${watched.url}: variant ${variantId} was not uniquely verified in the response; baseline retained.`);\n      return;\n    }\n    const variant = matching[0];\n    const key = `${requested.host}${requested.path}#${variantId}`;\n    const old = state.products[key];\n    const currency = typeof product.currency === 'string' && /^[a-z]{3}$/i.test(product.currency) ? product.currency.toUpperCase() : null;\n    const amount = price(variant.price);\n    let available = typeof variant.available === 'boolean' ? variant.available\n      : typeof variant.inStock === 'boolean' ? variant.inStock : null;\n    if (typeof variant.available === 'boolean' && typeof variant.inStock === 'boolean' && variant.available !== variant.inStock) {\n      available = null;\n      warnings.push(`${watched.url}: variant ${variantId} has conflicting availability fields; availability remains unknown.`);\n    }\n    const sameIdentity = old && old.product_id === productId && old.store === requested.host && old.variant_id === variantId;\n    if (old && !sameIdentity) warnings.push(`${watched.url}: product identity changed; this observation starts a new baseline.`);\n    if (sameIdentity && old.currency && currency && old.currency !== currency) {\n      warnings.push(`${watched.url}: currency changed from ${old.currency} to ${currency}; price baseline reset.`);\n    }\n    if (amount === null || currency === null) warnings.push(`${watched.url}: variant ${variantId} has unknown price or currency; price comparison skipped.`);\n    if (available === null) warnings.push(`${watched.url}: variant ${variantId} has unknown availability; restock comparison skipped.`);\n    const priceDrop = Boolean(sameIdentity && currency && currency === old.currency && amount !== null && price(old.price) !== null && Number(amount) < Number(old.price));\n    const restocked = Boolean(sameIdentity && old.available === false && available === true);\n    if (priceDrop || restocked) {\n      rows.push({\n        product_url: watched.url,\n        product_id: productId,\n        product: text(product.name),\n        variant_id: variantId,\n        variant: text(variant.title),\n        sku: text(variant.sku),\n        store: requested.host,\n        currency: currency ?? '',\n        previous_price: sameIdentity && old.currency === currency ? old.price ?? '' : '',\n        price: amount ?? '',\n        price_drop: priceDrop,\n        restocked,\n        available: available ?? '',\n        change: [priceDrop ? 'price_drop' : '', restocked ? 'restocked' : ''].filter(Boolean).join(', '),\n        observed_at: now,\n      });\n    }\n    state.products[key] = { product_id: productId, variant_id: variantId, store: requested.host, price: amount, currency, available, observed_at: now };\n    observed += 1;\n    if (!sameIdentity) seeded += 1;\n  });\n  return { state, rows, summary: { products_observed: observed, products_seeded: seeded, alerts: rows.length }, warnings };\n}\nfunction asCsv(rows) {\n  const columns = [...new Set(rows.flatMap(row => Object.keys(row)))];\n  const cell = value => {\n    let text = value == null ? '' : typeof value === 'object' ? JSON.stringify(value) : String(value);\n    // Public listing/ad text is untrusted. Do not let a spreadsheet evaluate formulas.\n    if (/^[\\s]*[=+@-]/.test(text) || /^[\\t\\r\\n]/.test(text)) text = `'${text}`;\n    return `\"${text.replace(/\"/g, '\"\"')}\"`;\n  };\n  return [columns.map(cell).join(','), ...rows.map(row => columns.map(key => cell(row[key])).join(','))].join('\\r\\n');\n}\nconst sample = {\n  \"label\": \"SYNTHETIC DEMO — not live data. No requests, credits, saved state or messages.\",\n  \"config\": {\n    \"demoMode\": true,\n    \"kind\": \"shopify-price-alerts\",\n    \"watchId\": \"shopify-price-alerts-1\",\n    \"tableId\": \"\",\n    \"chatId\": \"\",\n    \"products\": [\n      {\n        \"url\": \"https://store.example/products/headphones\",\n        \"variantId\": \"200000000001\"\n      }\n    ]\n  },\n  \"now\": \"2026-11-26T09:00:00.000Z\",\n  \"previous\": {\n    \"version\": 1,\n    \"kind\": \"shopify-price-alerts\",\n    \"products\": {\n      \"store.example/products/headphones#200000000001\": {\n        \"product_id\": \"2000\",\n        \"variant_id\": \"200000000001\",\n        \"store\": \"store.example\",\n        \"price\": \"129.00\",\n        \"currency\": \"USD\",\n        \"available\": false,\n        \"observed_at\": \"2026-11-25T09:00:00.000Z\"\n      }\n    }\n  },\n  \"responses\": [\n    {\n      \"product\": {\n        \"id\": \"2000\",\n        \"url\": \"https://store.example/products/headphones\",\n        \"name\": \"Example headphones\",\n        \"currency\": \"USD\",\n        \"selected_variant_id\": \"200000000001\",\n        \"selected_variant_found\": true,\n        \"variants\": [\n          {\n            \"id\": \"200000000001\",\n            \"title\": \"Black\",\n            \"sku\": \"DEMO-BLACK\",\n            \"price\": \"99.00\",\n            \"available\": true\n          }\n        ]\n      }\n    }\n  ]\n};\nconst result = processShopify(sample.responses, sample.previous, sample.config, sample.now);\nreturn [{json: {demo: true, label: sample.label, ...result, csv: asCsv(result.rows)}}];"
      },
      "position": [
        200,
        -260
      ]
    },
    {
      "id": "read-baseline",
      "name": "Read baseline",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "value": "={{ $('Settings').first().json.tableId }}",
          "mode": "id"
        },
        "matchType": "allConditions",
        "filters": {
          "conditions": [
            {
              "keyName": "key",
              "condition": "eq",
              "keyValue": "={{ $('Settings').first().json.stateKey }}"
            }
          ]
        },
        "returnAll": false,
        "limit": 2
      },
      "position": [
        200,
        180
      ],
      "alwaysOutputData": true
    },
    {
      "id": "read-saved-state",
      "name": "Read saved state",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "jsCode": "function readSavedState(items) {\n  const rows = items.filter(row => typeof row.key === 'string');\n  if (rows.length > 1) throw new Error('Duplicate state rows found. Stop overlapping runs and keep one verified row for this key.');\n  if (!rows.length) return null;\n  if (typeof rows[0].state !== 'string' || !rows[0].state.trim()) throw new Error('Saved state is empty; inspect the Data Table before retrying.');\n  const state = JSON.parse(rows[0].state);\n  if (!state || typeof state !== 'object' || Array.isArray(state)) throw new Error('Saved state is not an object.');\n  return state;\n}\nreturn [{json: {previous: readSavedState($input.all().map(item => item.json))}}];"
      },
      "position": [
        440,
        180
      ]
    },
    {
      "id": "build-requests",
      "name": "Build requests",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "jsCode": "function makeRequests(config) {\n  const base = 'https://api.vexqo.dev';\n  if (config.kind === 'meta-ad-swipe-file') return config.advertisers.map(a => ({\n    url: `${base}/facebook/ads`, query: { page_id: a.pageId, country: config.country,\n      active_status: 'active', limit: config.limit, view: 'compact' },\n  }));\n  if (config.kind === 'shopify-price-alerts') return config.products.map(p => {\n    // Replace a pre-existing variant parameter so the API verifies the watched variant.\n    const [path, query = ''] = p.url.split('?');\n    const params = query.split('&').filter(x => x && decodeURIComponent(x.split('=')[0]) !== 'variant');\n    params.push(`variant=${encodeURIComponent(p.variantId)}`);\n    return { url: `${base}/shopify`, body: { url: `${path}?${params.join('&')}` } };\n  });\n  // Do not send max_price: local checks preserve currency and reject price ranges safely.\n  return [{ url: `${base}/ebay/search`, query: { q: config.query, page: 1, per_page: 60,\n    sort: 'newly_listed', buying_format: config.buyingFormat, condition: config.condition } }];\n}\nreturn makeRequests($('Settings').first().json).map(request => ({json: request}));"
      },
      "position": [
        680,
        180
      ]
    },
    {
      "id": "collect-data",
      "name": "Collect data",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "parameters": {
        "method": "POST",
        "url": "={{ $json.url }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify($json.body) }}",
        "options": {
          "timeout": 120000,
          "batching": {
            "batch": {
              "batchSize": 1,
              "batchInterval": 7000
            }
          },
          "response": {
            "response": {
              "responseFormat": "json"
            }
          }
        }
      },
      "position": [
        920,
        180
      ],
      "notesInFlow": true,
      "notes": "Select a Header Auth credential: Name X-API-Key, Value your Vexqo key. Requests are serial, 7 seconds apart. Errors stop the run; saved state stays unchanged."
    },
    {
      "id": "configure-the-watch",
      "name": "Configure the watch",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "parameters": {
        "content": "## Configure and try the sample\nEdit the Settings object. Keep secrets in credentials. The manual trigger and schedule use the same settings. Demo mode returns a simulated result and bypasses every live node.",
        "width": 720,
        "height": 170,
        "color": 7
      },
      "position": [
        -600,
        -100
      ]
    },
    {
      "id": "load-history-and-fetch-data",
      "name": "Load history and fetch data",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "parameters": {
        "content": "## Read previous observations, then collect\nThe table stores one JSON baseline per watch. Do not edit it during a run. Collection requests are serial and seven seconds apart. A failed request stops before the baseline is changed.",
        "width": 960,
        "height": 170,
        "color": 7
      },
      "position": [
        160,
        -80
      ]
    },
    {
      "id": "compare-and-deliver",
      "name": "Compare and deliver",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "parameters": {
        "content": "## Deliver only matching changes\nNo new rows means no message. CSV output escapes spreadsheet formula prefixes. Choose your Telegram credential and set chatId before live use. Inspect Run result for skipped records and warnings.",
        "width": 920,
        "height": 170,
        "color": 7
      },
      "position": [
        1120,
        -180
      ]
    },
    {
      "id": "save-after-delivery",
      "name": "Save after delivery",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "parameters": {
        "content": "## Commit the next baseline\nState saves after successful delivery or a valid no-change run. Pause the schedule after errors. Retry the saved failure before fresh checks; fresh data can miss temporary changes. Delivery may repeat if saving fails. Never retry an older failure after newer state.",
        "width": 780,
        "height": 170,
        "color": 7
      },
      "position": [
        2080,
        -180
      ]
    },
    {
      "id": "coverage-and-credits",
      "name": "Coverage and credits",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "parameters": {
        "content": "## Coverage and credits\n2 credits per product URL per run. Supply every URL and exact variant yourself. Published availability is not a private stock count. A missing field clears its comparison baseline until a known value returns.",
        "width": 920,
        "height": 170,
        "color": 7
      },
      "position": [
        1120,
        440
      ]
    },
    {
      "id": "process-live",
      "name": "Process live",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "jsCode": "function processShopify(responses, previous, config, now) {\n  const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);\n  const identifier = value => typeof value === 'string' && value.trim() ? value.trim()\n    : Number.isSafeInteger(value) && value >= 0 ? String(value) : null;\n  const text = value => typeof value === 'string' ? value : '';\n  const price = value => {\n    if (typeof value !== 'string' && typeof value !== 'number') return null;\n    const result = String(value).trim();\n    return /^\\d+(?:\\.\\d+)?$/.test(result) && Number.isFinite(Number(result)) ? result : null;\n  };\n  const address = (value, productPath = true) => {\n    // n8n's Code sandbox does not expose URL. Accept only unambiguous web\n    // addresses; never normalize credentials, dot segments or escaped slashes.\n    if (typeof value !== 'string' || /[\\s\\\\\\u0000-\\u001f\\u007f]/.test(value)) return null;\n    const parts = /^(https?):\\/\\/([^/?#]+)(\\/[^?#]*)?(\\?[^#]*)?(#.*)?$/i.exec(value);\n    if (!parts) return null;\n    const authority = /^([a-z0-9.-]+)(?::(\\d+))?$/i.exec(parts[2]);\n    if (!authority) return null;\n    const hostname = authority[1].toLowerCase();\n    if (hostname.length > 253 || !hostname.includes('.') || !hostname.split('.').every(label => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label))) return null;\n    if (authority[2] && authority[2] !== (parts[1].toLowerCase() === 'https' ? '443' : '80')) return null;\n    let path = (parts[3] || '/').replace(/\\/$/, '');\n    if (productPath) {\n      const product = /^(\\/[a-zA-Z]{2}(?:-[a-zA-Z]{2})?)?(?:\\/collections\\/([^/]+))?\\/products\\/([^/]+)$/.exec(path);\n      if (!product) return null;\n      try {\n        for (const component of [product[2], product[3]].filter(Boolean)) {\n          const slug = decodeURIComponent(component);\n          if (slug === '.' || slug === '..' || /[\\s\\\\/?#\\u0000-\\u001f\\u007f]/.test(slug)) return null;\n        }\n      } catch { return null; }\n      path = `${product[1] || ''}/products/${product[3]}`;\n    } else if (path || parts[4] || parts[5]) return null;\n    return { host: hostname.replace(/^www\\./, ''), path };\n  };\n  if (!object(config) || !Array.isArray(config.products) || !config.products.length) {\n    throw new Error('Shopify config needs at least one product URL and variantId.');\n  }\n  if (!Array.isArray(responses) || responses.length !== config.products.length) {\n    throw new Error('Shopify responses must contain one response for each configured product, in the same order.');\n  }\n  if (previous !== null && previous !== undefined && (!object(previous) || previous.version !== 1 || previous.kind !== 'shopify-price-alerts' || !object(previous.products))) {\n    throw new Error('Unsupported Shopify state. Keep the saved state or reset it deliberately.');\n  }\n  const state = previous ? JSON.parse(JSON.stringify(previous)) : { version: 1, kind: 'shopify-price-alerts', products: {} };\n  const rows = [];\n  const warnings = [];\n  let observed = 0;\n  let seeded = 0;\n\n  responses.forEach((response, index) => {\n    if (!object(response) || response.error || !object(response.product)) {\n      throw new Error(`Invalid Shopify response for product ${index + 1}: expected a successful product object.`);\n    }\n    const watched = config.products[index];\n    const requested = address(watched?.url);\n    const variantId = identifier(watched?.variantId);\n    if (!requested || !variantId) {\n      warnings.push(`Product ${index + 1}: configure a product URL and an exact variantId before enabling alerts.`);\n      return;\n    }\n    const product = response.product;\n    const returned = address(product.url);\n    const suppliedDomain = product.store?.domain;\n    const domain = typeof suppliedDomain === 'string'\n      ? address(/^https?:\\/\\//i.test(suppliedDomain) ? suppliedDomain : `https://${suppliedDomain}`, false)?.host : null;\n    if (!returned || returned.host !== requested.host || returned.path !== requested.path || (suppliedDomain != null && (!domain || domain !== requested.host))) {\n      warnings.push(`${watched.url}: returned product URL or storefront does not match; baseline retained.`);\n      return;\n    }\n    const productId = identifier(product.id);\n    if (!productId) {\n      warnings.push(`${watched.url}: product identity is missing; baseline retained.`);\n      return;\n    }\n    const variants = Array.isArray(product.variants) ? product.variants.filter(object) : [];\n    const matching = variants.filter(variant => identifier(variant.id) === variantId);\n    if (matching.length !== 1 || product.selected_variant_found === false\n      || (identifier(product.selected_variant_id) && identifier(product.selected_variant_id) !== variantId)) {\n      warnings.push(`${watched.url}: variant ${variantId} was not uniquely verified in the response; baseline retained.`);\n      return;\n    }\n    const variant = matching[0];\n    const key = `${requested.host}${requested.path}#${variantId}`;\n    const old = state.products[key];\n    const currency = typeof product.currency === 'string' && /^[a-z]{3}$/i.test(product.currency) ? product.currency.toUpperCase() : null;\n    const amount = price(variant.price);\n    let available = typeof variant.available === 'boolean' ? variant.available\n      : typeof variant.inStock === 'boolean' ? variant.inStock : null;\n    if (typeof variant.available === 'boolean' && typeof variant.inStock === 'boolean' && variant.available !== variant.inStock) {\n      available = null;\n      warnings.push(`${watched.url}: variant ${variantId} has conflicting availability fields; availability remains unknown.`);\n    }\n    const sameIdentity = old && old.product_id === productId && old.store === requested.host && old.variant_id === variantId;\n    if (old && !sameIdentity) warnings.push(`${watched.url}: product identity changed; this observation starts a new baseline.`);\n    if (sameIdentity && old.currency && currency && old.currency !== currency) {\n      warnings.push(`${watched.url}: currency changed from ${old.currency} to ${currency}; price baseline reset.`);\n    }\n    if (amount === null || currency === null) warnings.push(`${watched.url}: variant ${variantId} has unknown price or currency; price comparison skipped.`);\n    if (available === null) warnings.push(`${watched.url}: variant ${variantId} has unknown availability; restock comparison skipped.`);\n    const priceDrop = Boolean(sameIdentity && currency && currency === old.currency && amount !== null && price(old.price) !== null && Number(amount) < Number(old.price));\n    const restocked = Boolean(sameIdentity && old.available === false && available === true);\n    if (priceDrop || restocked) {\n      rows.push({\n        product_url: watched.url,\n        product_id: productId,\n        product: text(product.name),\n        variant_id: variantId,\n        variant: text(variant.title),\n        sku: text(variant.sku),\n        store: requested.host,\n        currency: currency ?? '',\n        previous_price: sameIdentity && old.currency === currency ? old.price ?? '' : '',\n        price: amount ?? '',\n        price_drop: priceDrop,\n        restocked,\n        available: available ?? '',\n        change: [priceDrop ? 'price_drop' : '', restocked ? 'restocked' : ''].filter(Boolean).join(', '),\n        observed_at: now,\n      });\n    }\n    state.products[key] = { product_id: productId, variant_id: variantId, store: requested.host, price: amount, currency, available, observed_at: now };\n    observed += 1;\n    if (!sameIdentity) seeded += 1;\n  });\n  return { state, rows, summary: { products_observed: observed, products_seeded: seeded, alerts: rows.length }, warnings };\n}\nconst config = $('Settings').first().json;\nconst previous = $('Read saved state').first().json.previous;\nconst result = processShopify($input.all().map(item => item.json), previous, config, new Date().toISOString());\nreturn [{json: {demo: false, ...result}}];"
      },
      "position": [
        1160,
        180
      ]
    },
    {
      "id": "has-new-rows-",
      "name": "Has new rows?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "condition",
              "leftValue": "={{ $json.rows.length > 0 }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "position": [
        1400,
        180
      ]
    },
    {
      "id": "csv-attachment",
      "name": "CSV attachment",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "jsCode": "function asCsv(rows) {\n  const columns = [...new Set(rows.flatMap(row => Object.keys(row)))];\n  const cell = value => {\n    let text = value == null ? '' : typeof value === 'object' ? JSON.stringify(value) : String(value);\n    // Public listing/ad text is untrusted. Do not let a spreadsheet evaluate formulas.\n    if (/^[\\s]*[=+@-]/.test(text) || /^[\\t\\r\\n]/.test(text)) text = `'${text}`;\n    return `\"${text.replace(/\"/g, '\"\"')}\"`;\n  };\n  return [columns.map(cell).join(','), ...rows.map(row => columns.map(key => cell(row[key])).join(','))].join('\\r\\n');\n}\nconst result = $input.first().json;\nconst csv = asCsv(result.rows);\nconst caption = \"Shopify variant price drops and restocks\" + ': ' + result.rows.length + ' row(s).' + (result.warnings.length ? ' ' + result.warnings.length + ' warning(s); inspect Process live.' : '');\nreturn [{json: {caption}, binary: {data: {data: Buffer.from(csv, 'utf8').toString('base64'), mimeType: 'text/csv', fileName: \"shopify-price-alerts.csv\" }}}];"
      },
      "position": [
        1640,
        60
      ]
    },
    {
      "id": "send-csv-to-telegram",
      "name": "Send CSV to Telegram",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "parameters": {
        "resource": "message",
        "operation": "sendDocument",
        "chatId": "={{ $('Settings').first().json.chatId }}",
        "binaryData": true,
        "binaryPropertyName": "data",
        "additionalFields": {
          "caption": "={{ $json.caption }}"
        }
      },
      "position": [
        1880,
        60
      ],
      "notesInFlow": true,
      "notes": "Choose your Telegram bot credential and set chatId in Settings. Start a chat with the bot first. A failed send stops before saving state."
    },
    {
      "id": "prepare-state",
      "name": "Prepare state",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "jsCode": "const config = $('Settings').first().json;\nconst result = $('Process live').first().json;\nreturn [{json: {key: config.stateKey, state: JSON.stringify(result.state)}}];"
      },
      "position": [
        2120,
        180
      ]
    },
    {
      "id": "save-baseline",
      "name": "Save baseline",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "parameters": {
        "resource": "row",
        "operation": "upsert",
        "dataTableId": {
          "__rl": true,
          "value": "={{ $('Settings').first().json.tableId }}",
          "mode": "id"
        },
        "matchType": "allConditions",
        "filters": {
          "conditions": [
            {
              "keyName": "key",
              "condition": "eq",
              "keyValue": "={{ $('Settings').first().json.stateKey }}"
            }
          ]
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {},
          "matchingColumns": [],
          "schema": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "position": [
        2360,
        180
      ]
    },
    {
      "id": "run-result",
      "name": "Run result",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "jsCode": "const result = $('Process live').first().json;\nreturn [{json: {saved: true, rows: result.rows, summary: result.summary, warnings: result.warnings}}];"
      },
      "position": [
        2600,
        180
      ]
    }
  ],
  "connections": {
    "Manual Trigger": {
      "main": [
        [
          {
            "node": "Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Daily schedule": {
      "main": [
        [
          {
            "node": "Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Settings": {
      "main": [
        [
          {
            "node": "Demo?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Demo?": {
      "main": [
        [
          {
            "node": "Demo result",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Read baseline",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read baseline": {
      "main": [
        [
          {
            "node": "Read saved state",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read saved state": {
      "main": [
        [
          {
            "node": "Build requests",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build requests": {
      "main": [
        [
          {
            "node": "Collect data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Collect data": {
      "main": [
        [
          {
            "node": "Process live",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Process live": {
      "main": [
        [
          {
            "node": "Has new rows?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Has new rows?": {
      "main": [
        [
          {
            "node": "CSV attachment",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Prepare state",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "CSV attachment": {
      "main": [
        [
          {
            "node": "Send CSV to Telegram",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send CSV to Telegram": {
      "main": [
        [
          {
            "node": "Prepare state",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare state": {
      "main": [
        [
          {
            "node": "Save baseline",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save baseline": {
      "main": [
        [
          {
            "node": "Run result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "pinData": {},
  "settings": {
    "executionOrder": "v1",
    "timezone": "UTC",
    "saveDataErrorExecution": "all",
    "saveDataSuccessExecution": "all",
    "saveManualExecutions": true,
    "executionTimeout": 3600
  },
  "tags": [],
  "meta": {
    "templateCredsSetupCompleted": false
  }
}
