{
  "name": "ezGPT - PostgreSQL cumulative daily sales",
  "active": false,
  "nodes": [
    {
      "name": "Manual Trigger",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "parameters": {},
      "id": "pgcumulative-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": "pgcumulative-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": "pgcumulative-2",
      "position": [
        480,
        260
      ]
    },
    {
      "name": "Cumulative Report",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "onError": "stopWorkflow",
      "parameters": {
        "resource": "database",
        "operation": "executeQuery",
        "query": "WITH days AS (\n  SELECT $1::date + n AS day\n  FROM generate_series(0, $2::date - $1::date - 1) AS n\n), totals AS (\n  SELECT order_day AS day, count(*)::integer AS paid_orders,\n         sum(total_kopecks) AS total_kopecks\n  FROM app.orders\n  WHERE status = 'paid' AND order_day >= $1::date AND order_day < $2::date\n  GROUP BY order_day\n), daily AS (\n  SELECT d.day, COALESCE(t.paid_orders,0) AS paid_orders,\n         COALESCE(t.total_kopecks,0) AS total_kopecks\n  FROM days d LEFT JOIN totals t ON t.day = d.day\n), running AS (\n  SELECT day, paid_orders, total_kopecks,\n         sum(total_kopecks) OVER (\n           ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW\n         ) AS cumulative_kopecks\n  FROM daily\n)\nSELECT count(*)::integer AS day_count,\n       COALESCE(jsonb_agg(to_jsonb(r) ORDER BY r.day), '[]'::jsonb) AS rows\nFROM running r;",
        "options": {
          "queryReplacement": "={{ [$json.from, $json.to] }}"
        }
      },
      "id": "pgcumulative-3",
      "position": [
        720,
        260
      ]
    },
    {
      "name": "Check Cumulative",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const items = $input.all();\nif (items.length !== 1) throw new Error('Expected one cumulative envelope');\nconst d = items[0].json;\nconst p = $('Check Period').first().json;\nconst first = Date.parse(p.from + 'T00:00:00Z');\nconst expected = (Date.parse(p.to + 'T00:00:00Z') - first) / 86400000;\nif (Object.keys(d).length !== 2 || d.day_count !== expected ||\n    !Array.isArray(d.rows) || d.rows.length !== expected) throw new Error('Cumulative coverage mismatch');\nlet orders = 0, sum = 0;\nfor (let i=0; i<d.rows.length; i++) {\n  const r = d.rows[i];\n  const day = new Date(first + i*86400000).toISOString().slice(0,10);\n  if (!r || Object.keys(r).length !== 4 || r.day !== day ||\n      !Number.isSafeInteger(r.paid_orders) || r.paid_orders < 0 ||\n      !Number.isSafeInteger(r.total_kopecks) || r.total_kopecks < 0 ||\n      !Number.isSafeInteger(r.cumulative_kopecks) || r.cumulative_kopecks < 0 ||\n      (r.paid_orders === 0 && r.total_kopecks !== 0)) throw new Error('Invalid cumulative row');\n  orders += r.paid_orders; sum += r.total_kopecks;\n  if (!Number.isSafeInteger(orders) || !Number.isSafeInteger(sum)) throw new Error('Unsafe report totals');\n  if (r.cumulative_kopecks !== sum) throw new Error('Cumulative total mismatch');\n}\nreturn [{json:{from:p.from,to:p.to,days:expected,paid_orders:orders,\n  total_kopecks:sum,report:d.rows,verified:true,external_send:false}}];"
      },
      "id": "pgcumulative-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": "Cumulative Report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Cumulative Report": {
      "main": [
        [
          {
            "node": "Check Cumulative",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {}
}
