{
  "name": "MLM Chatbot Automation Workflow",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "chatbot",
        "options": {}
      },
      "id": "chatbot-webhook",
      "name": "Chatbot Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 1,
      "position": [
        240,
        300
      ]
    },
    {
      "parameters": {
        "functionCode": "// Parse incoming chatbot message\nconst body = $input.first().json.body;\nconst message = body.message || '';\nconst userId = body.userId || null;\nconst sessionId = body.sessionId || 'anonymous';\nconst language = body.language || 'en';\n\n// Extract intent from message\nconst intent = detectIntent(message.toLowerCase());\n\nfunction detectIntent(msg) {\n  // MLM-specific intent detection\n  if (msg.includes('commission') || msg.includes('earning') || msg.includes('payout')) {\n    return 'commission_inquiry';\n  }\n  if (msg.includes('rank') || msg.includes('level') || msg.includes('advancement')) {\n    return 'rank_inquiry';\n  }\n  if (msg.includes('product') || msg.includes('price') || msg.includes('buy')) {\n    return 'product_inquiry';\n  }\n  if (msg.includes('join') || msg.includes('register') || msg.includes('signup')) {\n    return 'registration_inquiry';\n  }\n  if (msg.includes('downline') || msg.includes('team') || msg.includes('genealogy')) {\n    return 'team_inquiry';\n  }\n  if (msg.includes('help') || msg.includes('support') || msg.includes('contact')) {\n    return 'support_request';\n  }\n  return 'general_inquiry';\n}\n\nreturn [{\n  json: {\n    message,\n    userId,\n    sessionId,\n    language,\n    intent,\n    timestamp: new Date().toISOString()\n  }\n}];"
      },
      "id": "parse-message",
      "name": "Parse Message",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        460,
        300
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "commission_inquiry",
              "leftValue": "={{ $json.intent }}",
              "rightValue": "commission_inquiry",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            },
            {
              "id": "rank_inquiry",
              "leftValue": "={{ $json.intent }}",
              "rightValue": "rank_inquiry",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            },
            {
              "id": "product_inquiry",
              "leftValue": "={{ $json.intent }}",
              "rightValue": "product_inquiry",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            },
            {
              "id": "registration_inquiry",
              "leftValue": "={{ $json.intent }}",
              "rightValue": "registration_inquiry",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "or"
        },
        "options": {}
      },
      "id": "route-intent",
      "name": "Route by Intent",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 1,
      "position": [
        680,
        300
      ]
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT u.id, u.name, u.email, u.rank, u.total_commission, u.current_pv, u.total_pv FROM users u WHERE u.id = $1 AND u.active = true",
        "additionalFields": {
          "values": "={{ $json.userId }}"
        }
      },
      "id": "get-user-data",
      "name": "Get User Data",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 1,
      "position": [
        900,
        200
      ],
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "functionCode": "// Generate commission response\nconst userData = $input.first().json;\nconst language = $('Parse Message').first().json.language;\n\nconst responses = {\n  en: {\n    commission_info: `Hi ${userData.name}! \ud83d\udcb0\\n\\nYour Commission Summary:\\n\u2022 Current Rank: ${userData.rank}\\n\u2022 Total Earnings: \u20b1${userData.total_commission.toLocaleString()}\\n\u2022 This Month PV: ${userData.current_pv}\\n\u2022 Total PV: ${userData.total_pv}\\n\\nNext payout is on the 15th of each month. Keep building your team! \ud83d\ude80`,\n    no_user: \"I'd be happy to help with commission information! Please log in to your account first, or contact support if you need assistance.\"\n  },\n  es: {\n    commission_info: `\u00a1Hola ${userData.name}! \ud83d\udcb0\\n\\nResumen de Comisiones:\\n\u2022 Rango Actual: ${userData.rank}\\n\u2022 Ganancias Totales: \u20b1${userData.total_commission.toLocaleString()}\\n\u2022 PV Este Mes: ${userData.current_pv}\\n\u2022 PV Total: ${userData.total_pv}\\n\\n\u00a1El pr\u00f3ximo pago es el 15 de cada mes. Sigue construyendo tu equipo! \ud83d\ude80`,\n    no_user: \"\u00a1Me encantar\u00eda ayudarte con informaci\u00f3n de comisiones! Por favor inicia sesi\u00f3n primero, o contacta soporte si necesitas ayuda.\"\n  }\n};\n\nconst lang = responses[language] || responses.en;\nconst response = userData.id ? lang.commission_info : lang.no_user;\n\nreturn [{\n  json: {\n    response,\n    intent: 'commission_inquiry',\n    userId: userData.id || null,\n    hasUserData: !!userData.id\n  }\n}];"
      },
      "id": "commission-response",
      "name": "Commission Response",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        1120,
        200
      ]
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT name, description, price, pv, image FROM products WHERE active = true ORDER BY featured DESC, created_at DESC LIMIT 5",
        "options": {}
      },
      "id": "get-products",
      "name": "Get Products",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 1,
      "position": [
        900,
        400
      ],
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "functionCode": "// Generate product response\nconst products = $input.first().json;\nconst language = $('Parse Message').first().json.language;\nconst domain = $env.MLM_API_BASE_URL.replace('/api', '');\n\nconst responses = {\n  en: {\n    product_list: `\ud83c\udf3f Our Premium Products:\\n\\n${products.map(p => `\u2022 **${p.name}** - \u20b1${p.price.toLocaleString()} (${p.pv} PV)\\n  ${p.description.substring(0, 80)}...`).join('\\n\\n')}\\n\\n\ud83d\uded2 Shop now: ${domain}/shop\\n\ud83d\udca1 Questions? Ask me about specific products!`\n  },\n  es: {\n    product_list: `\ud83c\udf3f Nuestros Productos Premium:\\n\\n${products.map(p => `\u2022 **${p.name}** - \u20b1${p.price.toLocaleString()} (${p.pv} PV)\\n  ${p.description.substring(0, 80)}...`).join('\\n\\n')}\\n\\n\ud83d\uded2 Compra ahora: ${domain}/shop\\n\ud83d\udca1 \u00bfPreguntas? \u00a1Preg\u00fantame sobre productos espec\u00edficos!`\n  }\n};\n\nconst lang = responses[language] || responses.en;\n\nreturn [{\n  json: {\n    response: lang.product_list,\n    intent: 'product_inquiry',\n    products: products.length\n  }\n}];"
      },
      "id": "product-response",
      "name": "Product Response",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        1120,
        400
      ]
    },
    {
      "parameters": {
        "functionCode": "// Generate rank advancement response\nconst language = $('Parse Message').first().json.language;\nconst domain = $env.MLM_API_BASE_URL.replace('/api', '');\n\nconst responses = {\n  en: {\n    rank_info: `\ud83c\udfc6 MLM Rank System:\\n\\n\ud83e\udd49 **Silver** (500 PV)\\n\u2022 1% commission on L1\\n\u2022 0.75% on L2-L6\\n\\n\ud83e\udd48 **Gold** (1,500 PV)\\n\u2022 1.5% commission on L1\\n\u2022 1% on L2-L6\\n\u2022 Monthly bonus: \u20b15,000\\n\\n\ud83e\udd47 **Platinum** (5,000 PV)\\n\u2022 2% commission on L1\\n\u2022 1.5% on L2-L6\\n\u2022 Monthly bonus: \u20b115,000\\n\u2022 Leadership rewards\\n\\n\ud83d\udcc8 Track progress: ${domain}/dashboard\\n\ud83d\udcaa Build your team and advance!`\n  },\n  es: {\n    rank_info: `\ud83c\udfc6 Sistema de Rangos MLM:\\n\\n\ud83e\udd49 **Plata** (500 PV)\\n\u2022 1% comisi\u00f3n en L1\\n\u2022 0.75% en L2-L6\\n\\n\ud83e\udd48 **Oro** (1,500 PV)\\n\u2022 1.5% comisi\u00f3n en L1\\n\u2022 1% en L2-L6\\n\u2022 Bono mensual: \u20b15,000\\n\\n\ud83e\udd47 **Platino** (5,000 PV)\\n\u2022 2% comisi\u00f3n en L1\\n\u2022 1.5% en L2-L6\\n\u2022 Bono mensual: \u20b115,000\\n\u2022 Recompensas de liderazgo\\n\\n\ud83d\udcc8 Seguir progreso: ${domain}/dashboard\\n\ud83d\udcaa \u00a1Construye tu equipo y avanza!`\n  }\n};\n\nconst lang = responses[language] || responses.en;\n\nreturn [{\n  json: {\n    response: lang.rank_info,\n    intent: 'rank_inquiry'\n  }\n}];"
      },
      "id": "rank-response",
      "name": "Rank Response",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        1120,
        600
      ]
    },
    {
      "parameters": {
        "functionCode": "// Generate registration response\nconst language = $('Parse Message').first().json.language;\nconst domain = $env.MLM_API_BASE_URL.replace('/api', '');\n\nconst responses = {\n  en: {\n    registration_info: `\ud83d\ude80 Join Extreme Life MLM Today!\\n\\n\u2728 **What You Get:**\\n\u2022 Premium herbal products at distributor prices\\n\u2022 Earn up to 6 levels deep\\n\u2022 Professional training & support\\n\u2022 Marketing materials included\\n\u2022 Mobile app for team management\\n\\n\ud83d\udcb0 **Starter Packages:**\\n\u2022 Basic: \u20b12,500 (includes 3 products)\\n\u2022 Premium: \u20b15,000 (includes 6 products + bonus)\\n\u2022 VIP: \u20b110,000 (includes 12 products + exclusive benefits)\\n\\n\ud83d\udcdd Register now: ${domain}/register\\n\ud83d\udcde Questions? Call: +63-XXX-XXXX`\n  },\n  es: {\n    registration_info: `\ud83d\ude80 \u00a1\u00danete a Extreme Life MLM Hoy!\\n\\n\u2728 **Lo Que Obtienes:**\\n\u2022 Productos herbales premium a precios de distribuidor\\n\u2022 Gana hasta 6 niveles de profundidad\\n\u2022 Entrenamiento profesional y soporte\\n\u2022 Materiales de marketing incluidos\\n\u2022 App m\u00f3vil para gesti\u00f3n de equipo\\n\\n\ud83d\udcb0 **Paquetes de Inicio:**\\n\u2022 B\u00e1sico: \u20b12,500 (incluye 3 productos)\\n\u2022 Premium: \u20b15,000 (incluye 6 productos + bono)\\n\u2022 VIP: \u20b110,000 (incluye 12 productos + beneficios exclusivos)\\n\\n\ud83d\udcdd Reg\u00edstrate ahora: ${domain}/register\\n\ud83d\udcde \u00bfPreguntas? Llama: +63-XXX-XXXX`\n  }\n};\n\nconst lang = responses[language] || responses.en;\n\nreturn [{\n  json: {\n    response: lang.registration_info,\n    intent: 'registration_inquiry'\n  }\n}];"
      },
      "id": "registration-response",
      "name": "Registration Response",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        1120,
        800
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $env.MLM_API_BASE_URL }}/chatbot/response",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "sessionId",
              "value": "={{ $('Parse Message').first().json.sessionId }}"
            },
            {
              "name": "response",
              "value": "={{ $json.response }}"
            },
            {
              "name": "intent",
              "value": "={{ $json.intent }}"
            },
            {
              "name": "timestamp",
              "value": "={{ new Date().toISOString() }}"
            }
          ]
        }
      },
      "id": "send-response",
      "name": "Send Response",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 1,
      "position": [
        1340,
        400
      ]
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "INSERT INTO chatbot_conversations (session_id, user_id, message, intent, response, language, created_at) VALUES ($1, $2, $3, $4, $5, $6, NOW())",
        "additionalFields": {
          "values": "={{ $('Parse Message').first().json.sessionId }}, {{ $('Parse Message').first().json.userId || null }}, {{ $('Parse Message').first().json.message }}, {{ $json.intent }}, {{ $json.response }}, {{ $('Parse Message').first().json.language }}"
        }
      },
      "id": "log-conversation",
      "name": "Log Conversation",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 1,
      "position": [
        1560,
        400
      ],
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    }
  ],
  "connections": {
    "Chatbot Webhook": {
      "main": [
        [
          {
            "node": "Parse Message",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse Message": {
      "main": [
        [
          {
            "node": "Route by Intent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Route by Intent": {
      "main": [
        [
          {
            "node": "Get User Data",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Rank Response",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Get Products",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Registration Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get User Data": {
      "main": [
        [
          {
            "node": "Commission Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Commission Response": {
      "main": [
        [
          {
            "node": "Send Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Products": {
      "main": [
        [
          {
            "node": "Product Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Product Response": {
      "main": [
        [
          {
            "node": "Send Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Rank Response": {
      "main": [
        [
          {
            "node": "Send Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Registration Response": {
      "main": [
        [
          {
            "node": "Send Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send Response": {
      "main": [
        [
          {
            "node": "Log Conversation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": true,
  "settings": {
    "timezone": "America/New_York"
  },
  "versionId": "1",
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "id": "mlm-chatbot-automation",
  "tags": [
    {
      "createdAt": "2024-01-01T00:00:00.000Z",
      "updatedAt": "2024-01-01T00:00:00.000Z",
      "id": "chatbot",
      "name": "Chatbot"
    },
    {
      "createdAt": "2024-01-01T00:00:00.000Z",
      "updatedAt": "2024-01-01T00:00:00.000Z",
      "id": "mlm",
      "name": "MLM"
    }
  ]
}