{
  "name": "Messenger AI Sales - Session Memory + Chốt Đơn",
  "nodes": [
    {
      "parameters": {
        "path": "fb-comment-webhook",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "5da5a19a-6802-43a2-99b8-06722cee38b4",
      "name": "Webhook Verify (GET)",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        -592,
        1088
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 1
          },
          "conditions": [
            {
              "leftValue": "={{ $json.query['hub.verify_token'] }}",
              "rightValue": "REPLACE_WITH_FACEBOOK_VERIFY_TOKEN",
              "operator": {
                "type": "string",
                "operation": "equals"
              },
              "id": "bf56c89d-c4cf-4fc6-9780-f7f6399e4fe9"
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "c1d605c1-3ed7-48f8-bf70-a2b7080fbb32",
      "name": "Check Verify Token",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        -416,
        1088
      ]
    },
    {
      "parameters": {
        "respondWith": "text",
        "responseBody": "={{ $json.query['hub.challenge'] }}",
        "options": {}
      },
      "id": "19c06cab-3aef-4c56-8c59-b5a8614ae46c",
      "name": "Respond Challenge",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        -240,
        1024
      ]
    },
    {
      "parameters": {
        "respondWith": "text",
        "responseBody": "Forbidden",
        "options": {
          "responseCode": 403
        }
      },
      "id": "40c4b4df-7292-4f5c-86a1-2229f2f7d0c6",
      "name": "Respond Forbidden",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        -240,
        1184
      ]
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "fb-comment-webhook",
        "options": {}
      },
      "id": "4b1798af-b216-4070-a02b-1aed2f06b0ad",
      "name": "Webhook Event (POST)",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        -592,
        1344
      ]
    },
    {
      "parameters": {
        "fieldToSplitOut": "body.entry",
        "options": {}
      },
      "id": "9c3d97f5-93e5-4bc0-8bde-e767ac8f1c9e",
      "name": "Split Entries",
      "type": "n8n-nodes-base.splitOut",
      "typeVersion": 1,
      "position": [
        -400,
        1360
      ]
    },
    {
      "parameters": {
        "operation": "download",
        "fileId": {
          "__rl": true,
          "value": "REPLACE_WITH_GOOGLE_DRIVE_FILE_ID",
          "mode": "id"
        },
        "options": {}
      },
      "id": "4ab6f26a-37b5-42a3-99c0-7c9b23f7b543",
      "name": "Get Product Guide (Drive)",
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        528,
        1056
      ]
    },
    {
      "parameters": {
        "operation": "text",
        "options": {}
      },
      "id": "f573204b-f8fd-4461-8e42-4e4e6ed6abac",
      "name": "Extract Guide Text",
      "type": "n8n-nodes-base.extractFromFile",
      "typeVersion": 1,
      "position": [
        704,
        1056
      ]
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "={{ $('Extract Fields1').item.json.message_text }}",
        "options": {
          "systemMessage": "=Bạn là nhân viên tư vấn bán hàng, trả lời bằng tiếng Việt, tự nhiên, ngắn gọn, thân thiện.\n\nQUY TRÌNH SẢN PHẨM (nguồn thông tin duy nhất, không bịa thêm):\n{{ $('Extract Guide Text').item.json.text }}\n\nQUY TẮC:\n1. Tư vấn dựa đúng theo nội dung quy trình sản phẩm ở trên.\n2. Khi khách thể hiện nhu cầu mua hàng hoặc đăng ký khóa học, hỏi LẦN LƯỢT từng thông tin: Họ tên -> Số điện thoại -> Email (không hỏi dồn một lúc).\n3. Khi đã có đủ Họ tên, Số điện thoại, Email, xác nhận lại với khách nội dung đơn hàng, sau đó gọi tool \"Save_Order_To_Sheet\" để lưu đơn.\n4. Không tự ý gọi tool khi chưa đủ thông tin hoặc khách chưa xác nhận."
        }
      },
      "id": "da1dbddb-6a58-48f4-865d-ccd5832daa37",
      "name": "AI Sales Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 1.7,
      "position": [
        448,
        1264
      ]
    },
    {
      "parameters": {
        "options": {}
      },
      "id": "ddf2d8ef-8003-40ce-b15b-661a61991413",
      "name": "Google Gemini Chat Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatGoogleGemini",
      "typeVersion": 1,
      "position": [
        336,
        1488
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://graph.facebook.com/v21.0/me/messages",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "access_token",
              "value": "REPLACE_WITH_FACEBOOK_PAGE_ACCESS_TOKEN"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ { \"recipient\": { \"id\": $('Extract Fields1').item.json.sender_id }, \"message\": { \"text\": $json.output } } }}",
        "options": {}
      },
      "id": "3790c9ea-6db4-42cc-85f1-40ac15fd484f",
      "name": "Send Message To Messenger",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        784,
        1472
      ]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "f1",
              "name": "sender_id",
              "type": "string",
              "value": "={{ $json.sender.id }}"
            },
            {
              "id": "f2",
              "name": "page_id",
              "type": "string",
              "value": "={{ $json.recipient.id }}"
            },
            {
              "id": "f3",
              "name": "message_text",
              "type": "string",
              "value": "={{ $json.message.text }}"
            },
            {
              "id": "f4",
              "name": "timestamp",
              "type": "string",
              "value": "={{ $json.timestamp }}"
            }
          ]
        },
        "options": {}
      },
      "id": "2b808e37-e041-4136-87e9-6afe5e81fb49",
      "name": "Extract Fields1",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        352,
        1056
      ]
    },
    {
      "parameters": {
        "fieldToSplitOut": "messaging",
        "options": {}
      },
      "id": "6633e295-b353-43f7-8828-88673c0759c9",
      "name": "Split Messaging",
      "type": "n8n-nodes-base.splitOut",
      "typeVersion": 1,
      "position": [
        -16,
        1344
      ]
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 1
                },
                "conditions": [
                  {
                    "leftValue": "={{ !!$json.messaging }}",
                    "rightValue": true,
                    "operator": {
                      "type": "boolean",
                      "operation": "equals"
                    },
                    "id": "has-messaging-01"
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Tin nhắn"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 1
                },
                "conditions": [
                  {
                    "leftValue": "={{ !!$json.changes }}",
                    "rightValue": true,
                    "operator": {
                      "type": "boolean",
                      "operation": "equals"
                    },
                    "id": "has-changes-01"
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Comment/Feed"
            }
          ]
        },
        "options": {
          "fallbackOutput": "none"
        }
      },
      "id": "f394e546-71a0-4a6d-9697-d7619210fe7b",
      "name": "Phân Loại Nguồn Sự Kiện",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3,
      "position": [
        -224,
        1360
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 1
          },
          "conditions": [
            {
              "leftValue": "={{ !!$json.message }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "equals"
              },
              "id": "has-msg-01"
            },
            {
              "leftValue": "={{ !!$json.message?.is_echo }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "notEquals"
              },
              "id": "not-echo-01"
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "c56b345f-27b5-4f94-bfe1-6241ef9e9752",
      "name": "Chỉ Nhận Tin Nhắn Text",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        112,
        1072
      ]
    },
    {
      "parameters": {
        "sessionIdType": "customKey",
        "sessionKey": "={{ $('Extract Fields1').item.json.sender_id }}",
        "tableName": "messenger_chat_memory",
        "contextWindowLength": 20
      },
      "id": "e5d25cc6-8066-4fa6-851c-0e7939bdfde9",
      "name": "Postgres Memory (theo PSID)",
      "type": "@n8n/n8n-nodes-langchain.memoryPostgresChat",
      "typeVersion": 1.3,
      "position": [
        480,
        1488
      ]
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "REPLACE_WITH_GOOGLE_SHEETS_DOCUMENT_ID",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Orders"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Timestamp": "={{ $now.toISO() }}",
            "PSID": "={{ $('Extract Fields1').item.json.sender_id }}",
            "HoTen": "={{ $fromAI('hoTen', 'Họ tên khách hàng', 'string') }}",
            "SoDienThoai": "={{ $fromAI('soDienThoai', 'Số điện thoại khách hàng', 'string') }}",
            "Email": "={{ $fromAI('email', 'Email khách hàng', 'string') }}",
            "SanPham": "={{ $fromAI('sanPham', 'Tên sản phẩm hoặc khóa học khách đặt mua', 'string') }}",
            "GhiChu": "={{ $fromAI('ghiChu', 'Ghi chú thêm về đơn hàng nếu có', 'string') }}"
          },
          "matchingColumns": [],
          "schema": [
            {
              "id": "Timestamp",
              "displayName": "Timestamp",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "PSID",
              "displayName": "PSID",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "HoTen",
              "displayName": "HoTen",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "SoDienThoai",
              "displayName": "SoDienThoai",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "Email",
              "displayName": "Email",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "SanPham",
              "displayName": "SanPham",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "GhiChu",
              "displayName": "GhiChu",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "id": "2346099a-9873-4a46-9c64-ce240c39dee0",
      "name": "Save_Order_To_Sheet",
      "type": "n8n-nodes-base.googleSheetsTool",
      "typeVersion": 4.6,
      "position": [
        608,
        1488
      ]
    }
  ],
  "pinData": {},
  "connections": {
    "Webhook Verify (GET)": {
      "main": [
        [
          {
            "node": "Check Verify Token",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Verify Token": {
      "main": [
        [
          {
            "node": "Respond Challenge",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Respond Forbidden",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Webhook Event (POST)": {
      "main": [
        [
          {
            "node": "Split Entries",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split Entries": {
      "main": [
        [
          {
            "node": "Phân Loại Nguồn Sự Kiện",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Product Guide (Drive)": {
      "main": [
        [
          {
            "node": "Extract Guide Text",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract Guide Text": {
      "main": [
        [
          {
            "node": "AI Sales Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI Sales Agent": {
      "main": [
        [
          {
            "node": "Send Message To Messenger",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Gemini Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "AI Sales Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Extract Fields1": {
      "main": [
        [
          {
            "node": "Get Product Guide (Drive)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split Messaging": {
      "main": [
        [
          {
            "node": "Chỉ Nhận Tin Nhắn Text",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Phân Loại Nguồn Sự Kiện": {
      "main": [
        [
          {
            "node": "Split Messaging",
            "type": "main",
            "index": 0
          }
        ],
        []
      ]
    },
    "Chỉ Nhận Tin Nhắn Text": {
      "main": [
        [
          {
            "node": "Extract Fields1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Postgres Memory (theo PSID)": {
      "ai_memory": [
        [
          {
            "node": "AI Sales Agent",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "Save_Order_To_Sheet": {
      "ai_tool": [
        [
          {
            "node": "AI Sales Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "binaryMode": "separate",
    "availableInMCP": false
  },
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "nodeGroups": [],
  "tags": []
}
