{
  "name": "ezGPT - PostgreSQL repeat customers in period",
  "active": false,
  "nodes": [
    {
      "name": "Manual Trigger",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "parameters": {},
      "id": "pgrepeat-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": "pgrepeat-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": "pgrepeat-2",
      "position": [
        480,
        260
      ]
    },
    {
      "name": "Repeat Customers",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "onError": "stopWorkflow",
      "parameters": {
        "resource": "database",
        "operation": "executeQuery",
        "query": "WITH 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), repeated AS (\n  SELECT customer_id, count(*) AS paid_orders, sum(total_kopecks) AS paid_kopecks,\n         min(order_day) AS first_order_day, max(order_day) AS last_order_day\n  FROM paid GROUP BY customer_id HAVING count(*) >= 2\n), visible AS (\n  SELECT * FROM repeated\n  ORDER BY paid_orders DESC, paid_kopecks DESC, customer_id COLLATE \"C\"\n  LIMIT 21\n)\nSELECT jsonb_build_object(\n  'paid_orders', (SELECT count(*) FROM paid),\n  'paid_kopecks', COALESCE((SELECT sum(total_kopecks) FROM paid),0),\n  'repeat_customers', (SELECT count(*) FROM repeated),\n  'repeat_orders', COALESCE((SELECT sum(paid_orders) FROM repeated),0),\n  'repeat_kopecks', COALESCE((SELECT sum(paid_kopecks) FROM repeated),0),\n  'customers', COALESCE((SELECT jsonb_agg(to_jsonb(v) ORDER BY paid_orders DESC, paid_kopecks DESC, customer_id COLLATE \"C\") FROM visible v),'[]'::jsonb)\n) AS summary;",
        "options": {
          "queryReplacement": "={{ [$json.from, $json.to] }}"
        }
      },
      "id": "pgrepeat-3",
      "position": [
        720,
        260
      ]
    },
    {
      "name": "Check Repeat 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 repeat 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 repeat envelope');\nconst s = envelope.summary;\nconst keys = ['paid_orders','paid_kopecks','repeat_customers','repeat_orders','repeat_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 repeat fields');\n}\nif (s.repeat_customers > 20) throw new Error('Report exceeds 20 customers; narrow period');\nif (s.customers.length !== s.repeat_customers || s.repeat_orders > s.paid_orders ||\n    s.repeat_kopecks > s.paid_kopecks || (s.paid_orders === 0 && s.paid_kopecks !== 0)) {\n  throw new Error('Invalid repeat 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','paid_orders','paid_kopecks','first_order_day','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 < 2 || !safe(row.paid_kopecks) ||\n      !day(row.first_order_day) || !day(row.last_order_day) || row.first_order_day < p.from ||\n      row.last_order_day >= p.to || row.first_order_day > row.last_order_day) throw new Error('Invalid customer row');\n  if (prev && (prev.paid_orders < row.paid_orders ||\n      (prev.paid_orders === row.paid_orders && (prev.paid_kopecks < row.paid_kopecks ||\n      (prev.paid_kopecks === row.paid_kopecks && prev.customer_id >= row.customer_id))))) throw new Error('Invalid 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.repeat_orders) || kopecks !== BigInt(s.repeat_kopecks)) throw new Error('Repeat sum mismatch');\nreturn [{json:{from:p.from,to:p.to,...s,verified:true,external_send:false}}];"
      },
      "id": "pgrepeat-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": "Repeat Customers",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Repeat Customers": {
      "main": [
        [
          {
            "node": "Check Repeat Customers",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {}
}
