VietCat commited on
Commit
43982ce
·
1 Parent(s): 6936c62

quick fix timestamp

Browse files
Files changed (1) hide show
  1. app/sheets.py +36 -35
app/sheets.py CHANGED
@@ -69,9 +69,8 @@ class SheetsClient:
69
 
70
  @timing_decorator_sync
71
  def get_conversation_history(self, user_id: str, page_id: str) -> List[Dict[str, Any]]:
72
- """Lấy lịch sử hội thoại từ sheet, đảm bảo so sánh kiểu dữ liệu an toàn."""
73
- # --- THÊM LOG ĐỂ DEBUG ---
74
- logger.info(f"[get_conversation_history] Bắt đầu lấy lịch sử cho user_id: '{user_id}' và page_id: '{page_id}'")
75
  try:
76
  if not self.service:
77
  self.authenticate()
@@ -83,45 +82,47 @@ class SheetsClient:
83
  values = result.get('values', [])
84
  history = []
85
 
86
- if not values or len(values) < 2:
87
- logger.warning(f"[get_conversation_history] Không tìm thấy dữ liệu hoặc chỉ có header trong sheet. Tổng số dòng: {len(values)}")
88
- return []
89
 
90
- logger.info(f"[get_conversation_history] Đã lấy được {len(values)} dòng từ sheet.")
91
- header = values[0]
92
-
93
- for i, row in enumerate(values[1:], start=1):
94
- row_data = dict(zip(header, row + [""] * (len(header) - len(row))))
95
-
96
- # --- THÊM LOG CHI TIẾT CHO TỪNG DÒNG ---
97
- sheet_recipient_id = row_data.get('recipient_id', 'N/A')
98
- sheet_page_id = row_data.get('page_id', 'N/A')
99
-
100
- logger.info(f"[get_conversation_history] Đang xử lý dòng {i+1}: recipient_id='{sheet_recipient_id}', page_id='{sheet_page_id}'")
101
-
102
- is_recipient_match = str(sheet_recipient_id) == str(user_id)
103
- is_page_match = str(sheet_page_id) == str(page_id)
104
-
105
- if is_recipient_match and is_page_match:
106
- logger.info(f"[get_conversation_history] >>> TÌM THẤY DÒNG KHỚP tại dòng {i+1}!")
107
  try:
108
- timestamps_raw = json.loads(row_data.get('timestamp', '[]'))
109
  timestamps = _flatten_and_unique_timestamps(timestamps_raw)
110
  except (json.JSONDecodeError, TypeError):
111
  timestamps = []
112
 
113
- row_data['timestamp'] = timestamps
114
- row_data['originalattachments'] = json.loads(row_data.get('originalattachments', '[]')) if row_data.get('originalattachments') else []
115
- row_data['isdone'] = str(row_data.get('isdone', 'false')).lower() == 'true'
116
- history.append(row_data)
117
- else:
118
- # Log lý do không khớp
119
- if not is_recipient_match:
120
- logger.info(f"[get_conversation_history] Dòng {i+1} không khớp: recipient_id (sheet: '{sheet_recipient_id}', input: '{user_id}')")
121
- if not is_page_match:
122
- logger.info(f"[get_conversation_history] Dòng {i+1} không khớp: page_id (sheet: '{sheet_page_id}', input: '{page_id}')")
 
 
 
 
 
 
123
 
124
- logger.info(f"[get_conversation_history] Hoàn tất xử lý. Tìm thấy {len(history)} bản ghi lịch sử.")
125
  return history
126
  except Exception as e:
127
  logger.error(f"Error getting conversation history: {e}", exc_info=True)
 
69
 
70
  @timing_decorator_sync
71
  def get_conversation_history(self, user_id: str, page_id: str) -> List[Dict[str, Any]]:
72
+ """Lấy lịch sử hội thoại từ sheet bằng vị trí cột cố định để đảm bảo độ tin cậy."""
73
+ logger.debug(f"[get_conversation_history] Bắt đầu lấy lịch sử cho user_id: '{user_id}' và page_id: '{page_id}'")
 
74
  try:
75
  if not self.service:
76
  self.authenticate()
 
82
  values = result.get('values', [])
83
  history = []
84
 
85
+ logger.debug(f"[get_conversation_history] Đã lấy được {len(values)} dòng từ sheet. Bắt đầu xử lý...")
 
 
86
 
87
+ # Bỏ qua dòng header (values[0]) và lặp qua các dòng dữ liệu
88
+ for i, row in enumerate(values, start=1):
89
+ # Đảm bảo dòng có đủ 14 cột để tránh lỗi IndexError
90
+ if len(row) < 14:
91
+ row.extend([""] * (14 - len(row)))
92
+
93
+ # ==================================================================
94
+ # >>>>> SỬA LỖI: ĐỌC DỮ LIỆU BẰNG VỊ TRÍ CỘT CỐ ĐỊNH <<<<<
95
+ # Vị trí cột được xác định dựa trên thứ tự trong hàm log_conversation
96
+ sheet_recipient_id = row[4] # Cột E
97
+ sheet_page_id = row[5] # Cột F
98
+ # ==================================================================
99
+
100
+ if str(sheet_recipient_id) == str(user_id) and str(sheet_page_id) == str(page_id):
101
+ logger.success(f"[get_conversation_history] >>> TÌM THẤY DÒNG KHỚP tại dòng {i}!")
 
 
102
  try:
103
+ timestamps_raw = json.loads(row[12]) # Cột M
104
  timestamps = _flatten_and_unique_timestamps(timestamps_raw)
105
  except (json.JSONDecodeError, TypeError):
106
  timestamps = []
107
 
108
+ history.append({
109
+ 'conversation_id': row[0],
110
+ 'originalcommand': row[1],
111
+ 'originalcontent': row[2],
112
+ 'originalattachments': json.loads(row[3]) if row[3] else [],
113
+ 'recipient_id': row[4],
114
+ 'page_id': row[5],
115
+ 'originaltext': row[6],
116
+ 'originalvehicle': row[7],
117
+ 'originalaction': row[8],
118
+ 'originalpurpose': row[9],
119
+ 'originalquestion': row[10],
120
+ 'systemresponse': row[11],
121
+ 'timestamp': timestamps,
122
+ 'isdone': str(row[13]).lower() == 'true'
123
+ })
124
 
125
+ logger.debug(f"[get_conversation_history] Hoàn tất xử lý. Tìm thấy {len(history)} bản ghi lịch sử.")
126
  return history
127
  except Exception as e:
128
  logger.error(f"Error getting conversation history: {e}", exc_info=True)