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']}

""" for _key, cri in criteria.items(): - html += f"""""" + html += f"""""" html += """
评分项目满分得分评分要点
{cri['label']}{cri['max']}分______{cri['description']}
{cri['label']}{cri['max']}分______{cri['description']}
合计100分______
评委签名:____________________日期:____年____月____日
@@ -1175,12 +1180,11 @@ HTML_TEMPLATE = """ * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: 'Microsoft YaHei', sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; padding: 20px; } .container { max-width: 1400px; margin: 0 auto; } - .clearfix { clear: both; } .header, .tabs, .batch-bar, .program-list-sidebar, .score-panel, .summary-panel, - .admin-panel, .settings-panel, .judge-scoring-container, .admin-scoring-container, + .settings-panel, .judge-scoring-container, .admin-scoring-container, .programs-sidebar, .scoring-panel { clear: both; } - .header { background: rgba(255,255,255,0.95); border-radius: 20px; padding: 20px 30px; margin-bottom: 25px; box-shadow: 0 10px 40px rgba(0,0,0,0.1); } + .header { background: rgba(255,255,255,0.95); border-radius: 20px; padding: 20px 30px; margin-bottom: 15px; box-shadow: 0 10px 40px rgba(0,0,0,0.1); } .header h1 { font-size: 28px; color: #2d3748; border-left: 5px solid #667eea; padding-left: 20px; } .header .subtitle { color: #718096; padding-left: 25px; font-size: 14px; margin-top: 8px; } .login-bar { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px; margin-top: 15px; padding-top: 15px; border-top: 1px solid #e2e8f0; } @@ -1205,15 +1209,16 @@ HTML_TEMPLATE = """ .admin-info { background: #fef5e7; color: #c05621; padding: 6px 16px; border-radius: 30px; font-size: 14px; } .progress-bar { background: #e2e8f0; border-radius: 20px; height: 8px; margin: 12px 0 5px; overflow: hidden; } .progress-fill { background: linear-gradient(90deg, #48bb78, #38a169); height: 100%; width: 0%; transition: width 0.3s; } - .tabs { display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap; } - .tab { padding: 8px 20px; cursor: pointer; border-radius: 20px; background: rgba(255,255,255,0.8); } - .tab.active { background: #667eea; color: white; } .mode-badge { display: inline-block; padding: 4px 12px; border-radius: 20px; font-size: 12px; margin-left: 10px; } .mode-judge { background: #48bb78; color: white; } .mode-admin { background: #ed8936; color: white; } - .batch-bar { display: flex; gap: 10px; margin-bottom: 15px; align-items: center; flex-wrap: wrap; } - .batch-btn { padding: 6px 15px; border: none; border-radius: 20px; cursor: pointer; background: #e2e8f0; font-size: 13px; } - .batch-btn.active { background: #667eea; color: white; } + .functionBar { padding: 10px 20px; margin-bottom: 10px; border-radius: 20px; background: #f7fafc; } + .tabs { display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap; } + .tab { padding: 8px 20px; cursor: pointer; border-radius: 14px; background: white; border-left: 3px solid transparent; } + .tab.active { background: #e0e7ff; font-weight: bold; border-left-color: #667eea; } + .batch-bar { display: flex; gap: 10px; margin-bottom: 5px; align-items: center; flex-wrap: wrap; } + .batch-btn { padding: 6px 15px; border: none; border-radius: 12px; cursor: pointer; background: white; font-size: 13px; border-left: 3px solid transparent; } + .batch-btn.active { background: #e0e7ff; font-weight: bold; border-left-color: #667eea } .judge-scoring-container, .admin-scoring-container { background: white; border-radius: 20px; padding: 20px; overflow-x: auto; margin-bottom: 20px; } .program-list-sidebar { flex: 1; min-width: 250px; background: #f7fafc; border-radius: 16px; padding: 15px; max-height: 600px; overflow-y: auto; } .program-list-sidebar h4 { margin-bottom: 10px; } @@ -1227,16 +1232,17 @@ HTML_TEMPLATE = """ .score-input { width: 70px; padding: 4px 6px; text-align: center; border: 1px solid #cbd5e1; border-radius: 4px; font-size: 13px; } .detail-score-input { width: 70px; padding: 6px; text-align: center; border: 1px solid #cbd5e1; border-radius: 6px; } .total-score { font-weight: bold; font-size: 18px; margin: 10px 0; text-align: center; padding: 10px; background: linear-gradient(135deg, #667eea, #764ba2); color: white; border-radius: 12px; } - .summary-panel { margin-top: 30px; background: white; border-radius: 20px; padding: 20px; overflow-x: auto; } + .summary-panel { margin-top: 20px; background: white; border-radius: 20px; padding: 20px; overflow-x: auto; } .summary-table { width: 100%; border-collapse: collapse; font-size: 13px; } .summary-table th, .summary-table td { padding: 10px 8px; text-align: center; border-bottom: 1px solid #e2e8f0; } .summary-table th { background: #f7fafc; } .rank-1 { background: #fef5e7; font-weight: bold; } + .admin-content { display: flex; column-gap: 10px; flex-wrap: nowrap; } .award-table-container { max-height: 400px; overflow-y: auto; margin-top: 15px; } .award-table { width: 100%; border-collapse: collapse; font-size: 13px; } .award-table th, .award-table td { padding: 10px 8px; text-align: center; border: 1px solid #e2e8f0; } .award-table th { background: #f7fafc; } - .admin-panel, .settings-panel { background: white; border-radius: 20px; padding: 20px; margin-bottom: 20px; } + .settings-panel { background: white; border-radius: 20px; padding: 20px; margin-bottom: 10px; } .print-buttons { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 15px; } .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000; justify-content: center; align-items: center; } .modal-content { background: white; padding: 25px; border-radius: 20px; width: 90%; max-width: 500px; } @@ -1244,7 +1250,7 @@ HTML_TEMPLATE = """ .batch-list-item, .judge-list-item, .program-list-item { display: flex; justify-content: space-between; align-items: center; padding: 10px 0; border-bottom: 1px solid #eee; clear: both; } .batch-list-item span, .judge-list-item span, .program-list-item span { font-size: 14px; } .batch-buttons, .judge-buttons, .program-buttons { display: flex; gap: 8px; } - .toast { position: fixed; bottom: 20px; right: 20px; background: #333; color: white; padding: 12px 20px; border-radius: 8px; animation: fadeOut 2s ease; z-index: 1000; } + .toast { position: fixed; top: 20px; left: 50%; transform: translateX(-50%); background: #333; color: white; padding: 12px 20px; border-radius: 8px; animation: fadeOut 2s ease; z-index: 1000; } .col-operation { display: none; } @@ -1253,49 +1259,18 @@ HTML_TEMPLATE = """ } @keyframes fadeOut { 0% { opacity: 1; } 70% { opacity: 1; } 100% { opacity: 0; visibility: hidden; } } @media (max-width: 768px) { - .judge-scoring-container > div { - flex-direction: column !important; - } - .judge-scoring-container .program-list-sidebar { - width: 100%; - max-height: 300px; - overflow-y: auto; - margin-bottom: 16px; - } - .judge-scoring-container .score-panel { - width: 100%; - } - #judgeScorePanel .score-cards { - grid-template-columns: 1fr !important; - gap: 12px !important; - } - .score-input, .detail-score-input, .admin-input, .judge-select { - width: 100%; - box-sizing: border-box; - } - .scoring-table, .summary-table { - display: block; - overflow-x: auto; - white-space: nowrap; - } - .batch-bar { - flex-wrap: wrap; - } - .batch-btn { - margin-bottom: 8px; - } - .header h1 { - font-size: 20px; - } - .login-area { - flex-wrap: wrap; - } .login-area .admin-input, .login-area .judge-select, .login-area .btn { width: 100%; margin-bottom: 8px; } + .judge-scoring-container .program-list-sidebar { + width: 100%; + max-height: 200px; + overflow-y: auto; + margin-bottom: 16px; + } .admin-scoring-container { overflow-x: auto; -webkit-overflow-scrolling: touch; @@ -1303,6 +1278,14 @@ HTML_TEMPLATE = """ .admin-scoring-container .scoring-table { min-width: max(100%, 600px); } + .admin-content { + flex-wrap: wrap; + } + .scoring-table, .summary-table { + display: block; + overflow-x: auto; + white-space: nowrap; + } } @@ -1330,16 +1313,18 @@ HTML_TEMPLATE = """
-
-
🎯 评分打分
- - -
🖨️ 打印中心
+
+
+
🎯 评分打分
+ + +
🖨️ 打印中心
+
+
-
请先登录选择节目评分
@@ -1347,34 +1332,31 @@ HTML_TEMPLATE = """