{
  "name": "Vexqo · eBay new-since-last-check feed",
  "nodes": [
    {
      "id": "start-here",
      "name": "Start here",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "parameters": {
        "content": "### How it works\nFor buyers tired of repeated search results: a manual run or daily schedule compares the first 60 eBay results with saved listing IDs. The first live run saves a quiet baseline. Later runs send newly observed IDs as a Telegram CSV. An item that disappears and returns remains seen. First observed is not the seller’s original listing date.\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 the query, exclusions and price filters 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": 45
            }
          ]
        }
      },
      "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\": \"ebay-new-listings\",\n  \"watchId\": \"ebay-new-listings-1\",\n  \"tableId\": \"\",\n  \"chatId\": \"\",\n  \"query\": \"portable music player\",\n  \"excludeTerms\": [\n    \"for parts\",\n    \"replica\"\n  ],\n  \"blockedSellers\": [],\n  \"maxPrice\": \"\",\n  \"currency\": \"USD\",\n  \"buyingFormat\": \"all\",\n  \"condition\": \"any\"\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 processEbay(responses, previous, config, now) {\n  const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);\n  const decimal = value => typeof value === 'string' && /^\\d+(?:\\.\\d+)?$/.test(value) && Number.isFinite(Number(value));\n  const text = value => typeof value === 'string' && value.trim() ? value.trim() : null;\n  const failed = value => !object(value) || value.error != null || Number(value.source?.http_status) >= 400;\n  const idValid = value => typeof value === 'string' && /^\\d+$/.test(value);\n  const kinds = ['ebay-rare-alerts', 'ebay-new-listings', 'ebay-seller-digest'];\n  if (!object(config) || !kinds.includes(config.kind)) throw new Error('Unknown eBay workflow kind.');\n  if (typeof now !== 'string' || !Number.isFinite(Date.parse(now))) throw new Error('A valid observation timestamp is required.');\n  for (const key of ['excludeTerms', 'blockedSellers']) {\n    if (!Array.isArray(config[key]) || config[key].some(value => typeof value !== 'string')) {\n      throw new Error(`${key} must be a list of strings.`);\n    }\n  }\n  if (!['all', 'buy_it_now', 'auction'].includes(config.buyingFormat)) throw new Error('Invalid buying format.');\n  if (!['any', 'new', 'used'].includes(config.condition)) throw new Error('Invalid condition.');\n  const hasCap = config.maxPrice !== '';\n  if (hasCap && !decimal(config.maxPrice)) throw new Error('maxPrice must be a plain decimal amount or an empty string.');\n  const currency = text(config.currency)?.toUpperCase();\n  if (hasCap && !/^[A-Z]{3}$/.test(currency ?? '')) throw new Error('Set a three-letter currency for the price limit.');\n  if (previous !== null && (!object(previous) || previous.version !== 1 || !object(previous.seen)\n    || Object.entries(previous.seen).some(([id, date]) => !idValid(id) || typeof date !== 'string' || !Number.isFinite(Date.parse(date))))) {\n    throw new Error('Invalid saved eBay baseline. Keep the existing state and inspect it before retrying.');\n  }\n\n  const search = Array.isArray(responses) ? responses[0] : null;\n  if (failed(search) || !Array.isArray(search.results) || !object(search.search_information)\n    || search.search_information.results_returned !== search.results.length\n    || typeof search.search_information.has_more !== 'boolean') {\n    throw new Error('Invalid or failed eBay search response. The saved baseline has not been changed.');\n  }\n  for (const listing of search.results) {\n    if (!object(listing) || !idValid(listing.listing_id) || !text(listing.url)) {\n      throw new Error('Malformed eBay listing in search results. The saved baseline has not been changed.');\n    }\n  }\n\n  const sellers = new Map();\n  for (const detail of responses.slice(1)) {\n    if (!failed(detail) && idValid(detail.listing_id) && text(detail.seller?.username)) {\n      sellers.set(detail.listing_id, detail.seller.username.trim());\n    }\n  }\n  const blocked = new Set(config.blockedSellers.map(value => value.trim().toLowerCase()).filter(Boolean));\n  const excluded = config.excludeTerms.map(value => value.trim().toLowerCase()).filter(Boolean);\n  const needsSeller = config.kind === 'ebay-seller-digest' || blocked.size > 0;\n  const baseline = previous === null;\n  const seen = { ...(previous?.seen ?? {}) };\n  const rows = [];\n  const warnings = [];\n  const processed = new Set();\n  let matching = 0;\n  let added = 0;\n  let uncertainPrices = 0;\n\n  for (const listing of search.results) {\n    const id = listing.listing_id;\n    if (processed.has(id)) continue;\n    processed.add(id);\n    const searchable = [listing.title, listing.subtitle, ...(Array.isArray(listing.details) ? listing.details : [])]\n      .filter(value => typeof value === 'string').join(' ').toLowerCase();\n    if (excluded.some(term => searchable.includes(term))) continue;\n    // Condition is sent to eBay by the HTTP node; category-specific display labels are not a second condition taxonomy.\n    const format = config.buyingFormat === 'buy_it_now' ? 'fixed_price' : config.buyingFormat;\n    if (format !== 'all' && listing.buying_format !== format) continue;\n\n    const money = !listing.price_range && object(listing.price) && decimal(listing.price.amount) ? listing.price : null;\n    const listedCurrency = text(money?.currency)?.toUpperCase() ?? null;\n    if (hasCap) {\n      if (!money || listedCurrency !== currency) {\n        uncertainPrices += 1;\n        continue;\n      }\n      if (Number(money.amount) > Number(config.maxPrice)) continue;\n    }\n    const seller = sellers.get(id) ?? null;\n    if (needsSeller && !seller) {\n      warnings.push(`Seller for listing ${id} could not be verified; skipped and left unseen so the next run can retry.`);\n      continue;\n    }\n    if (seller && blocked.has(seller.toLowerCase())) continue;\n    matching += 1;\n    if (Object.hasOwn(seen, id)) continue;\n    seen[id] = now;\n    added += 1;\n    if (baseline) continue;\n    rows.push({\n      id, title: text(listing.title), url: listing.url,\n      price: money?.amount ?? null, currency: listedCurrency,\n      price_text: text(listing.price_text), seller,\n      condition: text(listing.condition), buying_format: text(listing.buying_format),\n      image_url: text(listing.image_url), shipping_text: text(listing.shipping_text),\n      first_seen: now, observed_at: now, query: config.query,\n    });\n  }\n  if (uncertainPrices) warnings.push(`${uncertainPrices} listing(s) skipped because a single price in ${currency} was not available. No currency conversion was attempted.`);\n  if (search.search_information.has_more) warnings.push('More eBay results exist beyond this page; this run does not cover every matching listing.');\n  return {\n    state: { version: 1, seen, observed_at: now },\n    rows,\n    summary: baseline\n      ? `Baseline saved: ${added} matching listing(s). No alerts sent on the first run.`\n      : `${rows.length} newly seen matching listing(s); ${matching} matched in the returned search page.`,\n    warnings,\n  };\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\": \"ebay-new-listings\",\n    \"watchId\": \"ebay-new-listings-1\",\n    \"tableId\": \"\",\n    \"chatId\": \"\",\n    \"query\": \"portable music player\",\n    \"excludeTerms\": [\n      \"for parts\",\n      \"replica\"\n    ],\n    \"blockedSellers\": [],\n    \"maxPrice\": \"\",\n    \"currency\": \"USD\",\n    \"buyingFormat\": \"all\",\n    \"condition\": \"any\"\n  },\n  \"now\": \"2026-11-26T09:00:00.000Z\",\n  \"previous\": {\n    \"version\": 1,\n    \"seen\": {\n      \"400000000001\": \"2026-11-25T09:00:00.000Z\"\n    },\n    \"observed_at\": \"2026-11-25T09:00:00.000Z\"\n  },\n  \"responses\": [\n    {\n      \"results\": [\n        {\n          \"listing_id\": \"400000000001\",\n          \"title\": \"Example portable music player — silver\",\n          \"url\": \"https://www.ebay.com/itm/400000000001\",\n          \"price\": {\n            \"amount\": \"110.00\",\n            \"currency\": \"USD\"\n          },\n          \"price_range\": null,\n          \"price_text\": \"$110.00\",\n          \"buying_format\": \"fixed_price\",\n          \"condition\": \"Used\",\n          \"shipping_text\": \"See listing\",\n          \"details\": []\n        },\n        {\n          \"listing_id\": \"400000000002\",\n          \"title\": \"Example portable music player — blue\",\n          \"url\": \"https://www.ebay.com/itm/400000000002\",\n          \"price\": {\n            \"amount\": \"125.00\",\n            \"currency\": \"USD\"\n          },\n          \"price_range\": null,\n          \"price_text\": \"$125.00\",\n          \"buying_format\": \"fixed_price\",\n          \"condition\": \"Used\",\n          \"shipping_text\": \"See listing\",\n          \"details\": []\n        }\n      ],\n      \"search_information\": {\n        \"results_returned\": 2,\n        \"has_more\": false\n      },\n      \"source\": {\n        \"http_status\": 200\n      }\n    }\n  ]\n};\nconst result = processEbay(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": "GET",
        "url": "={{ $json.url }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendQuery": true,
        "specifyQuery": "json",
        "jsonQuery": "={{ JSON.stringify($json.query || {}) }}",
        "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\nOne page of 60 results: at most 4 credits, minimum 1. A busy search can hide additions. Seen IDs persist when absent. Disappearance does not prove a sale or listing end.",
        "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 processEbay(responses, previous, config, now) {\n  const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);\n  const decimal = value => typeof value === 'string' && /^\\d+(?:\\.\\d+)?$/.test(value) && Number.isFinite(Number(value));\n  const text = value => typeof value === 'string' && value.trim() ? value.trim() : null;\n  const failed = value => !object(value) || value.error != null || Number(value.source?.http_status) >= 400;\n  const idValid = value => typeof value === 'string' && /^\\d+$/.test(value);\n  const kinds = ['ebay-rare-alerts', 'ebay-new-listings', 'ebay-seller-digest'];\n  if (!object(config) || !kinds.includes(config.kind)) throw new Error('Unknown eBay workflow kind.');\n  if (typeof now !== 'string' || !Number.isFinite(Date.parse(now))) throw new Error('A valid observation timestamp is required.');\n  for (const key of ['excludeTerms', 'blockedSellers']) {\n    if (!Array.isArray(config[key]) || config[key].some(value => typeof value !== 'string')) {\n      throw new Error(`${key} must be a list of strings.`);\n    }\n  }\n  if (!['all', 'buy_it_now', 'auction'].includes(config.buyingFormat)) throw new Error('Invalid buying format.');\n  if (!['any', 'new', 'used'].includes(config.condition)) throw new Error('Invalid condition.');\n  const hasCap = config.maxPrice !== '';\n  if (hasCap && !decimal(config.maxPrice)) throw new Error('maxPrice must be a plain decimal amount or an empty string.');\n  const currency = text(config.currency)?.toUpperCase();\n  if (hasCap && !/^[A-Z]{3}$/.test(currency ?? '')) throw new Error('Set a three-letter currency for the price limit.');\n  if (previous !== null && (!object(previous) || previous.version !== 1 || !object(previous.seen)\n    || Object.entries(previous.seen).some(([id, date]) => !idValid(id) || typeof date !== 'string' || !Number.isFinite(Date.parse(date))))) {\n    throw new Error('Invalid saved eBay baseline. Keep the existing state and inspect it before retrying.');\n  }\n\n  const search = Array.isArray(responses) ? responses[0] : null;\n  if (failed(search) || !Array.isArray(search.results) || !object(search.search_information)\n    || search.search_information.results_returned !== search.results.length\n    || typeof search.search_information.has_more !== 'boolean') {\n    throw new Error('Invalid or failed eBay search response. The saved baseline has not been changed.');\n  }\n  for (const listing of search.results) {\n    if (!object(listing) || !idValid(listing.listing_id) || !text(listing.url)) {\n      throw new Error('Malformed eBay listing in search results. The saved baseline has not been changed.');\n    }\n  }\n\n  const sellers = new Map();\n  for (const detail of responses.slice(1)) {\n    if (!failed(detail) && idValid(detail.listing_id) && text(detail.seller?.username)) {\n      sellers.set(detail.listing_id, detail.seller.username.trim());\n    }\n  }\n  const blocked = new Set(config.blockedSellers.map(value => value.trim().toLowerCase()).filter(Boolean));\n  const excluded = config.excludeTerms.map(value => value.trim().toLowerCase()).filter(Boolean);\n  const needsSeller = config.kind === 'ebay-seller-digest' || blocked.size > 0;\n  const baseline = previous === null;\n  const seen = { ...(previous?.seen ?? {}) };\n  const rows = [];\n  const warnings = [];\n  const processed = new Set();\n  let matching = 0;\n  let added = 0;\n  let uncertainPrices = 0;\n\n  for (const listing of search.results) {\n    const id = listing.listing_id;\n    if (processed.has(id)) continue;\n    processed.add(id);\n    const searchable = [listing.title, listing.subtitle, ...(Array.isArray(listing.details) ? listing.details : [])]\n      .filter(value => typeof value === 'string').join(' ').toLowerCase();\n    if (excluded.some(term => searchable.includes(term))) continue;\n    // Condition is sent to eBay by the HTTP node; category-specific display labels are not a second condition taxonomy.\n    const format = config.buyingFormat === 'buy_it_now' ? 'fixed_price' : config.buyingFormat;\n    if (format !== 'all' && listing.buying_format !== format) continue;\n\n    const money = !listing.price_range && object(listing.price) && decimal(listing.price.amount) ? listing.price : null;\n    const listedCurrency = text(money?.currency)?.toUpperCase() ?? null;\n    if (hasCap) {\n      if (!money || listedCurrency !== currency) {\n        uncertainPrices += 1;\n        continue;\n      }\n      if (Number(money.amount) > Number(config.maxPrice)) continue;\n    }\n    const seller = sellers.get(id) ?? null;\n    if (needsSeller && !seller) {\n      warnings.push(`Seller for listing ${id} could not be verified; skipped and left unseen so the next run can retry.`);\n      continue;\n    }\n    if (seller && blocked.has(seller.toLowerCase())) continue;\n    matching += 1;\n    if (Object.hasOwn(seen, id)) continue;\n    seen[id] = now;\n    added += 1;\n    if (baseline) continue;\n    rows.push({\n      id, title: text(listing.title), url: listing.url,\n      price: money?.amount ?? null, currency: listedCurrency,\n      price_text: text(listing.price_text), seller,\n      condition: text(listing.condition), buying_format: text(listing.buying_format),\n      image_url: text(listing.image_url), shipping_text: text(listing.shipping_text),\n      first_seen: now, observed_at: now, query: config.query,\n    });\n  }\n  if (uncertainPrices) warnings.push(`${uncertainPrices} listing(s) skipped because a single price in ${currency} was not available. No currency conversion was attempted.`);\n  if (search.search_information.has_more) warnings.push('More eBay results exist beyond this page; this run does not cover every matching listing.');\n  return {\n    state: { version: 1, seen, observed_at: now },\n    rows,\n    summary: baseline\n      ? `Baseline saved: ${added} matching listing(s). No alerts sent on the first run.`\n      : `${rows.length} newly seen matching listing(s); ${matching} matched in the returned search page.`,\n    warnings,\n  };\n}\nconst config = $('Settings').first().json;\nconst previous = $('Read saved state').first().json.previous;\nconst result = processEbay($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 = \"eBay new-since-last-check feed\" + ': ' + 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: \"ebay-new-listings.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
  }
}
