phanquocdat123 commited on
Commit
5af6907
·
verified ·
1 Parent(s): 777958c

Create processors/analyzer.js

Browse files
Files changed (1) hide show
  1. processors/analyzer.js +156 -0
processors/analyzer.js ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const helpers = require('../utils/helpers');
2
+
3
+ const analyzer = {
4
+ // THAY ĐỔI: Nhận thêm tham số thứ 4 là globalInventory từ server.js truyền sang
5
+ extract: (text, session, dimConfig = [], globalInventory = null) => {
6
+ const raw = text.toLowerCase();
7
+ const clean = helpers.removeAccents(raw);
8
+
9
+ // --- 1. LẤY DANH SÁCH NHÓM HÀNG (SỬA LỖI INVENTORY RỖNG) ---
10
+ // Ưu tiên lấy từ globalInventory (Tham số mới), nếu không có mới tìm trong session (cũ)
11
+ const inventoryObj = globalInventory?.inventory || globalInventory || session?.inventoryData || {};
12
+
13
+ // Quét lấy danh sách Group duy nhất từ kho thực tế
14
+ const dynamicGroups = (Object.keys(inventoryObj).length > 0)
15
+ ? [...new Set(Object.values(inventoryObj).map(item => item.group).filter(Boolean))]
16
+ : [];
17
+
18
+ // Debug nhanh trên Terminal - Đã sửa logic kiểm tra
19
+ if (dynamicGroups.length === 0) {
20
+ console.log("⚠️ [Analyzer] Cảnh báo: Không tìm thấy nhóm hàng để đối soát.");
21
+ } else {
22
+ console.log(`🚀 [Analyzer] Đã nạp ${dynamicGroups.length} nhóm: ${dynamicGroups.join(', ')}`);
23
+ }
24
+
25
+ // --- 2. NHẬN DIỆN THỰC THỂ (ENTITIES) ---
26
+ const isSystemCommand = text.includes("chonsize") || text.includes("chốtsize") || text.startsWith("chọn ");
27
+ const productMatch = isSystemCommand ? null : text.match(/([a-zA-Z]+\d+)/i);
28
+ const phoneMatch = text.match(/(0|84)\d{8,10}/);
29
+ const addressMatch = text.match(/(?:dia chi|DC|So nhà|đường|ở|tại)[:\s]+(.*?)(?=\s*ACTION|$)/i);
30
+
31
+ const address = addressMatch ? addressMatch[1].trim() : (session?.entities?.address || null);
32
+
33
+ // Cải tiến bắt cân nặng linh hoạt hơn
34
+ const weightMatch = text.match(/(\d+)\s*(kg|kí|ký|cân|nặng)/i) || text.match(/(?:nặng|bé)\s*(\d+)/i);
35
+
36
+ const nameMatch = text.match(/(?:tên|bé tên|bé tên là|con tên là)[:\s]*([a-zA-ZÀ-ỹ\s]+)/i);
37
+
38
+ // Bắt tuổi: Đọc cả số tuổi và đơn vị (nếu có)
39
+ const ageMatch = text.match(/(?:tuổi|bé được|mấy tuổi|tháng tuổi)[:\s]*(\d+)\s*(tuổi|tháng)?/i);
40
+
41
+ // Tối ưu tìm nhóm hàng: Đối soát tin nhắn khách với danh sách nhóm trong kho
42
+ const foundGroup = dynamicGroups.find(g => {
43
+ const gClean = helpers.removeAccents(g.toLowerCase()).trim();
44
+ const textClean = helpers.removeAccents(text.toLowerCase()).trim();
45
+ return textClean.includes(gClean) || gClean.includes(textClean);
46
+ });
47
+
48
+ // Xử lý chuẩn hóa cân nặng
49
+ let extractedWeight = null;
50
+ if (weightMatch) {
51
+ // Lấy số từ weightMatch (kiểm tra xem nhóm nào chứa chữ số)
52
+ const weightStr = weightMatch[1] || weightMatch[2];
53
+ const numberMatch = weightStr ? weightStr.match(/\d+/) : null;
54
+ extractedWeight = numberMatch ? numberMatch[0] : null;
55
+ }
56
+
57
+ // Xử lý chuẩn hóa tuổi (lấy cả số và đơn vị)
58
+ let extractedAge = null;
59
+ if (ageMatch && ageMatch[1]) {
60
+ extractedAge = `${ageMatch[1]}${ageMatch[2] ? ' ' + ageMatch[2] : ' tuổi'}`;
61
+ }
62
+
63
+ const entities = {
64
+ productCode: productMatch ? productMatch[1].toUpperCase() : (session?.entities?.productCode || null),
65
+ phone: phoneMatch ? phoneMatch[0] : (session?.entities?.phone || null),
66
+ address: addressMatch ? addressMatch[1].trim() : (session?.entities?.address || null),
67
+ weight: extractedWeight || (session?.entities?.weight || null),
68
+ name: nameMatch ? nameMatch[1].trim() : (session?.entities?.name || null),
69
+ age: extractedAge || (session?.entities?.age || null),
70
+ group: foundGroup ? foundGroup : (session?.entities?.group || null) // Giữ group cũ nếu không tìm thấy cái mới
71
+ };
72
+ console.log("🎯 [DEBUG] Các biến nhận diện được từ tin nhắn:", JSON.stringify(entities, null, 2));
73
+ if (foundGroup) console.log(`🎯 [Analyzer] Đã xác định được Group: ${foundGroup}`);
74
+
75
+ // --- 3. TÍNH ĐIỂM CÁC VÙNG (ZONES) ---
76
+ let zoneScores = { CONSULT: 0, CONVERSION: 0, RETAIN: 0, REMEDY: 0 };
77
+ let detectedFlags = {};
78
+
79
+ if (dimConfig && dimConfig.length > 0) {
80
+ dimConfig.forEach(dim => {
81
+ let score = 0;
82
+ // Regex match
83
+ if (dim.regex && new RegExp(dim.regex, 'i').test(text)) score += 20;
84
+
85
+ // Keywords match
86
+ if (dim.keywords) {
87
+ const isKeywordMatch = dim.keywords.some(k => {
88
+ const kw = k.toLowerCase().trim();
89
+ return raw.includes(kw) || clean.includes(helpers.removeAccents(kw));
90
+ });
91
+
92
+ if (isKeywordMatch) {
93
+ score += (Number(dim.weight) || 20);
94
+ }
95
+ }
96
+
97
+ const isMatched = score >= 5;
98
+ detectedFlags[dim.name] = isMatched;
99
+ if (isMatched) {
100
+ const zone = (dim.zone || 'REMEDY').toUpperCase();
101
+ zoneScores[zone] = (zoneScores[zone] || 0) + (Number(dim.weight) || 10);
102
+ }
103
+ });
104
+ }
105
+
106
+ // --- 4. CHIẾN THUẬT ĐẨY ĐIỂM (BOOSTING) ---
107
+ if (raw.includes("action_submit_form")) {
108
+ zoneScores.CONVERSION = 999; // Điểm tối cao
109
+ zoneScores.CONSULT = 0;
110
+ zoneScores.RETAIN = 0;
111
+ zoneScores.REMEDY = 0;
112
+ console.log("🚀 [Analyzer] Phát hiện mã Form: Ép thắng CONVERSION");
113
+ } else {
114
+
115
+ // Nếu nhắc tới tên nhóm hàng (ví dụ: "Đồ bộ"), ép CONSULT thắng để hiện mẫu
116
+ if (foundGroup) { zoneScores.CONSULT += 150; }
117
+
118
+ const intentPurchase = ["chốt", "lấy", "mua", "ok", "đặt", "chọn", "gửi cho"];
119
+ if (intentPurchase.some(word => raw.includes(word))) zoneScores.CONVERSION += 100;
120
+
121
+ // Thưởng điểm nhẹ cho các thông tin cá nhân
122
+ if (productMatch) zoneScores.CONSULT += 50; // Thấy mã hàng là phải tư vấn ngay
123
+ if (entities.phone) zoneScores.CONVERSION += 5;
124
+ if (entities.address) zoneScores.CONVERSION += 5;
125
+ if (entities.weight) zoneScores.CONVERSION += 5;
126
+ if (entities.name) zoneScores.CONVERSION += 5;
127
+ if (entities.age) zoneScores.CONVERSION += 5;
128
+ // Ép CONSULT khi dùng lệnh hệ thống
129
+ if (raw.includes("#") || raw.includes("xoa:") || raw.includes("xóa:")) {
130
+ zoneScores.CONSULT = 500;
131
+ zoneScores.CONVERSION = 0;
132
+ console.log("⚡ [Analyzer] Lệnh hệ thống: Ưu tiên CONSULT");
133
+ }
134
+ }
135
+ // --- 5. QUYẾT ĐỊNH WINNER ---
136
+ let winner = 'RETAIN';
137
+ let maxScore = -1;
138
+
139
+ Object.keys(zoneScores).forEach(z => {
140
+ const currentScore = Number(zoneScores[z] || 0);
141
+ if (currentScore > maxScore) {
142
+ maxScore = currentScore;
143
+ winner = z;
144
+ } else if (currentScore === maxScore && maxScore > 0) {
145
+ const priority = { 'CONVERSION': 3, 'REMEDY': 2, 'CONSULT': 1, 'RETAIN': 0 };
146
+ if (priority[z] > priority[winner]) winner = z;
147
+ }
148
+ });
149
+
150
+ if (maxScore <= 0) winner = 'RETAIN';
151
+
152
+ return { entities, flags: detectedFlags, winner, zones: zoneScores };
153
+ }
154
+ };
155
+
156
+ module.exports = analyzer;