{
  "name": "ezGPT - PostgreSQL top two sales positions per category",
  "active": false,
  "nodes": [
    {
      "name": "Manual Trigger",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "parameters": {},
      "id": "pgtop-0",
      "position": [
        0,
        260
      ]
    },
    {
      "name": "Sample Period",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return [{json:{\"from\":\"2026-10-01\",\"to\":\"2026-10-06\"}}];"
      },
      "id": "pgtop-1",
      "position": [
        240,
        260
      ]
    },
    {
      "name": "Check Period",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const items = $input.all();\nif (items.length !== 1) throw new Error('Expected one period item');\nconst p = items[0].json;\nfunction day(s) {\n  if (typeof s !== 'string' || !/^20\\d{2}-\\d{2}-\\d{2}$/.test(s)) throw new Error('Invalid date');\n  const n = Date.parse(s + 'T00:00:00Z');\n  if (!Number.isFinite(n) || new Date(n).toISOString().slice(0,10) !== s) throw new Error('Invalid date');\n  return n;\n}\nif (Object.keys(p).length !== 2 || !Object.hasOwn(p,'from') || !Object.hasOwn(p,'to')) {\n  throw new Error('Invalid period fields');\n}\nconst count = (day(p.to) - day(p.from)) / 86400000;\nif (!Number.isInteger(count) || count < 1 || count > 31) throw new Error('Period must contain 1 to 31 days');\nreturn [{json:{from:p.from,to:p.to}}];"
      },
      "id": "pgtop-2",
      "position": [
        480,
        260
      ]
    },
    {
      "name": "Top Products",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "onError": "stopWorkflow",
      "parameters": {
        "resource": "database",
        "operation": "executeQuery",
        "query": "WITH totals AS (\n  SELECT category, sku, sum(units) AS units,\n         sum(total_kopecks) AS total_kopecks\n  FROM app.sales\n  WHERE status = 'paid' AND order_day >= $1::date AND order_day < $2::date\n  GROUP BY category, sku\n), ranked AS (\n  SELECT *, dense_rank() OVER (\n    PARTITION BY category ORDER BY total_kopecks DESC\n  ) AS sales_rank\n  FROM totals\n), chosen AS (\n  SELECT category, sku, units, total_kopecks, sales_rank\n  FROM ranked WHERE sales_rank <= 2\n)\nSELECT count(*)::integer AS row_count,\n       COALESCE(jsonb_agg(to_jsonb(r)\n         ORDER BY r.category, r.total_kopecks DESC, r.sku), '[]'::jsonb) AS rows\nFROM chosen r;",
        "options": {
          "queryReplacement": "={{ [$json.from, $json.to] }}"
        }
      },
      "id": "pgtop-3",
      "position": [
        720,
        260
      ]
    },
    {
      "name": "Check Top",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const items = $input.all();\nif (items.length !== 1) throw new Error('Expected one top envelope');\nconst d = items[0].json;\nif (Object.keys(d).length !== 2 || !Number.isSafeInteger(d.row_count) ||\n    !Array.isArray(d.rows) || d.row_count !== d.rows.length) throw new Error('Top envelope mismatch');\nconst seen = new Set();\nlet last = null, rank = 0, units = 0, sum = 0;\nfor (const r of d.rows) {\n  if (!r || Object.keys(r).length !== 5 ||\n      typeof r.category !== 'string' || !/^CAT-[A-Z]$/.test(r.category) ||\n      typeof r.sku !== 'string' || !/^SKU-[A-Z]$/.test(r.sku) ||\n      !Number.isSafeInteger(r.units) || r.units < 1 ||\n      !Number.isSafeInteger(r.total_kopecks) || r.total_kopecks < 0 ||\n      !Number.isSafeInteger(r.sales_rank)) throw new Error('Invalid top row');\n  const key = r.category + ':' + r.sku;\n  if (seen.has(key)) throw new Error('Duplicate product');\n  seen.add(key);\n  if (!last || r.category !== last.category) {\n    if (last && r.category <= last.category) throw new Error('Category order mismatch');\n    rank = 1;\n  } else {\n    if (r.total_kopecks > last.total_kopecks ||\n        (r.total_kopecks === last.total_kopecks && r.sku <= last.sku)) throw new Error('Product order mismatch');\n    if (r.total_kopecks < last.total_kopecks) rank++;\n  }\n  if (r.sales_rank !== rank || rank > 2) throw new Error('Dense rank mismatch');\n  units += r.units; sum += r.total_kopecks;\n  if (!Number.isSafeInteger(units) || !Number.isSafeInteger(sum)) throw new Error('Unsafe selected totals');\n  last = r;\n}\nconst p = $('Check Period').first().json;\nreturn [{json:{from:p.from,to:p.to,positions_per_category:2,products:d.row_count,\n  selected_units:units,selected_kopecks:sum,report:d.rows,verified:true,external_send:false}}];"
      },
      "id": "pgtop-4",
      "position": [
        960,
        260
      ]
    }
  ],
  "connections": {
    "Manual Trigger": {
      "main": [
        [
          {
            "node": "Sample Period",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Sample Period": {
      "main": [
        [
          {
            "node": "Check Period",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Period": {
      "main": [
        [
          {
            "node": "Top Products",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Top Products": {
      "main": [
        [
          {
            "node": "Check Top",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {}
}
