{
  "name": "ezGPT - PostgreSQL first paid order customers",
  "active": false,
  "nodes": [
    {
      "name": "Manual Trigger",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "parameters": {},
      "id": "pgfirst-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": "pgfirst-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": "pgfirst-2",
      "position": [
        480,
        260
      ]
    },
    {
      "name": "New Customers",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "onError": "stopWorkflow",
      "parameters": {
        "resource": "database",
        "operation": "executeQuery",
        "query": "WITH first_paid AS (\n  SELECT customer_id, min(order_day) AS first_paid_day\n  FROM app.orders WHERE status = 'paid' GROUP BY customer_id\n), period_paid AS (\n  SELECT customer_id, order_day, total_kopecks FROM app.orders\n  WHERE status = 'paid' AND order_day >= $1::date AND order_day < $2::date\n), newcomers AS (\n  SELECT p.customer_id, f.first_paid_day, count(*) AS paid_orders,\n         sum(p.total_kopecks) AS paid_kopecks, max(p.order_day) AS last_order_day\n  FROM period_paid p JOIN first_paid f ON f.customer_id = p.customer_id\n  WHERE f.first_paid_day >= $1::date AND f.first_paid_day < $2::date\n  GROUP BY p.customer_id, f.first_paid_day\n), visible AS (\n  SELECT * FROM newcomers ORDER BY first_paid_day, customer_id COLLATE \"C\" LIMIT 21\n)\nSELECT jsonb_build_object(\n  'paid_orders', (SELECT count(*) FROM period_paid),\n  'paid_kopecks', COALESCE((SELECT sum(total_kopecks) FROM period_paid),0),\n  'new_customers', (SELECT count(*) FROM newcomers),\n  'new_orders', COALESCE((SELECT sum(paid_orders) FROM newcomers),0),\n  'new_kopecks', COALESCE((SELECT sum(paid_kopecks) FROM newcomers),0),\n  'customers', COALESCE((SELECT jsonb_agg(to_jsonb(v) ORDER BY first_paid_day, customer_id COLLATE \"C\") FROM visible v),'[]'::jsonb)\n) AS summary;",
        "options": {
          "queryReplacement": "={{ [$json.from, $json.to] }}"
        }
      },
      "id": "pgfirst-3",
      "position": [
        720,
        260
      ]
    },
    {
      "name": "Check New Customers",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const items = $input.all();\nif (items.length !== 1) throw new Error('Expected one new customer item');\nconst envelope = items[0].json;\nconst exact = (o, keys) => o && typeof o === 'object' && !Array.isArray(o) &&\n  Object.keys(o).length === keys.length && keys.every(k => Object.hasOwn(o,k));\nif (!exact(envelope,['summary'])) throw new Error('Invalid new customer envelope');\nconst s = envelope.summary;\nconst keys = ['paid_orders','paid_kopecks','new_customers','new_orders','new_kopecks','customers'];\nconst safe = n => Number.isSafeInteger(n) && n >= 0;\nif (!exact(s,keys) || !keys.slice(0,5).every(k => safe(s[k])) || !Array.isArray(s.customers)) {\n  throw new Error('Invalid new customer fields');\n}\nif (s.new_customers > 20) throw new Error('Report exceeds 20 customers; narrow period');\nif (s.customers.length !== s.new_customers || s.new_orders > s.paid_orders ||\n    s.new_kopecks > s.paid_kopecks || (s.paid_orders === 0 && s.paid_kopecks !== 0)) {\n  throw new Error('Invalid new customer totals');\n}\nconst p = $('Check Period').first().json, ids = new Set();\nconst day = s => typeof s === 'string' && /^20\\d{2}-\\d{2}-\\d{2}$/.test(s) &&\n  Number.isFinite(Date.parse(s+'T00:00:00Z')) && new Date(s+'T00:00:00Z').toISOString().slice(0,10) === s;\nlet orders = 0n, kopecks = 0n, prev = null;\nfor (const row of s.customers) {\n  if (!exact(row,['customer_id','first_paid_day','paid_orders','paid_kopecks','last_order_day']) ||\n      typeof row.customer_id !== 'string' || !/^CUST-[0-9]{3}$/.test(row.customer_id) || ids.has(row.customer_id) ||\n      !safe(row.paid_orders) || row.paid_orders < 1 || !safe(row.paid_kopecks) ||\n      !day(row.first_paid_day) || !day(row.last_order_day) || row.first_paid_day < p.from ||\n      row.last_order_day >= p.to || row.first_paid_day > row.last_order_day) throw new Error('Invalid new customer row');\n  if (prev && (prev.first_paid_day > row.first_paid_day ||\n      (prev.first_paid_day === row.first_paid_day && prev.customer_id >= row.customer_id))) throw new Error('Invalid new customer order');\n  ids.add(row.customer_id); orders += BigInt(row.paid_orders); kopecks += BigInt(row.paid_kopecks); prev = row;\n}\nif (orders !== BigInt(s.new_orders) || kopecks !== BigInt(s.new_kopecks)) throw new Error('New customer sum mismatch');\nreturn [{json:{from:p.from,to:p.to,...s,verified:true,external_send:false}}];"
      },
      "id": "pgfirst-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": "New Customers",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "New Customers": {
      "main": [
        [
          {
            "node": "Check New Customers",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {}
}
