phanquocdat123 commited on
Commit
a970880
·
verified ·
1 Parent(s): 61e2c02

Update routes/order.js

Browse files
Files changed (1) hide show
  1. routes/order.js +59 -9
routes/order.js CHANGED
@@ -5,41 +5,91 @@ const googleSheets = require('../services/googleSheets');
5
  const sessionManager = require('../core/sessionManager');
6
  const facebookService = require('../services/facebookService');
7
 
8
- // Luồng này không cần processChatLogicWithTrace nên không cần truyền vào
9
  router.post('/api/submit-order', async (req, res) => {
10
  try {
11
  const { userId, name, phone, address } = req.body;
12
  if (!userId || !name || !phone || !address) {
13
  return res.status(400).json({ success: false, message: "Mẹ điền thiếu thông tin mất rồi nhen!" });
14
  }
 
15
  console.log(`\n📦 [Form Webview] Có đơn chốt mới từ khách ${userId}:`);
16
  console.log(` - Tên: ${name} | SĐT: ${phone} | ĐC: ${address}`);
17
-
18
  const safePhone = (phone.startsWith('+') || phone.startsWith('0')) ? `'${phone}` : phone;
 
 
19
  await googleSheets.syncCustomerToExcel(userId, {
20
  name: name,
21
  phone: safePhone,
22
  address: address,
23
  note: "Khách tự điền qua Form Webview"
24
  });
25
-
 
26
  let session = sessionManager.get(userId);
 
 
27
  if (session) {
28
  session.entities = session.entities || {};
29
  session.entities.name = name;
30
  session.entities.phone = phone;
31
  session.entities.address = address;
 
 
 
 
 
 
 
 
32
  sessionManager.update(userId, session);
33
  }
34
-
35
- const confirmText = `✅ Hệ thống Hương Kid đã ghi nhận thông tin của Mẹ thành công ạ:\n\n` +
36
- `👤 Tên: ${name}\n` +
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  `📞 SĐT: ${phone}\n` +
38
  `📍 Địa chỉ: ${address}\n\n` +
39
- `Em chuẩn bị hàng rồi gửi sớm cho bé nhen! ❤️ Cảm ơn Mẹ nhiều.`;
40
-
41
- await facebookService.sendResponse(userId, confirmText);
 
 
 
 
 
42
  return res.status(200).json({ success: true });
 
43
  } catch (error) {
44
  console.error("❌ Lỗi xử lý dữ liệu Form:", error);
45
  return res.status(500).json({ success: false, message: "Lỗi Server: " + error.message });
 
5
  const sessionManager = require('../core/sessionManager');
6
  const facebookService = require('../services/facebookService');
7
 
 
8
  router.post('/api/submit-order', async (req, res) => {
9
  try {
10
  const { userId, name, phone, address } = req.body;
11
  if (!userId || !name || !phone || !address) {
12
  return res.status(400).json({ success: false, message: "Mẹ điền thiếu thông tin mất rồi nhen!" });
13
  }
14
+
15
  console.log(`\n📦 [Form Webview] Có đơn chốt mới từ khách ${userId}:`);
16
  console.log(` - Tên: ${name} | SĐT: ${phone} | ĐC: ${address}`);
17
+
18
  const safePhone = (phone.startsWith('+') || phone.startsWith('0')) ? `'${phone}` : phone;
19
+
20
+ // 1. Đồng bộ thông tin khách vào tab Khách Hàng (Code cũ của bạn)
21
  await googleSheets.syncCustomerToExcel(userId, {
22
  name: name,
23
  phone: safePhone,
24
  address: address,
25
  note: "Khách tự điền qua Form Webview"
26
  });
27
+
28
+ // 2. Cập nhật và truy xuất giỏ hàng từ Session Memory
29
  let session = sessionManager.get(userId);
30
+ let orderProduct = "Sản phẩm chọn qua chat"; // Mặc định nếu không tìm thấy mã
31
+
32
  if (session) {
33
  session.entities = session.entities || {};
34
  session.entities.name = name;
35
  session.entities.phone = phone;
36
  session.entities.address = address;
37
+
38
+ // 🎯 LẤY MÃ SẢN PHẨM KHÁCH VỪA CHỌN (Ví dụ: G02 từ log của bạn)
39
+ if (session.entities.productCode) {
40
+ orderProduct = session.entities.productCode;
41
+ } else if (session.lastSelectedProduct) {
42
+ orderProduct = session.lastSelectedProduct;
43
+ }
44
+
45
  sessionManager.update(userId, session);
46
  }
47
+
48
+ // =========================================================
49
+ // 🎯 3. GHI ĐƠN HÀNG MỚI VÀO SHEET ĐƠN HÀNG (TỰ ĐỘNG CHỐT ĐƠN)
50
+ // =========================================================
51
+ try {
52
+ // Bạn kiểm tra xem file googleSheets.js của bạn tên hàm tạo đơn là gì nhen.
53
+ // Thường sẽ là appendOrder hoặc createNewOrder. Ở đây mình gọi cấu trúc chuẩn:
54
+ if (typeof googleSheets.createNewOrder === 'function') {
55
+ await googleSheets.createNewOrder({
56
+ userId,
57
+ name,
58
+ phone: safePhone,
59
+ address,
60
+ product: orderProduct,
61
+ date: new Date().toLocaleString('vi-VN', { timeZone: 'Asia/Ho_Chi_Minh' })
62
+ });
63
+ console.log(`✅ [Sheets] Đã tự động chốt đơn sản phẩm [${orderProduct}] vào Tab Đơn Hàng.`);
64
+ } else if (typeof googleSheets.appendRow === 'function') {
65
+ // Phương án dự phòng nếu bạn dùng hàm appendRow chung chung
66
+ await googleSheets.appendRow('DonHang', [userId, name, safePhone, address, orderProduct, new Date().toLocaleString('vi-VN')]);
67
+ console.log(`✅ [Sheets] Đã append đơn hàng [${orderProduct}] vào Sheet.`);
68
+ } else {
69
+ console.warn("⚠️ [Sheets] Chưa tìm thấy hàm tạo đơn riêng biệt trong googleSheets.js, Mẹ check lại tên hàm nhen!");
70
+ }
71
+ } catch (sheetErr) {
72
+ console.error("❌ Lỗi khi ghi dòng đơn hàng vào Sheets:", sheetErr.message);
73
+ }
74
+
75
+ // =========================================================
76
+ // 🎯 4. ĐÓNG GÓI TIN NHẮN XÁC NHẬN VÀ GỬI NGẦM (CHỐNG TREO WEBVIEW)
77
+ // =========================================================
78
+ const confirmText = `🎉 HƯƠNG KID XÁC NHẬN CHỐT ĐƠN THÀNH CÔNG! 🎉\n\n` +
79
+ `📦 Mẫu chốt: **${orderProduct}**\n` +
80
+ `👤 Người nhận: ${name}\n` +
81
  `📞 SĐT: ${phone}\n` +
82
  `📍 Địa chỉ: ${address}\n\n` +
83
+ `Em đang chuẩn bị gói hàng để gửi sớm cho bé rồi nhen mẹ ơi! ❤️ Cảm ơn Mẹ nhiều nhiều!`;
84
+
85
+ // 🚀 BỎ AWAIT: Bắn tin nhắn chạy ngầm để giải phóng phản hồi ngay lập tức
86
+ facebookService.sendResponse(userId, confirmText)
87
+ .then(() => console.log(`✅ [FB Service] Đã gửi tin nhắn chốt đơn tự động cho khách: ${userId}`))
88
+ .catch(err => console.error("❌ Lỗi gửi tin chốt đơn ngầm:", err.message));
89
+
90
+ // Trả kết quả 200 ngay tức khắc để Webview trên điện thoại đóng lại mượt mà
91
  return res.status(200).json({ success: true });
92
+
93
  } catch (error) {
94
  console.error("❌ Lỗi xử lý dữ liệu Form:", error);
95
  return res.status(500).json({ success: false, message: "Lỗi Server: " + error.message });