{
  "name": "ezGPT - PostgreSQL LEFT JOIN",
  "active": false,
  "nodes": [
    {
      "name": "Manual Trigger",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "parameters": {},
      "id": "pgjoin-0",
      "position": [
        0,
        260
      ]
    },
    {
      "name": "Sample Status",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return [{ json: {\"status\":\"paid\"} }];"
      },
      "id": "pgjoin-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    !['paid', 'new'].includes(p.status)) throw new Error('Invalid order status');\nreturn [{ json: { status: p.status } }];"
      },
      "id": "pgjoin-2",
      "position": [
        480,
        260
      ]
    },
    {
      "name": "Join Orders",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "onError": "stopWorkflow",
      "parameters": {
        "resource": "database",
        "operation": "executeQuery",
        "query": "WITH selected_orders AS (\n  SELECT order_id, customer_id, total_kopecks\n  FROM app.orders\n  WHERE status = $1\n  ORDER BY order_id\n  LIMIT 21\n), joined AS (\n  SELECT o.order_id, o.customer_id,\n         c.customer_id AS matched_customer_id,\n         c.customer_name, o.total_kopecks\n  FROM selected_orders o\n  LEFT JOIN app.customers c ON c.customer_id = o.customer_id\n)\nSELECT (SELECT count(*)::integer FROM selected_orders) AS source_count,\n       COALESCE(jsonb_agg(to_jsonb(j) ORDER BY j.order_id), '[]'::jsonb) AS rows\nFROM joined j;",
        "options": {
          "queryReplacement": "={{ [$json.status] }}"
        }
      },
      "id": "pgjoin-3",
      "position": [
        720,
        260
      ]
    },
    {
      "name": "Check Join",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const items = $input.all();\nif (items.length !== 1) throw new Error('Expected one join envelope');\nconst data = items[0].json;\nif (Object.keys(data).length !== 2 || !Number.isSafeInteger(data.source_count) ||\n    data.source_count < 0 || data.source_count > 20 || !Array.isArray(data.rows) ||\n    data.rows.length !== data.source_count) throw new Error('Join count mismatch or limit exceeded');\nconst keys = ['order_id', 'customer_id', 'matched_customer_id', 'customer_name', 'total_kopecks'];\nlet last = '';\nfor (const r of data.rows) {\n  if (!r || Object.keys(r).length !== keys.length || !keys.every(k => Object.hasOwn(r, k)) ||\n      typeof r.order_id !== 'string' || !/^ORD-\\d{3}$/.test(r.order_id) || r.order_id <= last ||\n      !Number.isSafeInteger(r.total_kopecks) || r.total_kopecks < 0 || r.total_kopecks > 100000000) {\n    throw new Error('Invalid or duplicated order row');\n  }\n  if (r.customer_id === null) {\n    if (r.matched_customer_id !== null || r.customer_name !== null) throw new Error('Unexpected joined customer');\n  } else if (typeof r.customer_id !== 'string' || !/^CUST-\\d{3}$/.test(r.customer_id) ||\n      r.matched_customer_id !== r.customer_id || typeof r.customer_name !== 'string' ||\n      !r.customer_name.trim() || r.customer_name.length > 100 ||\n      /[\\u0000-\\u001f\\u007f]/.test(r.customer_name) ||\n      Buffer.from(r.customer_name, 'utf8').toString('utf8') !== r.customer_name) {\n    throw new Error('Customer join mismatch');\n  }\n  last = r.order_id;\n}\nreturn [{ json: { status: $('Check Status').first().json.status,\n  source_count: data.source_count, found: data.rows.length,\n  without_customer: data.rows.filter(r => r.customer_id === null).length,\n  total_kopecks: data.rows.reduce((n, r) => n + r.total_kopecks, 0),\n  orders: data.rows.map(({ order_id, customer_id, customer_name, total_kopecks }) =>\n    ({ order_id, customer_id, customer_name, total_kopecks })),\n  verified: true, external_send: false } }];"
      },
      "id": "pgjoin-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": "Join Orders",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Join Orders": {
      "main": [
        [
          {
            "node": "Check Join",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {}
}
