VietCat commited on
Commit
996de23
·
1 Parent(s): 14277a4

quick fix timestamp

Browse files
Files changed (1) hide show
  1. app/sheets.py +52 -55
app/sheets.py CHANGED
@@ -21,14 +21,12 @@ def generate_conversation_id(user_id: str, page_id: str, timestamp: str) -> str:
21
  hash_input = f"{user_id}:{page_id}:{timestamp}"
22
  return hashlib.sha256(hash_input.encode()).hexdigest()[:32]
23
 
24
- # --- HÀM TIỆN ÍCH ĐƯỢC THÊM VÀO ĐỂ FIX LỖI ---
25
  def _flatten_and_unique_timestamps(items: Any) -> List[Any]:
26
  """
27
  Hàm tiện ích để làm phẳng danh sách timestamp (xử lý list lồng nhau)
28
  và loại bỏ các giá trị trùng lặp, giữ nguyên thứ tự.
29
  """
30
  if not isinstance(items, list):
31
- # Nếu đầu vào không phải list, gói nó vào một list
32
  return [items]
33
 
34
  flat_list = []
@@ -37,7 +35,6 @@ def _flatten_and_unique_timestamps(items: Any) -> List[Any]:
37
  flat_list.extend(_flatten_and_unique_timestamps(item))
38
  else:
39
  flat_list.append(item)
40
- # Dùng dict để giữ lại thứ tự và loại bỏ trùng lặp
41
  return list(dict.fromkeys(flat_list))
42
 
43
 
@@ -83,22 +80,23 @@ class SheetsClient:
83
  ).execute()
84
  values = result.get('values', [])
85
  history = []
86
- if not values or len(values) < 1:
87
  return []
88
 
89
  header = values[0]
90
  for row in values[1:]:
 
91
  row_data = dict(zip(header, row + [""] * (len(header) - len(row))))
92
 
93
  if row_data.get('recipient_id') == user_id and row_data.get('page_id') == page_id:
94
  try:
95
- # Dùng hàm tiện ích để đảm bảo timestamp đọc ra luôn phẳng
96
- timestamps = _flatten_and_unique_timestamps(json.loads(row_data.get('timestamp', '[]')))
97
  except (json.JSONDecodeError, TypeError):
98
  timestamps = []
99
 
100
  row_data['timestamp'] = timestamps
101
- row_data['originalattachments'] = json.loads(row_data.get('originalattachments', '[]'))
102
  row_data['isdone'] = str(row_data.get('isdone', 'false')).lower() == 'true'
103
  history.append(row_data)
104
  return history
@@ -121,7 +119,7 @@ class SheetsClient:
121
  originalpurpose: str = "",
122
  originalquestion: str = "",
123
  systemresponse: str = "",
124
- timestamp: Optional[Any] = None, # Cho phép timestamp có thể là list
125
  isdone: bool = False
126
  ) -> Optional[Dict[str, Any]]:
127
  """Ghi lại một hội thoại, giữ nguyên logic gốc của người dùng."""
@@ -134,57 +132,57 @@ class SheetsClient:
134
  range=SHEET_RANGE
135
  ).execute()
136
  values = result.get('values', [])
137
- header = values[0] if values else []
138
 
139
- # --- SỬA LỖI LỒNG TIMESTAMP TẠI ĐÂY ---
140
- # 1. Luôn đảm bảo `timestamps_list` một danh sách phẳng, không lồng nhau.
141
- timestamps_list = _flatten_and_unique_timestamps(timestamp or [])
142
-
143
- # 2. Xác định timestamp cho sự kiện hiện tại (dùng để kiểm tra trùng lặp).
144
- # Lấy timestamp mới nhất (cuối cùng trong list). Nếu list rỗng thì tạo mới.
145
- if not timestamps_list:
146
- current_ts = datetime.now().isoformat()
147
- timestamps_list.append(current_ts)
148
  else:
149
- current_ts = timestamps_list[-1]
150
- # --- KẾT THÚC SỬA LỖI ---
151
 
152
  # Logic kiểm tra trùng lặp của bạn được giữ nguyên
