{
  "name": "ezGPT - CSV to PostgreSQL Transaction",
  "active": false,
  "nodes": [
    {
      "name": "Manual Trigger",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "parameters": {},
      "id": "pgcsv-0",
      "position": [
        0,
        260
      ]
    },
    {
      "name": "Read CSV File",
      "type": "n8n-nodes-base.readWriteFile",
      "typeVersion": 1,
      "alwaysOutputData": true,
      "parameters": {
        "operation": "read",
        "fileSelector": "/files/input/orders.csv",
        "options": {
          "dataPropertyName": "csv"
        }
      },
      "id": "pgcsv-1",
      "position": [
        240,
        260
      ]
    },
    {
      "name": "Check File",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const items = $input.all();\nif (items.length !== 1 || Object.keys(items[0].binary ?? {}).join('|') !== 'csv') {\n  throw new Error('Expected one CSV file');\n}\nconst item = items[0];\nconst bytes = await this.helpers.getBinaryDataBuffer(0, 'csv');\nconst text = bytes.toString('utf8');\nif (item.binary.csv.fileName !== 'orders.csv' || bytes.length < 1 || bytes.length > 8192 ||\n    !Buffer.from(text, 'utf8').equals(bytes) || text.includes('\\u0000')) {\n  throw new Error('Expected small UTF-8 orders.csv');\n}\nconst header = text.replace(/^\\uFEFF/, '').split(/\\r?\\n/, 1)[0];\nif (header !== 'order_id,customer_name,total_kopecks') {\n  throw new Error('Unexpected CSV header');\n}\nreturn [{ json: {}, binary: item.binary }];"
      },
      "id": "pgcsv-2",
      "position": [
        480,
        260
      ]
    },
    {
      "name": "Parse CSV",
      "type": "n8n-nodes-base.extractFromFile",
      "typeVersion": 1.1,
      "alwaysOutputData": true,
      "parameters": {
        "operation": "csv",
        "binaryPropertyName": "csv",
        "options": {
          "headerRow": true,
          "delimiter": ",",
          "encoding": "utf8",
          "enableBOM": true,
          "includeEmptyCells": true,
          "relaxQuotes": false
        }
      },
      "id": "pgcsv-3",
      "position": [
        720,
        260
      ]
    },
    {
      "name": "Check Rows",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const rows = $input.all().map(i => i.json);\nif (rows.length < 1 || rows.length > 20) throw new Error('Expected 1 to 20 rows');\nconst keys = ['order_id', 'customer_name', 'total_kopecks'];\nconst ids = new Set();\nconst batch = [];\nfor (const r of rows) {\n  if (Object.keys(r).length !== 3 || !keys.every(k => typeof r[k] === 'string') ||\n      !/^ORD-\\d{3}$/.test(r.order_id) || ids.has(r.order_id) ||\n      !r.customer_name.trim() || r.customer_name.length > 100 ||\n      /[\\u0000-\\u001f\\u007f]/.test(r.customer_name) ||\n      !/^(0|[1-9]\\d{0,8})$/.test(r.total_kopecks)) {\n    throw new Error('Invalid CSV row or duplicate ID');\n  }\n  const amount = Number(r.total_kopecks);\n  if (!Number.isSafeInteger(amount) || amount > 100000000) {\n    throw new Error('Amount out of range');\n  }\n  ids.add(r.order_id);\n  batch.push({ json: { order_id: r.order_id, customer_name: r.customer_name,\n    total_kopecks: amount } });\n}\nreturn batch;"
      },
      "id": "pgcsv-4",
      "position": [
        960,
        260
      ]
    },
    {
      "name": "Insert Batch",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "onError": "stopWorkflow",
      "parameters": {
        "resource": "database",
        "operation": "executeQuery",
        "query": "INSERT INTO app.orders (order_id, customer_name, total_kopecks)\nVALUES ($1, $2, $3)\nRETURNING order_id, customer_name, total_kopecks;",
        "options": {
          "queryBatching": "transaction",
          "queryReplacement": "={{ [$json.order_id, $json.customer_name, $json.total_kopecks] }}"
        }
      },
      "id": "pgcsv-5",
      "position": [
        1200,
        260
      ]
    },
    {
      "name": "Verify Insert",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const expected = $('Check Rows').all().map(i => i.json);\nconst actual = $input.all().map(i => i.json);\nif (actual.length !== expected.length) throw new Error('Inserted row count mismatch');\nconst byId = new Map(expected.map(r => [r.order_id, r]));\nconst seen = new Set();\nconst keys = ['order_id', 'customer_name', 'total_kopecks'];\nfor (const r of actual) {\n  const source = byId.get(r.order_id);\n  if (!source || seen.has(r.order_id) || Object.keys(r).length !== 3 ||\n      keys.some(k => r[k] !== source[k])) throw new Error('Inserted row mismatch');\n  seen.add(r.order_id);\n}\nreturn [{ json: { source_file: 'orders.csv', inserted_count: actual.length,\n  order_ids: [...seen].sort(),\n  total_kopecks: actual.reduce((n, r) => n + r.total_kopecks, 0),\n  verified: true, external_send: false } }];"
      },
      "id": "pgcsv-6",
      "position": [
        1440,
        260
      ]
    }
  ],
  "connections": {
    "Manual Trigger": {
      "main": [
        [
          {
            "node": "Read CSV File",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read CSV File": {
      "main": [
        [
          {
            "node": "Check File",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check File": {
      "main": [
        [
          {
            "node": "Parse CSV",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse CSV": {
      "main": [
        [
          {
            "node": "Check Rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Rows": {
      "main": [
        [
          {
            "node": "Insert Batch",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Insert Batch": {
      "main": [
        [
          {
            "node": "Verify Insert",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {}
}
