phanquocdat123 commited on
Commit
77e46d0
·
verified ·
1 Parent(s): f18917e

Create recognizer.js

Browse files
Files changed (1) hide show
  1. processors/recognizer.js +63 -0
processors/recognizer.js ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // processors/recognizer.js
2
+ const googleSheets = require('../services/googleSheets');
3
+
4
+ /**
5
+ * Hàm nhận diện khách hàng từ Excel
6
+ * Trả về session đã được nạp dữ liệu cũ (nếu có)
7
+ */
8
+ async function identify(userId, session) {
9
+ // 1. Nếu đã nhận diện trong phiên này rồi thì thôi
10
+ if (!session || session.isRecognized) return session;
11
+
12
+ try {
13
+ // Tìm thông tin khách trong Sheet bằng userId
14
+ const customerData = await googleSheets.findCustomerById(userId);
15
+
16
+ if (customerData) {
17
+ if (!session.entities) session.entities = {};
18
+
19
+ // Dữ liệu từ Excel làm "nền"
20
+ const excelData = {
21
+ name: customerData.Ho_Ten || "",
22
+ phone: String(customerData.SDT || ""),
23
+ address: customerData.Dia_Chi || "",
24
+ weight: customerData.Can_Nang_1 || customerData.Can_Nang || "",
25
+ };
26
+
27
+ /**
28
+ * CƠ CHẾ GỘP DỮ LIỆU AN TOÀN:
29
+ * - Nếu trong Session hiện tại đang trống (null/rỗng), ta mới lấy từ Excel đắp vào.
30
+ * - Nếu Session hiện tại đã có dữ liệu (do khách vừa nhắn), ta giữ nguyên dữ liệu đó.
31
+ * - Tuyệt đối không để giá trị rỗng từ tin nhắn mới ghi đè lên giá trị đã có từ Excel.
32
+ */
33
+ for (const key in excelData) {
34
+ const currentValue = session.entities[key];
35
+ const hasNoCurrentValue = !currentValue || currentValue === "" || currentValue === "null";
36
+
37
+ if (hasNoCurrentValue && excelData[key] !== "") {
38
+ session.entities[key] = excelData[key];
39
+ }
40
+ }
41
+
42
+ // Đồng bộ ngược lại các biến trực tiếp trên session để các file khác dễ dùng
43
+ session.phone = session.entities.phone;
44
+ session.address = session.entities.address;
45
+ session.weight = session.entities.weight;
46
+
47
+ // Đánh dấu đã nhận diện thành công
48
+ session.isRecognized = true;
49
+
50
+ console.log(`\x1b[32m🔍 [Recognizer] Khách quen quay lại: ${session.entities.name || userId} (${session.entities.weight}kg)\x1b[0m`);
51
+ } else {
52
+ // Khách mới hoàn toàn
53
+ session.isRecognized = true;
54
+ console.log(`🔍 [Recognizer] Khách mới hoàn toàn: ${userId}`);
55
+ }
56
+ } catch (err) {
57
+ console.error("❌ [Recognizer Error]:", err.message);
58
+ }
59
+
60
+ return session;
61
+ }
62
+
63
+ module.exports = { identify };