Files
wechat_backend/routes/course_vote.py
王宏豪 f3fbd0377a feat(init): 添加完整的认证和业务路由模块
- 实现微信登录、手机号绑定、token验证和登出功能
- 添加打卡系统,支持正常、迟到、请假等状态记录
- 集成课程投票功能,支持多课程选择和评分评论
- 开发反馈系统,支持图文反馈提交和管理员处理
- 构建首页页面模块,动态展示学习资源和个人信息
- 设计计划管理系统,支持周/月/年计划制定和跟踪
- 实现小组计划统计和历史记录查询功能
- 完善用户认证会话管理和数据库交互逻辑
2026-09-03 16:43:11 +08:00

86 lines
2.5 KiB
Python

import json
import os
from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from .. import config
from .auth import get_current_user
router = APIRouter(prefix="/api/v1", tags=["course-vote"])
def _load():
if not os.path.exists(config.COURSE_VOTES_FILE):
return {}
with open(config.COURSE_VOTES_FILE, encoding="utf-8") as f:
content = f.read().strip()
return json.loads(content) if content else {}
def _save(data):
os.makedirs(os.path.dirname(config.COURSE_VOTES_FILE), exist_ok=True)
with open(config.COURSE_VOTES_FILE, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
class CourseVoteRequest(BaseModel):
votes: list = []
rating: int = 0
comment: str = ""
@router.post("/course-vote")
def submit_vote(req: CourseVoteRequest, user=Depends(get_current_user)):
votes = req.votes
if not votes or len(votes) < 3 or len(votes) > 6:
raise HTTPException(status_code=400, detail="请选择3-6门课程")
data = _load()
data[user["student_id"]] = {
"name": user["name"],
"votes": votes,
"rating": req.rating,
"comment": req.comment.strip()[:500],
"time": str(datetime.now()),
}
_save(data)
return {"success": True, "msg": "投票成功"}
@router.get("/course-votes")
def get_votes(user=Depends(get_current_user)):
data = _load()
totals = {}
reviews = []
total_rating = 0
rating_count = 0
for sid, info in data.items():
for v in info.get("votes", []):
totals[v] = totals.get(v, 0) + 1
r = info.get("rating", 0)
t = info.get("time", "")
if t and " " in t:
t = t.split(" ")[0]
if r > 0:
total_rating += r
rating_count += 1
reviews.append({"name": info.get("name", sid), "rating": r, "comment": info.get("comment", ""), "time": t})
my_votes = []
my_rating = 0
my_comment = ""
if user["student_id"] in data:
my_votes = data[user["student_id"]].get("votes", [])
my_rating = data[user["student_id"]].get("rating", 0)
my_comment = data[user["student_id"]].get("comment", "")
avg_score = round(total_rating / rating_count, 1) if rating_count > 0 else 0
return {
"success": True,
"totals": totals,
"reviews": reviews,
"avgScore": avg_score,
"myVotes": my_votes,
"myRating": my_rating,
"myComment": my_comment,
"totalVoters": len(data),
}