diff --git a/api/app/controllers/emotion_controller.py b/api/app/controllers/emotion_controller.py index c92c04d5..24bdc434 100644 --- a/api/app/controllers/emotion_controller.py +++ b/api/app/controllers/emotion_controller.py @@ -59,7 +59,7 @@ async def get_emotion_tags( "limit": request.limit } ) - + # 调用服务层 data = await emotion_service.get_emotion_tags( end_user_id=request.group_id, @@ -68,7 +68,7 @@ async def get_emotion_tags( end_date=request.end_date, limit=request.limit ) - + api_logger.info( "情绪标签统计获取成功", extra={ @@ -77,9 +77,9 @@ async def get_emotion_tags( "tags_count": len(data.get("tags", [])) } ) - + return success(data=data, msg="情绪标签获取成功") - + except Exception as e: api_logger.error( f"获取情绪标签统计失败: {str(e)}", @@ -108,14 +108,14 @@ async def get_emotion_wordcloud( "limit": request.limit } ) - + # 调用服务层 data = await emotion_service.get_emotion_wordcloud( end_user_id=request.group_id, emotion_type=request.emotion_type, limit=request.limit ) - + api_logger.info( "情绪词云数据获取成功", extra={ @@ -123,9 +123,9 @@ async def get_emotion_wordcloud( "total_keywords": data.get("total_keywords", 0) } ) - + return success(data=data, msg="情绪词云获取成功") - + except Exception as e: api_logger.error( f"获取情绪词云数据失败: {str(e)}", @@ -152,7 +152,7 @@ async def get_emotion_health( status_code=status.HTTP_400_BAD_REQUEST, detail="时间范围参数无效,必须是 7d、30d 或 90d" ) - + api_logger.info( f"用户 {current_user.username} 请求获取情绪健康指数", extra={ @@ -160,13 +160,13 @@ async def get_emotion_health( "time_range": request.time_range } ) - + # 调用服务层 data = await emotion_service.calculate_emotion_health_index( end_user_id=request.group_id, time_range=request.time_range ) - + api_logger.info( "情绪健康指数获取成功", extra={ @@ -175,9 +175,9 @@ async def get_emotion_health( "level": data.get("level", "未知") } ) - + return success(data=data, msg="情绪健康指数获取成功") - + except HTTPException: raise except Exception as e: @@ -200,12 +200,12 @@ async def get_emotion_suggestions( current_user: User = Depends(get_current_user), ): """获取个性化情绪建议(从缓存读取) - + Args: request: 包含 group_id 和可选的 config_id db: 数据库会话 current_user: 当前用户 - + Returns: 缓存的个性化情绪建议响应 """ @@ -217,13 +217,13 @@ async def get_emotion_suggestions( "config_id": request.config_id } ) - + # 从缓存获取建议 data = await emotion_service.get_cached_suggestions( end_user_id=request.group_id, db=db ) - + if data is None: # 缓存不存在或已过期 api_logger.info( @@ -235,7 +235,7 @@ async def get_emotion_suggestions( "建议缓存不存在或已过期,请调用 /generate_suggestions 接口生成新建议", None ) - + api_logger.info( "个性化建议获取成功(缓存)", extra={ @@ -243,9 +243,9 @@ async def get_emotion_suggestions( "suggestions_count": len(data.get("suggestions", [])) } ) - + return success(data=data, msg="个性化建议获取成功(缓存)") - + except Exception as e: api_logger.error( f"获取个性化建议失败: {str(e)}", @@ -265,12 +265,12 @@ async def generate_emotion_suggestions( current_user: User = Depends(get_current_user), ): """生成个性化情绪建议(调用LLM并缓存) - + Args: request: 包含 group_id、可选的 config_id 和 force_refresh db: 数据库会话 current_user: 当前用户 - + Returns: 新生成的个性化情绪建议响应 """ @@ -298,7 +298,7 @@ async def generate_emotion_suggestions( return fail(BizCode.INVALID_PARAMETER, "配置ID无效", f"配置 {config_id} 不存在") except Exception as e: return fail(BizCode.INVALID_PARAMETER, "配置ID验证失败", str(e)) - + api_logger.info( f"用户 {current_user.username} 请求生成个性化情绪建议", extra={ @@ -306,13 +306,13 @@ async def generate_emotion_suggestions( "config_id": config_id } ) - + # 调用服务层生成建议 data = await emotion_service.generate_emotion_suggestions( end_user_id=request.group_id, db=db ) - + # 保存到缓存 await emotion_service.save_suggestions_cache( end_user_id=request.group_id, @@ -320,7 +320,7 @@ async def generate_emotion_suggestions( db=db, expires_hours=24 ) - + api_logger.info( "个性化建议生成成功", extra={ @@ -328,9 +328,9 @@ async def generate_emotion_suggestions( "suggestions_count": len(data.get("suggestions", [])) } ) - + return success(data=data, msg="个性化建议生成成功") - + except Exception as e: api_logger.error( f"生成个性化建议失败: {str(e)}", diff --git a/api/app/repositories/memory_increment_repository.py b/api/app/repositories/memory_increment_repository.py index 37396fbd..f3a56622 100644 --- a/api/app/repositories/memory_increment_repository.py +++ b/api/app/repositories/memory_increment_repository.py @@ -25,7 +25,7 @@ class MemoryIncrementRepository: MemoryIncrement, func.row_number().over( partition_by=func.date(MemoryIncrement.created_at), # 按日期分区 - order_by=MemoryIncrement.created_at.desc() # 按时间戳升序排序 + order_by=MemoryIncrement.created_at.desc() # 按时间戳降序排序,取每天最新的 ).label('row_num') ) .filter(MemoryIncrement.workspace_id == workspace_id) @@ -34,14 +34,24 @@ class MemoryIncrementRepository: memory_increment_alias = aliased(MemoryIncrement, subquery) - memory_increments = ( + # 先取最近的limit条记录的子查询 + recent_records_subquery = ( self.db.query(memory_increment_alias) .filter(subquery.c.row_num == 1) # 只取每个日期的第一条(最新的) - .order_by(memory_increment_alias.created_at.asc()) # 按时间戳降序排序 + .order_by(memory_increment_alias.created_at.desc()) # 按时间戳降序排序,取最近的 .limit(limit) + .subquery() + ) + + # 在外层按升序排列(从旧到新) + recent_alias = aliased(MemoryIncrement, recent_records_subquery) + memory_increments = ( + self.db.query(recent_alias) + .order_by(recent_alias.created_at.asc()) # 按时间戳升序排序 .all() ) - db_logger.info(f"成功查询工作空间 {workspace_id} 下的内存增量") + + db_logger.info(f"成功查询工作空间 {workspace_id} 下的内存增量,返回最近 {len(memory_increments)} 条记录") return memory_increments except Exception as e: db_logger.error(f"查询工作空间 {workspace_id} 下内存增量时出错: {str(e)}")