{ "name": "MOBLE: Google Sheets → Leads - Artifact", "nodes": [ { "parameters": { "content": "# šŸ“Š SOURCE SHEET\n\n## Quick Start\n**Import Sheet:**\nhttps://cdn.moble.com/w/919/2290654/file/MOBLE-Leads-Source-Sheet.xlsx\n\n**Required Columns:**\n- Email (must be valid)\n- First Name OR Last Name (at least one)\n\n**Optional SPI Columns** (AI calculates if empty):\n- Status (0-10)\n- Priority (1-10)\n- Importance (1-10)\n\n**Other Optional Columns:**\n- Mobile, Phone 2\n- Company, Website\n- Solution, Price, Price 2\n- Forecast Date, Next Action\n- Tags, Source, Notes\n- Industry, Staff Count, Annual Revenue\n- Option 1-10 (custom fields)\n\n## AI SPI Calculation\nāœ… AI runs ONLY if Status field is empty\nāœ… Leave Status blank = AI calculates SPI\nāœ… Set Status = 0 (or any value) = Skip AI\n\n**Default SPI if AI skipped:**\n- Status = 0 (New Lead)\n- Priority = 1 (Low urgency)\n- Importance = 1 (Low value)\n\n## Column Format Examples\n- Email: `john@company.com`\n- Mobile: `+61400123456` or `0400123456`\n- Tags: `vip,enterprise` (comma-separated)\n- Forecast Date: `2025-12-31` or `31/12/2025`\n- Status: `3` (0-10 scale)\n- Priority: `7` (1-10 scale)\n- Importance: `8` (1-10 scale)\n\n## Tips\nšŸ’” Use Google Sheets formulas for smart defaults\nšŸ’” Add data validation for SPI fields (dropdowns)\nšŸ’” Status 0 + AI = calculate, Status 0 + no AI = New Lead\nšŸ’” Check Sync Log for operation results", "height": 672, "width": 492, "color": 4 }, "id": "d842b046-c199-42ad-9337-d88295a8b7af", "name": "Sticky Note5", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [ 656, -1024 ] }, { "parameters": { "content": "# šŸ“‹ SYNC LOG SHEET\n\n## Quick Start\n**Import Sheet:**\nhttps://cdn.moble.com/w/919/2290655/file/MOBLE-Leads-Sync-Log.xlsx\n\n**Auto-Created Columns:**\n- Email (lead identifier)\n- Action (created/updated/failed)\n- Status Code (API response)\n- MOBLE ID (lead ID if successful)\n- SPI Stamp (e.g., S3P7I8)\n- AI Used (yes/no/skipped)\n- Error (if failed)\n- Timestamp (ISO format)\n\n## Action Types\nāœ… **created** - New lead created\nāœ… **updated** - Existing lead updated\nāŒ **failed** - Validation or API error\n\n## Status Codes\n- 200/201 = Success\n- 400 = Validation error\n- 401 = Auth error (check API key)\n- 409 = Duplicate (email exists)\n- 500 = Server error\n\n## AI Used Values\n- **yes** = AI calculated SPI\n- **no** = Manual SPI from sheet\n- **skipped** = AI not configured\n- **error** = AI failed (uses default S0P1I1)\n\n## Monitoring Tips\nšŸ” Filter by action='failed' to find issues\nšŸ” Check timestamp to track sync frequency\nšŸ” Monitor SPI stamps for lead quality\nšŸ” Use MOBLE ID to locate leads in CRM\n\n## Troubleshooting\nāŒ Validation errors → Check email format\nāŒ Auth errors → Verify API key\nāŒ AI errors → Check OpenAI credential\nāŒ No MOBLE ID → Lead creation failed", "height": 672, "width": 492, "color": 4 }, "id": "fcaa633a-4d3c-4b4d-9a3a-32c6082a2f8f", "name": "Sticky Note6", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [ 1184, -1024 ] }, { "parameters": { "content": "# šŸ“‹ COMPLETE SPI REFERENCE\n\n## STATUS (S) - Deal Stage (0-10)\n**0** = New Lead (Unassigned)\n**1** = Assigned (To Sales Rep)\n**2** = Outreach (Initial Contact)\n**3** = Discovery (Needs Analysis) ā¬…ļø Most common for new inquiries\n**4** = Presentation (Pitching)\n**5** = Meetings (Engagement)\n**6** = Proposal (Proposal Sent) ā¬…ļø Quote requests\n**7** = Objections (Handling Concerns)\n**8** = Contract (Contract Signing)\n**9** = Negotiation (Finalising Terms)\n**10** = Sold (Closed-Won) āœ…\n\n## PRIORITY (P) - Urgency (1-10)\n**10** = Now or Never (Pay TODAY)\n**9** = Closing Window (Fast-moving)\n**8** = Final Stages (Near completion)\n**7** = Active Decision (Considering options)\n**6** = Ongoing Engagement (Progressing)\n**5** = Progressing at Pace (Strategic)\n**4** = Keeping Warm (Regular touchpoints)\n**3** = Future Potential (Low urgency)\n**2** = Long-Term Interest (Relationship building)\n**1** = Dormant (Unlikely to move soon)\n\n## IMPORTANCE (I) - Business Impact (1-10)\n**10** = Game Changer (Transforms results)\n**9** = Major Win (High value)\n**8** = Key Account (Substantial revenue)\n**7** = Strong Contributor (Meaningful)\n**6** = Consistent Performer (Decent size)\n**5** = Reliable Sale (Steady win)\n**4** = Good Addition (Worth pursuing)\n**3** = Minor Impact (Small value)\n**2** = Filler Sale (Minimal impact)\n**1** = Low-Stakes Win (Insignificant)\n\n## RECLASSIFICATION\nS-P-I-**GE** = Move to General Enquiries\nS-P-I-**SL** = Move to Sales Leads\nS-P-I-**ST** = Move to Support Tickets\nS-P-I-**PT** = Move to Project Tasks", "height": 672, "width": 492 }, "id": "45495d82-02f7-4ec3-8679-3887f9bf750f", "name": "Sticky Note7", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [ 1712, -1024 ] }, { "parameters": { "content": "# šŸ”„ APP SWAP: Alternative Integrations\n\n## Replace Google Sheets With:\n\n### Option 1: Airtable\n**Trigger:** `Airtable Trigger`\n**Benefit:** Better UI, more field types\n**Caveat:** Rate limits on free plan\n\n### Option 2: Notion Database\n**Trigger:** `Notion Trigger`\n**Benefit:** All-in-one workspace\n**Caveat:** Complex setup\n\n### Option 3: Monday.com\n**Trigger:** `Monday.com Trigger`\n**Benefit:** Project management integration\n**Caveat:** Requires paid plan\n\n### Option 4: Direct Form Webhook\n**Trigger:** `Webhook` node\n**Benefit:** Real-time, no polling\n**Caveat:** Requires form integration\n\n## Replace OpenAI With:\n\n### Option 1: Anthropic Claude\n**Node:** `Anthropic` node\n**Model:** `claude-3-sonnet-20240229`\n**Benefit:** Better reasoning, longer context\n\n### Option 2: Manual Entry\n**Action:** Remove AI node entirely\n**Benefit:** Full control over SPI\n**Caveat:** More manual work\n\n### Option 3: Rule-Based Logic\n**Node:** `Switch` or `If` nodes\n**Benefit:** Deterministic, free\n**Caveat:** Less flexible", "height": 672, "width": 492, "color": 5 }, "id": "cdbfbbd6-6794-423a-899e-827bba24d3b8", "name": "Sticky Note8", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [ 2240, -1024 ] }, { "parameters": { "content": "# šŸ“˜ MOBLE LEADS SYNC USER GUIDE\n\n## What This Workflow Does\nāœ… Imports leads from Google Sheets to MOBLE\nāœ… AI calculates SPI scores (if Status empty)\nāœ… Validates email + name requirements\nāœ… Checks if Lead exists in MOBLE\nāœ… NEW Lead → Creates Lead\nāœ… EXISTING Lead → Updates Lead\nāœ… Logs all operations to Sync Log\n\n## API Logic\n- **New Lead:** POST /api/site/leads/create\n- **Existing Lead:** POST /api/site/leads/update\n\n## Required Credentials\nšŸ“ Google Sheets OAuth2 (trigger + log)\nšŸ“ OpenAI API (for SPI calculation)\nšŸ“ MOBLE API: Bearer ak_... (Header Auth)\n\n## Quick Setup\n1. Copy spreadsheet template\n2. Add Google Sheets OAuth2 credential\n3. **Add MOBLE API credential** to HTTP Request nodes\n - Get API key: MOBLE > Global Settings > API\n - Format: `Bearer ak_YOUR_API_KEY`\n4. Add OpenAI credential\n5. Activate workflow\n\n## Sheet Names Required\n- **Leads Source Sheet** (source data)\nhttps://cdn.moble.com/w/919/2290654/file/MOBLE-Leads-Source-Sheet.xlsx\n- **Leads Sync Log** (operation history)\nhttps://cdn.moble.com/w/919/2290655/file/MOBLE-Leads-Sync-Log.xlsx\n\n# šŸ”€ ROUTING LOGIC\n\n## Validation Check\n- Email required (valid format)\n- First OR Last name required\n\n## AI Decision\n- Status EMPTY → AI calculates SPI\n- Status HAS VALUE → Use manual SPI\n\n## Lead Exists Check\n- Lookup by email in MOBLE\n- Found → Update existing\n- Not Found → Create new\n\n## Actions\n- /api/site/leads/create\n- /api/site/leads/update", "height": 672, "width": 468 }, "id": "70c4d36d-1eb6-4935-a44d-80e73b03e14e", "name": "User Guide", "type": "n8n-nodes-base.stickyNote", "typeVersion": 1, "position": [ 160, -1024 ] }, { "parameters": { "pollTimes": { "item": [ { "mode": "everyMinute" } ] }, "documentId": { "__rl": true, "value": "", "mode": "list", "cachedResultName": "" }, "sheetName": { "__rl": true, "value": "Leads", "mode": "list", "cachedResultName": "Leads" }, "options": {} }, "id": "0c34da1a-3fdd-4f55-87ec-860cb2458919", "name": "When Row Added/Updated", "type": "n8n-nodes-base.googleSheetsTrigger", "typeVersion": 1, "position": [ 160, -1360 ], "notes": "TODO: Add Google Sheets OAuth2 credential\nTODO: Select your spreadsheet\nTODO: Verify sheet name is 'Leads'\n\nTriggers when:\nāœ… New row added\nāœ… Existing row updated\n\nPolls every 1 minute." }, { "parameters": { "jsCode": "// ═══════════════════════════════════════════════════════\n// TRANSFORM & VALIDATE GOOGLE SHEET DATA\n// Maps columns to MOBLE fields + validates required fields\n// ═══════════════════════════════════════════════════════\n\nconst fieldMapping = {\n // REQUIRED\n 'Email': 'email',\n 'First Name': 'first_name',\n 'Last Name': 'last_name',\n \n // CONTACT\n 'Mobile': 'mobile',\n 'Phone 2': 'phone_2',\n 'Company': 'company_name',\n 'Website': 'website_url',\n \n // SPI (AI calculates if Status empty)\n 'Status': 'status',\n 'Priority': 'priority',\n 'Importance': 'importance',\n \n // SALES\n 'Solution': 'solution',\n 'Price': 'price',\n 'Price 2': 'price_2',\n 'Forecast Date': 'date',\n 'Next Action': 'date_action',\n \n // METADATA\n 'Tags': 'data_tags',\n 'Source': 'data_source',\n 'Notes': 'notes',\n 'Industry': 'industry',\n 'Staff Count': 'no_of_staff',\n 'Annual Revenue': 'gross_annual_revenue',\n 'Software': 'software',\n \n // CUSTOM\n 'Option 1': 'option_1',\n 'Option 2': 'option_2',\n 'Option 3': 'option_3',\n 'Option 4': 'option_4',\n 'Option 5': 'option_5',\n 'Option 6': 'option_6',\n 'Option 7': 'option_7',\n 'Option 8': 'option_8',\n 'Option 9': 'option_9',\n 'Option 10': 'option_10'\n};\n\n// Helper functions\nfunction normalizePhone(phone) {\n if (!phone) return null;\n const cleaned = phone.toString().replace(/[\\s\\-\\(\\)]/g, '');\n return cleaned.startsWith('00') ? cleaned.replace(/^00/, '+') : cleaned;\n}\n\nfunction validateEmail(email) {\n if (!email) return false;\n return /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email);\n}\n\nfunction parseTags(value) {\n if (!value) return [];\n if (Array.isArray(value)) return value.map(t => t.trim()).filter(t => t);\n if (typeof value === 'string' && value.trim().startsWith('[')) {\n try {\n const parsed = JSON.parse(value);\n if (Array.isArray(parsed)) return parsed.map(t => t.trim()).filter(t => t);\n } catch (e) {}\n }\n return value.toString().split(',').map(t => t.trim()).filter(t => t);\n}\n\nfunction parseInteger(value, min, max, defaultValue = null) {\n if (value === null || value === undefined || value === '') return defaultValue;\n const num = parseInt(value);\n if (isNaN(num)) return defaultValue;\n if (min !== null && num < min) return defaultValue;\n if (max !== null && num > max) return defaultValue;\n return num;\n}\n\nfunction parseDecimal(value) {\n if (value === null || value === undefined || value === '') return null;\n const num = parseFloat(value);\n return isNaN(num) ? null : num;\n}\n\nfunction parseDate(value) {\n if (!value) return null;\n const str = value.toString().trim();\n if (!str) return null;\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(str)) return str;\n const ddmmyyyyMatch = str.match(/^(\\d{1,2})[\\/\\-](\\d{1,2})[\\/\\-](\\d{4})$/);\n if (ddmmyyyyMatch) {\n const [, day, month, year] = ddmmyyyyMatch;\n return `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`;\n }\n try {\n const date = new Date(str);\n if (!isNaN(date.getTime())) return date.toISOString().split('T')[0];\n } catch (e) {}\n return null;\n}\n\n// Process row\nconst row = $input.first().json;\nconst lead = {\n site_name: 'YOUR_SITE_NAME',\n funnel_status: 'Lead',\n data_source: lead.data_source || 'Google Sheets Import'\n};\nconst validationErrors = [];\n\n// Map fields\nfor (const [sheetCol, mobleField] of Object.entries(fieldMapping)) {\n const value = row[sheetCol];\n if (value === null || value === undefined || value === '') continue;\n \n if (mobleField === 'data_tags') {\n lead[mobleField] = parseTags(value);\n } else if (mobleField === 'status') {\n lead[mobleField] = parseInteger(value, 0, 10, null);\n } else if (mobleField === 'priority') {\n lead[mobleField] = parseInteger(value, 1, 10, null);\n } else if (mobleField === 'importance') {\n lead[mobleField] = parseInteger(value, 1, 10, null);\n } else if (mobleField === 'price' || mobleField === 'price_2') {\n lead[mobleField] = parseDecimal(value);\n } else if (mobleField === 'date' || mobleField === 'date_action') {\n const parsed = parseDate(value);\n if (parsed) lead[mobleField] = parsed;\n } else if (mobleField === 'mobile' || mobleField === 'phone_2') {\n lead[mobleField] = normalizePhone(value);\n } else if (mobleField === 'email') {\n lead[mobleField] = value.toString().trim().toLowerCase();\n } else {\n lead[mobleField] = value.toString().trim();\n }\n}\n\n// Validate required fields\nif (!lead.email || !validateEmail(lead.email)) {\n validationErrors.push('Missing or invalid email');\n}\nif (!lead.first_name && !lead.last_name) {\n validationErrors.push('Missing both first_name and last_name');\n}\n\n// AI decision: runs ONLY if Status is empty/null\nconst needsAI = (lead.status === null || lead.status === undefined);\n\n// Build summary for AI\nlet aiSummary = '';\nif (needsAI) {\n aiSummary = `Lead Information:\\n`;\n if (lead.first_name) aiSummary += `Name: ${lead.first_name} ${lead.last_name || ''}\\n`;\n if (lead.company_name) aiSummary += `Company: ${lead.company_name}\\n`;\n if (lead.industry) aiSummary += `Industry: ${lead.industry}\\n`;\n if (lead.solution) aiSummary += `Solution/Product: ${lead.solution}\\n`;\n if (lead.price) aiSummary += `Price: ${lead.price}\\n`;\n if (lead.notes) aiSummary += `Notes: ${lead.notes}\\n`;\n if (lead.data_tags && lead.data_tags.length) aiSummary += `Tags: ${lead.data_tags.join(', ')}\\n`;\n if (lead.no_of_staff) aiSummary += `Company Size: ${lead.no_of_staff}\\n`;\n if (lead.gross_annual_revenue) aiSummary += `Revenue: ${lead.gross_annual_revenue}\\n`;\n}\n\n// Output\nif (validationErrors.length > 0) {\n return [{\n json: {\n validation_status: 'error',\n email: lead.email || 'N/A',\n errors: validationErrors,\n error_message: validationErrors.join('; '),\n timestamp: new Date().toISOString(),\n needs_ai: false\n }\n }];\n}\n\nreturn [{\n json: {\n validation_status: 'valid',\n lead_data: lead,\n email: lead.email,\n first_name: lead.first_name || 'N/A',\n last_name: lead.last_name || 'N/A',\n needs_ai: needsAI,\n ai_summary: aiSummary,\n has_manual_spi: !needsAI,\n manual_spi: needsAI ? null : {\n status: lead.status || 0,\n priority: lead.priority || 1,\n importance: lead.importance || 1\n },\n timestamp: new Date().toISOString()\n }\n}];" }, "id": "94bebccf-8c02-4f95-8169-e032f563bcfd", "name": "Transform & Validate", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 400, -1360 ], "notes": "TODO: Replace YOUR_SITE_NAME\n\nMaps Google Sheet columns to MOBLE fields:\nāœ… Validates email format\nāœ… Normalizes phone numbers\nāœ… Converts tags (comma to array)\nāœ… Parses SPI integers\nāœ… Parses dates\n\nAI Decision:\n- needs_ai = true if Status EMPTY\n- needs_ai = false if Status HAS VALUE" }, { "parameters": { "conditions": { "options": { "leftValue": "", "caseSensitive": true, "typeValidation": "strict" }, "combinator": "and", "conditions": [ { "id": "validation-check", "leftValue": "={{ $json.validation_status }}", "rightValue": "valid", "operator": { "type": "string", "operation": "equals" } } ] }, "options": {} }, "id": "c17e65b4-214f-45f6-88de-6d68a1aaa13e", "name": "Valid Data?", "type": "n8n-nodes-base.if", "typeVersion": 2.2, "position": [ 640, -1360 ], "notes": "TRUE → Check if AI needed\nFALSE → Log validation error" }, { "parameters": { "conditions": { "options": { "leftValue": "", "caseSensitive": true, "typeValidation": "strict" }, "combinator": "and", "conditions": [ { "id": "needs-ai-check", "leftValue": "={{ $json.needs_ai }}", "rightValue": true, "operator": { "type": "boolean", "operation": "true" } } ] }, "options": {} }, "id": "f2be5016-2034-4de5-a917-7e728a93e463", "name": "Needs AI SPI?", "type": "n8n-nodes-base.if", "typeVersion": 2.2, "position": [ 880, -1456 ], "notes": "TRUE → Status empty → AI calculates SPI\nFALSE → Status has value → Skip AI" }, { "parameters": { "resource": "chat", "chatModel": "gpt-4o-mini", "prompt": { "messages": [ { "role": "system", "content": "You are an expert sales qualification AI that analyzes lead data and assigns precise SPI scores using MOBLE's complete scoring framework.\n\n# SALES LEAD STATUS TOOL\nAnalyze the lead information and set the \"Sales Lead Status Value\". If uncertain, default to '0' (New Lead).\n\n## Status Values (S) - Deal Stage (0-10)\n[10] **Sold** = (Closed - Won) – Deal successfully closed.\n[9] **Negotiation** = (Finalising Terms) – Terms and pricing being discussed.\n[8] **Contract** = (Contract Signing) – Contract drafted, awaiting signature.\n[7] **Objections** = (Handling Concerns) – Lead raised objections, being addressed.\n[6] **Proposal** = (Proposal Sent) – Formal proposal sent, awaiting feedback.\n[5] **Meetings** = (Engagement) – Sales meetings happening.\n[4] **Presentation** = (Pitching) – Lead receiving demo/presentation.\n[3] **Discovery** = (Needs Analysis) – Learning lead's needs, qualifying.\n[2] **Outreach** = (Initial Contact) – Sales team reached out.\n[1] **Assigned** = (Assigned to Sales Rep) – Lead assigned to salesperson.\n[0] **New Lead** = (Unassigned / Fresh Lead) – Default state.\n\n### Reclassification:\nIf not a Sales Lead, use format S-P-I-XX where XX is:\n- GE = General Enquiry\n- ST = Support Ticket\n- PT = Project Task\n\n## SALES LEAD PRIORITY TOOL\nPriority (Urgency) - How quickly to act on the deal.\n\n### Priority Values (P) - Urgency (1-10)\n[10] **Now or Never** – Must act immediately.\n[9] **Closing Window** – Deal progressing fast.\n[8] **Final Stages** – Discussions nearing completion.\n[7] **Active Decision** – Buyer actively considering.\n[6] **Ongoing Engagement** – Progressing with breathing room.\n[5] **Progressing at Pace** – Strategic follow-ups.\n[4] **Keeping Warm** – Regular touchpoints needed.\n[3] **Future Potential** – Low urgency.\n[2] **Long-Term Interest** – Relationship building.\n[1] **Dormant or Low Urgency** – Unlikely to move soon.\n\n## SALES LEAD IMPORTANCE TOOL\nImportance (Sales Impact) - How much deal matters.\n\n### Importance Values (I) - Business Impact (1-10)\n[10] **Game Changer** – Transforms sales results.\n[9] **Major Win** – Significant impact on targets.\n[8] **Key Account** – Substantial revenue.\n[7] **Strong Contributor** – Meaningful contribution.\n[6] **Consistent Performer** – Decent size.\n[5] **Reliable Sale** – Steady, dependable.\n[4] **Good Addition** – Worth pursuing.\n[3] **Minor Impact** – Small value.\n[2] **Filler Sale** – Minimal impact.\n[1] **Low-Stakes Win** – Insignificant.\n\n# ANALYSIS GUIDELINES\n\n## From Lead Data:\n- Company size / revenue → Importance indicator\n- Solution/product mentioned → Status indicator\n- Price discussed → Usually S6+ (Proposal stage)\n- Industry context → Importance modifier\n- Notes content → Key signals\n\n## Default Conservative:\n- No clear signals → S0P1I1\n- Basic inquiry → S3P5I5\n- Price mentioned → S6P6I6\n\n## Output Format\n\nReturn ONLY valid JSON:\n{\n \"status\": 3,\n \"priority\": 5,\n \"importance\": 5,\n \"stamp\": \"S3P5I5\",\n \"reasoning\": \"Brief explanation of scoring decision.\",\n \"reclassify\": null\n}\n\nCRITICAL: Return ONLY valid JSON. No markdown, no code blocks." }, { "content": "={{ $json.ai_summary }}" } ] }, "options": { "maxTokens": 500, "temperature": 0.3 }, "requestOptions": {} }, "id": "fdffb4d0-c2c4-48a2-ae8d-0c8093faf63d", "name": "OpenAI: Calculate SPI", "type": "n8n-nodes-base.openAi", "typeVersion": 1.1, "position": [ 1120, -1536 ], "retryOnFail": true, "maxTries": 3, "waitBetweenTries": 2000, "continueOnFail": true, "notes": "TODO: Add OpenAI API credential\n\nAnalyzes lead data for SPI:\n- Status (0-10): Deal stage\n- Priority (1-10): Urgency\n- Importance (1-10): Impact\n\nModel: gpt-4o-mini\nTemperature: 0.3\nMax tokens: 500\n\nRetries: 3x with 2s delay\nFallback: S0P1I1" }, { "parameters": { "jsCode": "// Pass through with manual SPI values\nconst data = $input.first().json;\n\nreturn [{\n json: {\n ...data,\n spi_source: 'manual',\n spi: {\n status: data.manual_spi.status,\n priority: data.manual_spi.priority,\n importance: data.manual_spi.importance,\n stamp: `S${data.manual_spi.status}P${data.manual_spi.priority}I${data.manual_spi.importance}`,\n reasoning: 'Manual SPI from Google Sheet'\n }\n }\n}];" }, "id": "8d5ebc5b-a02d-4d29-9f7f-656fc7baab8e", "name": "Use Manual SPI", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 1120, -1376 ], "notes": "Passes through manual SPI values when Status was provided in sheet." }, { "parameters": { "method": "POST", "url": "=https://api.moble.com/api/site/leads?email={{ encodeURIComponent($json.email) }}", "authentication": "genericCredentialType", "genericAuthType": "httpHeaderAuth", "sendHeaders": true, "headerParameters": { "parameters": [ { "name": "Content-Type", "value": "application/json" } ] }, "options": { "response": { "response": { "neverError": true } }, "timeout": 15000 } }, "id": "0eff621b-de34-4842-9081-c7ce11d40e3a", "name": "Check if Lead Exists", "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.2, "position": [ 1600, -1456 ], "alwaysOutputData": true, "notes": "TODO: Add MOBLE API credential\n\nLooks up lead by email.\n- 200 + data = Exists\n- 404 or empty = New lead" }, { "parameters": { "jsCode": "// ═══════════════════════════════════════════════════════\n// DETERMINE CREATE OR UPDATE\n// ═══════════════════════════════════════════════════════\n\nconst lookupResponse = $input.first().json;\nconst mergedData = $('Merge SPI Data1').first().json;\n\nlet leadExists = false;\nlet existingLeadId = null;\n\nif (lookupResponse) {\n if (lookupResponse.id) {\n leadExists = true;\n existingLeadId = lookupResponse.id;\n } else if (lookupResponse.data && lookupResponse.data.id) {\n leadExists = true;\n existingLeadId = lookupResponse.data.id;\n } else if (Array.isArray(lookupResponse) && lookupResponse.length > 0) {\n leadExists = true;\n existingLeadId = lookupResponse[0].id;\n } else if (lookupResponse.items && lookupResponse.items.length > 0) {\n leadExists = true;\n existingLeadId = lookupResponse.items[0].id;\n }\n}\n\nreturn [{\n json: {\n ...mergedData,\n lead_exists: leadExists,\n existing_lead_id: existingLeadId,\n action: leadExists ? 'update' : 'create'\n }\n}];" }, "id": "ae475d6d-c427-4438-a1dc-3e8b1ed52aaf", "name": "Determine Action", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 1840, -1456 ], "notes": "Checks lookup response:\n- Lead found → update\n- Not found → create" }, { "parameters": { "conditions": { "options": { "leftValue": "", "caseSensitive": true, "typeValidation": "strict" }, "combinator": "and", "conditions": [ { "id": "lead-exists", "leftValue": "={{ $json.lead_exists }}", "rightValue": true, "operator": { "type": "boolean", "operation": "true" } } ] }, "options": {} }, "id": "0621a47f-d67b-4767-93c5-e0f6d14e355d", "name": "Lead Exists?", "type": "n8n-nodes-base.if", "typeVersion": 2.2, "position": [ 2080, -1456 ], "notes": "TRUE → Update existing lead\nFALSE → Create new lead" }, { "parameters": { "method": "POST", "url": "https://api.moble.com/api/site/leads/create", "authentication": "genericCredentialType", "genericAuthType": "httpHeaderAuth", "sendHeaders": true, "headerParameters": { "parameters": [ { "name": "Content-Type", "value": "application/json" } ] }, "sendBody": true, "specifyBody": "json", "jsonBody": "={{ JSON.stringify($json.lead_payload) }}", "options": { "response": { "response": { "neverError": true } }, "timeout": 30000 } }, "id": "40e0126a-f331-4f40-b4ad-3dc0309737c4", "name": "MOBLE: Create Lead", "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.2, "position": [ 2320, -1376 ], "retryOnFail": true, "maxTries": 3, "waitBetweenTries": 2000, "alwaysOutputData": true, "notes": "TODO: Add MOBLE API credential\n\nPOST /api/site/leads/create\nCreates NEW lead.\n\nRetries: 3x with 2s delay" }, { "parameters": { "method": "POST", "url": "https://api.moble.com/api/site/leads/update", "authentication": "genericCredentialType", "genericAuthType": "httpHeaderAuth", "sendHeaders": true, "headerParameters": { "parameters": [ { "name": "Content-Type", "value": "application/json" } ] }, "sendBody": true, "specifyBody": "json", "jsonBody": "={{ JSON.stringify($json.lead_payload) }}", "options": { "response": { "response": { "neverError": true } }, "timeout": 30000 } }, "id": "97687dab-3a96-4272-b368-4c79d3910254", "name": "MOBLE: Update Lead", "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.2, "position": [ 2320, -1536 ], "retryOnFail": true, "maxTries": 3, "waitBetweenTries": 2000, "alwaysOutputData": true, "notes": "TODO: Add MOBLE API credential\n\nPOST /api/site/leads/update\nUpdates EXISTING lead.\n\nRetries: 3x with 2s delay" }, { "parameters": { "jsCode": "// ═══════════════════════════════════════════════════════\n// PREPARE SYNC LOG - SUCCESS PATH\n// ═══════════════════════════════════════════════════════\n\nconst apiResponse = $input.first().json;\nconst actionData = $('Determine Action').first().json;\n\nconst statusCode = apiResponse.statusCode || 200;\nconst success = statusCode >= 200 && statusCode < 300;\nconst leadId = apiResponse.id || apiResponse.data?.id || actionData.existing_lead_id || null;\n\nreturn [{\n json: {\n email: actionData.email,\n action: actionData.action,\n status_code: statusCode,\n moble_id: leadId,\n spi_stamp: actionData.spi.stamp,\n spi_source: actionData.spi_source,\n spi_reasoning: actionData.spi.reasoning,\n error: success ? null : (apiResponse.error || apiResponse.message || `HTTP ${statusCode}`),\n timestamp: actionData.timestamp\n }\n}];" }, "id": "ad493897-443a-4419-b39d-3c054709b1a8", "name": "Prepare Log Entry", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 2560, -1456 ], "notes": "Prepares sync log entry for success path." }, { "parameters": { "jsCode": "// ═══════════════════════════════════════════════════════\n// PREPARE SYNC LOG - VALIDATION ERROR PATH\n// ═══════════════════════════════════════════════════════\n\nconst errorData = $input.first().json;\n\nreturn [{\n json: {\n email: errorData.email || 'N/A',\n action: 'validation_failed',\n status_code: 400,\n moble_id: null,\n spi_stamp: 'N/A',\n spi_source: 'N/A',\n spi_reasoning: 'Validation failed',\n error: errorData.error_message || 'Validation error',\n timestamp: errorData.timestamp || new Date().toISOString()\n }\n}];" }, "id": "be571fb1-be0d-4686-a850-0d2ae798c07f", "name": "Prepare Error Log", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 880, -1200 ], "notes": "Prepares sync log for validation errors." }, { "parameters": { "operation": "append", "documentId": { "__rl": true, "value": "", "mode": "list", "cachedResultName": "" }, "sheetName": { "__rl": true, "value": "Sync Log", "mode": "list", "cachedResultName": "Sync Log" }, "columns": { "mappingMode": "defineBelow", "value": { "Email": "={{ $json.email }}", "Action": "={{ $json.action }}", "Status Code": "={{ $json.status_code }}", "MOBLE ID": "={{ $json.moble_id }}", "SPI Stamp": "={{ $json.spi_stamp }}", "SPI Source": "={{ $json.spi_source }}", "SPI Reasoning": "={{ $json.spi_reasoning }}", "Error": "={{ $json.error }}", "Timestamp": "={{ $json.timestamp }}" }, "schema": [ { "id": "Email", "displayName": "Email", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true }, { "id": "Action", "displayName": "Action", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true }, { "id": "Status Code", "displayName": "Status Code", "required": false, "defaultMatch": false, "display": true, "type": "number", "canBeUsedToMatch": true }, { "id": "MOBLE ID", "displayName": "MOBLE ID", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true }, { "id": "SPI Stamp", "displayName": "SPI Stamp", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true }, { "id": "SPI Source", "displayName": "SPI Source", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true }, { "id": "SPI Reasoning", "displayName": "SPI Reasoning", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true }, { "id": "Error", "displayName": "Error", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true }, { "id": "Timestamp", "displayName": "Timestamp", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true } ], "matchingColumns": [], "attemptToConvertTypes": true, "convertFieldsToString": true }, "options": {} }, "id": "5c452bd7-62dd-48bf-9d63-c6c28707649d", "name": "Log to Sync Log", "type": "n8n-nodes-base.googleSheets", "typeVersion": 4.5, "position": [ 2800, -1200 ], "retryOnFail": true, "maxTries": 3, "waitBetweenTries": 1000, "alwaysOutputData": true, "continueOnFail": true, "notes": "TODO: Same Google Sheets credential\nTODO: Same spreadsheet as trigger\nTODO: Sheet name: 'Sync Log'\n\nCreate sheet with columns:\nEmail | Action | Status Code | MOBLE ID |\nSPI Stamp | SPI Source | SPI Reasoning |\nError | Timestamp" }, { "parameters": { "jsCode": "// ═══════════════════════════════════════════════════════\n// MERGE SPI DATA (AI OR MANUAL)\n// Combines lead data with SPI scores\n// ═══════════════════════════════════════════════════════\n\nconst inputData = $input.first().json;\nconst transformData = $('Transform & Validate').first().json;\n\nlet spi = {};\nlet spiSource = 'manual';\n\n// Check if this is AI path or manual path\nif (inputData.message && inputData.message.content) {\n // AI path - parse OpenAI response\n spiSource = 'ai';\n try {\n let content = inputData.message.content;\n content = content.replace(/```json\\n?/g, '').replace(/```\\n?/g, '').trim();\n spi = JSON.parse(content);\n } catch (e) {\n spi = {\n status: 0,\n priority: 1,\n importance: 1,\n stamp: 'S0P1I1',\n reasoning: 'AI parsing failed - default values'\n };\n spiSource = 'default';\n }\n} else if (inputData.spi) {\n // Manual path - already processed\n spi = inputData.spi;\n spiSource = inputData.spi_source || 'manual';\n} else {\n // Fallback\n spi = {\n status: 0,\n priority: 1,\n importance: 1,\n stamp: 'S0P1I1',\n reasoning: 'Fallback - default values'\n };\n spiSource = 'default';\n}\n\n// Build final lead payload\nconst lead = {\n ...transformData.lead_data,\n status: spi.status !== null ? spi.status : 0,\n priority: spi.priority !== null ? spi.priority : 1,\n importance: spi.importance !== null ? spi.importance : 1\n};\n\n// Add SPI to notes if AI-generated\nif (spiSource === 'ai' && spi.reasoning) {\n const spiNote = `\\n\\n[AI SPI] ${spi.stamp}\\nReasoning: ${spi.reasoning}`;\n lead.notes = (lead.notes || '') + spiNote;\n}\n\nreturn [{\n json: {\n lead_payload: lead,\n email: lead.email,\n spi: {\n status: spi.status || 0,\n priority: spi.priority || 1,\n importance: spi.importance || 1,\n stamp: spi.stamp || 'S0P1I1',\n reasoning: spi.reasoning || 'N/A'\n },\n spi_source: spiSource,\n timestamp: new Date().toISOString()\n }\n}];" }, "id": "6867bc20-9bbf-426a-84b7-ec3500135c28", "name": "Merge SPI Data1", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 1360, -1456 ], "notes": "Merges lead data with SPI:\n- AI path: Parse OpenAI JSON\n- Manual path: Use sheet values\n- Fallback: S0P1I1\n\nAdds SPI reasoning to notes if AI-generated." } ], "pinData": {}, "connections": { "When Row Added/Updated": { "main": [ [ { "node": "Transform & Validate", "type": "main", "index": 0 } ] ] }, "Transform & Validate": { "main": [ [ { "node": "Valid Data?", "type": "main", "index": 0 } ] ] }, "Valid Data?": { "main": [ [ { "node": "Needs AI SPI?", "type": "main", "index": 0 } ], [ { "node": "Prepare Error Log", "type": "main", "index": 0 } ] ] }, "Needs AI SPI?": { "main": [ [ { "node": "OpenAI: Calculate SPI", "type": "main", "index": 0 } ], [ { "node": "Use Manual SPI", "type": "main", "index": 0 } ] ] }, "OpenAI: Calculate SPI": { "main": [ [ { "node": "Merge SPI Data1", "type": "main", "index": 0 } ] ] }, "Use Manual SPI": { "main": [ [ { "node": "Merge SPI Data1", "type": "main", "index": 0 } ] ] }, "Check if Lead Exists": { "main": [ [ { "node": "Determine Action", "type": "main", "index": 0 } ] ] }, "Determine Action": { "main": [ [ { "node": "Lead Exists?", "type": "main", "index": 0 } ] ] }, "Lead Exists?": { "main": [ [ { "node": "MOBLE: Update Lead", "type": "main", "index": 0 } ], [ { "node": "MOBLE: Create Lead", "type": "main", "index": 0 } ] ] }, "MOBLE: Update Lead": { "main": [ [ { "node": "Prepare Log Entry", "type": "main", "index": 0 } ] ] }, "MOBLE: Create Lead": { "main": [ [ { "node": "Prepare Log Entry", "type": "main", "index": 0 } ] ] }, "Prepare Log Entry": { "main": [ [ { "node": "Log to Sync Log", "type": "main", "index": 0 } ] ] }, "Prepare Error Log": { "main": [ [ { "node": "Log to Sync Log", "type": "main", "index": 0 } ] ] }, "Merge SPI Data1": { "main": [ [ { "node": "Check if Lead Exists", "type": "main", "index": 0 } ] ] } }, "active": false, "settings": { "executionOrder": "v1" }, "versionId": "547fdd76-e436-46a1-a517-0ad17f10b46a", "meta": { "instanceId": "069444fe6fc97c95b9f0f1ee7ccaf958a45ec743b91abbe8c7056f5a53e9d7ca" }, "id": "XFbwXDO57VXKUiL4", "tags": [ { "updatedAt": "2025-11-29T23:37:35.120Z", "createdAt": "2025-11-29T23:37:35.120Z", "id": "CKXoBM6H4D4m3Xqz", "name": "v2" }, { "updatedAt": "2025-10-15T21:03:14.853Z", "createdAt": "2025-10-15T21:03:14.853Z", "id": "El46vEFWUasbDMXU", "name": "moble" }, { "updatedAt": "2025-10-15T21:03:14.782Z", "createdAt": "2025-10-15T21:03:14.782Z", "id": "EpiLtQAx9fqmgZqU", "name": "spi" }, { "updatedAt": "2025-11-23T20:56:25.327Z", "createdAt": "2025-11-23T20:56:25.327Z", "id": "RS0aX0HYTk9pACWX", "name": "sync-log" }, { "updatedAt": "2025-10-15T21:03:14.805Z", "createdAt": "2025-10-15T21:03:14.805Z", "id": "UBP6OKMBel62sdsM", "name": "leads" }, { "updatedAt": "2025-11-23T19:50:38.169Z", "createdAt": "2025-11-23T19:50:38.169Z", "id": "Y0vu8c6TlnNdZeci", "name": "production-ready" }, { "updatedAt": "2025-10-17T23:38:18.718Z", "createdAt": "2025-10-17T23:38:18.718Z", "id": "gj5zcoaFgKXqBsGH", "name": "google-sheets" }, { "updatedAt": "2025-10-19T18:18:40.011Z", "createdAt": "2025-10-19T18:18:40.011Z", "id": "lbIdiyXzmOsSrMhv", "name": "import" }, { "updatedAt": "2025-10-16T20:35:06.022Z", "createdAt": "2025-10-16T20:35:06.022Z", "id": "lcTkptC5qj3UnRqN", "name": "openai" }, { "updatedAt": "2025-11-23T21:35:46.405Z", "createdAt": "2025-11-23T21:35:46.405Z", "id": "n61IZnK1OTGYuM4i", "name": "ai-optional" } ] }