{
  "name": "AICARE Email Blast System",
  "nodes": [
    {
      "parameters": {},
      "id": "c1-manual-trigger",
      "name": "Setup Knowledge Base",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        240,
        -200
      ],
      "notes": "PART C: Run this first to upload knowledge base files to Gemini"
    },
    {
      "parameters": {
        "operation": "list",
        "folderId": {
          "__rl": true,
          "value": "1jw9xW6h2f8ei-XJFlbCoAtxLqqIh7-7x",
          "mode": "id"
        },
        "options": {
          "fields": [
            "id",
            "name",
            "mimeType",
            "size"
          ]
        }
      },
      "id": "c2-drive-list",
      "name": "Get Knowledge Docs",
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        460,
        -200
      ],
      "credentials": {
        "googleDriveOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "batchSize": 1,
        "options": {}
      },
      "id": "c3-loop",
      "name": "Process Each File",
      "type": "n8n-nodes-base.splitInBatches",
      "typeVersion": 3,
      "position": [
        680,
        -200
      ]
    },
    {
      "parameters": {
        "operation": "download",
        "fileId": {
          "__rl": true,
          "value": "={{ $json.id }}",
          "mode": "id"
        }
      },
      "id": "c4-download",
      "name": "Download File",
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        900,
        -200
      ],
      "credentials": {
        "googleDriveOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://generativelanguage.googleapis.com/upload/v1beta/files",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpQueryAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "X-Goog-Upload-Protocol",
              "value": "resumable"
            },
            {
              "name": "X-Goog-Upload-Command",
              "value": "start"
            },
            {
              "name": "X-Goog-Upload-Header-Content-Length",
              "value": "={{ $binary.data.fileSize }}"
            },
            {
              "name": "X-Goog-Upload-Header-Content-Type",
              "value": "={{ $binary.data.mimeType }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ file: { display_name: $('Process Each File').item.json.name } }) }}",
        "options": {
          "response": {
            "response": {
              "fullResponse": true,
              "responseFormat": "json"
            }
          }
        }
      },
      "id": "c5-gemini-start",
      "name": "Gemini: Start Upload",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1120,
        -200
      ],
      "credentials": {
        "httpQueryAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $json.headers['x-goog-upload-url'] }}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "X-Goog-Upload-Offset",
              "value": "0"
            },
            {
              "name": "X-Goog-Upload-Command",
              "value": "upload, finalize"
            }
          ]
        },
        "sendBody": true,
        "contentType": "binaryData",
        "inputDataFieldName": "data",
        "options": {}
      },
      "id": "c6-gemini-upload",
      "name": "Gemini: Upload Content",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1340,
        -200
      ]
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "1t1scMqFj8HwWkGcHwadosl7LONLL6Nr3fF0ZEFs5oyk",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "RAG_Files",
          "mode": "list",
          "cachedResultName": "RAG_Files"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "file_name": "={{ $json.file.displayName }}",
            "gemini_file_uri": "={{ $json.file.uri }}",
            "mime_type": "={{ $json.file.mimeType }}",
            "uploaded_date": "={{ $now.toISO() }}",
            "expiration_date": "={{ $json.file.expirationTime }}"
          }
        }
      },
      "id": "c7-store-uri",
      "name": "Store RAG File URI",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.4,
      "position": [
        1560,
        -200
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "hours",
              "triggerAtHour": 9
            }
          ]
        }
      },
      "id": "a1-schedule",
      "name": "Daily Email Blast",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        240,
        100
      ],
      "notes": "PART A: Outbound Email Blast - Runs daily at 9 AM"
    },
    {
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "1t1scMqFj8HwWkGcHwadosl7LONLL6Nr3fF0ZEFs5oyk",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Leads",
          "mode": "list",
          "cachedResultName": "Leads"
        },
        "filtersUI": {
          "values": [
            {
              "lookupColumn": "status",
              "lookupValue": "pending"
            }
          ]
        },
        "options": {
          "returnAllMatches": {
            "values": {
              "returnAll": false,
              "limit": 10
            }
          }
        }
      },
      "id": "a2-get-leads",
      "name": "Get Pending Leads",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.4,
      "position": [
        460,
        100
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// Validate email format\nconst email = $input.item.json.email;\nconst emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\nif (!email || !emailRegex.test(email)) {\n  throw new Error(`Invalid email format: ${email}`);\n}\n\nreturn $input.item;"
      },
      "id": "a3-validate",
      "name": "Validate Email",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        680,
        100
      ]
    },
    {
      "parameters": {
        "method": "GET",
        "url": "={{ $json.website }}",
        "options": {
          "timeout": 10000,
          "response": {
            "response": {
              "responseFormat": "text"
            }
          }
        }
      },
      "id": "a4-scrape",
      "name": "Scrape Lead Website",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        900,
        100
      ],
      "continueOnFail": true
    },
    {
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "1t1scMqFj8HwWkGcHwadosl7LONLL6Nr3fF0ZEFs5oyk",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "RAG_Files",
          "mode": "list",
          "cachedResultName": "RAG_Files"
        },
        "options": {
          "returnAllMatches": {
            "values": {
              "returnAll": true
            }
          }
        }
      },
      "id": "a5-get-rag",
      "name": "Get RAG File URIs",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.4,
      "position": [
        900,
        280
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// Merge lead info with scraped data and RAG files\nconst lead = $('Validate Email').item.json;\nconst scrapedData = $('Scrape Lead Website').item.json;\nconst ragFiles = $('Get RAG File URIs').all();\n\n// Build the file parts array for Gemini\nconst fileParts = ragFiles.slice(0, 3).map(file => ({\n  file_data: {\n    file_uri: file.json.gemini_file_uri,\n    mime_type: file.json.mime_type\n  }\n}));\n\nreturn {\n  json: {\n    lead: lead,\n    website_content: typeof scrapedData.data === 'string' ? \n      scrapedData.data.substring(0, 2000) : \n      JSON.stringify(scrapedData).substring(0, 2000),\n    rag_file_parts: fileParts\n  }\n};"
      },
      "id": "a5b-merge",
      "name": "Merge Data",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1120,
        100
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpQueryAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"contents\": [\n    {\n      \"parts\": [\n        {{ JSON.stringify($json.rag_file_parts).slice(1, -1) }},\n        {\n          \"text\": \"You are an expert email copywriter for B2B outreach. Using the knowledge base provided above and the following lead information, write a personalized cold outreach email.\\n\\nLead Name: {{ $json.lead.name }}\\nCompany: {{ $json.lead.company }}\\nWebsite Content: {{ $json.website_content }}\\n\\nWrite a compelling, personalized email that:\\n1. Has a catchy subject line (not salesy)\\n2. Opens with something specific about their company\\n3. Clearly explains the value proposition from our knowledge base\\n4. Has a clear call-to-action\\n5. Is under 150 words\\n6. Sounds human and conversational\\n\\nReturn ONLY valid JSON (no markdown, no code blocks):\\n{\\n  \\\"subject\\\": \\\"...\\\",\\n  \\\"body\\\": \\\"...\\\",\\n  \\\"personalization_notes\\\": \\\"...\\\"\\n}\"\n        }\n      ]\n    }\n  ],\n  \"generationConfig\": {\n    \"temperature\": 0.7,\n    \"maxOutputTokens\": 1024\n  }\n}",
        "options": {}
      },
      "id": "a6-gemini-generate",
      "name": "Gemini: Generate Email",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1340,
        100
      ],
      "credentials": {
        "httpQueryAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// Parse Gemini response to extract email JSON\nconst response = $input.item.json;\nconst text = response.candidates[0].content.parts[0].text;\n\n// Clean up any markdown code blocks\nlet cleanText = text.replace(/```json\\s*/g, '').replace(/```\\s*/g, '').trim();\n\n// Extract JSON object\nconst jsonMatch = cleanText.match(/\\{[\\s\\S]*\\}/);\n\nif (!jsonMatch) {\n  throw new Error('Could not parse email JSON from Gemini response');\n}\n\nconst emailData = JSON.parse(jsonMatch[0]);\n\nreturn {\n  json: {\n    subject: emailData.subject,\n    body: emailData.body,\n    personalization_notes: emailData.personalization_notes,\n    lead: $('Merge Data').item.json.lead\n  }\n};"
      },
      "id": "a7-parse",
      "name": "Parse Email JSON",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1560,
        100
      ]
    },
    {
      "parameters": {
        "operation": "send",
        "sendTo": "kevin.aicareexpo@gmail.com",
        "subject": "=[APPROVAL NEEDED] Email to {{ $json.lead.name }} @ {{ $json.lead.company }}",
        "emailType": "html",
        "message": "=<html>\n<body style=\"font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;\">\n  <div style=\"background: #f5f5f5; padding: 20px; border-radius: 8px;\">\n    <h2 style=\"color: #333; margin-top: 0;\">\ud83d\udce7 Email Draft for Approval</h2>\n    \n    <div style=\"background: white; padding: 15px; border-radius: 4px; margin-bottom: 15px;\">\n      <p><strong>To:</strong> {{ $json.lead.name }} &lt;{{ $json.lead.email }}&gt;</p>\n      <p><strong>Company:</strong> {{ $json.lead.company }}</p>\n      <p><strong>Subject:</strong> {{ $json.subject }}</p>\n    </div>\n    \n    <div style=\"background: white; padding: 15px; border-radius: 4px; margin-bottom: 15px;\">\n      <h3 style=\"margin-top: 0; color: #666;\">Email Body:</h3>\n      <div style=\"white-space: pre-wrap;\">{{ $json.body }}</div>\n    </div>\n    \n    <div style=\"background: #e8f4f8; padding: 15px; border-radius: 4px; margin-bottom: 15px;\">\n      <h3 style=\"margin-top: 0; color: #0066cc;\">\ud83e\udd16 AI Notes:</h3>\n      <p style=\"margin-bottom: 0;\">{{ $json.personalization_notes }}</p>\n    </div>\n    \n    <hr style=\"border: none; border-top: 1px solid #ddd; margin: 20px 0;\">\n    \n    <div style=\"background: #fff3cd; padding: 15px; border-radius: 4px;\">\n      <h3 style=\"margin-top: 0; color: #856404;\">\ud83d\udccb Reply Instructions:</h3>\n      <ul style=\"margin-bottom: 0; padding-left: 20px;\">\n        <li><strong>APPROVED</strong> - Send as-is</li>\n        <li><strong>EDIT: [your changes]</strong> - Modify and resend for approval</li>\n        <li><strong>DECLINED</strong> - Skip this lead</li>\n      </ul>\n    </div>\n  </div>\n</body>\n</html>",
        "options": {}
      },
      "id": "a8-approval-email",
      "name": "Send Approval Request",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        1780,
        100
      ],
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "1t1scMqFj8HwWkGcHwadosl7LONLL6Nr3fF0ZEFs5oyk",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Approval_Log",
          "mode": "list",
          "cachedResultName": "Approval_Log"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "lead_id": "={{ $('Parse Email JSON').item.json.lead.id }}",
            "draft_subject": "={{ $('Parse Email JSON').item.json.subject }}",
            "draft_body": "={{ $('Parse Email JSON').item.json.body }}",
            "approval_status": "pending",
            "created_date": "={{ $now.toISO() }}"
          }
        }
      },
      "id": "a8b-log-approval",
      "name": "Log Approval Request",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.4,
      "position": [
        2000,
        100
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "pollTimes": {
          "item": [
            {
              "mode": "everyMinute"
            }
          ]
        },
        "filters": {
          "subject": "[APPROVAL NEEDED]",
          "readStatus": "unread",
          "sender": "kevin.aicareexpo@gmail.com"
        },
        "options": {
          "searchType": "subject"
        }
      },
      "id": "a9-wait-approval",
      "name": "Wait for Approval",
      "type": "n8n-nodes-base.gmailTrigger",
      "typeVersion": 1.2,
      "position": [
        240,
        420
      ],
      "notes": "PART A: Approval Handler"
    },
    {
      "parameters": {
        "operation": "get",
        "messageId": "={{ $json.id }}"
      },
      "id": "a9b-get-full",
      "name": "Get Full Approval Email",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        460,
        420
      ],
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// Extract lead info from subject and parse response\nconst email = $input.item.json;\nconst subject = email.subject || '';\nconst body = email.text || email.snippet || '';\n\n// Extract lead name from subject: \"Re: [APPROVAL NEEDED] Email to Name @ Company\"\nconst match = subject.match(/Email to ([^@]+)@\\s*(.+)/);\nconst leadName = match ? match[1].trim() : 'Unknown';\nconst company = match ? match[2].trim() : 'Unknown';\n\n// Determine response type\nlet responseType = 'UNKNOWN';\nlet editContent = '';\n\nconst upperBody = body.toUpperCase().trim();\n\nif (upperBody.startsWith('APPROVED') || upperBody.includes('\\nAPPROVED')) {\n  responseType = 'APPROVED';\n} else if (upperBody.startsWith('DECLINED') || upperBody.includes('\\nDECLINED')) {\n  responseType = 'DECLINED';\n} else if (upperBody.startsWith('EDIT:') || upperBody.includes('\\nEDIT:')) {\n  responseType = 'EDIT';\n  const editMatch = body.match(/EDIT:\\s*([\\s\\S]*)/i);\n  editContent = editMatch ? editMatch[1].trim() : '';\n}\n\nreturn {\n  json: {\n    response_type: responseType,\n    edit_content: editContent,\n    lead_name: leadName,\n    company: company,\n    original_email_id: email.id\n  }\n};"
      },
      "id": "a10-parse-response",
      "name": "Parse Approval Response",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        680,
        420
      ]
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": false,
                  "leftValue": "",
                  "typeValidation": "loose"
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.response_type }}",
                    "rightValue": "APPROVED",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Approved"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": false,
                  "leftValue": "",
                  "typeValidation": "loose"
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.response_type }}",
                    "rightValue": "EDIT",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Edit"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": false,
                  "leftValue": "",
                  "typeValidation": "loose"
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.response_type }}",
                    "rightValue": "DECLINED",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Declined"
            }
          ]
        },
        "options": {}
      },
      "id": "a11-switch",
      "name": "Route Decision",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.1,
      "position": [
        900,
        420
      ]
    },
    {
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "1t1scMqFj8HwWkGcHwadosl7LONLL6Nr3fF0ZEFs5oyk",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Approval_Log",
          "mode": "list",
          "cachedResultName": "Approval_Log"
        },
        "filtersUI": {
          "values": [
            {
              "lookupColumn": "approval_status",
              "lookupValue": "pending"
            }
          ]
        },
        "options": {
          "returnAllMatches": {
            "values": {
              "returnAll": false,
              "limit": 1
            }
          }
        }
      },
      "id": "a12-get-draft",
      "name": "Get Pending Draft",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.4,
      "position": [
        1120,
        300
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "value": "1t1scMqFj8HwWkGcHwadosl7LONLL6Nr3fF0ZEFs5oyk",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Leads",
          "mode": "list",
          "cachedResultName": "Leads"
        },
        "filtersUI": {
          "values": [
            {
              "lookupColumn": "id",
              "lookupValue": "={{ $('Get Pending Draft').item.json.lead_id }}"
            }
          ]
        },
        "options": {}
      },
      "id": "a12b-get-lead",
      "name": "Get Lead Details",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.4,
      "position": [
        1340,
        300
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "send",
        "sendTo": "={{ $('Get Lead Details').item.json.email }}",
        "subject": "={{ $('Get Pending Draft').item.json.draft_subject }}",
        "emailType": "text",
        "message": "={{ $('Get Pending Draft').item.json.draft_body }}",
        "options": {}
      },
      "id": "a13-send-approved",
      "name": "Send to Lead",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        1560,
        300
      ],
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "update",
        "documentId": {
          "__rl": true,
          "value": "1t1scMqFj8HwWkGcHwadosl7LONLL6Nr3fF0ZEFs5oyk",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Leads",
          "mode": "list",
          "cachedResultName": "Leads"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "status": "sent",
            "email_sent_date": "={{ $now.toISO() }}"
          }
        },
        "options": {
          "cellFormat": "USER_ENTERED"
        }
      },
      "id": "a14-update-sent",
      "name": "Update Lead: Sent",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.4,
      "position": [
        1780,
        300
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "update",
        "documentId": {
          "__rl": true,
          "value": "1t1scMqFj8HwWkGcHwadosl7LONLL6Nr3fF0ZEFs5oyk",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Approval_Log",
          "mode": "list",
          "cachedResultName": "Approval_Log"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "approval_status": "approved",
            "approved_date": "={{ $now.toISO() }}"
          }
        },
        "options": {}
      },
      "id": "a14b-update-log",
      "name": "Update Approval Log",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.4,
      "position": [
        2000,
        300
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "update",
        "documentId": {
          "__rl": true,
          "value": "1t1scMqFj8HwWkGcHwadosl7LONLL6Nr3fF0ZEFs5oyk",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Leads",
          "mode": "list",
          "cachedResultName": "Leads"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "status": "declined",
            "notes": "Declined by approver"
          }
        },
        "options": {}
      },
      "id": "a15-declined",
      "name": "Update Lead: Declined",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.4,
      "position": [
        1120,
        540
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "pollTimes": {
          "item": [
            {
              "mode": "everyMinute"
            }
          ]
        },
        "filters": {
          "readStatus": "unread"
        },
        "options": {}
      },
      "id": "b1-trigger",
      "name": "New Email Received",
      "type": "n8n-nodes-base.gmailTrigger",
      "typeVersion": 1.2,
      "position": [
        240,
        800
      ],
      "notes": "PART B: Inbound Reply Classification"
    },
    {
      "parameters": {
        "operation": "get",
        "messageId": "={{ $json.id }}"
      },
      "id": "b2-get-full",
      "name": "Get Full Email",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        460,
        800
      ],
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": false,
            "leftValue": "",
            "typeValidation": "loose"
          },
          "conditions": [
            {
              "id": "filter-approval",
              "leftValue": "={{ $json.subject }}",
              "rightValue": "[APPROVAL NEEDED]",
              "operator": {
                "type": "string",
                "operation": "notContains"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "b2b-filter",
      "name": "Filter Out Approvals",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.1,
      "position": [
        680,
        800
      ]
    },
    {
      "parameters": {
        "operation": "getAll",
        "returnAll": false,
        "limit": 5,
        "filters": {
          "labelIds": [
            "SENT"
          ],
          "q": "=to:{{ $json.from }}"
        },
        "options": {}
      },
      "id": "b3-check-sent",
      "name": "Check Sent History",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        900,
        800
      ],
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// Check if this is a campaign reply and prepare for classification\nconst incomingEmail = $('Get Full Email').item.json;\nconst sentEmails = $input.all();\n\nconst isCampaignReply = sentEmails.length > 0;\n\nreturn {\n  json: {\n    email_id: incomingEmail.id,\n    from: incomingEmail.from,\n    subject: incomingEmail.subject,\n    body: incomingEmail.text || incomingEmail.snippet,\n    date: incomingEmail.date,\n    is_campaign_reply: isCampaignReply,\n    sent_history_count: sentEmails.length\n  }\n};"
      },
      "id": "b3b-merge",
      "name": "Prepare for Classification",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1120,
        800
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpQueryAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"contents\": [\n    {\n      \"parts\": [\n        {\n          \"text\": \"You are an email classification assistant. Analyze the following email and classify the sender's intent.\\n\\nEmail Details:\\nFrom: {{ $json.from }}\\nSubject: {{ $json.subject }}\\nBody: {{ $json.body }}\\n\\nIs this a reply to our marketing campaign? {{ $json.is_campaign_reply ? 'Yes (we have ' + $json.sent_history_count + ' previous emails to this sender)' : 'No previous emails found' }}\\n\\nClassify into one of these categories:\\n- INTERESTED: Wants to learn more, positive response, requesting meeting/call\\n- NOT_INTERESTED: Polite decline, unsubscribe request, not a fit\\n- QUESTION: Asking for more information, clarification, pricing\\n- OUT_OF_OFFICE: Auto-reply, vacation notice\\n- UNRELATED: Not a reply to our campaign\\n- SPAM: Spam or completely irrelevant\\n\\nReturn ONLY valid JSON (no markdown):\\n{\\n  \\\"classification\\\": \\\"CATEGORY\\\",\\n  \\\"confidence\\\": 0.0-1.0,\\n  \\\"suggested_action\\\": \\\"what to do next\\\",\\n  \\\"summary\\\": \\\"brief summary of the email content\\\",\\n  \\\"sentiment\\\": \\\"positive/neutral/negative\\\"\\n}\"\n        }\n      ]\n    }\n  ],\n  \"generationConfig\": {\n    \"temperature\": 0.2,\n    \"maxOutputTokens\": 512\n  }\n}",
        "options": {}
      },
      "id": "b4-classify",
      "name": "Gemini: Classify Reply",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1340,
        800
      ],
      "credentials": {
        "httpQueryAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// Parse classification response\nconst response = $input.item.json;\nconst emailData = $('Prepare for Classification').item.json;\n\nconst text = response.candidates[0].content.parts[0].text;\nlet cleanText = text.replace(/```json\\s*/g, '').replace(/```\\s*/g, '').trim();\nconst jsonMatch = cleanText.match(/\\{[\\s\\S]*\\}/);\n\nif (!jsonMatch) {\n  throw new Error('Could not parse classification JSON');\n}\n\nconst classification = JSON.parse(jsonMatch[0]);\n\nreturn {\n  json: {\n    ...emailData,\n    ...classification\n  }\n};"
      },
      "id": "b5-parse",
      "name": "Parse Classification",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1560,
        800
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": false,
            "leftValue": "",
            "typeValidation": "loose"
          },
          "conditions": [
            {
              "id": "is-campaign",
              "leftValue": "={{ $json.is_campaign_reply }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "b6-if-campaign",
      "name": "Is Campaign Reply?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.1,
      "position": [
        1780,
        800
      ]
    },
    {
      "parameters": {
        "operation": "update",
        "documentId": {
          "__rl": true,
          "value": "1t1scMqFj8HwWkGcHwadosl7LONLL6Nr3fF0ZEFs5oyk",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Leads",
          "mode": "list",
          "cachedResultName": "Leads"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "status": "={{ $json.classification.toLowerCase() }}",
            "reply_date": "={{ $now.toISO() }}",
            "reply_classification": "={{ $json.classification }}",
            "notes": "={{ $json.summary }}"
          }
        },
        "options": {}
      },
      "id": "b7-update-lead",
      "name": "Update Lead from Reply",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.4,
      "position": [
        2000,
        700
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": false,
                  "leftValue": "",
                  "typeValidation": "loose"
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.classification }}",
                    "rightValue": "INTERESTED",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Interested"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": false,
                  "leftValue": "",
                  "typeValidation": "loose"
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.classification }}",
                    "rightValue": "QUESTION",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Question"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": false,
                  "leftValue": "",
                  "typeValidation": "loose"
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.classification }}",
                    "rightValue": "NOT_INTERESTED",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Not Interested"
            }
          ]
        },
        "options": {
          "fallbackOutput": "extra"
        }
      },
      "id": "b8-switch",
      "name": "Handle Reply Type",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.1,
      "position": [
        2220,
        700
      ]
    },
    {
      "parameters": {
        "operation": "send",
        "sendTo": "kevin.aicareexpo@gmail.com",
        "subject": "=\ud83c\udf89 Interested Lead: {{ $json.from }}",
        "emailType": "html",
        "message": "=<html>\n<body style=\"font-family: Arial, sans-serif;\">\n  <h2 style=\"color: green;\">\ud83c\udf89 New Interested Lead!</h2>\n  <p><strong>From:</strong> {{ $json.from }}</p>\n  <p><strong>Subject:</strong> {{ $json.subject }}</p>\n  <hr>\n  <p><strong>Their Message:</strong></p>\n  <blockquote style=\"background: #f5f5f5; padding: 15px; border-left: 4px solid green;\">{{ $json.body }}</blockquote>\n  <hr>\n  <p><strong>AI Summary:</strong> {{ $json.summary }}</p>\n  <p><strong>Suggested Action:</strong> {{ $json.suggested_action }}</p>\n</body>\n</html>",
        "options": {}
      },
      "id": "b9-notify-interested",
      "name": "Notify: Interested Lead",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        2440,
        600
      ],
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "send",
        "sendTo": "kevin.aicareexpo@gmail.com",
        "subject": "=\u2753 Question from Lead: {{ $json.from }}",
        "emailType": "html",
        "message": "=<html>\n<body style=\"font-family: Arial, sans-serif;\">\n  <h2 style=\"color: blue;\">\u2753 Lead Has a Question</h2>\n  <p><strong>From:</strong> {{ $json.from }}</p>\n  <p><strong>Subject:</strong> {{ $json.subject }}</p>\n  <hr>\n  <p><strong>Their Question:</strong></p>\n  <blockquote style=\"background: #f5f5f5; padding: 15px; border-left: 4px solid blue;\">{{ $json.body }}</blockquote>\n  <hr>\n  <p><strong>AI Summary:</strong> {{ $json.summary }}</p>\n  <p><strong>Suggested Response:</strong> {{ $json.suggested_action }}</p>\n</body>\n</html>",
        "options": {}
      },
      "id": "b10-notify-question",
      "name": "Notify: Lead Question",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        2440,
        760
      ],
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      }
    }
  ],
  "connections": {
    "Setup Knowledge Base": {
      "main": [
        [
          {
            "node": "Get Knowledge Docs",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Knowledge Docs": {
      "main": [
        [
          {
            "node": "Process Each File",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Process Each File": {
      "main": [
        [
          {
            "node": "Download File",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Download File": {
      "main": [
        [
          {
            "node": "Gemini: Start Upload",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gemini: Start Upload": {
      "main": [
        [
          {
            "node": "Gemini: Upload Content",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gemini: Upload Content": {
      "main": [
        [
          {
            "node": "Store RAG File URI",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Store RAG File URI": {
      "main": [
        [
          {
            "node": "Process Each File",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Daily Email Blast": {
      "main": [
        [
          {
            "node": "Get Pending Leads",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Pending Leads": {
      "main": [
        [
          {
            "node": "Validate Email",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Validate Email": {
      "main": [
        [
          {
            "node": "Scrape Lead Website",
            "type": "main",
            "index": 0
          },
          {
            "node": "Get RAG File URIs",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Scrape Lead Website": {
      "main": [
        [
          {
            "node": "Merge Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get RAG File URIs": {
      "main": [
        [
          {
            "node": "Merge Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Merge Data": {
      "main": [
        [
          {
            "node": "Gemini: Generate Email",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gemini: Generate Email": {
      "main": [
        [
          {
            "node": "Parse Email JSON",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse Email JSON": {
      "main": [
        [
          {
            "node": "Send Approval Request",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send Approval Request": {
      "main": [
        [
          {
            "node": "Log Approval Request",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wait for Approval": {
      "main": [
        [
          {
            "node": "Get Full Approval Email",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Full Approval Email": {
      "main": [
        [
          {
            "node": "Parse Approval Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse Approval Response": {
      "main": [
        [
          {
            "node": "Route Decision",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Route Decision": {
      "main": [
        [
          {
            "node": "Get Pending Draft",
            "type": "main",
            "index": 0
          }
        ],
        [],
        [
          {
            "node": "Update Lead: Declined",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Pending Draft": {
      "main": [
        [
          {
            "node": "Get Lead Details",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Lead Details": {
      "main": [
        [
          {
            "node": "Send to Lead",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send to Lead": {
      "main": [
        [
          {
            "node": "Update Lead: Sent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Update Lead: Sent": {
      "main": [
        [
          {
            "node": "Update Approval Log",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "New Email Received": {
      "main": [
        [
          {
            "node": "Get Full Email",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Full Email": {
      "main": [
        [
          {
            "node": "Filter Out Approvals",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Filter Out Approvals": {
      "main": [
        [
          {
            "node": "Check Sent History",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Sent History": {
      "main": [
        [
          {
            "node": "Prepare for Classification",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare for Classification": {
      "main": [
        [
          {
            "node": "Gemini: Classify Reply",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gemini: Classify Reply": {
      "main": [
        [
          {
            "node": "Parse Classification",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse Classification": {
      "main": [
        [
          {
            "node": "Is Campaign Reply?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Is Campaign Reply?": {
      "main": [
        [
          {
            "node": "Update Lead from Reply",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Update Lead from Reply": {
      "main": [
        [
          {
            "node": "Handle Reply Type",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Handle Reply Type": {
      "main": [
        [
          {
            "node": "Notify: Interested Lead",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Notify: Lead Question",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "1",
  "tags": [
    {
      "name": "email-marketing"
    },
    {
      "name": "gemini-rag"
    },
    {
      "name": "approval-workflow"
    }
  ]
}