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), }