{
  "name": "ezGPT - PostgreSQL catalogue comparison",
  "active": false,
  "nodes": [
    {
      "name": "Manual Trigger",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "parameters": {},
      "id": "pgcatalogdiff-0",
      "position": [
        0,
        260
      ]
    },
    {
      "name": "Sample Mode",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return [{json:{mode:\"differences\"}}];"
      },
      "id": "pgcatalogdiff-1",
      "position": [
        240,
        260
      ]
    },
    {
      "name": "Check Mode",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const items = $input.all();\nif (items.length !== 1) throw new Error('Expected one mode item');\nconst p = items[0].json;\nif (Object.keys(p).length !== 1 || typeof p.mode !== 'string' ||\n    !['differences','all'].includes(p.mode)) throw new Error('Invalid comparison mode');\nreturn [{json:{mode:p.mode}}];"
      },
      "id": "pgcatalogdiff-2",
      "position": [
        480,
        260
      ]
    },
    {
      "name": "Compare Catalogs",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "onError": "stopWorkflow",
      "parameters": {
        "resource": "database",
        "operation": "executeQuery",
        "query": "WITH compared AS (\n  SELECT COALESCE(c.sku, i.sku) AS sku,\n    CASE WHEN c.sku IS NULL THEN 'new'\n         WHEN i.sku IS NULL THEN 'missing'\n         WHEN ROW(c.product_name,c.price_kopecks) IS DISTINCT FROM\n              ROW(i.product_name,i.price_kopecks) THEN 'changed'\n         ELSE 'unchanged' END AS state,\n    CASE WHEN c.sku IS NULL THEN NULL ELSE\n      jsonb_build_object('product_name',c.product_name,'price_kopecks',c.price_kopecks) END AS before,\n    CASE WHEN i.sku IS NULL THEN NULL ELSE\n      jsonb_build_object('product_name',i.product_name,'price_kopecks',i.price_kopecks) END AS after\n  FROM app.catalog c FULL OUTER JOIN app.incoming i ON c.sku = i.sku\n), selected AS (\n  SELECT * FROM compared\n  WHERE $1 = 'all' OR state <> 'unchanged'\n  ORDER BY sku LIMIT 21\n)\nSELECT count(*)::integer AS found_count,\n       COALESCE(jsonb_agg(to_jsonb(s) ORDER BY s.sku), '[]'::jsonb) AS rows\nFROM selected s;",
        "options": {
          "queryReplacement": "={{ [$json.mode] }}"
        }
      },
      "id": "pgcatalogdiff-3",
      "position": [
        720,
        260
      ]
    },
    {
      "name": "Check Comparison",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const items = $input.all();\nif (items.length !== 1) throw new Error('Expected one comparison envelope');\nconst d = items[0].json;\nconst mode = $('Check Mode').first().json.mode;\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 comparison result or limit exceeded');\nfunction validSide(s) {\n  return s && Object.keys(s).length === 2 && typeof s.product_name === 'string' &&\n    !!s.product_name.trim() && s.product_name.length <= 100 &&\n    !/[\\u0000-\\u001f\\u007f]/.test(s.product_name) &&\n    Buffer.from(s.product_name,'utf8').toString('utf8') === s.product_name &&\n    Number.isSafeInteger(s.price_kopecks) && s.price_kopecks >= 0 && s.price_kopecks <= 100000000;\n}\nconst counts = {new:0,changed:0,missing:0,unchanged:0};\nlet last = '';\nfor (const r of d.rows) {\n  if (!r || Object.keys(r).length !== 4 || typeof r.sku !== 'string' ||\n      !/^SKU-\\d{3}$/.test(r.sku) || r.sku <= last ||\n      !(r.before === null || validSide(r.before)) || !(r.after === null || validSide(r.after)) ||\n      (r.before === null && r.after === null)) throw new Error('Invalid comparison row');\n  const state = r.before === null ? 'new' : r.after === null ? 'missing' :\n    (r.before.product_name !== r.after.product_name || r.before.price_kopecks !== r.after.price_kopecks) ?\n    'changed' : 'unchanged';\n  if (r.state !== state || (mode === 'differences' && state === 'unchanged')) {\n    throw new Error('Comparison state mismatch');\n  }\n  counts[state]++; last = r.sku;\n}\nreturn [{json:{mode,found:d.found_count,counts,products:d.rows,\n  verified:true,write_performed:false,external_send:false}}];"
      },
      "id": "pgcatalogdiff-4",
      "position": [
        960,
        260
      ]
    }
  ],
  "connections": {
    "Manual Trigger": {
      "main": [
        [
          {
            "node": "Sample Mode",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Sample Mode": {
      "main": [
        [
          {
            "node": "Check Mode",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Mode": {
      "main": [
        [
          {
            "node": "Compare Catalogs",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Compare Catalogs": {
      "main": [
        [
          {
            "node": "Check Comparison",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {}
}
