{
  "name": "ezGPT - PostgreSQL inactive paid-order customers as of date",
  "active": false,
  "nodes": [
    {
      "name": "Manual Trigger",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "parameters": {},
      "id": "pglastbuy-0",
      "position": [
        0,
        260
      ]
    },
    {
      "name": "Sample Settings",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return [{json:{as_of:'2026-10-20',min_days:15}}];"
      },
      "id": "pglastbuy-1",
      "position": [
        240,
        260
      ]
    },
    {
      "name": "Check Settings",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const items = $input.all();\nif (items.length !== 1) throw new Error('Expected one settings item');\nconst p = items[0].json;\nif (Object.keys(p).length !== 2 || !Object.hasOwn(p,'as_of') || !Object.hasOwn(p,'min_days')) {\n  throw new Error('Invalid settings fields');\n}\nif (typeof p.as_of !== 'string' || !/^20\\d{2}-\\d{2}-\\d{2}$/.test(p.as_of)) throw new Error('Invalid as_of date');\nconst n = Date.parse(p.as_of+'T00:00:00Z');\nif (!Number.isFinite(n) || new Date(n).toISOString().slice(0,10) !== p.as_of) throw new Error('Invalid as_of date');\nif (!Number.isInteger(p.min_days) || p.min_days < 1 || p.min_days > 365) throw new Error('min_days must be integer 1 to 365');\nreturn [{json:{as_of:p.as_of,min_days:p.min_days}}];"
      },
      "id": "pglastbuy-2",
      "position": [
        480,
        260
      ]
    },
    {
      "name": "Inactive Customers",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "onError": "stopWorkflow",
      "parameters": {
        "resource": "database",
        "operation": "executeQuery",
        "query": "WITH history AS (\n  SELECT customer_id, max(order_day) AS last_paid_day,\n         count(*) AS paid_orders, sum(total_kopecks) AS paid_kopecks\n  FROM app.orders WHERE status = 'paid' AND order_day < $1::date\n  GROUP BY customer_id\n), inactive AS (\n  SELECT *, $1::date - last_paid_day AS days_since\n  FROM history WHERE $1::date - last_paid_day >= $2::integer\n), visible AS (\n  SELECT * FROM inactive ORDER BY days_since DESC, customer_id COLLATE \"C\" LIMIT 21\n)\nSELECT jsonb_build_object(\n  'known_customers', (SELECT count(*) FROM history),\n  'inactive_customers', (SELECT count(*) FROM inactive),\n  'inactive_orders', COALESCE((SELECT sum(paid_orders) FROM inactive),0),\n  'inactive_kopecks', COALESCE((SELECT sum(paid_kopecks) FROM inactive),0),\n  'customers', COALESCE((SELECT jsonb_agg(to_jsonb(v) ORDER BY days_since DESC, customer_id COLLATE \"C\") FROM visible v),'[]'::jsonb)\n) AS summary;",
        "options": {
          "queryReplacement": "={{ [$json.as_of, $json.min_days] }}"
        }
      },
      "id": "pglastbuy-3",
      "position": [
        720,
        260
      ]
    },
    {
      "name": "Check Inactive 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 inactivity item');\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));\nconst envelope = items[0].json;\nif (!exact(envelope,['summary'])) throw new Error('Invalid inactivity envelope');\nconst s = envelope.summary, keys = ['known_customers','inactive_customers','inactive_orders','inactive_kopecks','customers'];\nconst safe = n => Number.isSafeInteger(n) && n >= 0;\nif (!exact(s,keys) || !keys.slice(0,4).every(k=>safe(s[k])) || !Array.isArray(s.customers)) throw new Error('Invalid inactivity fields');\nif (s.inactive_customers > 20) throw new Error('Report exceeds 20 customers; raise threshold');\nif (s.inactive_customers > s.known_customers || s.customers.length !== s.inactive_customers) throw new Error('Invalid inactivity totals');\nconst p = $('Check Settings').first().json;\nconst asOf = Date.parse(p.as_of+'T00:00:00Z'), ids = new Set();\nlet orders = 0n, kopecks = 0n, prev = null;\nfor (const row of s.customers) {\n  if (!exact(row,['customer_id','last_paid_day','paid_orders','paid_kopecks','days_since']) ||\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      !safe(row.days_since) || row.days_since < p.min_days || typeof row.last_paid_day !== 'string' ||\n      !/^20\\d{2}-\\d{2}-\\d{2}$/.test(row.last_paid_day)) throw new Error('Invalid inactivity row');\n  const last = Date.parse(row.last_paid_day+'T00:00:00Z');\n  if (!Number.isFinite(last) || new Date(last).toISOString().slice(0,10) !== row.last_paid_day ||\n      last >= asOf || (asOf-last)/86400000 !== row.days_since) throw new Error('Invalid days since');\n  if (prev && (prev.days_since < row.days_since ||\n      (prev.days_since === row.days_since && prev.customer_id >= row.customer_id))) throw new Error('Invalid inactivity order');\n  ids.add(row.customer_id); orders += BigInt(row.paid_orders); kopecks += BigInt(row.paid_kopecks); prev = row;\n}\nif (orders !== BigInt(s.inactive_orders) || kopecks !== BigInt(s.inactive_kopecks)) throw new Error('Inactivity sum mismatch');\nreturn [{json:{as_of:p.as_of,min_days:p.min_days,...s,verified:true,external_send:false}}];"
      },
      "id": "pglastbuy-4",
      "position": [
        960,
        260
      ]
    }
  ],
  "connections": {
    "Manual Trigger": {
      "main": [
        [
          {
            "node": "Sample Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Sample Settings": {
      "main": [
        [
          {
            "node": "Check Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Settings": {
      "main": [
        [
          {
            "node": "Inactive Customers",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Inactive Customers": {
      "main": [
        [
          {
            "node": "Check Inactive Customers",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {}
}
