diff --git a/main.py b/main.py index c258d1d..3541188 100644 --- a/main.py +++ b/main.py @@ -1,14 +1,43 @@ import sqlite3 from contextlib import contextmanager -from datetime import datetime +from datetime import UTC, datetime, timedelta +from html import escape from io import BytesIO -from typing import cast +from typing import Annotated, cast +import jwt import pandas as pd -from fastapi import FastAPI, File, HTTPException, Query, UploadFile +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 +from pydantic import BaseModel, BeforeValidator + +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(title='文艺汇演评分系统', description='乌鲁木齐群众文化艺术展评') @@ -25,12 +54,20 @@ DB_PATH = 'score_system.db' @contextmanager -def get_db(): +def get_db(write=False): conn = sqlite3.connect(DB_PATH) conn.row_factory = sqlite3.Row + conn.execute('PRAGMA journal_mode=WAL') + conn.execute('PRAGMA busy_timeout=5000') + conn.execute('PRAGMA foreign_keys=ON') + if write: + conn.execute('BEGIN IMMEDIATE') try: yield conn conn.commit() + except Exception: + conn.rollback() + raise finally: conn.close() @@ -43,13 +80,13 @@ def init_db(): """CREATE TABLE IF NOT EXISTS batches (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, created_at TIMESTAMP)""" ) cursor.execute( - """CREATE TABLE IF NOT EXISTS programs (sn TEXT PRIMARY KEY, name TEXT NOT NULL, unit TEXT, performer TEXT, category TEXT, batch_id INTEGER, order_num INTEGER, created_at TIMESTAMP)""" + """CREATE TABLE IF NOT EXISTS programs (sn TEXT PRIMARY KEY, name TEXT NOT NULL, unit TEXT, performer TEXT, category TEXT, batch_id INTEGER NOT NULL, order_num INTEGER, created_at TIMESTAMP, UNIQUE(batch_id, order_num), FOREIGN KEY (batch_id) REFERENCES batches(id) ON DELETE CASCADE ON UPDATE CASCADE)""" ) cursor.execute( """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))""" + """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)""" ) cursor.execute( """CREATE TABLE IF NOT EXISTS admins (id TEXT PRIMARY KEY, username TEXT UNIQUE NOT NULL, password TEXT NOT NULL, created_at TIMESTAMP)""" @@ -113,60 +150,69 @@ init_db() # ==================== Pydantic模型 ==================== +def escape_html(value: str) -> str: + if value is None: + return '' + return escape(str(value).strip()) + + +EscapedStr = Annotated[str, BeforeValidator(escape_html)] + + class AdminLogin(BaseModel): - username: str - password: str + username: EscapedStr + password: EscapedStr class JudgeLogin(BaseModel): - judge_id: str - judge_name: str + judge_id: EscapedStr + judge_name: EscapedStr class JudgeCreate(BaseModel): - id: str - name: str + id: EscapedStr + name: EscapedStr class JudgeUpdate(BaseModel): - name: str + name: EscapedStr class ProgramCreate(BaseModel): - sn: str - name: str - unit: str - performer: str - category: str + sn: EscapedStr + name: EscapedStr + unit: EscapedStr + performer: EscapedStr + category: EscapedStr batch_id: int class ProgramUpdate(BaseModel): - name: str - unit: str - performer: str - category: str + name: EscapedStr + unit: EscapedStr + performer: EscapedStr + category: EscapedStr batch_id: int class BatchCreate(BaseModel): - name: str + name: EscapedStr class ScoreDetailUpdate(BaseModel): - program_sn: str - field: str + program_sn: EscapedStr + field: EscapedStr value: float | None = None class ScoreBatchUpdate(BaseModel): - program_sn: str - judge_scores: dict[str, float | None] + program_sn: EscapedStr + judge_scores: dict[EscapedStr, float | None] class CommentUpdate(BaseModel): - program_sn: str - comment: str + program_sn: EscapedStr + comment: EscapedStr class AwardSettings(BaseModel): @@ -176,14 +222,14 @@ class AwardSettings(BaseModel): class AwardNamesSettings(BaseModel): - first_name: str - second_name: str - third_name: str + first_name: EscapedStr + second_name: EscapedStr + third_name: EscapedStr class TitleSettings(BaseModel): - main_title: str - sub_title: str + main_title: EscapedStr + sub_title: EscapedStr # ==================== 根路径 ==================== @@ -204,7 +250,15 @@ async def admin_login(login_data: AdminLogin): admin = cursor.fetchone() if not admin: raise HTTPException(status_code=401, detail='管理员用户名或密码错误') - return {'success': True, 'admin_id': admin['id'], 'username': admin['username']} + token = create_access_token( + {'id': admin['id'], 'username': admin['username'], 'role': 'admin'} + ) + return { + 'success': True, + 'admin_id': admin['id'], + 'username': admin['username'], + 'token': token, + } @app.get('/api/admin/check') @@ -254,9 +308,9 @@ async def get_title_settings(): } -@app.post('/api/settings/titles') +@app.post('/api/settings/titles', dependencies=[Depends(require_admin)]) async def update_title_settings(titles: TitleSettings): - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() cursor.execute( "UPDATE settings SET value = ? WHERE key = 'main_title'", @@ -290,9 +344,9 @@ async def get_award_settings(): } -@app.post('/api/settings/awards') +@app.post('/api/settings/awards', dependencies=[Depends(require_admin)]) async def update_award_settings(settings: AwardSettings): - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() cursor.execute( "UPDATE settings SET value = ? WHERE key = 'award_first'", @@ -309,9 +363,9 @@ async def update_award_settings(settings: AwardSettings): return {'success': True} -@app.post('/api/settings/award_names') +@app.post('/api/settings/award_names', dependencies=[Depends(require_admin)]) async def update_award_names(settings: AwardNamesSettings): - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() cursor.execute( "UPDATE settings SET value = ? WHERE key = 'award_first_name'", @@ -364,9 +418,9 @@ async def get_batches(): return batches -@app.post('/api/batches') +@app.post('/api/batches', dependencies=[Depends(require_admin)]) async def create_batch(batch: BatchCreate): - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() cursor.execute( 'INSERT INTO batches (name, created_at) VALUES (?, ?)', @@ -376,35 +430,23 @@ async def create_batch(batch: BatchCreate): return {'success': True, 'id': new_id, 'name': batch.name} -@app.delete('/api/batches/{batch_id}') +@app.delete('/api/batches/{batch_id}', dependencies=[Depends(require_admin)]) async def delete_batch(batch_id: int): - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() - cursor.execute('SELECT id FROM batches WHERE id = ?', (batch_id,)) - if not cursor.fetchone(): - raise HTTPException(status_code=404, detail='批次不存在') - # 获取该批次所有节目序号 - cursor.execute('SELECT sn FROM programs WHERE batch_id = ?', (batch_id,)) - programs = cursor.fetchall() - for prog in programs: - cursor.execute('DELETE FROM scores WHERE program_sn = ?', (prog['sn'],)) - cursor.execute('DELETE FROM programs WHERE batch_id = ?', (batch_id,)) cursor.execute('DELETE FROM batches WHERE id = ?', (batch_id,)) + if cursor.rowcount == 0: + raise HTTPException(status_code=404, detail='批次不存在') return {'success': True} -@app.delete('/api/batches/{batch_id}/programs') +@app.delete('/api/batches/{batch_id}/programs', dependencies=[Depends(require_admin)]) async def clear_batch_programs(batch_id: int): - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() - cursor.execute('SELECT id FROM batches WHERE id = ?', (batch_id,)) - if not cursor.fetchone(): - raise HTTPException(status_code=404, detail='批次不存在') - cursor.execute('SELECT sn FROM programs WHERE batch_id = ?', (batch_id,)) - programs = cursor.fetchall() - for prog in programs: - cursor.execute('DELETE FROM scores WHERE program_sn = ?', (prog['sn'],)) cursor.execute('DELETE FROM programs WHERE batch_id = ?', (batch_id,)) + if cursor.rowcount == 0: + raise HTTPException(status_code=404, detail='批次不存在') return {'success': True} @@ -421,9 +463,9 @@ async def get_judges(): return judges -@app.post('/api/judges') +@app.post('/api/judges', dependencies=[Depends(require_admin)]) async def create_judge(judge: JudgeCreate): - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() cursor.execute('SELECT id FROM judges WHERE id = ?', (judge.id,)) if cursor.fetchone(): @@ -443,9 +485,9 @@ async def create_judge(judge: JudgeCreate): return {'success': True} -@app.put('/api/judges/{judge_id}') +@app.put('/api/judges/{judge_id}', dependencies=[Depends(require_admin)]) async def update_judge(judge_id: str, judge: JudgeUpdate): - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() cursor.execute('SELECT id FROM judges WHERE id = ?', (judge_id,)) if not cursor.fetchone(): @@ -456,15 +498,13 @@ async def update_judge(judge_id: str, judge: JudgeUpdate): return {'success': True} -@app.delete('/api/judges/{judge_id}') +@app.delete('/api/judges/{judge_id}', dependencies=[Depends(require_admin)]) async def delete_judge(judge_id: str): - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() - cursor.execute('SELECT id FROM judges WHERE id = ?', (judge_id,)) - if not cursor.fetchone(): - raise HTTPException(status_code=404, detail='评委不存在') - cursor.execute('DELETE FROM scores WHERE judge_id = ?', (judge_id,)) cursor.execute('DELETE FROM judges WHERE id = ?', (judge_id,)) + if cursor.rowcount == 0: + raise HTTPException(status_code=404, detail='评委不存在') return {'success': True} @@ -497,22 +537,16 @@ async def get_programs(batch_id: int | None = Query(None)): return programs -@app.post('/api/programs') +@app.post('/api/programs', dependencies=[Depends(require_admin)]) async def create_program(program: ProgramCreate): - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() - cursor.execute('SELECT sn FROM programs WHERE sn = ?', (program.sn,)) - if cursor.fetchone(): - raise HTTPException(status_code=400, detail='节目序号已存在') cursor.execute( - 'SELECT MAX(order_num) FROM programs WHERE batch_id = ?', - (program.batch_id,), - ) - max_order = cursor.fetchone()[0] - if max_order is None: - max_order = 0 - cursor.execute( - 'INSERT INTO programs (sn, name, unit, performer, category, batch_id, order_num, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', + """ + INSERT INTO programs (sn, name, unit, performer, category, batch_id, order_num, created_at) + SELECT ?, ?, ?, ?, ?, ?, COALESCE(MAX(order_num), 0) + 1, ? + FROM programs WHERE batch_id = ? + """, ( program.sn, program.name, @@ -520,10 +554,12 @@ async def create_program(program: ProgramCreate): program.performer, program.category, program.batch_id, - max_order + 1, datetime.now(), + program.batch_id, ), ) + if cursor.rowcount == 0: + raise HTTPException(status_code=400, detail='节目序号已存在') cursor.execute('SELECT id FROM judges') for judge in cursor.fetchall(): cursor.execute( @@ -533,43 +569,47 @@ async def create_program(program: ProgramCreate): return {'success': True} -@app.post('/api/programs/import') -async def import_programs(batch_id: int = Query(...), file: UploadFile = File(...)): +@app.post('/api/programs/import', dependencies=[Depends(require_admin)]) +async def import_programs( + request: Request, batch_id: int = Query(...), file: UploadFile = File(...) +): + MAX_MB = 10 + content_length = request.headers.get('content-length') + if content_length and int(content_length) > MAX_MB * 1024 * 1024: + raise HTTPException(status_code=413, detail=f'文件大小超过 {MAX_MB}MB 限制') try: contents = await file.read() df = pd.read_excel(BytesIO(contents)) - required_columns = ['节目序号', '节目名称', '演出单位', '表演者', '节目类别'] + required_columns = ['节目编号', '节目名称', '演出单位', '表演者', '节目类别'] for col in required_columns: if col not in df.columns: raise HTTPException(status_code=400, detail=f'Excel缺少必要列:{col}') - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() cursor.execute( 'SELECT MAX(order_num) FROM programs WHERE batch_id = ?', (batch_id,) ) max_order_result = cursor.fetchone()[0] start_order = max_order_result if max_order_result is not None else 0 - - for idx, row in df.iterrows(): - sn = str(row['节目序号']).strip() - name = str(row['节目名称']).strip() - unit = str(row['演出单位']).strip() if pd.notna(row['演出单位']) else '' + order_counter = 0 + for _, row in df.iterrows(): + sn = escape_html(row['节目编号']) + name = escape_html(row['节目名称']) + unit = escape_html(row['演出单位']) if pd.notna(row['演出单位']) else '' performer = ( - str(row['表演者']).strip() if pd.notna(row['表演者']) else '' + escape_html(row['表演者']) if pd.notna(row['表演者']) else '' ) category = ( - str(row['节目类别']).strip() - if pd.notna(row['节目类别']) - else '舞蹈' + escape_html(row['节目类别']) if pd.notna(row['节目类别']) else '' ) if not sn or not name: continue - idx = cast(int, idx) - current_order = start_order + idx + 1 + order_counter += 1 + current_order = start_order + order_counter cursor.execute('SELECT sn FROM programs WHERE sn = ?', (sn,)) if cursor.fetchone(): cursor.execute( @@ -584,7 +624,7 @@ async def import_programs(batch_id: int = Query(...), file: UploadFile = File(.. ) else: cursor.execute( - 'INSERT INTO programs (sn, name, unit, performer, category, batch_id, order_num, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', + 'INSERT OR IGNORE INTO programs (sn, name, unit, performer, category, batch_id, order_num, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', ( sn, name, @@ -604,13 +644,13 @@ async def import_programs(batch_id: int = Query(...), file: UploadFile = File(.. ) return {'success': True, 'message': f'成功导入/更新 {df.shape[0]} 个节目'} - except Exception as e: - raise HTTPException(status_code=400, detail=f'导入失败:{str(e)}') from e + except Exception as exc: + raise HTTPException(status_code=400, detail=f'导入失败:{str(exc)}') from exc -@app.put('/api/programs/{program_sn}') +@app.put('/api/programs/{program_sn}', dependencies=[Depends(require_admin)]) async def update_program(program_sn: str, program: ProgramUpdate): - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() cursor.execute('SELECT sn FROM programs WHERE sn = ?', (program_sn,)) if not cursor.fetchone(): @@ -629,15 +669,13 @@ async def update_program(program_sn: str, program: ProgramUpdate): return {'success': True} -@app.delete('/api/programs/{program_sn}') +@app.delete('/api/programs/{program_sn}', dependencies=[Depends(require_admin)]) async def delete_program(program_sn: str): - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() - cursor.execute('SELECT sn FROM programs WHERE sn = ?', (program_sn,)) - if not cursor.fetchone(): - raise HTTPException(status_code=404, detail='节目不存在') - cursor.execute('DELETE FROM scores WHERE program_sn = ?', (program_sn,)) cursor.execute('DELETE FROM programs WHERE sn = ?', (program_sn,)) + if cursor.rowcount == 0: + raise HTTPException(status_code=404, detail='节目不存在') return {'success': True} @@ -689,7 +727,7 @@ async def update_score(judge_id: str, score_data: ScoreDetailUpdate): 'art': 'art_score', 'overall': 'overall_score', } - with get_db() as conn: + with get_db(write=True) as conn: cursor = conn.cursor() cursor.execute( f""" @@ -721,7 +759,7 @@ async def update_score(judge_id: str, score_data: ScoreDetailUpdate): @app.post('/api/comment/{judge_id}') async def update_comment(judge_id: str, comment_data: CommentUpdate): - with get_db() as conn: + 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', @@ -730,7 +768,7 @@ async def update_comment(judge_id: str, comment_data: CommentUpdate): return {'success': True} -@app.post('/api/scores/admin/batch') +@app.post('/api/scores/admin/batch', dependencies=[Depends(require_admin)]) async def batch_update_scores(batch_data: ScoreBatchUpdate): """管理员批量更新总分""" with get_db() as conn: @@ -738,7 +776,12 @@ async def batch_update_scores(batch_data: ScoreBatchUpdate): for judge_id, total_score in batch_data.judge_scores.items(): if total_score is not None and (total_score < 0 or total_score > 100): raise HTTPException(status_code=400, detail='总分必须在0-100之间') - + cursor.execute('SELECT id FROM judges WHERE id = ?', (judge_id,)) + if not cursor.fetchone(): + raise HTTPException(status_code=404, detail=f'评委 {judge_id} 不存在') + with get_db(write=True) as conn: + cursor = conn.cursor() + for judge_id, total_score in batch_data.judge_scores.items(): if total_score is None: cursor.execute( """ @@ -920,7 +963,7 @@ async def export_excel(batch_id: int | None = Query(None)): data = [ { '名次': item['rank'], - '节目序号': item['sn'], + '节目编号': item['sn'], '节目名称': item['name'], '演出单位': item['unit'], '表演者': item['performer'], @@ -1064,12 +1107,12 @@ def render_print_program_template( html = f"""{program['name']} - 评分详情

{titles['main_title']}

{titles['sub_title']} · 评分详情表
-

节目序号: {program['sn']}

节目名称: {program['name']}

演出单位: {program['unit']}

表演者: {program['performer']}

节目类别: {program['category']}

+

节目编号: {program['sn']}

节目名称: {program['name']}

演出单位: {program['unit']}

表演者: {program['performer']}

节目类别: {program['category']}

📊 平均分
{avg_score}
🎯 最高分
{max_score}
⭐ 最低分
{min_score}
""" for judge in judges: s = scores_data.get(judge['name'], {}) - html += f"""""" + html += f"""""" html += f"""
评委姓名总分(100分)评委点评
{judge['name']}{s.get('total') if s.get('total') > 0 else '-'}{s.get('comment', '')}
{judge['name']}{s.get('total') if s.get('total', 0) > 0 else '-'}{s.get('comment', '')}

评委组签名:____________________

日期:{datetime.now().strftime('%Y年%m月%d日')}

""" return html @@ -1082,7 +1125,7 @@ def render_print_blank_template(program, judges, criteria, titles): for _judge in judges: html += f"""

{titles['main_title']}

{titles['sub_title']} · 节目评分表
-

节目序号: {program['sn']} | 节目名称: {program['name']}

+

节目编号: {program['sn']} | 节目名称: {program['name']}

演出单位: {program['unit']} | 表演者: {program['performer']} | 节目类别: {program['category']}

""" for _key, cri in criteria.items(): @@ -1117,7 +1160,7 @@ def render_print_award_template(award_type, award_name, winners, titles, batch_n
{award_name}
评分项目满分得分评分要点
- + """ for idx, prog in enumerate(winners, 1): @@ -1386,13 +1429,13 @@ HTML_TEMPLATE = """

📊 评分汇总表

-
名次节目序号节目名称演出单位表演者节目类别平均分
名次节目编号节目名称演出单位表演者节目类别平均分
名次节目序号节目名称演出单位表演者类别平均分最高分最低分评委数操作
+
名次节目编号节目名称演出单位表演者类别平均分最高分最低分评委数操作
- - + + @@ -1403,6 +1446,7 @@ HTML_TEMPLATE = """ let editingProgramSn = null, editingJudgeId = null; let cachedAggregate = null, cachedAwardSettings = null; let refreshTimer = null; + let userToken = null; async function restoreLogin() { const stored = localStorage.getItem('score_user'); @@ -1433,6 +1477,7 @@ HTML_TEMPLATE = """ if (!checkData.exists) throw new Error('用户不存在'); currentUser = { id: user.id, username: user.username }; userType = 'admin'; + userToken = user.token; document.getElementById('loginArea').style.display = 'none'; document.getElementById('userInfoArea').style.display = 'flex'; document.getElementById('userInfo').innerHTML = `👑 管理员:${user.username} 管理员模式`; @@ -1525,7 +1570,10 @@ HTML_TEMPLATE = """ async function clearBatchPrograms(batchId) { if(confirm(`确定要清空该批次的所有节目吗?此操作不可恢复!`)){ - const res = await fetch(`/api/batches/${batchId}/programs`, { method:'DELETE' }); + const res = await fetch(`/api/batches/${batchId}/programs`, { + method:'DELETE', + headers:{'Authorization': 'Bearer ' + userToken}, + }); if(res.ok){ showToast('该批次所有节目已清空'); await loadPrograms(); @@ -1586,8 +1634,10 @@ HTML_TEMPLATE = """ localStorage.setItem('score_user', JSON.stringify({ type: 'admin', id: data.admin_id, - username: data.username + username: data.username, + token: data.token, })); + userToken = data.token; document.getElementById('loginArea').style.display = 'none'; document.getElementById('userInfoArea').style.display = 'flex'; document.getElementById('userInfo').innerHTML = `👑 管理员:${data.username} 管理员模式`; @@ -1635,7 +1685,7 @@ HTML_TEMPLATE = """ programsData.forEach(prog => { const isActive = currentJudgeProgram && currentJudgeProgram.sn === prog.sn; html += `
  • - ${escapeHtml(prog.name)}
    ${prog.sn} | ${escapeHtml(prog.performer)} + ${prog.name}
    ${prog.sn} | ${prog.performer}
  • `; }); } @@ -1657,7 +1707,7 @@ HTML_TEMPLATE = """ if(!prog) return; const total = (scores.content||0)+(scores.stage||0)+(scores.art||0)+(scores.overall||0); const html = `
    -

    ${escapeHtml(prog.name)}

    序号:${prog.sn} | 单位:${escapeHtml(prog.unit)} | 表演者:${escapeHtml(prog.performer)} | 类别:${prog.category}

    +

    ${prog.name}

    编号:${prog.sn} | 单位:${prog.unit} | 表演者:${prog.performer} | 类别:${prog.category}

    满分20分
    @@ -1681,7 +1731,7 @@ HTML_TEMPLATE = """
    🏆 节目总分:${total} / 100
    -
    +
    `; document.getElementById('judgeScorePanel').innerHTML = html; @@ -1730,11 +1780,11 @@ HTML_TEMPLATE = """ }); const scoresMap = await scoresMapRes.json(); // { program_sn: { judge_id: total } } - let html = ''; + let html = '
    节目序号节目名称表演者
    '; judgesData.forEach(j => { html += ``; }); html += ''; for(let prog of programsData){ - html += `
    节目编号节目名称表演者${j.name}
    (${j.id})
    操作
    ${prog.sn}${prog.name}${escapeHtml(prog.performer)}`; + html += `
    ${prog.sn}${prog.name}${prog.performer}`; for(let judge of judgesData){ let score = ''; const progScores = scoresMap[prog.sn]; @@ -1761,7 +1811,7 @@ HTML_TEMPLATE = """ try { const res = await fetch('/api/scores/admin/batch', { method:'POST', - headers:{'Content-Type':'application/json'}, + headers:{'Content-Type':'application/json', 'Authorization': 'Bearer ' + userToken}, body:JSON.stringify({program_sn:programSn, judge_scores:scores}) }); if(res.ok){ @@ -1868,7 +1918,7 @@ HTML_TEMPLATE = """ } } const firstCount = settings.first, secondCount = settings.second, thirdCount = settings.third; - let html = '
    '; + let html = '
    名次节目序号节目名称演出单位表演者类别平均分奖项
    '; programs.forEach((p, idx) => { let award = ''; if (idx < firstCount) award = settings.first_name; @@ -1896,7 +1946,7 @@ HTML_TEMPLATE = """ html += `

    📁 ${batchName}

    `; grouped[batchName].forEach(p => { html += `
    - ${p.sn} | ${escapeHtml(p.name)} | ${escapeHtml(p.unit)} | ${escapeHtml(p.performer)} + ${p.sn} | ${p.name} | ${p.unit} | ${p.performer}
    @@ -1938,7 +1988,7 @@ HTML_TEMPLATE = """ const third = parseInt(document.getElementById('awardThird').value) || 0; await fetch('/api/settings/awards', { method: 'POST', - headers: { 'Content-Type': 'application/json' }, + headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + userToken }, body: JSON.stringify({ first, second, third }) }); cachedAwardSettings = null; @@ -1952,7 +2002,7 @@ HTML_TEMPLATE = """ const third_name = document.getElementById('awardThirdName').value; await fetch('/api/settings/award_names', { method: 'POST', - headers: { 'Content-Type': 'application/json' }, + headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + userToken }, body: JSON.stringify({ first_name, second_name, third_name }) }); cachedAwardSettings = null; @@ -1961,10 +2011,23 @@ HTML_TEMPLATE = """ } function showAddBatchModal() { document.getElementById('batchModal').style.display='flex'; } - async function saveBatch() { const name = document.getElementById('batchName').value.trim(); if(!name){ showToast('请输入批次名称'); return; } await fetch('/api/batches', { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({name}) }); closeBatchModal(); await loadBatches(); } + async function saveBatch() { + const name = document.getElementById('batchName').value.trim(); + if(!name){ showToast('请输入批次名称'); return; } + await fetch('/api/batches', { + method:'POST', + headers:{'Content-Type':'application/json', 'Authorization': 'Bearer ' + userToken}, + body:JSON.stringify({name}) + }); + closeBatchModal(); + await loadBatches(); + } async function deleteBatch(id) { if(confirm('确定删除该批次吗?')) { - const res = await fetch(`/api/batches/${id}`, { method:'DELETE' }); + const res = await fetch(`/api/batches/${id}`, { + method:'DELETE', + headers:{'Authorization': 'Bearer ' + userToken}, + }); if (res.ok) { currentBatchId = null; renderBatchBars(); @@ -1982,25 +2045,135 @@ HTML_TEMPLATE = """ function showAddProgramModal() { editingProgramSn=null; document.getElementById('programModalTitle').innerText='添加节目'; document.getElementById('programSn').disabled=false; document.getElementById('programSn').value=''; document.getElementById('programName').value=''; document.getElementById('programUnit').value=''; document.getElementById('programPerformer').value=''; document.getElementById('programCategory').value='舞蹈'; renderBatchSelect(); document.getElementById('programModal').style.display='flex'; } function editProgram(sn) { const prog = programsData.find(p=>p.sn===sn); if(!prog) return; editingProgramSn=sn; document.getElementById('programModalTitle').innerText='编辑节目'; document.getElementById('programSn').value=prog.sn; document.getElementById('programSn').disabled=true; document.getElementById('programName').value=prog.name; document.getElementById('programUnit').value=prog.unit; document.getElementById('programPerformer').value=prog.performer; document.getElementById('programCategory').value=prog.category; renderBatchSelect(); document.getElementById('programBatchId').value=prog.batch_id; document.getElementById('programModal').style.display='flex'; } - async function saveProgram() { const sn = document.getElementById('programSn').value.trim(); const name = document.getElementById('programName').value.trim(); const unit = document.getElementById('programUnit').value.trim(); const performer = document.getElementById('programPerformer').value.trim(); const category = document.getElementById('programCategory').value; const batch_id = parseInt(document.getElementById('programBatchId').value); if(!sn||!name){ showToast('请填写节目序号和名称'); return; } let res; if(editingProgramSn){ res = await fetch(`/api/programs/${editingProgramSn}`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify({name,unit,performer,category,batch_id}) }); } else { res = await fetch('/api/programs', { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({sn,name,unit,performer,category,batch_id}) }); } if(res.ok){ closeProgramModal(); await loadPrograms(); if(userType==='judge') await loadJudgePrograms(); if(userType==='admin') await loadAdminScoring(); await loadAggregate(); } else { const err=await res.json(); showToast(err.detail); } } - async function deleteProgram(sn) { if(confirm(`确定删除节目 ${sn} 吗?`)){ await fetch(`/api/programs/${sn}`, { method:'DELETE' }); await loadPrograms(); if(userType==='judge') await loadJudgePrograms(); if(userType==='admin') await loadAdminScoring(); await loadAggregate(); } } + async function saveProgram() { + const sn = document.getElementById('programSn').value.trim(); + const name = document.getElementById('programName').value.trim(); + const unit = document.getElementById('programUnit').value.trim(); + const performer = document.getElementById('programPerformer').value.trim(); + const category = document.getElementById('programCategory').value; + const batch_id = parseInt(document.getElementById('programBatchId').value); + if(!sn||!name){ showToast('请填写节目编号和名称'); return; } + let res; + if(editingProgramSn){ + res = await fetch(`/api/programs/${editingProgramSn}`, { + method:'PUT', + headers:{'Content-Type':'application/json', 'Authorization': 'Bearer ' + userToken}, + body:JSON.stringify({name,unit,performer,category,batch_id}) + }); + } else { + res = await fetch('/api/programs', { + method:'POST', + headers:{'Content-Type':'application/json', 'Authorization': 'Bearer ' + userToken}, + body:JSON.stringify({sn,name,unit,performer,category,batch_id}) + }); + } + if(res.ok){ + closeProgramModal(); + await loadPrograms(); + if(userType==='judge') await loadJudgePrograms(); + if(userType==='admin') await loadAdminScoring(); + await loadAggregate(); + } else { + const err=await res.json(); + showToast(err.detail); + } + } + async function deleteProgram(sn) { + if(confirm(`确定删除节目 ${sn} 吗?`)){ + await fetch(`/api/programs/${sn}`, { + method:'DELETE', + headers:{'Authorization': 'Bearer ' + userToken}, + }); + await loadPrograms(); + if(userType==='judge') await loadJudgePrograms(); + if(userType==='admin') await loadAdminScoring(); + await loadAggregate(); + } + } function closeProgramModal() { document.getElementById('programModal').style.display='none'; document.getElementById('programSn').disabled=false; } function showImportProgramModal() { renderBatchSelect(); document.getElementById('importBatchId').innerHTML = document.getElementById('programBatchId').innerHTML; document.getElementById('importModal').style.display='flex'; } - async function importPrograms() { const file = document.getElementById('importFile').files[0]; if(!file){ showToast('请选择Excel文件'); return; } const batch_id = document.getElementById('importBatchId').value; const formData = new FormData(); formData.append('file', file); const res = await fetch(`/api/programs/import?batch_id=${batch_id}`, { method:'POST', body:formData }); if(res.ok){ showToast('导入成功'); closeImportModal(); await loadPrograms(); if(userType==='judge') await loadJudgePrograms(); if(userType==='admin') await loadAdminScoring(); await loadAggregate(); } else { const err=await res.json(); showToast('导入失败:'+err.detail); } } + async function importPrograms() { + const file = document.getElementById('importFile').files[0]; + if(!file){ showToast('请选择Excel文件'); return; } + const batch_id = document.getElementById('importBatchId').value; + const formData = new FormData(); + formData.append('file', file); + const res = await fetch(`/api/programs/import?batch_id=${batch_id}`, { + method:'POST', + headers:{'Authorization': 'Bearer ' + userToken}, + body:formData + }); + if(res.ok){ + showToast('导入成功'); + closeImportModal(); + await loadPrograms(); + if(userType==='judge') await loadJudgePrograms(); + if(userType==='admin') await loadAdminScoring(); + await loadAggregate(); + } else { + const err=await res.json(); + showToast('导入失败:'+err.detail); + } + } function closeImportModal() { document.getElementById('importModal').style.display='none'; document.getElementById('importFile').value=''; } function showAddJudgeModal() { editingJudgeId=null; document.getElementById('judgeModalTitle').innerText='添加评委'; document.getElementById('judgeId').value=''; document.getElementById('judgeName').value=''; document.getElementById('judgeModal').style.display='flex'; } function editJudge(id) { const judge = judgesData.find(j=>j.id===id); if(!judge) return; editingJudgeId=id; document.getElementById('judgeModalTitle').innerText='编辑评委'; document.getElementById('judgeId').value=judge.id; document.getElementById('judgeId').disabled=true; document.getElementById('judgeName').value=judge.name; document.getElementById('judgeModal').style.display='flex'; } - async function saveJudge() { const id = document.getElementById('judgeId').value.trim(); const name = document.getElementById('judgeName').value.trim(); if(!id||!name){ showToast('请填写评委编号和姓名'); return; } let res; if(editingJudgeId){ res = await fetch(`/api/judges/${editingJudgeId}`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify({name}) }); } else { res = await fetch('/api/judges', { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({id,name}) }); } if(res.ok){ closeJudgeModal(); await loadJudges(); if(userType==='admin') await renderAdminScoringTable(); } else { const err=await res.json(); showToast(err.detail); } } - async function deleteJudge(id) { if(confirm(`确定删除评委 ${id} 吗?`)){ await fetch(`/api/judges/${id}`, { method:'DELETE' }); await loadJudges(); if(userType==='admin') await renderAdminScoringTable(); await loadAggregate(); } } + async function saveJudge() { + const id = document.getElementById('judgeId').value.trim(); + const name = document.getElementById('judgeName').value.trim(); + if(!id||!name){ showToast('请填写评委编号和姓名'); return; } + let res; + if(editingJudgeId){ + res = await fetch(`/api/judges/${editingJudgeId}`, { + method:'PUT', + headers:{'Content-Type':'application/json', 'Authorization': 'Bearer ' + userToken}, + body:JSON.stringify({name}) + }); + } else { + res = await fetch('/api/judges', { + method:'POST', + headers:{'Content-Type':'application/json', 'Authorization': 'Bearer ' + userToken}, + body:JSON.stringify({id,name}) + }); + } + if(res.ok){ + closeJudgeModal(); + await loadJudges(); + if(userType==='admin') await renderAdminScoringTable(); + } else { + const err=await res.json(); + showToast(err.detail); + } + } + async function deleteJudge(id) { + if(confirm(`确定删除评委 ${id} 吗?`)){ + await fetch(`/api/judges/${id}`, { + method:'DELETE', + headers:{'Authorization': 'Bearer ' + userToken}, + }); + await loadJudges(); + if(userType==='admin') await renderAdminScoringTable(); + await loadAggregate(); + } + } function closeJudgeModal() { document.getElementById('judgeModal').style.display='none'; document.getElementById('judgeId').disabled=false; } function closeBatchModal() { document.getElementById('batchModal').style.display='none'; document.getElementById('batchName').value=''; } function showTitleModal() { fetch('/api/settings/titles').then(r=>r.json()).then(data=>{ document.getElementById('mainTitleInput').value=data.main_title; document.getElementById('subTitleInput').value=data.sub_title; document.getElementById('titleModal').style.display='flex'; }); } - async function saveTitleSettings() { const main_title = document.getElementById('mainTitleInput').value; const sub_title = document.getElementById('subTitleInput').value; await fetch('/api/settings/titles', { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({main_title,sub_title}) }); closeTitleModal(); await loadTitles(); } + async function saveTitleSettings() { + const main_title = document.getElementById('mainTitleInput').value; + const sub_title = document.getElementById('subTitleInput').value; + await fetch('/api/settings/titles', { + method:'POST', + headers:{'Content-Type':'application/json', 'Authorization': 'Bearer ' + userToken}, + body:JSON.stringify({main_title,sub_title}) + }); + closeTitleModal(); + await loadTitles(); + } function closeTitleModal() { document.getElementById('titleModal').style.display='none'; } - function escapeHtml(str) { if(!str) return ''; return str.replace(/[&<>]/g, function(m){ if(m==='&') return '&'; if(m==='<') return '<'; if(m==='>') return '>'; return m; }); } function showToast(msg) { const toast = document.createElement('div'); toast.className='toast'; toast.innerText=msg; document.body.appendChild(toast); setTimeout(()=>toast.remove(),2000); } init(); diff --git a/pyproject.toml b/pyproject.toml index 8e61c36..a6a2824 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,6 +8,8 @@ dependencies = [ 'hypercorn', 'fastapi', 'python-multipart', + 'cryptography', + 'pyjwt', 'pandas', 'openpyxl', ] diff --git a/score_system.db b/score_system.db index 6b5a954..5b43bd9 100644 Binary files a/score_system.db and b/score_system.db differ
    名次节目编号节目名称演出单位表演者类别平均分奖项