File size: 14,087 Bytes
dbb6988
 
fdbc36f
c84afa0
9c21ccb
 
7b6756e
0dfd3e3
 
9c21ccb
fdbc36f
9c21ccb
 
 
 
dbb6988
3c6d6b3
dbb6988
 
 
 
14277a4
9c21ccb
c84afa0
 
 
14277a4
9c21ccb
14277a4
 
9c21ccb
 
 
 
14277a4
9c21ccb
 
 
 
 
 
 
e6bc1bf
 
 
 
 
 
 
 
 
0dfd3e3
e6bc1bf
 
0dfd3e3
e6bc1bf
9c21ccb
dbb6988
 
 
 
 
 
 
 
3c6d6b3
dbb6988
9c21ccb
fdbc36f
 
 
9c21ccb
fdbc36f
 
 
 
 
9c21ccb
fdbc36f
 
9c21ccb
fdbc36f
 
 
dbb6988
 
3c6d6b3
 
43982ce
 
dbb6988
 
 
14277a4
dbb6988
 
14277a4
dbb6988
 
14277a4
55400cc
7b6756e
 
 
 
43982ce
14277a4
e6bc1bf
 
43982ce
 
35c4977
43982ce
 
35c4977
43982ce
9c21ccb
43982ce
996de23
9c21ccb
 
14277a4
43982ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35c4977
43982ce
dbb6988
 
35c4977
dbb6988
 
3c6d6b3
14277a4
 
0dfd3e3
14277a4
7b6756e
0dfd3e3
7b6756e
dbb6988
 
 
0dfd3e3
 
7b6756e
 
 
 
 
 
 
 
0dfd3e3
 
7b6756e
 
0dfd3e3
 
3fff8fa
 
0dfd3e3
3fff8fa
0dfd3e3
3fff8fa
 
0dfd3e3
 
 
 
14277a4
0dfd3e3
 
 
 
 
 
 
 
14277a4
3fff8fa
0dfd3e3
3fff8fa
0dfd3e3
3fff8fa
 
 
e529ed6
3fff8fa
 
 
 
 
9c21ccb
0dfd3e3
3fff8fa
0dfd3e3
 
 
3fff8fa
 
 
 
 
e529ed6
0dfd3e3
3fff8fa
0dfd3e3
3fff8fa
 
e529ed6
3fff8fa
0dfd3e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b6756e
0dfd3e3
 
7b6756e
0dfd3e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f92231e
dbb6988
7b6756e
f92231e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import os
import pickle
import json
import hashlib
from datetime import datetime
from typing import Any, Dict, List, Optional
import re # Import re để phân tích range
import time # Import để sử dụng sleep
import random # Import để tạo độ trễ ngẫu nhiên

from google.oauth2.service_account import Credentials
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from loguru import logger

from .utils import timing_decorator_sync
from .constants import SHEET_RANGE

SCOPES = ['https://www.googleapis.com/auth/spreadsheets']

def generate_conversation_id(user_id: str, page_id: str, timestamp: str) -> str:
    """Tạo ID hội thoại duy nhất."""
    hash_input = f"{user_id}:{page_id}:{timestamp}"
    return hashlib.sha256(hash_input.encode()).hexdigest()[:32]

def _flatten_and_unique_timestamps(items: Any) -> List[Any]:
    """
    Hàm tiện ích để làm phẳng danh sách timestamp (xử lý list lồng nhau)
    và loại bỏ các giá trị trùng lặp, giữ nguyên thứ tự.
    """
    if not isinstance(items, list):
        return [items]
        
    flat_list = []
    for item in items:
        if isinstance(item, list):
            flat_list.extend(_flatten_and_unique_timestamps(item))
        else:
            flat_list.append(item)
    return list(dict.fromkeys(flat_list))

def _get_start_row_from_range(range_string: str) -> int:
    """
    Phân tích một chuỗi range (ví dụ: 'Sheet1!A2:Z') để lấy ra số của dòng bắt đầu.
    """
    match = re.search(r"[A-Z]+([0-9]+)", range_string)
    if match:
        try:
            return int(match.group(1))
        except (ValueError, IndexError):
            pass
    
    logger.warning(f"Không thể xác định dòng bắt đầu từ range '{range_string}'. Mặc định là 2.")
    return 2


