|
9 | 9 | from sqlalchemy.orm import aliased |
10 | 10 |
|
11 | 11 | from apps.chat.models.chat_model import Chat, ChatRecord, CreateChat, ChatInfo, RenameChat, ChatQuestion, ChatLog, \ |
12 | | - TypeEnum, OperationEnum, ChatRecordResult, ChatLogHistory, ChatLogHistoryItem |
| 12 | + TypeEnum, OperationEnum, ChatRecordResult, ChatLogHistory, ChatLogHistoryItem, ChatItem |
13 | 13 | from apps.datasource.crud.datasource import get_ds |
14 | 14 | from apps.datasource.crud.recommended_problem import get_datasource_recommended_chart |
15 | 15 | from apps.datasource.models.datasource import CoreDatasource |
@@ -41,10 +41,31 @@ def get_chat(session: SessionDep, chat_id: int) -> Chat: |
41 | 41 | return chat |
42 | 42 |
|
43 | 43 |
|
44 | | -def list_chats(session: SessionDep, current_user: CurrentUser) -> List[Chat]: |
| 44 | +def list_chats(session: SessionDep, current_user: CurrentUser) -> List[ChatItem]: |
45 | 45 | oid = current_user.oid if current_user.oid is not None else 1 |
46 | | - chart_list = session.query(Chat).filter(and_(Chat.create_by == current_user.id, Chat.oid == oid)).order_by( |
47 | | - Chat.create_time.desc()).all() |
| 46 | + # 子查询:获取每个chat对应的最新chat_record的create_time |
| 47 | + latest_record_subq = ( |
| 48 | + session.query( |
| 49 | + ChatRecord.chat_id, |
| 50 | + func.max(ChatRecord.create_time).label('latest_record_time') |
| 51 | + ) |
| 52 | + .group_by(ChatRecord.chat_id) |
| 53 | + .subquery() |
| 54 | + ) |
| 55 | + # 按最新chat_record的create_time排序,如果没有chat_record则使用chat自身的create_time |
| 56 | + sort_time = func.coalesce(latest_record_subq.c.latest_record_time, Chat.create_time) |
| 57 | + results = ( |
| 58 | + session.query(Chat, sort_time.label('latest_record_time')) |
| 59 | + .outerjoin(latest_record_subq, Chat.id == latest_record_subq.c.chat_id) |
| 60 | + .filter(and_(Chat.create_by == current_user.id, Chat.oid == oid)) |
| 61 | + .order_by(sort_time.desc()) |
| 62 | + .all() |
| 63 | + ) |
| 64 | + chart_list = [] |
| 65 | + for chat, latest_record_time in results: |
| 66 | + item = ChatItem(**chat.model_dump()) |
| 67 | + item.latest_record_time = latest_record_time |
| 68 | + chart_list.append(item) |
48 | 69 | return chart_list |
49 | 70 |
|
50 | 71 |
|
@@ -476,6 +497,11 @@ def get_chat_with_records(session: SessionDep, chart_id: int, current_user: Curr |
476 | 497 |
|
477 | 498 | chat_info.records = result |
478 | 499 |
|
| 500 | + # 从已查出的records中取最新的create_time |
| 501 | + record_times = [r.get('create_time') for r in result if r.get('create_time') is not None] |
| 502 | + if record_times: |
| 503 | + chat_info.latest_record_time = max(record_times) |
| 504 | + |
479 | 505 | return chat_info |
480 | 506 |
|
481 | 507 |
|
|
0 commit comments