{
  "name": "Fan a lead out to HubSpot, Pipedrive, and Sheets",
  "nodes": [
    {
      "parameters": {
        "content": "## Fan a lead out to HubSpot, Pipedrive, and Sheets\n\nPortfolio demo only. This workflow is an original example for demonstration. It is not client work and it does not represent a deployment for any customer.\n\nRun **Run demo** to execute the offline rules engine. The live branch is used only when the incoming item sets `demo` to false and the placeholder credentials have been replaced.",
        "height": 220,
        "width": 520,
        "color": 4
      },
      "id": "61dd17cc-e53c-4f66-bc92-c6ae32553990",
      "name": "Overview",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -40,
        -40
      ]
    },
    {
      "parameters": {},
      "id": "9c7e261c-9613-4705-a295-d1c89a4c1353",
      "name": "Run demo",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        40,
        280
      ],
      "notes": "CLI and the n8n editor start here. An empty manual run loads the bundled sample.",
      "notesInFlow": true
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "multi-crm-fanout",
        "authentication": "none",
        "responseMode": "lastNode",
        "responseData": "firstEntryJson",
        "options": {}
      },
      "id": "e881e666-45aa-4c7c-b1e0-d682db897ebd",
      "name": "Inbound webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        40,
        460
      ],
      "notes": "POST JSON to this path. Include demo:false only after credentials are connected.",
      "notesInFlow": true,
      "webhookId": "07ff4bf9-12f4-4f92-b105-4e80afc10e97"
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "const sample = {\n  \"demo\": true,\n  \"firstName\": \"Nora\",\n  \"lastName\": \"Rahman\",\n  \"email\": \"nora@brightline.example\",\n  \"company\": \"Brightline Studio\",\n  \"title\": \"Head of Operations\",\n  \"employees\": 42,\n  \"budget\": 8000,\n  \"source\": \"demo\",\n  \"utmSource\": \"linkedin\",\n  \"utmMedium\": \"cpc\",\n  \"utmCampaign\": \"ops-audit-q1\"\n};\nconst incoming = $input.first()?.json ?? {};\nconst provided = Object.keys(incoming).filter((key) => incoming[key] !== undefined && incoming[key] !== null && incoming[key] !== '');\nconst base = provided.length ? { ...sample, ...incoming } : { ...sample };\nconst flag = incoming.demo;\nbase.demo = !(flag === false || flag === 'false' || flag === 0 || flag === '0');\nreturn [{ json: base }];\n"
      },
      "id": "f1f16a24-759e-4b4f-bd21-ecf45d235caf",
      "name": "Normalize input",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        340,
        360
      ],
      "notes": "Merges the request over the bundled sample. demo stays true unless the caller explicitly turns it off.",
      "notesInFlow": true
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "const item = $input.first().json;\nconst produced = (() => {\n\nconst email = String(item.email || '').trim().toLowerCase();\nconst company = String(item.company || 'Unknown company').trim();\nconst source = String(item.source || 'unknown').trim().toLowerCase();\nconst employees = Number(item.employees || item.headcount || 0);\nconst budget = Number(item.budget || 0);\nconst title = String(item.title || '').toLowerCase();\nconst domain = email.includes('@') ? email.split('@')[1] : '';\nconst freeDomains = ['gmail.com', 'yahoo.com', 'hotmail.com', 'outlook.com'];\nconst intentSources = ['demo', 'pricing', 'referral'];\nlet score = 15;\nconst reasons = [];\nif (email && !freeDomains.includes(domain)) {\n  score += 15;\n  reasons.push('work email');\n} else if (email) {\n  reasons.push('free inbox, keep it in nurture');\n}\nif (employees >= 50) {\n  score += 20;\n  reasons.push('headcount at or above 50');\n} else if (employees >= 10) {\n  score += 10;\n  reasons.push('team of 10 or more');\n}\nif (intentSources.includes(source)) {\n  score += 25;\n  reasons.push('high-intent source: ' + source);\n}\nif (budget >= 5000) {\n  score += 15;\n  reasons.push('budget at or above 5000');\n}\nif (/(founder|owner|vp|head|director|ceo|cto|cmo)/.test(title)) {\n  score += 10;\n  reasons.push('buyer title');\n}\nscore = Math.max(0, Math.min(100, score));\nlet tier = score >= 75 ? 'sql' : score >= 45 ? 'mql' : 'nurture';\nconst known = Array.isArray(item.knownEmails) ? item.knownEmails.map((value) => String(value).toLowerCase()) : [];\nif (email && known.includes(email)) tier = 'duplicate';\nconst record = {\n  email,\n  firstName: item.firstName || '',\n  lastName: item.lastName || '',\n  company,\n  title: item.title || '',\n  source,\n  employees,\n  budget,\n  score,\n  tier,\n  reasons: reasons.join('; '),\n  dealName: company + ' \u2014 ' + tier.toUpperCase(),\n  amount: budget,\n  stage: tier === 'sql' ? 'appointmentscheduled' : 'qualifiedtobuy',\n};\nreturn {\n  summary: tier === 'duplicate'\n    ? email + ' is already on file. No new HubSpot and Pipedrive record is required.'\n    : company + ' (' + email + ') scored ' + score + ' and landed in ' + tier + ' for HubSpot and Pipedrive.',\n  route: tier,\n  record,\n  slackText: tier.toUpperCase() + ' lead ' + email + ' at ' + company + ' scored ' + score + '. ' + reasons[0],\n  actions: [\n    { app: 'HubSpot and Pipedrive', operation: 'upsert', payload: record },\n  ],\n};\n\n})();\nif (!produced || typeof produced.summary !== 'string' || !produced.summary.trim()) {\n  throw new Error('Apply rules must return a summary string');\n}\nreturn [{\n  json: {\n    ...item,\n    ...produced,\n    demo: item.demo !== false,\n  },\n}];\n"
      },
      "id": "2a9a1582-99b5-420f-be8f-eb9c9c40e1ee",
      "name": "Apply rules",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        620,
        360
      ],
      "notes": "Deterministic stand-in for the model or enrichment API. Replace or precede this with a live model node when you turn demo mode off.",
      "notesInFlow": true
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "b468c1c1-dad3-462e-9b79-fb80bb42031c",
              "leftValue": "={{ $json.demo }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "1c56cd79-055e-48f6-84bb-733687429615",
      "name": "Demo mode?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        900,
        360
      ],
      "notes": "True: package the offline result. False: run the credentialed apps.",
      "notesInFlow": true
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "const item = $input.first().json;\nreturn [{\n  json: {\n    demo: true,\n    status: 'demo_ready',\n    workflow: 'multi-crm-fanout',\n    summary: item.summary,\n    route: item.route ?? null,\n    record: item.record ?? {},\n    actions: item.actions ?? [],\n    slackText: item.slackText ?? item.summary,\n    notes: 'Demo mode did not call external apps. Send {\"demo\": false} after placeholder credentials are replaced.',\n  },\n}];\n"
      },
      "id": "cbd3efeb-6512-4b60-83f8-a9f29772efde",
      "name": "Package demo result",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1180,
        180
      ]
    },
    {
      "parameters": {
        "authentication": "oAuth2",
        "resource": "sheet",
        "operation": "append",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "YOUR_SPREADSHEET_ID"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Fanout log"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {},
          "matchingColumns": [],
          "schema": []
        },
        "options": {}
      },
      "id": "785f1d69-ec98-4c76-8b61-c46244e124a1",
      "name": "Append Fanout log",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1180,
        760
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "PLACEHOLDER_GOOGLESHEETSOAUTH2API",
          "name": "Google Sheets account"
        }
      }
    },
    {
      "parameters": {
        "authentication": "oAuth2",
        "resource": "contact",
        "operation": "upsert",
        "email": "={{ $json.record.email || $json.email }}",
        "additionalFields": {
          "firstName": "={{ $json.record.firstName || $json.firstName }}",
          "lastName": "={{ $json.record.lastName || $json.lastName }}",
          "companyName": "={{ $json.record.company || $json.company }}"
        }
      },
      "id": "a81ada08-0e79-4fbd-a28b-8f8fbee9e272",
      "name": "Upsert HubSpot contact",
      "type": "n8n-nodes-base.hubspot",
      "typeVersion": 2.2,
      "position": [
        1460,
        760
      ],
      "credentials": {
        "hubspotOAuth2Api": {
          "id": "PLACEHOLDER_HUBSPOTOAUTH2API",
          "name": "HubSpot account"
        }
      }
    },
    {
      "parameters": {
        "authentication": "apiToken",
        "resource": "person",
        "operation": "create",
        "title": "={{ $json.record.dealName || $json.record.company || $json.summary }}",
        "name": "={{ $json.record.fullName || $json.record.email || 'Lead' }}",
        "associateWith": "organization",
        "org_id": 0,
        "additionalFields": {}
      },
      "id": "36a9e71e-e631-4cec-9a18-91c080122c37",
      "name": "Create Pipedrive person",
      "type": "n8n-nodes-base.pipedrive",
      "typeVersion": 2,
      "position": [
        1740,
        760
      ],
      "credentials": {
        "pipedriveApi": {
          "id": "PLACEHOLDER_PIPEDRIVEAPI",
          "name": "Pipedrive account"
        }
      }
    },
    {
      "parameters": {
        "authentication": "apiToken",
        "resource": "deal",
        "operation": "create",
        "title": "={{ $json.record.dealName || $json.record.company || $json.summary }}",
        "name": "={{ $json.record.fullName || $json.record.email || 'Lead' }}",
        "associateWith": "organization",
        "org_id": 0,
        "additionalFields": {}
      },
      "id": "1b220f20-5149-4615-8f99-4281223a1d25",
      "name": "Create Pipedrive deal",
      "type": "n8n-nodes-base.pipedrive",
      "typeVersion": 2,
      "position": [
        2020,
        760
      ],
      "credentials": {
        "pipedriveApi": {
          "id": "PLACEHOLDER_PIPEDRIVEAPI",
          "name": "Pipedrive account"
        }
      }
    },
    {
      "parameters": {
        "content": "## Live path\n\nReplace every `PLACEHOLDER_*` credential, then POST the sample with `\"demo\": false`.\n\nThe nodes on this branch use the `record` and `actions` fields produced by Apply rules.",
        "height": 180,
        "width": 420,
        "color": 6
      },
      "id": "876c69f3-12af-4bfb-afc1-65514bc6e294",
      "name": "Live path",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1120,
        520
      ]
    }
  ],
  "connections": {
    "Run demo": {
      "main": [
        [
          {
            "node": "Normalize input",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Inbound webhook": {
      "main": [
        [
          {
            "node": "Normalize input",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Normalize input": {
      "main": [
        [
          {
            "node": "Apply rules",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Apply rules": {
      "main": [
        [
          {
            "node": "Demo mode?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Demo mode?": {
      "main": [
        [
          {
            "node": "Package demo result",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Append Fanout log",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Append Fanout log": {
      "main": [
        [
          {
            "node": "Upsert HubSpot contact",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Upsert HubSpot contact": {
      "main": [
        [
          {
            "node": "Create Pipedrive person",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Pipedrive person": {
      "main": [
        [
          {
            "node": "Create Pipedrive deal",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "staticData": null,
  "meta": {
    "templateCredsSetupCompleted": false,
    "description": "One scored lead is written to a sheet and to two CRMs. Useful when a studio is mid-migration and both systems must stay current."
  },
  "active": false
}
