diff --git a/main.py b/main.py index d3b1fca..1c9bb0e 100644 --- a/main.py +++ b/main.py @@ -10,35 +10,12 @@ import pandas as pd from fastapi import Depends, FastAPI, File, HTTPException, Query, Request, UploadFile from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import HTMLResponse, StreamingResponse -from pydantic import BaseModel, BeforeValidator +from pydantic import BaseModel, BeforeValidator, InstanceOf SECRET_KEY = 'QET5hv3A@148fefo#5#W5x#aF%9Y#8!2' ALGORITHM = 'HS256' ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 - -def create_access_token(data: dict): - to_encode = data.copy() - expire = datetime.now(UTC) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) - to_encode.update({'exp': expire}) - return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) - - -def verify_token(token: str): - try: - return jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - except jwt.PyJWTError as exc: - raise HTTPException(status_code=401, detail='Token 无效') from exc - - -async def require_admin(request: Request): - token = request.headers.get('Authorization', '').replace('Bearer ', '') - payload = verify_token(token) - if payload.get('role') != 'admin': - raise HTTPException(status_code=403, detail='需要管理员权限') - return payload - - app = FastAPI() app.add_middleware( @@ -86,7 +63,7 @@ def init_db(): """CREATE TABLE IF NOT EXISTS judges (id TEXT PRIMARY KEY, name TEXT NOT NULL, order_num INTEGER, created_at TIMESTAMP)""" ) cursor.execute( - """CREATE TABLE IF NOT EXISTS scores (id INTEGER PRIMARY KEY AUTOINCREMENT, judge_id TEXT NOT NULL, program_sn TEXT NOT NULL, content_score REAL, stage_score REAL, art_score REAL, overall_score REAL, comment TEXT, updated_at TIMESTAMP, UNIQUE(judge_id, program_sn), FOREIGN KEY (program_sn) REFERENCES programs(sn) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY (judge_id) REFERENCES judges(id) ON DELETE CASCADE ON UPDATE CASCADE)""" + """CREATE TABLE IF NOT EXISTS scores (id INTEGER PRIMARY KEY AUTOINCREMENT, judge_id TEXT NOT NULL, program_sn TEXT NOT NULL, content_score REAL, stage_score REAL, art_score REAL, overall_score REAL, admin_total_score REAL, comment TEXT, updated_at TIMESTAMP, UNIQUE(judge_id, program_sn), FOREIGN KEY (program_sn) REFERENCES programs(sn) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY (judge_id) REFERENCES judges(id) ON DELETE CASCADE ON UPDATE CASCADE)""" ) cursor.execute( """CREATE TABLE IF NOT EXISTS admins (id TEXT PRIMARY KEY, username TEXT UNIQUE NOT NULL, password TEXT NOT NULL, created_at TIMESTAMP)""" @@ -140,6 +117,28 @@ def init_db(): init_db() +def create_access_token(data: dict): + to_encode = data.copy() + expire = datetime.now(UTC) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) + to_encode.update({'exp': expire}) + return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) + + +def verify_token(token: str): + try: + return jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) + except jwt.PyJWTError as exc: + raise HTTPException(status_code=401, detail='Token 无效') from exc + + +async def require_admin(request: Request): + token = request.headers.get('Authorization', '').replace('Bearer ', '') + payload = verify_token(token) + if payload.get('role') != 'admin': + raise HTTPException(status_code=403, detail='需要管理员权限') + return payload + + # ==================== Pydantic模型 ==================== def escape_html(value: str) -> str: if value is None: @@ -636,7 +635,10 @@ async def import_programs( return {'success': True, 'message': f'成功导入/更新 {df.shape[0]} 个节目'} except Exception as exc: - raise HTTPException(status_code=400, detail=f'导入失败:{str(exc)}') from exc + raise HTTPException( + status_code=400, + detail=exc.detail if isinstance(exc, HTTPException) else str(exc), + ) from exc @app.put('/api/programs/{program_sn}', dependencies=[Depends(require_admin)]) @@ -726,7 +728,8 @@ async def update_score(judge_id: str, score_data: ScoreDetailUpdate): VALUES (?, ?, ?, ?) ON CONFLICT(judge_id, program_sn) DO UPDATE SET {field_map[score_data.field]} = excluded.{field_map[score_data.field]}, - updated_at = excluded.updated_at + updated_at = excluded.updated_at, + admin_total_score = NULL """, (judge_id, score_data.program_sn, val, datetime.now()), ) @@ -753,7 +756,13 @@ async def update_comment(judge_id: str, comment_data: CommentUpdate): with get_db(write=True) as conn: cursor = conn.cursor() cursor.execute( - 'INSERT INTO scores (judge_id, program_sn, comment, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT(judge_id, program_sn) DO UPDATE SET comment = excluded.comment, updated_at = excluded.updated_at', + """ + INSERT INTO scores (judge_id, program_sn, comment, updated_at) + VALUES (?, ?, ?, ?) + ON CONFLICT(judge_id, program_sn) DO UPDATE SET + comment = excluded.comment, + updated_at = excluded.updated_at + """, (judge_id, comment_data.program_sn, comment_data.comment, datetime.now()), ) return {'success': True} @@ -776,7 +785,7 @@ async def batch_update_scores(batch_data: ScoreBatchUpdate): if total_score is None: cursor.execute( """ - UPDATE scores SET content_score = NULL, stage_score = NULL, art_score = NULL, overall_score = NULL, updated_at = ? + UPDATE scores SET admin_total_score = NULL, updated_at = ? WHERE judge_id = ? AND program_sn = ? """, (datetime.now(), judge_id, batch_data.program_sn), @@ -784,24 +793,21 @@ async def batch_update_scores(batch_data: ScoreBatchUpdate): else: cursor.execute( """ - INSERT INTO scores (judge_id, program_sn, content_score, stage_score, art_score, overall_score, comment, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?) + INSERT INTO scores (judge_id, program_sn, admin_total_score, updated_at) + VALUES (?, ?, ?, ?) ON CONFLICT(judge_id, program_sn) DO UPDATE SET - content_score = excluded.content_score, - stage_score = excluded.stage_score, - art_score = excluded.art_score, - overall_score = excluded.overall_score, - comment = excluded.comment, + content_score = NULL, + stage_score = NULL, + art_score = NULL, + overall_score = NULL, + admin_total_score = excluded.admin_total_score, + comment = NULL, updated_at = excluded.updated_at """, ( judge_id, batch_data.program_sn, total_score, - None, - None, - None, - '', datetime.now(), ), ) @@ -821,7 +827,10 @@ async def get_programs_scores(data: dict): cursor.execute( f""" SELECT program_sn, judge_id, - content_score, stage_score, art_score, overall_score + COALESCE(admin_total_score, + COALESCE(content_score,0) + COALESCE(stage_score,0) + + COALESCE(art_score,0) + COALESCE(overall_score,0) + ) AS final_total FROM scores WHERE program_sn IN ({placeholders}) """, sn_list, @@ -832,16 +841,9 @@ async def get_programs_scores(data: dict): prog_sn = row['program_sn'] if prog_sn not in result: result[prog_sn] = {} - total = 0 - if row['content_score'] is not None: - total += row['content_score'] - if row['stage_score'] is not None: - total += row['stage_score'] - if row['art_score'] is not None: - total += row['art_score'] - if row['overall_score'] is not None: - total += row['overall_score'] - result[prog_sn][row['judge_id']] = total if total != 0 else None + result[prog_sn][row['judge_id']] = ( + row['final_total'] if row['final_total'] != 0 else None + ) return result @@ -870,15 +872,18 @@ async def get_aggregate(batch_id: int | None = Query(None)): f""" SELECT t.program_sn, - AVG(CASE WHEN t.total > 0 THEN t.total ELSE NULL END) AS avg_score, - MAX(CASE WHEN t.total > 0 THEN t.total ELSE NULL END) AS max_score, - MIN(CASE WHEN t.total > 0 THEN t.total ELSE NULL END) AS min_score, - COUNT(CASE WHEN t.total > 0 THEN 1 ELSE NULL END) AS scored_count + AVG(CASE WHEN t.final_total > 0 THEN t.final_total ELSE NULL END) AS avg_score, + MAX(CASE WHEN t.final_total > 0 THEN t.final_total ELSE NULL END) AS max_score, + MIN(CASE WHEN t.final_total > 0 THEN t.final_total ELSE NULL END) AS min_score, + COUNT(CASE WHEN t.final_total > 0 THEN 1 ELSE NULL END) AS scored_count FROM ( SELECT program_sn, judge_id, - (COALESCE(content_score,0) + COALESCE(stage_score,0) + COALESCE(art_score,0) + COALESCE(overall_score,0)) AS total + COALESCE(admin_total_score, + COALESCE(content_score,0) + COALESCE(stage_score,0) + + COALESCE(art_score,0) + COALESCE(overall_score,0) + ) AS final_total FROM scores WHERE program_sn IN ({placeholders}) ) t @@ -936,7 +941,7 @@ async def get_progress(): total_judges = cursor.execute('SELECT COUNT(*) FROM judges').fetchone()[0] total_cells = total_programs * total_judges scored_cells = cursor.execute( - 'SELECT COUNT(*) FROM scores WHERE content_score IS NOT NULL' + 'SELECT COUNT(*) FROM scores WHERE content_score IS NOT NULL OR stage_score IS NOT NULL OR art_score IS NOT NULL OR overall_score IS NOT NULL OR admin_total_score IS NOT NULL' ).fetchone()[0] progress = round(scored_cells / total_cells * 100, 1) if total_cells > 0 else 0 return { @@ -1120,7 +1125,7 @@ def render_print_blank_template(program, judges, criteria, titles):
演出单位: {program['unit']} | 表演者: {program['performer']} | 节目类别: {program['category']}
| 评分项目 | 满分 | 得分 | 评分要点 |
|---|---|---|---|
| {cri['label']} | {cri['max']}分 | ______ | {cri['description']} |
| {cri['label']} | {cri['max']}分 | ______ | {cri['description']} |
| 合计 | 100分 | ______ | |