153
- if header:
154
- for row in values[1:]:
155
- row_data = dict(zip(header, row + [""] * (len(header) - len(row))))
156
- try:
157
- row_timestamps = json.loads(row_data.get('timestamp', '[]'))
158
- if not isinstance(row_timestamps, list):
159
- row_timestamps = [row_timestamps]
160
- except Exception:
161
- row_timestamps = []
162
-
163
- if str(current_ts) in [str(ts) for ts in row_timestamps] and \
164
- row_data.get('recipient_id') == str(recipient_id) and \
165
- row_data.get('page_id') == str(page_id):
166
- logger.info(f"Found duplicate conversation for user {recipient_id}, page {page_id}, timestamp {current_ts}")
167
- # Trả về dữ liệu tìm thấy, logic không đổi
168
- return {
169
- 'conversation_id': row_data.get('conversation_id'),
170
- 'originalcommand': row_data.get('originalcommand'),
171
- 'originalcontent': row_data.get('originalcontent'),
172
- 'originalattachments': json.loads(row_data.get('originalattachments', '[]')),
173
- 'recipient_id': row_data.get('recipient_id'),
174
- 'page_id': row_data.get('page_id'),
175
- 'originaltext': row_data.get('originaltext'),
176
- 'originalvehicle': row_data.get('originalvehicle'),
177
- 'originalaction': row_data.get('originalaction'),
178
- 'originalpurpose': row_data.get('originalpurpose'),
179
- 'originalquestion': row_data.get('originalquestion'),
180
- 'systemresponse': row_data.get('systemresponse'),
181
- 'timestamp': row_timestamps,
182
- 'isdone': str(row_data.get('isdone', 'false')).lower() == 'true'
183
- }
 
184
 
185
  # Logic tạo dòng mới và append vào sheet được giữ nguyên
186
  if not conversation_id:
187
- conversation_id = generate_conversation_id(recipient_id, page_id, current_ts)
188
 
189
  new_row = [
190
  conversation_id,
@@ -199,7 +197,7 @@ class SheetsClient:
199
  originalpurpose,
200
  originalquestion,
201
  systemresponse,
202
- json.dumps(timestamps_list), # Lưu danh sách đã được làm phẳng
203
  str(isdone).lower()
204
  ]
205
 
@@ -213,7 +211,6 @@ class SheetsClient:
213
 
214
  logger.info(f"Thêm mới conversation: {conversation_id}")
215
 
216
- # Trả về dữ liệu đã được ghi, logic không đổi
217
  return {
218
  'conversation_id': conversation_id,
219
  'originalcommand': originalcommand,
@@ -227,7 +224,7 @@ class SheetsClient:
227
  'originalpurpose': originalpurpose,
228
  'originalquestion': originalquestion,
229
  'systemresponse': systemresponse,
230
- 'timestamp': timestamps_list, # Trả về danh sách đã được làm phẳng
231
  'isdone': isdone
232
  }
233
  except Exception as e:
 
21
  hash_input = f"{user_id}:{page_id}:{timestamp}"
22
  return hashlib.sha256(hash_input.encode()).hexdigest()[:32]
23
 
 
24
  def _flatten_and_unique_timestamps(items: Any) -> List[Any]:
25
  """
26
  Hàm tiện ích để làm phẳng danh sách timestamp (xử lý list lồng nhau)
27
  và loại bỏ các giá trị trùng lặp, giữ nguyên thứ tự.
28
  """
29
  if not isinstance(items, list):
 
30
  return [items]
31
 
32
  flat_list = []
 
35
  flat_list.extend(_flatten_and_unique_timestamps(item))
36
  else:
37
  flat_list.append(item)
 
38
  return list(dict.fromkeys(flat_list))
39
 
40
 
 
80
  ).execute()
81
  values = result.get('values', [])
82
  history = []
83
+ if not values or len(values) < 2: # Cần có header và ít nhất 1 dòng dữ liệu
84
  return []
85
 
86
  header = values[0]
87
  for row in values[1:]:
88
+ # Zip header với row để tạo dict, an toàn hơn
89
  row_data = dict(zip(header, row + [""] * (len(header) - len(row))))
90
 
91
  if row_data.get('recipient_id') == user_id and row_data.get('page_id') == page_id:
92
  try:
93
+ timestamps_raw = json.loads(row_data.get('timestamp', '[]'))
94
+ timestamps = _flatten_and_unique_timestamps(timestamps_raw)
95
  except (json.JSONDecodeError, TypeError):
