{
  "name": "Generador Semanal de Reportes de Ventas",
  "nodes": [
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "weeks",
              "triggerAtDay": [1],
              "triggerAtHour": 7
            }
          ]
        }
      },
      "id": "d0e1f2a3-0010-4a01-b001-ef1234567001",
      "name": "Schedule Trigger - Lunes 7AM",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1,
      "position": [250, 300]
    },
    {
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": ""
        },
        "sheetName": {
          "__rl": true,
          "mode": "byName",
          "value": "Ventas"
        },
        "options": {
          "range": "A:H"
        }
      },
      "id": "d0e1f2a3-0010-4a02-b002-ef1234567002",
      "name": "Google Sheets - Leer Ventas",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4,
      "position": [500, 300],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "",
          "name": "Google Sheets account"
        }
      }
    },
    {
      "parameters": {
        "functionCode": "const now = new Date();\nconst oneWeekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);\nconst twoWeeksAgo = new Date(now.getTime() - 14 * 24 * 60 * 60 * 1000);\n\nconst thisWeekSales = items.filter(item => {\n  const saleDate = new Date(item.json.fecha);\n  return saleDate >= oneWeekAgo && saleDate <= now;\n});\n\nconst lastWeekSales = items.filter(item => {\n  const saleDate = new Date(item.json.fecha);\n  return saleDate >= twoWeeksAgo && saleDate < oneWeekAgo;\n});\n\nconst totalThisWeek = thisWeekSales.reduce((sum, item) => sum + parseFloat(item.json.monto || 0), 0);\nconst totalLastWeek = lastWeekSales.reduce((sum, item) => sum + parseFloat(item.json.monto || 0), 0);\nconst ticketPromedio = thisWeekSales.length > 0 ? totalThisWeek / thisWeekSales.length : 0;\nconst variacion = totalLastWeek > 0 ? ((totalThisWeek - totalLastWeek) / totalLastWeek * 100).toFixed(1) : 0;\n\n// Producto más vendido\nconst productCount = {};\nthisWeekSales.forEach(item => {\n  const prod = item.json.producto;\n  productCount[prod] = (productCount[prod] || 0) + 1;\n});\nconst topProduct = Object.keys(productCount).sort((a, b) => productCount[b] - productCount[a])[0] || 'N/A';\n\nreturn [{\n  json: {\n    totalVentas: totalThisWeek.toFixed(2),\n    numTransacciones: thisWeekSales.length,\n    ticketPromedio: ticketPromedio.toFixed(2),\n    variacionSemanal: variacion,\n    productoEstrella: topProduct,\n    totalSemanaAnterior: totalLastWeek.toFixed(2),\n    fechaReporte: now.toISOString().split('T')[0]\n  }\n}];"
      },
      "id": "d0e1f2a3-0010-4a03-b003-ef1234567003",
      "name": "Function - Calcular Métricas",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [750, 300]
    },
    {
      "parameters": {
        "values": {
          "string": [
            {
              "name": "htmlReport",
              "value": "=<html><body style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;'><div style='background: #1a73e8; color: white; padding: 20px; text-align: center;'><h1>📊 Reporte Semanal de Ventas</h1><p>{{ $json.fechaReporte }}</p></div><div style='padding: 20px;'><table style='width: 100%; border-collapse: collapse;'><tr style='background: #f8f9fa;'><td style='padding: 12px; border: 1px solid #dee2e6;'><strong>Total Ventas</strong></td><td style='padding: 12px; border: 1px solid #dee2e6; text-align: right; font-size: 20px; color: #1a73e8;'><strong>${{ $json.totalVentas }}</strong></td></tr><tr><td style='padding: 12px; border: 1px solid #dee2e6;'><strong>Transacciones</strong></td><td style='padding: 12px; border: 1px solid #dee2e6; text-align: right;'>{{ $json.numTransacciones }}</td></tr><tr style='background: #f8f9fa;'><td style='padding: 12px; border: 1px solid #dee2e6;'><strong>Ticket Promedio</strong></td><td style='padding: 12px; border: 1px solid #dee2e6; text-align: right;'>${{ $json.ticketPromedio }}</td></tr><tr><td style='padding: 12px; border: 1px solid #dee2e6;'><strong>Variación vs Semana Anterior</strong></td><td style='padding: 12px; border: 1px solid #dee2e6; text-align: right; color: {{ parseFloat($json.variacionSemanal) >= 0 ? \"green\" : \"red\" }};'>{{ $json.variacionSemanal }}%</td></tr><tr style='background: #f8f9fa;'><td style='padding: 12px; border: 1px solid #dee2e6;'><strong>Producto Estrella</strong></td><td style='padding: 12px; border: 1px solid #dee2e6; text-align: right;'>{{ $json.productoEstrella }}</td></tr></table></div></body></html>"
            }
          ]
        },
        "options": {}
      },
      "id": "d0e1f2a3-0010-4a04-b004-ef1234567004",
      "name": "Set - Generar HTML Reporte",
      "type": "n8n-nodes-base.set",
      "typeVersion": 2,
      "position": [1000, 300]
    },
    {
      "parameters": {
        "sendTo": "=dueño@negocio.com, ventas@negocio.com",
        "subject": "=📊 Reporte Semanal de Ventas | Total: ${{ $json.totalVentas }} | {{ $json.variacionSemanal }}% vs semana anterior",
        "emailType": "html",
        "message": "={{ $json.htmlReport }}",
        "options": {}
      },
      "id": "d0e1f2a3-0010-4a05-b005-ef1234567005",
      "name": "Gmail - Enviar Reporte",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2,
      "position": [1250, 300],
      "credentials": {
        "gmailOAuth2": {
          "id": "",
          "name": "Gmail account"
        }
      }
    }
  ],
  "connections": {
    "Schedule Trigger - Lunes 7AM": {
      "main": [
        [
          {
            "node": "Google Sheets - Leer Ventas",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Sheets - Leer Ventas": {
      "main": [
        [
          {
            "node": "Function - Calcular Métricas",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Function - Calcular Métricas": {
      "main": [
        [
          {
            "node": "Set - Generar HTML Reporte",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set - Generar HTML Reporte": {
      "main": [
        [
          {
            "node": "Gmail - Enviar Reporte",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "staticData": null,
  "tags": [
    {
      "name": "analytics"
    },
    {
      "name": "reportes"
    },
    {
      "name": "ventas"
    }
  ]
}
