{
  "name": "ezGPT - PostgreSQL latest order status",
  "active": false,
  "nodes": [
    {
      "name": "Manual Trigger",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "parameters": {},
      "id": "pglatest-0",
      "position": [
        0,
        260
      ]
    },
    {
      "name": "Sample Status",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return [{json:{\"status\":\"paid\"}}];"
      },
      "id": "pglatest-1",
      "position": [
        240,
        260
      ]
    },
    {
      "name": "Check Status",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const items = $input.all();\nif (items.length !== 1) throw new Error('Expected one status item');\nconst p = items[0].json;\nif (Object.keys(p).length !== 1 || typeof p.status !== 'string' ||\n    !['new','paid','cancelled'].includes(p.status)) throw new Error('Invalid order status');\nreturn [{json:{status:p.status}}];"
      },
      "id": "pglatest-2",
      "position": [
        480,
        260
      ]
    },
    {
      "name": "Latest Orders",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "onError": "stopWorkflow",
      "parameters": {
        "resource": "database",
        "operation": "executeQuery",
        "query": "WITH latest AS (\n  SELECT DISTINCT ON (order_id) order_id, event_version, status, note\n  FROM app.order_events\n  ORDER BY order_id, event_version DESC\n), selected AS (\n  SELECT * FROM latest WHERE status = $1\n  ORDER BY order_id\n  LIMIT 21\n)\nSELECT count(*)::integer AS found_count,\n       COALESCE(jsonb_agg(to_jsonb(s) ORDER BY s.order_id), '[]'::jsonb) AS rows\nFROM selected s;",
        "options": {
          "queryReplacement": "={{ [$json.status] }}"
        }
      },
      "id": "pglatest-3",
      "position": [
        720,
        260
      ]
    },
    {
      "name": "Check Latest",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const items = $input.all();\nif (items.length !== 1) throw new Error('Expected one latest envelope');\nconst d = items[0].json;\nconst wanted = $('Check Status').first().json.status;\nif (Object.keys(d).length !== 2 || !Number.isSafeInteger(d.found_count) ||\n    d.found_count < 0 || d.found_count > 20 || !Array.isArray(d.rows) ||\n    d.rows.length !== d.found_count) throw new Error('Invalid latest result or limit exceeded');\nlet last = '';\nfor (const r of d.rows) {\n  if (!r || Object.keys(r).length !== 4 || typeof r.order_id !== 'string' ||\n      !/^ORD-\\d{3}$/.test(r.order_id) || r.order_id <= last ||\n      !Number.isSafeInteger(r.event_version) || r.event_version < 1 || r.event_version > 1000 ||\n      r.status !== wanted || typeof r.note !== 'string' || !r.note.trim() || r.note.length > 100 ||\n      /[\\u0000-\\u001f\\u007f]/.test(r.note) ||\n      Buffer.from(r.note,'utf8').toString('utf8') !== r.note) {\n    throw new Error('Invalid or duplicated latest order');\n  }\n  last = r.order_id;\n}\nreturn [{json:{status:wanted,found:d.found_count,orders:d.rows,\n  verified:true,external_send:false}}];"
      },
      "id": "pglatest-4",
      "position": [
        960,
        260
      ]
    }
  ],
  "connections": {
    "Manual Trigger": {
      "main": [
        [
          {
            "node": "Sample Status",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Sample Status": {
      "main": [
        [
          {
            "node": "Check Status",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Status": {
      "main": [
        [
          {
            "node": "Latest Orders",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Latest Orders": {
      "main": [
        [
          {
            "node": "Check Latest",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {}
}