96
  timestamps = []
97
 
98
  row_data['timestamp'] = timestamps
99
+ row_data['originalattachments'] = json.loads(row_data.get('originalattachments', '[]')) if row_data.get('originalattachments') else []
100
  row_data['isdone'] = str(row_data.get('isdone', 'false')).lower() == 'true'
101
  history.append(row_data)
102
  return history
 
119
  originalpurpose: str = "",
120
  originalquestion: str = "",
121
  systemresponse: str = "",
122
+ timestamp: Optional[Any] = None,
123
  isdone: bool = False
124
  ) -> Optional[Dict[str, Any]]:
125
  """Ghi lại một hội thoại, giữ nguyên logic gốc của người dùng."""
 
132
  range=SHEET_RANGE
133
  ).execute()
134
  values = result.get('values', [])
 
135
 
136
+ # ==================================================================
137
+ # >>>>> SỬA LỖI LỒNG TIMESTAMP TẠI ĐÂY <<<<<
138
+ # Bước 1: Xử lý `timestamp` đầu vào để nó LUÔN LUÔN là một danh sách phẳng.
139
+ processed_timestamps = _flatten_and_unique_timestamps(timestamp or [])
140
+
141
+ # Bước 2: Lấy timestamp mới nhất để kiểm tra trùng lặp. Nếu list rỗng thì tạo mới.
142
+ if not processed_timestamps:
143
+ current_ts_for_check = datetime.now().isoformat()
144
+ processed_timestamps.append(current_ts_for_check)
145
  else:
146
+ current_ts_for_check = processed_timestamps[-1]
147
+ # ==================================================================
148
 
149
  # Logic kiểm tra trùng lặp của bạn được giữ nguyên
150
+ for row in values:
151
+ row = row + [""] * 14
152
+ try:
153
+ row_timestamps = json.loads(row[12]) if row[12] else []
154
+ if not isinstance(row_timestamps, list):
155
+ row_timestamps = [row_timestamps]
156
+ except Exception:
157
+ row_timestamps = []
158
+
159
+ row_recipient_id = row[4]
160
+ row_page_id = row[5]
161
+
162
+ if str(current_ts_for_check) in [str(ts) for ts in row_timestamps] and \
163
+ str(row_recipient_id) == str(recipient_id) and \
164
+ str(row_page_id) == str(page_id):
165
+ logger.info(f"Found duplicate conversation for user {recipient_id}, page {page_id}, timestamp {current_ts_for_check}")
166
+ return {
167
+ 'conversation_id': row[0],
168
+ 'originalcommand': row[1],
169
+ 'originalcontent': row[2],
170
+ 'originalattachments': json.loads(row[3]) if row[3] else [],
171
+ 'recipient_id': row[4],
172
+ 'page_id': row[5],
173
+ 'originaltext': row[6],
174
+ 'originalvehicle': row[7],
175
+ 'originalaction': row[8],
176
+ 'originalpurpose': row[9],
177
+ 'originalquestion': row[10],
178
+ 'systemresponse': row[11],
179
+ 'timestamp': row_timestamps,
180
+ 'isdone': row[13].lower() == 'true' if len(row) > 13 else False
181
+ }
182
 
183
  # Logic tạo dòng mới và append vào sheet được giữ nguyên
184
  if not conversation_id:
185
+ conversation_id = generate_conversation_id(recipient_id, page_id, current_ts_for_check)
186
 
187
  new_row = [
188
  conversation_id,
 
197
  originalpurpose,
198
  originalquestion,
199
  systemresponse,
200
+ json.dumps(processed_timestamps), # <<<< SỬ DỤNG BIẾN ĐÃ ĐƯỢC XỬ LÝ
201
  str(isdone).lower()
202
  ]
203
 
 
211
 
212
  logger.info(f"Thêm mới conversation: {conversation_id}")
213
 
 
214
  return {
215
  'conversation_id': conversation_id,
216
  'originalcommand': originalcommand,
 
224
  'originalpurpose': originalpurpose,
225
  'originalquestion': originalquestion,
226
  'systemresponse': systemresponse,
227
+ 'timestamp': processed_timestamps, # <<<< TRẢ VỀ DANH SÁCH ĐÃ ĐƯỢC XỬ LÝ
228
  'isdone': isdone
229
  }
230
  except Exception as e: