{
  "name": "ezGPT - PostgreSQL duplicate report",
  "active": false,
  "nodes": [
    {
      "name": "Manual Trigger",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "parameters": {},
      "id": "pgduplicates-0",
      "position": [
        0,
        260
      ]
    },
    {
      "name": "Sample Settings",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return [{ json: {\"min_count\":2} }];"
      },
      "id": "pgduplicates-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 !== 1 || !Number.isSafeInteger(p.min_count) ||\n    p.min_count < 2 || p.min_count > 5) throw new Error('Invalid minimum count');\nreturn [{ json: { min_count: p.min_count } }];"
      },
      "id": "pgduplicates-2",
      "position": [
        480,
        260
      ]
    },
    {
      "name": "Find Duplicates",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "onError": "stopWorkflow",
      "parameters": {
        "resource": "database",
        "operation": "executeQuery",
        "query": "WITH prepared AS (\n  SELECT contact_id, contact_name, email,\n         NULLIF(lower(btrim(email)), '') AS email_key\n  FROM app.contacts\n), duplicates AS (\n  SELECT email_key, count(*)::integer AS contact_count,\n         jsonb_agg(jsonb_build_object('contact_id', contact_id,\n           'contact_name', contact_name, 'email', email)\n           ORDER BY contact_id) AS contacts\n  FROM prepared\n  WHERE email_key IS NOT NULL\n  GROUP BY email_key\n  HAVING count(*) >= $1\n), selected_groups AS (\n  SELECT * FROM duplicates ORDER BY email_key LIMIT 21\n)\nSELECT (SELECT count(*)::integer FROM prepared) AS source_count,\n       (SELECT count(*)::integer FROM prepared WHERE email_key IS NULL) AS ignored_count,\n       (SELECT count(*)::integer FROM duplicates) AS group_count,\n       COALESCE(jsonb_agg(to_jsonb(g) ORDER BY g.email_key), '[]'::jsonb) AS groups\nFROM selected_groups g;",
        "options": {
          "queryReplacement": "={{ [$json.min_count] }}"
        }
      },
      "id": "pgduplicates-3",
      "position": [
        720,
        260
      ]
    },
    {
      "name": "Check Report",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const items = $input.all();\nif (items.length !== 1) throw new Error('Expected one report envelope');\nconst d = items[0].json;\nconst minimum = $('Check Settings').first().json.min_count;\nif (Object.keys(d).length !== 4 || !Number.isSafeInteger(d.source_count) ||\n    d.source_count < 0 || d.source_count > 100 || !Number.isSafeInteger(d.ignored_count) ||\n    d.ignored_count < 0 || d.ignored_count > d.source_count ||\n    !Number.isSafeInteger(d.group_count) || d.group_count < 0 || d.group_count > 20 ||\n    !Array.isArray(d.groups) || d.groups.length !== d.group_count) {\n  throw new Error('Invalid report count or demo limit exceeded');\n}\nconst seen = new Set();\nlet members = 0;\nfor (const g of d.groups) {\n  if (!g || Object.keys(g).length !== 3 || typeof g.email_key !== 'string' ||\n      !g.email_key || !/^[ -~]+$/.test(g.email_key) || g.email_key.length > 100 ||\n      g.email_key !== g.email_key.replace(/^ +| +$/g, '').toLowerCase() ||\n      !Number.isSafeInteger(g.contact_count) || g.contact_count < minimum ||\n      !Array.isArray(g.contacts) || g.contacts.length !== g.contact_count ||\n      d.groups.filter(x => x.email_key === g.email_key).length !== 1) {\n    throw new Error('Invalid duplicate group');\n  }\n  let last = '';\n  for (const c of g.contacts) {\n    if (!c || Object.keys(c).length !== 3 || typeof c.contact_id !== 'string' ||\n        !/^CT-\\d{3}$/.test(c.contact_id) || c.contact_id <= last || seen.has(c.contact_id) ||\n        typeof c.contact_name !== 'string' || !c.contact_name.trim() || c.contact_name.length > 100 ||\n        /[\\u0000-\\u001f\\u007f]/.test(c.contact_name) ||\n        Buffer.from(c.contact_name, 'utf8').toString('utf8') !== c.contact_name ||\n        typeof c.email !== 'string' || c.email.length > 100 || !/^[ -~]+$/.test(c.email) ||\n        c.email.replace(/^ +| +$/g, '').toLowerCase() !== g.email_key) {\n      throw new Error('Invalid group member');\n    }\n    seen.add(c.contact_id); last = c.contact_id; members++;\n  }\n}\nif (members > d.source_count - d.ignored_count) throw new Error('Member total exceeds source');\nreturn [{ json: { min_count: minimum, source_count: d.source_count,\n  ignored_count: d.ignored_count, duplicate_groups: d.group_count,\n  contacts_in_groups: members, extra_records: members - d.group_count,\n  groups: d.groups, verified: true, deleted: false, external_send: false } }];"
      },
      "id": "pgduplicates-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": "Find Duplicates",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Find Duplicates": {
      "main": [
        [
          {
            "node": "Check Report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {}
}
