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
| 1 |
+
const googleSheets = require('../../services/googleSheets');
|
| 2 |
+
const helpers = require('../../utils/helpers');
|
| 3 |
+
const { buildCartReply } = require('../cartFormatter');
|
| 4 |
+
|
| 5 |
+
const conversionHandler = {
|
| 6 |
+
handle: async (session, message, dimConfig, retainConfig = [], globalInventory = null, sessionManager = null) => {
|
| 7 |
+
try {
|
| 8 |
+
// Lấy ID từ mọi nguồn có thể trong object session
|
| 9 |
+
const userId = session?.id || session?.userId || session?.sessionId;
|
| 10 |
+
|
| 11 |
+
console.log("🎯 [DEBUG] ID chốt chặn cuối cùng:", userId);
|
| 12 |
+
if (!userId || userId === "undefined") {
|
| 13 |
+
console.error("❌ Lỗi: Vẫn không tìm thấy ID khách hàng!");
|
| 14 |
+
return { reply: "Dạ, đợi em xíu em kiểm tra lại mã khách nhen!" };
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
const rawText = (message || "").trim();
|
| 18 |
+
const textLower = rawText.toLowerCase();
|
| 19 |
+
const inventory = globalInventory?.inventory || globalInventory || {};
|
| 20 |
+
|
| 21 |
+
// =========================================================
|
| 22 |
+
// 🚨 ƯU TIÊN SỐ 1: CHỐT ĐƠN & CẬP NHẬT THÔNG TIN KHÁCH
|
| 23 |
+
// =========================================================
|
| 24 |
+
if (rawText.includes("ACTION_SUBMIT_FORM")) {
|
| 25 |
+
console.log("🚀 Phát hiện mã chốt đơn từ Form!");
|
| 26 |
+
|
| 27 |
+
const nameMatch = rawText.match(/Tên:\s*(.*?)\s*,/i);
|
| 28 |
+
const phoneMatch = rawText.match(/SĐT:\s*(.*?)\s*,/i);
|
| 29 |
+
const ageMatch = rawText.match(/Bé\s*(.*?)\s*,/i);
|
| 30 |
+
const weightMatch = rawText.match(/Nặng\s*([\d\.,\s]*)/i);
|
| 31 |
+
const addressMatch = rawText.match(/Địa chỉ:\s*(.*?)\s*ACTION_SUBMIT_FORM/i);
|
| 32 |
+
|
| 33 |
+
const dataForExcel = {
|
| 34 |
+
userId: userId,
|
| 35 |
+
name: nameMatch ? nameMatch[1].trim() : "",
|
| 36 |
+
phone: phoneMatch ? phoneMatch[1].trim() : "",
|
| 37 |
+
age: ageMatch ? ageMatch[1].trim() : "",
|
| 38 |
+
weight: weightMatch ? weightMatch[1].trim() : "",
|
| 39 |
+
address: addressMatch ? addressMatch[1].trim() : ""
|
| 40 |
+
};
|
| 41 |
+
|
| 42 |
+
// ✅ CẬP NHẬT VÀO BỘ NHỚ ROBOT (SESSION) - QUAN TRỌNG NHẤT
|
| 43 |
+
session.phone = dataForExcel.phone;
|
| 44 |
+
session.address = dataForExcel.address;
|
| 45 |
+
session.weight = dataForExcel.weight;
|
| 46 |
+
session.name = dataForExcel.name;
|
| 47 |
+
|
| 48 |
+
// Cập nhật cả vào entities để Phần 4 kiểm tra chính xác
|
| 49 |
+
if (!session.entities) session.entities = {};
|
| 50 |
+
session.entities.phone = dataForExcel.phone;
|
| 51 |
+
session.entities.address = dataForExcel.address;
|
| 52 |
+
session.entities.weight = dataForExcel.weight;
|
| 53 |
+
|
| 54 |
+
// ✅ GỌI ĐỒNG BỘ SANG EXCEL (Chỉ cần 1 lần trong try...catch)
|
| 55 |
+
try {
|
| 56 |
+
if (session.id && (dataForExcel.phone || dataForExcel.name)) {
|
| 57 |
+
await googleSheets.syncCustomerToExcel(session.id, dataForExcel);
|
| 58 |
+
}
|
| 59 |
+
} catch (error) {
|
| 60 |
+
console.error("❌ Lỗi khi đồng bộ khách hàng:", error);
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
// 3. Ghi đơn hàng vào Sheet 'khachhang'
|
| 64 |
+
if (session.cart?.length > 0) {
|
| 65 |
+
const cartCodes = session.cart.map(i => `${i.code}(S:${i.size})`).join(", ");
|
| 66 |
+
const rowOrder = [
|
| 67 |
+
new Date().toLocaleString("vi-VN", {timeZone: "Asia/Ho_Chi_Minh"}),
|
| 68 |
+
`DH_${Date.now()}`,
|
| 69 |
+
dataForExcel.phone,
|
| 70 |
+
dataForExcel.address,
|
| 71 |
+
cartCodes,
|
| 72 |
+
"Đã chốt từ Form",
|
| 73 |
+
dataForExcel.weight + "kg",
|
| 74 |
+
`${session.totals?.finalTotal || 0}đ`
|
| 75 |
+
];
|
| 76 |
+
|
| 77 |
+
const success = await googleSheets.appendRow('khachhang', rowOrder);
|
| 78 |
+
|
| 79 |
+
if (success) {
|
| 80 |
+
session.cart = []; // Reset giỏ hàng sau khi chốt
|
| 81 |
+
return {
|
| 82 |
+
reply: `🎉 **XÁC NHẬN CHỐT ĐƠN THÀNH CÔNG!**\n\nShop Hương Kid đã ghi nhận thông tin của Mẹ **${dataForExcel.name}**. Đơn hàng sẽ được gửi đến **${dataForExcel.address}** sớm nhất ạ. Cảm ơn Mẹ! ❤️`
|
| 83 |
+
};
|
| 84 |
+
}
|
| 85 |
+
} else {
|
| 86 |
+
return { reply: "⚠️ Giỏ hàng trống, Mẹ chọn mẫu trước nhen!" };
|
| 87 |
+
}
|
| 88 |
+
}
|
| 89 |
+
// =========================================================
|
| 90 |
+
// 🛑 BƯỚC 2: LẤY DỮ LIỆU CŨ ĐỂ HIỂN THỊ (NẾU CHƯA CHỐT)
|
| 91 |
+
// =========================================================
|
| 92 |
+
const phone = session.phone || session.entities?.phone || "";
|
| 93 |
+
const address = session.address || session.entities?.address || "";
|
| 94 |
+
const weight = session.weight || session.entities?.weight || "";
|
| 95 |
+
|
| 96 |
+
// ... (Giữ nguyên Phần 2: Nút bấm và Phần 3: Excel của file trước) ...
|
| 97 |
+
const isButtonAction = rawText.includes("ACTION_");
|
| 98 |
+
const excelRow = dimConfig.find(row => {
|
| 99 |
+
const kws = String(row.keywords || "").split(',').map(k => k.trim().toLowerCase());
|
| 100 |
+
return kws.some(k => k && textLower.includes(k));
|
| 101 |
+
});
|
| 102 |
+
|
| 103 |
+
if (isButtonAction) {
|
| 104 |
+
// ... (Logic giỏ hàng giữ nguyên)
|
| 105 |
+
if (!Array.isArray(session.cart)) session.cart = [];
|
| 106 |
+
if (rawText.includes("ACTION_ADD:")) {
|
| 107 |
+
const code = rawText.split("ACTION_ADD:")[1]?.trim().split(/\s/)[0].toUpperCase();
|
| 108 |
+
if (inventory[code] && !session.cart.find(i => i.code === code)) {
|
| 109 |
+
session.cart.push({ code, name: inventory[code].name, price: inventory[code].price, size: session.entities?.size || "10" });
|
| 110 |
+
}
|
| 111 |
+
}
|
| 112 |
+
if (rawText.includes("ACTION_REMOVE:")) {
|
| 113 |
+
const code = rawText.split("ACTION_REMOVE:")[1]?.trim().split(/\s/)[0].toUpperCase();
|
| 114 |
+
session.cart = session.cart.filter(item => item.code !== code);
|
| 115 |
+
}
|
| 116 |
+
return { reply: buildCartReply(session, "✅ Hệ thống đã cập nhật giỏ hàng cho Mẹ:", inventory) };
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
if (excelRow) return { reply: excelRow.template || excelRow.Template };
|
| 120 |
+
|
| 121 |
+
// =========================================================
|
| 122 |
+
// 🎯 PHẦN 4: LUỒNG BẤM NÚT XÁC NHẬN (KIỂM TRA THÔNG TIN)
|
| 123 |
+
// =========================================================
|
| 124 |
+
if (textLower.includes("xác nhận") || textLower.includes("xac nhan") || rawText.includes("ACTION_CONFIRM")) {
|
| 125 |
+
|
| 126 |
+
// Đã đủ thông tin -> Chốt luôn
|
| 127 |
+
if (phone && address && weight && session.cart?.length > 0) {
|
| 128 |
+
const cartCodes = session.cart.map(i => `${i.code}(S:${i.size})`).join(", ");
|
| 129 |
+
const rowData = [
|
| 130 |
+
new Date().toLocaleString("vi-VN", {timeZone: "Asia/Ho_Chi_Minh"}),
|
| 131 |
+
`DH${Date.now()}`, phone, address, cartCodes, "Đã chốt", weight, `${session.totals?.finalTotal || 0}đ`
|
| 132 |
+
];
|
| 133 |
+
const success = await googleSheets.appendRow('khachhang', rowData);
|
| 134 |
+
if (success) {
|
| 135 |
+
session.cart = [];
|
| 136 |
+
return { reply: `🎉 **ĐẶT HÀNG THÀNH CÔNG!**\n\nĐơn hàng của Mẹ đã được ghi lại thành công ạ! ❤️` };
|
| 137 |
+
}
|
| 138 |
+
}
|
| 139 |
+
// Thiếu thông tin -> Hiện Form (Dữ liệu cũ sẽ được nạp vào ${weight}|${phone}|${address})
|
| 140 |
+
else if (session.cart?.length > 0) {
|
| 141 |
+
return {
|
| 142 |
+
reply: `⚠️ Thông tin của Mẹ còn thiếu một chút, Mẹ kiểm tra lại và bổ sung nhé:\n\n[[SHOW_ORDER_FORM|${weight}|${phone}|${address}]]`
|
| 143 |
+
};
|
| 144 |
+
}
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
// Mặc định hiện giỏ hàng
|
| 148 |
+
if (session.cart?.length > 0) {
|
| 149 |
+
return { reply: buildCartReply(session, "🌸 **GIỎ HÀNG HIỆN TẠI**", inventory) };
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
return null;
|
| 153 |
+
|
| 154 |
+
} catch (err) {
|
| 155 |
+
console.error("❌ Lỗi tại conversion.js:", err);
|
| 156 |
+
return null;
|
| 157 |
+
}
|
| 158 |
+
}
|
| 159 |
+
};
|
| 160 |
+
|
| 161 |
+
module.exports = conversionHandler;
|