class SheetsClient:
    def __init__(self, credentials_file: str, token_file: str, sheet_id: str):
        self.credentials_file = credentials_file
        self.token_file = token_file
        self.sheet_id = sheet_id
        self.creds = None
        self.service = None

    @timing_decorator_sync
    def authenticate(self) -> None:
        """Xác thực với Google Sheets API."""
        credentials_json = os.getenv("GOOGLE_SHEETS_CREDENTIALS_JSON")
        if credentials_json:
            info = json.loads(credentials_json)
            self.creds = Credentials.from_service_account_info(info, scopes=SCOPES)
        else:
            if os.path.exists(self.token_file):
                with open(self.token_file, 'rb') as token:
                    self.creds = pickle.load(token)
            if not self.creds or not self.creds.valid:
                if self.creds and self.creds.expired and self.creds.refresh_token:
                    self.creds.refresh(Request())
                else:
                    flow = InstalledAppFlow.from_client_secrets_file(self.credentials_file, SCOPES)
                    self.creds = flow.run_local_server(port=0)
                with open(self.token_file, 'wb') as token:
                    pickle.dump(self.creds, token)
        self.service = build('sheets', 'v4', credentials=self.creds)

    @timing_decorator_sync
    def get_conversation_history(self, user_id: str, page_id: str) -> List[Dict[str, Any]]:
        """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."""
        logger.debug(f"[get_conversation_history] Bắt đầu lấy lịch sử cho user_id: '{user_id}' và page_id: '{page_id}'")
        try:
            if not self.service:
                self.authenticate()
            range_name = SHEET_RANGE
            result = self.service.spreadsheets().values().get(
                spreadsheetId=self.sheet_id,
                range=range_name
            ).execute()
            values = result.get('values', [])
            history = []
            
            if not values:
                logger.warning(f"[get_conversation_history] Không tìm thấy dữ liệu trong sheet. Range: {range_name}")
                return []
            
            logger.debug(f"[get_conversation_history] Đã lấy được {len(values)} dòng từ sheet. Bắt đầu xử lý...")
            
            start_row = _get_start_row_from_range(range_name)
            for i, row in enumerate(values, start=start_row):
                if len(row) < 14:
                    row.extend([""] * (14 - len(row)))

                sheet_recipient_id = row[4] # Cột E
                sheet_page_id = row[5]      # Cột F

                if str(sheet_recipient_id) == str(user_id) and str(sheet_page_id) == str(page_id):
                    try:
                        timestamps_raw = json.loads(row[12]) # Cột M
                        timestamps = _flatten_and_unique_timestamps(timestamps_raw)
                    except (json.JSONDecodeError, TypeError):
                        timestamps = []
                    
                    history.append({
                        'conversation_id': row[0],
                        'originalcommand': row[1],
                        'originalcontent': row[2],
                        'originalattachments': json.loads(row[3]) if row[3] else [],
                        'recipient_id': row[4],
                        'page_id': row[5],
                        'originaltext': row[6],
                        'originalvehicle': row[7],
                        'originalaction': row[8],
                        'originalpurpose': row[9],
                        'originalquestion': row[10],
                        'systemresponse': row[11],
                        'timestamp': timestamps,
                        'isdone': str(row[13]).lower() == 'true'
                    })

            logger.debug(f"[get_conversation_history] Hoàn tất xử lý. Tìm thấy {len(history)} bản ghi lịch sử.")
            return history
        except Exception as e:
            logger.error(f"Error getting conversation history: {e}", exc_info=True)
            return []

    @timing_decorator_sync
    def log_conversation(
        self,
        **kwargs: Any
    ) -> Optional[Dict[str, Any]]:
        """
        Thực hiện "UPSERT" (Update hoặc Insert) một hội thoại với logic chống trùng lặp mạnh mẽ.
        """
        try:
            if not self.service:
                self.authenticate()

            # --- 1. Thiết lập & Lấy Header ---
            sheet_name_match = re.match(r"([^!]+)!", SHEET_RANGE)
            sheet_name = sheet_name_match.group(1) if sheet_name_match else "Sheet1"
            header_range = f"{sheet_name}!A1:Z1"
            header_result = self.service.spreadsheets().values().get(spreadsheetId=self.sheet_id, range=header_range).execute()
            header = header_result.get('values', [[]])[0]
            if not header:
                logger.error(f"Không thể lấy được header từ range '{header_range}'.")
                return None
            
            # --- 2. Đọc dữ liệu và xác định các định danh ---
            data_result = self.service.spreadsheets().values().get(spreadsheetId=self.sheet_id, range=SHEET_RANGE).execute()
            values = data_result.get('values', [])
            
            # Định danh của sự kiện đang xử lý
            recipient_id = str(kwargs.get('recipient_id')).strip()
            page_id = str(kwargs.get('page_id')).strip()
            ts_list = _flatten_and_unique_timestamps(kwargs.get('timestamp', []))
            event_timestamp = str(ts_list[-1]).strip() if ts_list else ''
            
            logger.debug(f"UPSERT: Bắt đầu tìm kiếm với recipient_id='{recipient_id}', page_id='{page_id}', event_timestamp='{event_timestamp}'")

            # --- 3. Tìm kiếm bản ghi đã tồn tại ---
            found_row_index = -1
            found_row_data = {}
            start_row = _get_start_row_from_range(SHEET_RANGE)

            try:
                id_col_idx = header.index('conversation_id')
                recipient_col_idx = header.index('recipient_id')
                page_col_idx = header.index('page_id')
                timestamp_col_idx = header.index('timestamp')
            except ValueError as e:
                logger.error(f"Thiếu cột bắt buộc trong header: {e}")
                return None

            target_conv_id = str(kwargs.get('conversation_id') or '').strip()
            if target_conv_id:
                logger.debug(f"UPSERT: Ưu tiên tìm bằng conversation_id='{target_conv_id}'")
                for i, row in enumerate(values, start=start_row):
                    if len(row) > id_col_idx:
                        sheet_conv_id = str(row[id_col_idx]).strip()
                        is_match = sheet_conv_id == target_conv_id
                        # logger.trace(f"Dòng {i}: So sánh ID: '{sheet_conv_id}' == '{target_conv_id}' -> {is_match}")
                        if is_match:
                            found_row_index = i
                            found_row_data = dict(zip(header, row))
                            logger.success(f"Tìm thấy bằng conversation_id tại dòng {i}.")
                            break
            
            if found_row_index == -1:
                logger.debug(f"UPSERT: Không tìm thấy bằng ID, chuyển sang tìm bằng (user, page, timestamp).")
                for i, row in enumerate(values, start=start_row):
                    if len(row) <= max(recipient_col_idx, page_col_idx, timestamp_col_idx):
                        continue
                    
                    sheet_recipient_id = str(row[recipient_col_idx]).strip()
                    sheet_page_id = str(row[page_col_idx]).strip()
                    
                    id_match = (sheet_recipient_id == recipient_id) and (sheet_page_id == page_id)
                    # logger.trace(f"Dòng {i}: So sánh (user, page): ('{sheet_recipient_id}' == '{recipient_id}') AND ('{sheet_page_id}' == '{page_id}') -> {id_match}")

                    if id_match:
                        try:
                            sheet_timestamps = [str(ts).strip() for ts in _flatten_and_unique_timestamps(json.loads(row[timestamp_col_idx]))]
                            ts_match = event_timestamp and event_timestamp in sheet_timestamps
                            # logger.trace(f"Dòng {i}: So sánh timestamp: '{event_timestamp}' in {sheet_timestamps} -> {ts_match}")
                            if ts_match:
                                found_row_index = i
                                found_row_data = dict(zip(header, row))
                                logger.success(f"Tìm thấy bằng (user, page, timestamp) tại dòng {i}.")
                                break
                        except (json.JSONDecodeError, TypeError):
                            continue
            
            # --- 4. Thực hiện UPDATE hoặc INSERT ---
            if found_row_index != -1:
                # --- LOGIC CẬP NHẬT (UPDATE) ---
                logger.info(f"Đang cập nhật hội thoại tại dòng {found_row_index}")
                
                updated_data = found_row_data.copy()
                for key, value in kwargs.items():
                    if value is not None and value != '' or isinstance(value, bool):
                        updated_data[key] = value

                existing_ts = _flatten_and_unique_timestamps(json.loads(found_row_data.get('timestamp', '[]')))
                new_ts = _flatten_and_unique_timestamps(kwargs.get('timestamp', []))
                updated_data['timestamp'] = _flatten_and_unique_timestamps(existing_ts + new_ts)

                row_data_to_write = []
                for col_name in header:
                    value = updated_data.get(col_name, '')
                    if col_name in ['originalattachments', 'timestamp']:
                        row_data_to_write.append(json.dumps(value or []))
                    elif col_name == 'isdone':
                        row_data_to_write.append(str(value).lower())
                    else:
                        row_data_to_write.append(str(value))

                range_to_update = f"{sheet_name}!A{found_row_index}"
                body = {'values': [row_data_to_write]}
                self.service.spreadsheets().values().update(spreadsheetId=self.sheet_id, range=range_to_update, valueInputOption='RAW', body=body).execute()
                
                kwargs.update(updated_data)
                return kwargs
            else:
                # --- LOGIC TẠO MỚI (INSERT) ---
                logger.info(f"Không tìm thấy dòng khớp. Tiến hành tạo bản ghi mới.")
                
                kwargs['conversation_id'] = kwargs.get('conversation_id') or generate_conversation_id(recipient_id, page_id, event_timestamp)
                kwargs['timestamp'] = _flatten_and_unique_timestamps(kwargs.get('timestamp', []))

                row_data_to_write = []
                for col_name in header:
                    value = kwargs.get(col_name, '')
                    if col_name in ['originalattachments', 'timestamp']:
                        row_data_to_write.append(json.dumps(value or []))
                    elif col_name == 'isdone':
                        row_data_to_write.append(str(value).lower())
                    else:
                        row_data_to_write.append(str(value))
                
                body = {'values': [row_data_to_write]}
                self.service.spreadsheets().values().append(spreadsheetId=self.sheet_id, range=SHEET_RANGE, valueInputOption='RAW', insertDataOption='INSERT_ROWS', body=body).execute()
                
                return kwargs

        except Exception as e:
            logger.error(f"Lỗi khi ghi/cập nhật conversation: {e}", exc_info=True)
            return None