{
  "name": "BNBCalc: owner lead to proposal draft",
  "nodes": [
    {
      "parameters": {
        "content": "## BNBCalc: owner lead to proposal draft\n\nEach new owner lead runs **one BNBCalc Cohost analysis** of the address through the BNBCalc API, then leaves **one Gmail draft**: the proposal, addressed to the owner, or a note to you when something needs a look. **It never sends anything.**\n\n**Cost per run:** $0.20 for each new address (one created report; the workflow turns on neither the AI Underwriter nor AI expense estimates). Skipped repeats and incomplete leads cost nothing, and BNBCalc doesn't bill a request it turns down. A request that times out can still bill, though.\n\n**Rules it follows**\n- One create call per lead, and **no retries**. Retry On Fail stays off on the BNBCalc node, because a retried create makes a second report and bills twice.\n- An address sent in the last 30 days is skipped, unless the lead says to run it again.\n- The BNBCalc node waits up to 300 seconds. On a timeout, a 504 or any other error it stops, keeps the address on hold and drafts a note telling you to check API Usage under Settings → API & MCP in your BNBCalc dashboard before you run it again.\n- Your API key lives in the **BNBCalc API key** credential (Header Auth, name `x-bnbcalc-api-key`). Never paste it into a node.\n\n**Set up:** connect the three credentials (Lead form login, BNBCalc API key, Gmail), fill in **Your settings**, then publish the workflow. The 30-day memory only works in published runs, so every test run bills and nothing is remembered.\n\nThe report is saved to your BNBCalc account with a shareable link. Analyses made through the API don't show in your Properties list, so keep the link from the draft.\n",
        "height": 700,
        "width": 520,
        "color": 4
      },
      "id": "a1000000-0000-4000-8000-000000000001",
      "name": "Read me",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -620,
        -520
      ]
    },
    {
      "parameters": {
        "authentication": "basicAuth",
        "formTitle": "New owner lead",
        "formDescription": "Runs one BNBCalc Cohost analysis of the address ($0.20) and leaves a proposal in your Gmail drafts. Nothing is sent to the owner.",
        "formFields": {
          "values": [
            {
              "fieldLabel": "Owner name",
              "placeholder": "e.g. Jordan Lee",
              "requiredField": true
            },
            {
              "fieldLabel": "Owner email",
              "fieldType": "email",
              "placeholder": "e.g. jordan@example.com",
              "requiredField": true
            },
            {
              "fieldLabel": "Property address",
              "placeholder": "Number, street, city, state and ZIP",
              "requiredField": true
            },
            {
              "fieldLabel": "Bedrooms",
              "fieldType": "number",
              "requiredField": true
            },
            {
              "fieldLabel": "Bathrooms",
              "fieldType": "number",
              "requiredField": true
            },
            {
              "fieldLabel": "Sleeps",
              "fieldType": "number",
              "placeholder": "How many guests",
              "requiredField": true
            },
            {
              "fieldLabel": "Your commission %",
              "fieldType": "number",
              "placeholder": "0 to 50, e.g. 20",
              "requiredField": true
            },
            {
              "fieldLabel": "Run it again if this address was analyzed in the last 30 days?",
              "fieldType": "dropdown",
              "fieldOptions": {
                "values": [
                  {
                    "option": "No"
                  },
                  {
                    "option": "Yes, I've checked API Usage"
                  }
                ]
              }
            }
          ]
        },
        "responseMode": "onReceived",
        "options": {
          "appendAttribution": false,
          "ignoreBots": true,
          "respondWithOptions": {
            "values": {
              "respondWith": "text",
              "formSubmittedText": "Got it. Check your Gmail drafts in a minute: you'll find the proposal, or a note saying what needs a look."
            }
          }
        }
      },
      "id": "a1000000-0000-4000-8000-000000000002",
      "name": "New owner lead",
      "type": "n8n-nodes-base.formTrigger",
      "typeVersion": 2.2,
      "position": [
        0,
        0
      ],
      "webhookId": "b5c1a7e2-3f4d-4e8a-9b61-0c2d7e9f4a11",
      "credentials": {
        "httpBasicAuth": {
          "id": "",
          "name": "Lead form login"
        }
      }
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "s-name",
              "name": "yourName",
              "value": "",
              "type": "string"
            },
            {
              "id": "s-company",
              "name": "yourCompany",
              "value": "",
              "type": "string"
            },
            {
              "id": "s-api",
              "name": "apiBaseUrl",
              "value": "https://atlas.bnbcalc.com",
              "type": "string"
            },
            {
              "id": "s-hold",
              "name": "holdDays",
              "value": 30,
              "type": "number"
            }
          ]
        },
        "includeOtherFields": true,
        "options": {}
      },
      "id": "a1000000-0000-4000-8000-000000000003",
      "name": "Your settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        220,
        0
      ]
    },
    {
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "// Checks one lead before anything costs money, and builds the key used to\n// spot an address that was already sent to BNBCalc. The form's labels work as\n// field names, and so do the short names (ownerName, ownerEmail, address,\n// bedrooms, bathrooms, sleeps, commission, runAgain), so a webhook or CRM\n// trigger can send those instead.\nconst f = $json;\nconst get = (short, label) => {\n  for (const key of [short, label]) {\n    const value = f[key];\n    if (value !== undefined && value !== null && String(value).trim() !== '') return value;\n  }\n  return '';\n};\nconst num = (value) => (value === '' ? NaN : Number(value));\n\nconst lead = {\n  ownerName: String(get('ownerName', 'Owner name')).trim(),\n  ownerEmail: String(get('ownerEmail', 'Owner email')).trim(),\n  address: String(get('address', 'Property address')).replace(/\\s+/g, ' ').trim(),\n  bedrooms: num(get('bedrooms', 'Bedrooms')),\n  bathrooms: num(get('bathrooms', 'Bathrooms')),\n  sleeps: num(get('sleeps', 'Sleeps')),\n  commission: num(get('commission', 'Your commission %')),\n  runAgain: /^y/i.test(String(get('runAgain', 'Run it again if this address was analyzed in the last 30 days?'))),\n};\n\nconst problems = [];\nif (!lead.ownerName) problems.push(\"the owner's name\");\nif (!/^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$/.test(lead.ownerEmail)) problems.push(\"the owner's email address\");\nif (!/\\d/.test(lead.address) || lead.address.split(/[\\s,]+/).filter(Boolean).length < 4) {\n  problems.push('the full property address (number, street, city, state and ZIP)');\n}\nif (!(lead.bedrooms > 0 && lead.bedrooms <= 50)) problems.push('the number of bedrooms');\nif (!(lead.bathrooms > 0 && lead.bathrooms <= 50)) problems.push('the number of bathrooms');\nif (!(lead.sleeps > 0 && lead.sleeps <= 100)) problems.push('how many guests it sleeps');\n// BNBCalc's Cohost commission runs from 0 to 50%, so the check does too.\nif (!(lead.commission >= 0 && lead.commission <= 50)) problems.push('your commission as a number from 0 to 50');\n\n// The same address typed two ways (\"Drive\" and \"Dr.\", \"Florida\" and \"FL\")\n// should count as one, so the key drops case, punctuation and spelling choices.\nconst STATES = { alabama: 'al', alaska: 'ak', arizona: 'az', arkansas: 'ar', california: 'ca',\n  colorado: 'co', connecticut: 'ct', delaware: 'de', 'district of columbia': 'dc', florida: 'fl',\n  georgia: 'ga', hawaii: 'hi', idaho: 'id', illinois: 'il', indiana: 'in', iowa: 'ia', kansas: 'ks',\n  kentucky: 'ky', louisiana: 'la', maine: 'me', maryland: 'md', massachusetts: 'ma', michigan: 'mi',\n  minnesota: 'mn', mississippi: 'ms', missouri: 'mo', montana: 'mt', nebraska: 'ne', nevada: 'nv',\n  'new hampshire': 'nh', 'new jersey': 'nj', 'new mexico': 'nm', 'new york': 'ny',\n  'north carolina': 'nc', 'north dakota': 'nd', ohio: 'oh', oklahoma: 'ok', oregon: 'or',\n  pennsylvania: 'pa', 'rhode island': 'ri', 'south carolina': 'sc', 'south dakota': 'sd',\n  tennessee: 'tn', texas: 'tx', utah: 'ut', vermont: 'vt', virginia: 'va', washington: 'wa',\n  'west virginia': 'wv', wisconsin: 'wi', wyoming: 'wy' };\nconst WORDS = { street: 'st', avenue: 'ave', drive: 'dr', road: 'rd', boulevard: 'blvd', lane: 'ln',\n  court: 'ct', place: 'pl', terrace: 'ter', circle: 'cir', parkway: 'pkwy', highway: 'hwy',\n  trail: 'trl', way: 'way', north: 'n', south: 's', east: 'e', west: 'w', northeast: 'ne',\n  northwest: 'nw', southeast: 'se', southwest: 'sw', apartment: 'apt', suite: 'ste', '#': 'unit' };\nlet key = lead.address.toLowerCase()\n  .replace(/[\\s,]+(usa|us|united states(?: of america)?)\\s*$/, '')\n  .replace(/\\b(\\d{5})-\\d{4}\\b/g, '$1');\nfor (const name of Object.keys(STATES).sort((a, b) => b.length - a.length)) {\n  key = key.replace(new RegExp('\\\\b' + name + '\\\\b(?=[\\\\s,]+\\\\d{5}|\\\\s*$)'), STATES[name]);\n}\nconst addressKey = key.replace(/[.,]/g, ' ').replace(/#/g, ' # ')\n  .split(/\\s+/).filter(Boolean).map((word) => WORDS[word] || word).join(' ');\n\nconst settings = {\n  yourName: String(f.yourName || '').trim(),\n  yourCompany: String(f.yourCompany || '').trim(),\n  apiBaseUrl: String(f.apiBaseUrl || 'https://atlas.bnbcalc.com').replace(/\\/+$/, ''),\n  holdDays: Number(f.holdDays) > 0 ? Number(f.holdDays) : 30,\n};\n\nreturn { json: { lead, valid: problems.length === 0, problems, addressKey, settings } };\n"
      },
      "id": "a1000000-0000-4000-8000-000000000004",
      "name": "Check the lead",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        440,
        0
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "a1000000-0000-4000-8000-000000000005-c1",
              "leftValue": "={{ $json.valid }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "a1000000-0000-4000-8000-000000000005",
      "name": "Lead complete?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        660,
        0
      ]
    },
    {
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "// BNBCalc's create call isn't idempotent: sending the same address twice\n// makes two reports and bills twice. So this node remembers every address it\n// sends for 30 days, in the workflow's static data, and skips a repeat.\n// n8n only saves static data on published runs, so test runs don't remember.\nconst store = $getWorkflowStaticData('global');\nstore.addresses = store.addresses || {};\nconst holdMs = $json.settings.holdDays * 24 * 60 * 60 * 1000;\nconst now = Date.now();\nfor (const [key, entry] of Object.entries(store.addresses)) {\n  if (now - entry.at > holdMs) delete store.addresses[key];\n}\n\nconst seen = store.addresses[$json.addressKey];\nif (seen && !$json.lead.runAgain) {\n  return { json: { ...$json, duplicate: true, seen } };\n}\n\n// Recorded before the call goes out, so a request that never comes back\n// still holds the address.\nstore.addresses[$json.addressKey] = { at: now, status: 'sent', address: $json.lead.address };\nreturn { json: { ...$json, duplicate: false } };\n"
      },
      "id": "a1000000-0000-4000-8000-000000000006",
      "name": "Skip recent addresses",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        880,
        -100
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "a1000000-0000-4000-8000-000000000007-c1",
              "leftValue": "={{ !$json.duplicate }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "a1000000-0000-4000-8000-000000000007",
      "name": "New address?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1100,
        -100
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $json.settings.apiBaseUrl }}/v1/external/analysis/create/cohost",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ fullAddress: $json.lead.address, bedrooms: $json.lead.bedrooms, bathrooms: $json.lead.bathrooms, accomodates: $json.lead.sleeps, cohostCommissionPercentage: $json.lead.commission }) }}",
        "options": {
          "timeout": 300000
        }
      },
      "id": "a1000000-0000-4000-8000-000000000008",
      "name": "Create Cohost analysis",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1320,
        -200
      ],
      "credentials": {
        "httpHeaderAuth": {
          "id": "",
          "name": "BNBCalc API key"
        }
      },
      "retryOnFail": false,
      "onError": "continueErrorOutput",
      "notes": "One create per lead. Retry On Fail must stay off: a retried create bills twice."
    },
    {
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "// BNBCalc has saved and billed the report by now, so record it first.\nconst sent = $('Skip recent addresses').item.json;\nconst data = ($json && $json.data) || {};\nconst store = $getWorkflowStaticData('global');\nstore.addresses = store.addresses || {};\nstore.addresses[sent.addressKey] = {\n  at: Date.now(), status: 'created', address: sent.lead.address, reportUrl: data.url || '',\n};\n\n// Figures as the Cohost analysis shows them for one year: Revenue, Cleaning\n// (cleaning and supplies), Cohost commission and Owner payout. The response\n// carries all but Cleaning, which is what's left between them.\nconst revenue = Number(data.yearOneRevenueUSD);\nconst commission = Number(data.yearOneCohostCommissionUSD);\nconst payout = Number(data.yearOneCohostReturnUSD);\nconst figures = {\n  revenue,\n  cleaning: revenue - commission - payout,\n  commission,\n  payout,\n  avgDailyRate: Number(data.ratePerNightUSD),\n  occupancy: Number(data.occupancyRatePercentage),\n};\nconst usable = Boolean(data.url) && revenue > 0 && payout > 0 && Number.isFinite(commission);\n\nreturn {\n  json: {\n    ...sent,\n    reportUrl: data.url || '',\n    analysisId: data._id || '',\n    figures,\n    usable,\n    warnings: $json.warnings || [],\n  },\n};\n"
      },
      "id": "a1000000-0000-4000-8000-000000000009",
      "name": "Read the report",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1540,
        -300
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "a1000000-0000-4000-8000-000000000010-c1",
              "leftValue": "={{ $json.usable }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "a1000000-0000-4000-8000-000000000010",
      "name": "Revenue came back?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1760,
        -300
      ]
    },
    {
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "// Writes the proposal as a draft to the owner. Nothing here sends it.\n// The API returns the starting estimate BNBCalc saved when it created the\n// analysis, while the report opens on its Select comps estimate, so the two can\n// differ. Every figure therefore goes in as a bracketed placeholder: a draft\n// nobody edited looks unfinished, and the report's own figure replaces each one.\nconst { lead, settings, figures, reportUrl } = $json;\nconst money = (n) => '$' + String(Math.round(n)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\nconst fill = (value, label) => `[${value}, BNBCalc's starting estimate: replace with the report's ${label}]`;\nconst firstName = lead.ownerName.split(/\\s+/)[0];\nconst street = lead.address.split(',')[0];\nconst signature = [settings.yourName || '[Your name]', settings.yourCompany].filter(Boolean);\n\nconst body = [\n  \"[Before you send: open the report, replace every figure in square brackets with the report's own figure, then delete this line.]\",\n  '',\n  `Hi ${firstName},`,\n  '',\n  `Thanks for telling me about ${lead.address}. I ran it through BNBCalc, which estimates what a home could earn from comparable short-term rentals nearby, and here's its first-year projection with me managing it:`,\n  '',\n  `Revenue: ${fill(money(figures.revenue), 'Revenue')}`,\n  `Cleaning: ${fill(money(figures.cleaning), 'Cleaning')}`,\n  `Cohost commission (${lead.commission}%): ${fill(money(figures.commission), 'Cohost commission')}`,\n  `Owner payout: ${fill(money(figures.payout), 'Owner payout')}`,\n  `Average daily rate: ${fill(money(figures.avgDailyRate), 'Avg Daily Rate')}`,\n  `Occupancy: ${fill(Math.round(figures.occupancy) + '%', 'Occupancy')}`,\n  '',\n  'The owner payout is the revenue minus cleaning, supplies and my commission. You can open the full report, with the comparable homes behind the estimate, here:',\n  reportUrl,\n  '',\n  \"Keep in mind it's a projection, not a guarantee. What the home earns will depend on how it's set up and run and on the market, and the owner payout comes before the booking platform's fee and your own costs, like utilities, insurance, property tax and any mortgage.\",\n  '',\n  'Would you have time for a quick call this week to walk through it?',\n  '',\n  ...signature,\n].join('\\n');\n\nreturn {\n  json: {\n    ...$json,\n    draft: { kind: 'proposal', to: lead.ownerEmail, subject: `What ${street} could earn as a short-term rental`, body },\n  },\n};\n"
      },
      "id": "a1000000-0000-4000-8000-000000000011",
      "name": "Write the proposal",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1980,
        -400
      ]
    },
    {
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "// A note to you, with no recipient. The report exists and was billed.\nconst { lead, reportUrl, figures } = $json;\nconst money = (n) => (Number.isFinite(n)\n  ? (n < 0 ? '-$' : '$') + String(Math.round(Math.abs(n))).replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',') : 'none');\nconst body = [\n  `BNBCalc created the report for ${lead.address}, so this run was billed ($0.20), but it came back without a revenue estimate and owner payout to put in a proposal (Revenue ${money(figures.revenue)}, Owner payout ${money(figures.payout)}). No proposal was written.`,\n  '',\n  reportUrl ? `Open the report to see what BNBCalc found: ${reportUrl}` : 'No report link came back, so check API Usage under Settings → API & MCP in your BNBCalc dashboard.',\n  '',\n  \"The address is held for 30 days, so submitting it again won't bill twice.\",\n].join('\\n');\nreturn {\n  json: {\n    ...$json,\n    draft: { kind: 'note', to: '', subject: `BNBCalc lead needs a look: ${lead.address.split(',')[0]}`, body },\n  },\n};\n"
      },
      "id": "a1000000-0000-4000-8000-000000000012",
      "name": "Note: report needs a look",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1980,
        -220
      ]
    },
    {
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "// The BNBCalc request failed. BNBCalc doesn't bill a request it turns down\n// (a 4xx), but a request that times out or fails on the server can still\n// finish and bill, so the workflow never retries. It writes you a note instead.\nconst sent = $('Skip recent addresses').item.json;\nconst e = $json.error || $json;\nconst message = String(e.description || e.message || '');\nlet code = null;\nfor (const c of [e.httpCode, e.status, e.statusCode, e.cause && e.cause.status, (message.match(/^(\\d{3}) - /) || [])[1]]) {\n  if (/^\\d{3}$/.test(String(c))) { code = Number(c); break; }\n}\n// n8n reports an HTTP error as `402 - \"{...BNBCalc's JSON...}\"`; keep BNBCalc's own message.\nlet detail = message.replace(/^\\d{3} - /, '');\nfor (let i = 0; i < 2; i++) {\n  try {\n    const parsed = JSON.parse(detail);\n    if (typeof parsed === 'string') { detail = parsed; continue; }\n    if (parsed && parsed.message) detail = [].concat(parsed.message).join('; ');\n  } catch (err) { /* plain text */ }\n  break;\n}\ndetail = detail.replace(/<[^>]+>/g, ' ').replace(/\\s+/g, ' ').trim().slice(0, 300).replace(/[.\\s]+$/, '') || 'no details came back';\nif (!code && (e.code === 'ECONNABORTED' || /timeout/i.test(detail))) detail = `n8n's timeout ran out (${detail})`;\n\nconst notBilled = {\n  400: \"BNBCalc couldn't analyze this lead. Check the address and the numbers, then submit it again.\",\n  401: \"BNBCalc didn't accept the API key. Check the key in the n8n credential named BNBCalc API key, or regenerate it under Settings → API & MCP in your BNBCalc dashboard.\",\n  402: 'BNBCalc says API access needs an active API subscription. Subscribe under Settings → API & MCP in your BNBCalc dashboard, then submit the lead again.',\n  403: \"BNBCalc says the API key is suspended or inactive. Check it under Settings → API & MCP in your BNBCalc dashboard.\",\n  404: \"BNBCalc didn't recognize the web address the workflow called, so check the apiBaseUrl in the Your settings node. It should be https://atlas.bnbcalc.com.\",\n  429: 'BNBCalc asked the workflow to slow down. Wait a minute, then submit the lead again.',\n};\n// These mean the request never reached BNBCalc, so it can't have billed either.\nconst neverReached = ['ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN'].includes(e.code);\nconst reason = notBilled[code] || (neverReached\n  ? `n8n couldn't reach BNBCalc at ${sent.settings.apiBaseUrl}. Check the apiBaseUrl in the Your settings node (it should be https://atlas.bnbcalc.com) and your connection, then submit the lead again.`\n  : null);\n\nconst store = $getWorkflowStaticData('global');\nstore.addresses = store.addresses || {};\nconst lines = [`The BNBCalc request for ${sent.lead.address} stopped with ${code ? 'error ' + code : 'no answer'}: ${detail}.`, ''];\nlet subject;\nif (reason) {\n  // A turned-down request isn't billed, so the address is freed for a fixed lead.\n  delete store.addresses[sent.addressKey];\n  lines.push(reason, '', 'Nothing was billed.');\n  subject = `BNBCalc lead not analyzed: ${sent.lead.address.split(',')[0]}`;\n} else {\n  store.addresses[sent.addressKey] = { at: Date.now(), status: 'may_have_billed', address: sent.lead.address, code };\n  lines.push(\n    'BNBCalc may still have created the report and billed it ($0.20), so the workflow stopped and won\\'t retry.',\n    '',\n    'Before you run this address again, open your BNBCalc dashboard, go to Settings → API & MCP and check API Usage: if Successful requests went up, the report was billed.',\n    '',\n    `The workflow holds this address for ${sent.settings.holdDays} days so a second submission can't bill twice. If you've checked and it wasn't billed, submit the lead again with \"Run it again\" set to Yes.`,\n  );\n  subject = `Check BNBCalc before you run this again: ${sent.lead.address.split(',')[0]}`;\n}\nlines.push('', 'BNBCalc API settings: https://www.bnbcalc.com/dashboard/settings/api-access?utm_source=toolkit&utm_medium=automation&utm_content=n8n-owner-lead-to-proposal');\nreturn { json: { ...sent, error: { code, detail }, draft: { kind: 'note', to: '', subject, body: lines.join('\\n') } } };\n"
      },
      "id": "a1000000-0000-4000-8000-000000000013",
      "name": "Note: BNBCalc request failed",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1540,
        -100
      ]
    },
    {
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "// A note to you, with no recipient. This lead wasn't sent to BNBCalc.\nconst { lead, seen } = $json;\nconst when = new Date(seen.at).toISOString().slice(0, 10);\nconst typed = seen.address !== lead.address ? ` (this lead typed it as ${lead.address})` : '';\nconst lines = [\n  `${seen.address} was already sent to BNBCalc on ${when}${typed}, so the workflow skipped it and nothing was billed this time.`,\n  '',\n];\nif (seen.reportUrl) lines.push(`Here's the report from that run: ${seen.reportUrl}`, '');\nif (seen.status !== 'created') {\n  lines.push(\"That run didn't come back with a report, so check API Usage under Settings → API & MCP in your BNBCalc dashboard before you run it again.\", '');\n}\nlines.push(`To run it again anyway, submit the lead with \"Run it again\" set to Yes. That creates a new report and bills another $0.20.`);\nreturn {\n  json: {\n    ...$json,\n    draft: { kind: 'note', to: '', subject: `BNBCalc lead skipped, already analyzed: ${seen.address.split(',')[0]}`, body: lines.join('\\n') },\n  },\n};\n"
      },
      "id": "a1000000-0000-4000-8000-000000000014",
      "name": "Note: already analyzed",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1320,
        60
      ]
    },
    {
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "// A note to you, with no recipient. Nothing was sent to BNBCalc.\nconst { lead, problems } = $json;\nconst list = (items) => (items.length < 2 ? items.join('')\n  : items.slice(0, -1).join(', ') + ' and ' + items[items.length - 1]);\nconst body = [\n  \"This lead wasn't sent to BNBCalc, so nothing was billed.\",\n  '',\n  `It still needs ${list(problems)}. Fix it and submit the lead again.`,\n].join('\\n');\nreturn {\n  json: {\n    ...$json,\n    draft: { kind: 'note', to: '', subject: `BNBCalc lead incomplete: ${lead.address || lead.ownerName || 'new lead'}`, body },\n  },\n};\n"
      },
      "id": "a1000000-0000-4000-8000-000000000015",
      "name": "Note: lead incomplete",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        880,
        160
      ]
    },
    {
      "parameters": {
        "resource": "draft",
        "operation": "create",
        "subject": "={{ $json.draft.subject }}",
        "emailType": "text",
        "message": "={{ $json.draft.body }}",
        "options": {
          "sendTo": "={{ $json.draft.to }}"
        }
      },
      "id": "a1000000-0000-4000-8000-000000000016",
      "name": "Create Gmail draft",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        2260,
        0
      ],
      "credentials": {
        "gmailOAuth2": {
          "id": "",
          "name": "Gmail"
        }
      },
      "notes": "Creates a draft only. The proposal is addressed to the owner; notes have no recipient."
    }
  ],
  "connections": {
    "New owner lead": {
      "main": [
        [
          {
            "node": "Your settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Your settings": {
      "main": [
        [
          {
            "node": "Check the lead",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check the lead": {
      "main": [
        [
          {
            "node": "Lead complete?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Lead complete?": {
      "main": [
        [
          {
            "node": "Skip recent addresses",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Note: lead incomplete",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Skip recent addresses": {
      "main": [
        [
          {
            "node": "New address?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "New address?": {
      "main": [
        [
          {
            "node": "Create Cohost analysis",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Note: already analyzed",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Cohost analysis": {
      "main": [
        [
          {
            "node": "Read the report",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Note: BNBCalc request failed",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read the report": {
      "main": [
        [
          {
            "node": "Revenue came back?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Revenue came back?": {
      "main": [
        [
          {
            "node": "Write the proposal",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Note: report needs a look",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Write the proposal": {
      "main": [
        [
          {
            "node": "Create Gmail draft",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Note: report needs a look": {
      "main": [
        [
          {
            "node": "Create Gmail draft",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Note: BNBCalc request failed": {
      "main": [
        [
          {
            "node": "Create Gmail draft",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Note: already analyzed": {
      "main": [
        [
          {
            "node": "Create Gmail draft",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Note: lead incomplete": {
      "main": [
        [
          {
            "node": "Create Gmail draft",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "active": false,
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "tags": []
}
