{
  "name": "QRlytics Heritage Interest Monitoring",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "qrlytics-heritage-scan",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "webhook-1",
      "name": "Heritage Scan Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [240, 300],
      "webhookId": "qrlytics-heritage"
    },
    {
      "parameters": {
        "jsCode": "// Parse QRlytics webhook data for heritage site\nconst scan = $input.first().json;\nconst now = new Date(scan.scanned_at || new Date().toISOString());\n\n// Determine season\nconst month = now.getMonth() + 1;\nlet season;\nif (month >= 3 && month <= 5) season = 'Spring';\nelse if (month >= 6 && month <= 8) season = 'Summer';\nelse if (month >= 9 && month <= 11) season = 'Autumn';\nelse season = 'Winter';\n\n// Extract attraction info from QR code name/metadata\nconst attractionId = scan.qr_code_id || 'ATTRACTION-001';\nconst attractionName = scan.qr_code_name || 'Unknown Attraction';\n\nreturn [{\n  json: {\n    attraction_id: attractionId,\n    attraction_name: attractionName,\n    scanned_at: now.toISOString(),\n    date: now.toISOString().split('T')[0],\n    month: now.toLocaleDateString('en-US', { month: 'long' }),\n    month_number: month,\n    season: season,\n    year: now.getFullYear(),\n    day_of_week: now.toLocaleDateString('en-US', { weekday: 'long' }),\n    hour: now.getHours(),\n    location: scan.location ? `${scan.location.city}, ${scan.location.country}` : 'On-site',\n    visitor_country: scan.location?.country || 'Unknown',\n    device: scan.device?.type || 'Unknown',\n    is_unique: scan.is_unique || false\n  }\n}];"
      },
      "id": "code-1",
      "name": "Parse Heritage 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": "Heritage Scans",
          "mode": "list"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Attraction ID": "={{ $json.attraction_id }}",
            "Attraction Name": "={{ $json.attraction_name }}",
            "Scanned At": "={{ $json.scanned_at }}",
            "Date": "={{ $json.date }}",
            "Month": "={{ $json.month }}",
            "Season": "={{ $json.season }}",
            "Year": "={{ $json.year }}",
            "Day of Week": "={{ $json.day_of_week }}",
            "Visitor Country": "={{ $json.visitor_country }}",
            "Device": "={{ $json.device }}",
            "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, attraction: $('Parse Heritage Scan').item.json.attraction_name, season: $('Parse Heritage Scan').item.json.season }) }}",
        "options": {}
      },
      "id": "respond-1",
      "name": "Respond Success",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [900, 300]
    },
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "months",
              "triggerAtDayOfMonth": 1,
              "triggerAtHour": 9
            }
          ]
        }
      },
      "id": "schedule-1",
      "name": "Monthly 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": "Heritage Scans",
          "mode": "list"
        },
        "options": {
          "range": "A:K"
        }
      },
      "id": "sheets-2",
      "name": "Read All Scans",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [460, 520],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "YOUR_CREDENTIAL_ID",
          "name": "Google Sheets"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// Generate monthly seasonal report\nconst items = $input.all();\nconst now = new Date();\nconst lastMonth = now.getMonth() === 0 ? 12 : now.getMonth();\nconst lastMonthName = new Date(now.getFullYear(), lastMonth - 1, 1).toLocaleDateString('en-US', { month: 'long' });\n\n// Filter last month's data\nconst lastMonthData = items.filter(item => {\n  const scanDate = new Date(item.json['Scanned At']);\n  return scanDate.getMonth() + 1 === lastMonth;\n});\n\n// Group by attraction\nconst byAttraction = {};\nlastMonthData.forEach(scan => {\n  const name = scan.json['Attraction Name'];\n  if (!byAttraction[name]) {\n    byAttraction[name] = { total: 0, unique: 0 };\n  }\n  byAttraction[name].total++;\n  if (scan.json['Is Unique'] === true || scan.json['Is Unique'] === 'true') {\n    byAttraction[name].unique++;\n  }\n});\n\n// Sort by total scans\nconst sorted = Object.entries(byAttraction)\n  .sort((a, b) => b[1].total - a[1].total);\n\n// Get season from first item\nconst season = lastMonthData[0]?.json['Season'] || 'Unknown';\n\nreturn [{\n  json: {\n    report_month: lastMonthName,\n    report_year: now.getFullYear(),\n    season: season,\n    total_scans: lastMonthData.length,\n    attractions_ranking: sorted.slice(0, 10).map(([name, data]) => ({\n      name,\n      total: data.total,\n      unique: data.unique\n    })),\n    top_attraction: sorted[0] ? sorted[0][0] : 'N/A',\n    top_attraction_scans: sorted[0] ? sorted[0][1].total : 0\n  }\n}];"
      },
      "id": "code-2",
      "name": "Generate Monthly Report",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [680, 520]
    },
    {
      "parameters": {
        "operation": "send",
        "toEmail": "management@yoursite.com",
        "subject": "=Monthly Heritage Interest Report - {{ $json.report_month }} {{ $json.report_year }}",
        "emailType": "html",
        "message": "=<h2>Heritage Interest Report - {{ $json.report_month }} {{ $json.report_year }}</h2>\n<p><strong>Season:</strong> {{ $json.season }}</p>\n<p><strong>Total Scans:</strong> {{ $json.total_scans }}</p>\n<hr>\n<h3>Top Attractions</h3>\n<table border=\"1\" cellpadding=\"8\">\n<tr><th>Rank</th><th>Attraction</th><th>Total Scans</th><th>Unique Visitors</th></tr>\n{{ $json.attractions_ranking.map((a, i) => `<tr><td>${i+1}</td><td>${a.name}</td><td>${a.total}</td><td>${a.unique}</td></tr>`).join('') }}\n</table>\n<hr>\n<p>Generated by QRlytics Heritage Monitoring</p>",
        "options": {}
      },
      "id": "email-1",
      "name": "Send Monthly Report",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [900, 520],
      "credentials": {
        "gmailOAuth2": {
          "id": "YOUR_CREDENTIAL_ID",
          "name": "Gmail"
        }
      }
    }
  ],
  "connections": {
    "Heritage Scan Webhook": {
      "main": [[{ "node": "Parse Heritage Scan", "type": "main", "index": 0 }]]
    },
    "Parse Heritage Scan": {
      "main": [[{ "node": "Log to Google Sheets", "type": "main", "index": 0 }]]
    },
    "Log to Google Sheets": {
      "main": [[{ "node": "Respond Success", "type": "main", "index": 0 }]]
    },
    "Monthly Report Trigger": {
      "main": [[{ "node": "Read All Scans", "type": "main", "index": 0 }]]
    },
    "Read All Scans": {
      "main": [[{ "node": "Generate Monthly Report", "type": "main", "index": 0 }]]
    },
    "Generate Monthly Report": {
      "main": [[{ "node": "Send Monthly Report", "type": "main", "index": 0 }]]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "meta": {
    "templateCredsSetupCompleted": false,
    "instanceId": "qrlytics-template"
  },
  "tags": [
    { "name": "QRlytics" },
    { "name": "Heritage" },
    { "name": "Seasonal Analytics" }
  ]
}
