{
  "name": "QRlytics Global Product Distribution",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "qrlytics-product-scan",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "webhook-1",
      "name": "Product Scan Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [240, 300],
      "webhookId": "qrlytics-product"
    },
    {
      "parameters": {
        "jsCode": "// Parse QRlytics webhook for product distribution tracking\nconst scan = $input.first().json;\nconst now = new Date(scan.scanned_at || new Date().toISOString());\n\n// Extract product info from QR code\nconst productId = scan.qr_code_id || 'PRODUCT-001';\nconst productName = scan.qr_code_name || 'Product';\n\n// Geographic data from IP\nconst country = scan.location?.country || 'Unknown';\nconst city = scan.location?.city || 'Unknown';\nconst region = scan.location?.region || 'Unknown';\n\n// Continent mapping (simplified)\nconst continentMap = {\n  'US': 'North America', 'CA': 'North America', 'MX': 'North America',\n  'GB': 'Europe', 'DE': 'Europe', 'FR': 'Europe', 'IT': 'Europe', 'ES': 'Europe', 'CZ': 'Europe', 'PL': 'Europe',\n  'CN': 'Asia', 'JP': 'Asia', 'KR': 'Asia', 'IN': 'Asia',\n  'AU': 'Oceania', 'NZ': 'Oceania',\n  'BR': 'South America', 'AR': 'South America',\n  'ZA': 'Africa', 'EG': 'Africa', 'NG': 'Africa'\n};\nconst countryCode = scan.location?.country_code || '';\nconst continent = continentMap[countryCode] || 'Other';\n\nreturn [{\n  json: {\n    product_id: productId,\n    product_name: productName,\n    scanned_at: now.toISOString(),\n    date: now.toISOString().split('T')[0],\n    week: `W${Math.ceil((now.getDate()) / 7)}`,\n    month: now.toLocaleDateString('en-US', { month: 'long' }),\n    year: now.getFullYear(),\n    hour: now.getHours(),\n    country: country,\n    country_code: countryCode,\n    city: city,\n    region: region,\n    continent: continent,\n    device: scan.device?.type || 'Unknown',\n    device_os: scan.device?.os || 'Unknown',\n    is_unique: scan.is_unique || false\n  }\n}];"
      },
      "id": "code-1",
      "name": "Parse Product Scan",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [460, 300]
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "YOUR_GOOGLE_SHEET_ID",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Product Scans",
          "mode": "list"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Product ID": "={{ $json.product_id }}",
            "Product Name": "={{ $json.product_name }}",
            "Scanned At": "={{ $json.scanned_at }}",
            "Date": "={{ $json.date }}",
            "Month": "={{ $json.month }}",
            "Year": "={{ $json.year }}",
            "Country": "={{ $json.country }}",
            "Country Code": "={{ $json.country_code }}",
            "City": "={{ $json.city }}",
            "Continent": "={{ $json.continent }}",
            "Device": "={{ $json.device }}",
            "Device OS": "={{ $json.device_os }}",
            "Is Unique": "={{ $json.is_unique }}"
          }
        },
        "options": {}
      },
      "id": "sheets-1",
      "name": "Log to Google Sheets",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [680, 300],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "YOUR_CREDENTIAL_ID",
          "name": "Google Sheets"
        }
      }
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ JSON.stringify({ success: true, product: $('Parse Product Scan').item.json.product_name, country: $('Parse Product Scan').item.json.country }) }}",
        "options": {}
      },
      "id": "respond-1",
      "name": "Respond Success",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [900, 300]
    },
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "weeks",
              "weeksInterval": 1,
              "triggerAtDay": [1],
              "triggerAtHour": 9
            }
          ]
        }
      },
      "id": "schedule-1",
      "name": "Weekly Geo Report Trigger",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [240, 520]
    },
    {
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "YOUR_GOOGLE_SHEET_ID",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Product Scans",
          "mode": "list"
        },
        "options": {
          "range": "A:M"
        }
      },
      "id": "sheets-2",
      "name": "Read All Product Scans",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [460, 520],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "YOUR_CREDENTIAL_ID",
          "name": "Google Sheets"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// Generate weekly geographic distribution report\nconst items = $input.all();\nconst now = new Date();\nconst oneWeekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);\n\n// Filter last 7 days\nconst recentScans = items.filter(item => {\n  const scanDate = new Date(item.json['Scanned At']);\n  return scanDate >= oneWeekAgo;\n});\n\n// Group by country\nconst byCountry = {};\nrecentScans.forEach(scan => {\n  const country = scan.json['Country'] || 'Unknown';\n  if (!byCountry[country]) {\n    byCountry[country] = { total: 0, unique: 0, cities: new Set() };\n  }\n  byCountry[country].total++;\n  byCountry[country].cities.add(scan.json['City']);\n  if (scan.json['Is Unique'] === true || scan.json['Is Unique'] === 'true') {\n    byCountry[country].unique++;\n  }\n});\n\n// Group by continent\nconst byContinent = {};\nrecentScans.forEach(scan => {\n  const continent = scan.json['Continent'] || 'Other';\n  byContinent[continent] = (byContinent[continent] || 0) + 1;\n});\n\n// Sort countries by total scans\nconst sortedCountries = Object.entries(byCountry)\n  .sort((a, b) => b[1].total - a[1].total)\n  .map(([country, data]) => ({\n    country,\n    total: data.total,\n    unique: data.unique,\n    cities: data.cities.size\n  }));\n\nreturn [{\n  json: {\n    period: `${oneWeekAgo.toISOString().split('T')[0]} to ${now.toISOString().split('T')[0]}`,\n    total_scans: recentScans.length,\n    countries_reached: Object.keys(byCountry).length,\n    continent_breakdown: byContinent,\n    top_countries: sortedCountries.slice(0, 10),\n    top_country: sortedCountries[0]?.country || 'N/A',\n    top_country_scans: sortedCountries[0]?.total || 0\n  }\n}];"
      },
      "id": "code-2",
      "name": "Generate Geo Report",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [680, 520]
    },
    {
      "parameters": {
        "operation": "send",
        "toEmail": "sales@yourcompany.com",
        "subject": "=Weekly Global Product Distribution Report - {{ $json.period }}",
        "emailType": "html",
        "message": "=<h2>Global Product Distribution Report</h2>\n<p><strong>Period:</strong> {{ $json.period }}</p>\n<p><strong>Total Scans:</strong> {{ $json.total_scans }}</p>\n<p><strong>Countries Reached:</strong> {{ $json.countries_reached }}</p>\n<hr>\n<h3>Top Country: {{ $json.top_country }} ({{ $json.top_country_scans }} scans)</h3>\n<h3>By Continent</h3>\n<ul>\n{{ Object.entries($json.continent_breakdown).map(([c, n]) => `<li>${c}: ${n} scans</li>`).join('') }}\n</ul>\n<h3>Top 10 Countries</h3>\n<table border=\"1\" cellpadding=\"8\">\n<tr><th>Country</th><th>Total Scans</th><th>Unique</th><th>Cities</th></tr>\n{{ $json.top_countries.map(c => `<tr><td>${c.country}</td><td>${c.total}</td><td>${c.unique}</td><td>${c.cities}</td></tr>`).join('') }}\n</table>\n<hr>\n<p>Generated by QRlytics Global Product Tracking</p>",
        "options": {}
      },
      "id": "email-1",
      "name": "Send Geo Report",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [900, 520],
      "credentials": {
        "gmailOAuth2": {
          "id": "YOUR_CREDENTIAL_ID",
          "name": "Gmail"
        }
      }
    }
  ],
  "connections": {
    "Product Scan Webhook": {
      "main": [[{ "node": "Parse Product Scan", "type": "main", "index": 0 }]]
    },
    "Parse Product Scan": {
      "main": [[{ "node": "Log to Google Sheets", "type": "main", "index": 0 }]]
    },
    "Log to Google Sheets": {
      "main": [[{ "node": "Respond Success", "type": "main", "index": 0 }]]
    },
    "Weekly Geo Report Trigger": {
      "main": [[{ "node": "Read All Product Scans", "type": "main", "index": 0 }]]
    },
    "Read All Product Scans": {
      "main": [[{ "node": "Generate Geo Report", "type": "main", "index": 0 }]]
    },
    "Generate Geo Report": {
      "main": [[{ "node": "Send Geo Report", "type": "main", "index": 0 }]]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "meta": {
    "templateCredsSetupCompleted": false,
    "instanceId": "qrlytics-template"
  },
  "tags": [
    { "name": "QRlytics" },
    { "name": "Product" },
    { "name": "Geographic" }
  ]
}
