feat: 初始化考培练系统项目
- 从服务器拉取完整代码 - 按框架规范整理项目结构 - 配置 Drone CI 测试环境部署 - 包含后端(FastAPI)、前端(Vue3)、管理端 技术栈: Vue3 + TypeScript + FastAPI + MySQL
This commit is contained in:
65
backend/app/services/course_statistics_service.py
Normal file
65
backend/app/services/course_statistics_service.py
Normal file
@@ -0,0 +1,65 @@
|
||||
"""
|
||||
课程统计服务
|
||||
"""
|
||||
from sqlalchemy import select, func
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.models.exam import Exam
|
||||
from app.models.course import Course
|
||||
from app.core.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class CourseStatisticsService:
|
||||
"""课程统计服务类"""
|
||||
|
||||
async def update_course_student_count(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
course_id: int
|
||||
) -> int:
|
||||
"""
|
||||
更新课程学员数统计
|
||||
|
||||
Args:
|
||||
db: 数据库会话
|
||||
course_id: 课程ID
|
||||
|
||||
Returns:
|
||||
更新后的学员数
|
||||
"""
|
||||
try:
|
||||
# 统计该课程的不同学员数(基于考试记录)
|
||||
stmt = select(func.count(func.distinct(Exam.user_id))).where(
|
||||
Exam.course_id == course_id,
|
||||
Exam.is_deleted == False
|
||||
)
|
||||
result = await db.execute(stmt)
|
||||
student_count = result.scalar_one() or 0
|
||||
|
||||
# 更新课程表
|
||||
course_stmt = select(Course).where(
|
||||
Course.id == course_id,
|
||||
Course.is_deleted == False
|
||||
)
|
||||
course_result = await db.execute(course_stmt)
|
||||
course = course_result.scalar_one_or_none()
|
||||
|
||||
if course:
|
||||
course.student_count = student_count
|
||||
await db.commit()
|
||||
logger.info(f"更新课程 {course_id} 学员数: {student_count}")
|
||||
return student_count
|
||||
else:
|
||||
logger.warning(f"课程 {course_id} 不存在")
|
||||
return 0
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"更新课程学员数失败: {str(e)}", exc_info=True)
|
||||
await db.rollback()
|
||||
raise
|
||||
|
||||
|
||||
# 创建全局实例
|
||||
course_statistics_service = CourseStatisticsService()
|
||||
|
||||
Reference in New Issue
Block a user