初版:教务抢课系统 jwxt(从线上实例导出)
@@ -0,0 +1,340 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Flask应用工厂
|
||||
"""
|
||||
import os
|
||||
import random
|
||||
import time
|
||||
import threading
|
||||
import urllib.request
|
||||
from flask import Flask, g
|
||||
from werkzeug.middleware.proxy_fix import ProxyFix
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_login import LoginManager
|
||||
from flask_cors import CORS
|
||||
|
||||
from app.config import config
|
||||
from app.models import db, User
|
||||
from app.grab_engine import grab_engine
|
||||
|
||||
# 初始化扩展
|
||||
login_manager = LoginManager()
|
||||
|
||||
|
||||
def create_app(config_name='default'):
|
||||
"""应用工厂函数"""
|
||||
app = Flask(__name__,
|
||||
template_folder='templates',
|
||||
static_folder='static')
|
||||
|
||||
# 加载配置
|
||||
app.config.from_object(config[config_name])
|
||||
|
||||
# 确保 Tailwind CSS 本地缓存
|
||||
_ensure_tailwind_cache(app.static_folder)
|
||||
|
||||
# 初始化扩展
|
||||
db.init_app(app)
|
||||
login_manager.init_app(app)
|
||||
CORS(app)
|
||||
|
||||
# AI 选课助手使用原生 WebSocket,避免 HTTP 响应流被代理或浏览器缓冲。
|
||||
from flask_sock import Sock
|
||||
sock = Sock(app)
|
||||
|
||||
# 信任Nginx反向代理头,让request.remote_addr返回真实IP
|
||||
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=0, x_prefix=0)
|
||||
|
||||
# 配置登录管理
|
||||
login_manager.login_view = 'main.login'
|
||||
login_manager.login_message = '请先登录'
|
||||
login_manager.login_message_category = 'warning'
|
||||
|
||||
@login_manager.user_loader
|
||||
def load_user(user_id):
|
||||
return User.query.get(int(user_id))
|
||||
|
||||
# 注册蓝图
|
||||
from app.routes import main_bp, api_bp
|
||||
app.register_blueprint(main_bp)
|
||||
app.register_blueprint(api_bp, url_prefix='/api')
|
||||
from app.ai_websocket import register_ai_websocket
|
||||
register_ai_websocket(sock)
|
||||
|
||||
# ── 品牌注入:网页标题/题头/favicon 按访问者学校自适应 ──
|
||||
# 学生 → "{学校缩写}教务助手" + 学校 ICO;登录页/管理面板等无法或
|
||||
# 不需要挂学校的场景 → 通用"教务助手" + 默认图标
|
||||
@app.context_processor
|
||||
def _inject_brand():
|
||||
from flask_login import current_user
|
||||
from app.school_manager import school_abbr, school_favicon, DEFAULT_SCHOOL_ID
|
||||
brand, favicon = '教务助手', None
|
||||
try:
|
||||
if current_user.is_authenticated and not current_user.is_admin:
|
||||
school_id = current_user.school_id or DEFAULT_SCHOOL_ID
|
||||
brand = f"{school_abbr(school_id)}教务助手"
|
||||
favicon = school_favicon(school_id)
|
||||
except Exception:
|
||||
pass
|
||||
default_favicon = (
|
||||
"data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'"
|
||||
"%20viewBox='0%200%20100%20100'%3E%3Ctext%20y='.9em'%20font-size='90'%3E"
|
||||
"%F0%9F%8E%93%3C/text%3E%3C/svg%3E"
|
||||
)
|
||||
return {'brand_name': brand, 'brand_favicon': favicon or default_favicon}
|
||||
|
||||
# 注册IP访问控制中间件
|
||||
from app.ip_middleware import init_ip_middleware
|
||||
init_ip_middleware(app)
|
||||
|
||||
# ── 请求计时中间件(为所有 JSON 响应注入 _timing)──
|
||||
@app.before_request
|
||||
def _timing_before():
|
||||
g._request_start = time.perf_counter()
|
||||
|
||||
@app.after_request
|
||||
def _timing_after(response):
|
||||
if not hasattr(g, '_request_start'):
|
||||
return response
|
||||
|
||||
total_ms = int((time.perf_counter() - g._request_start) * 1000)
|
||||
|
||||
# 只对 JSON 响应注入计时
|
||||
ct = response.content_type or ''
|
||||
if 'application/json' not in ct:
|
||||
return response
|
||||
|
||||
try:
|
||||
import json
|
||||
data = json.loads(response.get_data(as_text=True))
|
||||
if isinstance(data, dict):
|
||||
if '_timing' not in data:
|
||||
# 没有 _timing 的 JSON 响应(非 with_session_retry 路由)
|
||||
data['_timing'] = {
|
||||
'backend_total_ms': total_ms,
|
||||
'jwxt_api_ms': 0,
|
||||
'source': 'request_total',
|
||||
}
|
||||
else:
|
||||
# 已有 _timing(来自 with_session_retry),补充请求总耗时
|
||||
data['_timing']['request_total_ms'] = total_ms
|
||||
response.set_data(json.dumps(data, ensure_ascii=False))
|
||||
except (json.JSONDecodeError, UnicodeDecodeError, TypeError):
|
||||
pass # 非标准 JSON,不管
|
||||
|
||||
return response
|
||||
|
||||
# 初始化抢课引擎
|
||||
grab_engine.init_app(app)
|
||||
|
||||
# 创建数据库表
|
||||
with app.app_context():
|
||||
db.create_all()
|
||||
# 先补全旧数据库缺失的列(兼容 MySQL / SQLite),
|
||||
# 再初始化数据:模型列必须先与库结构对齐,否则任何 ORM 查询都会报 Unknown column。
|
||||
_auto_upgrade_schema(app)
|
||||
_init_admin_user(app)
|
||||
|
||||
# 启动抢课引擎(在数据库表创建之后)
|
||||
grab_engine.start()
|
||||
|
||||
# 启动 AI 定时任务调度器(到点自动执行用户委托的 AI 指令)
|
||||
from app.ai_scheduler import init_scheduler
|
||||
init_scheduler(app)
|
||||
|
||||
# 清理服务器重启前中断的课程索引文件
|
||||
from app.jwxt_api import JwxtApi
|
||||
JwxtApi.cleanup_stale_index()
|
||||
|
||||
# 初始化 URL 地址管理器:选最优地址 + 定时检测切换
|
||||
from app.url_manager import switch_if_needed, get_base_url
|
||||
from app.school_manager import list_schools
|
||||
try:
|
||||
switched, old, new = switch_if_needed()
|
||||
print(f"[url_manager] 初始地址: {get_base_url()}"
|
||||
+ (f" (已从 {old} 切换)" if switched else ""))
|
||||
except Exception as e:
|
||||
print(f"[url_manager] 初始化地址失败: {e},使用默认: {get_base_url()}")
|
||||
|
||||
# 多线路 Session 预热(管理端按学校开关,任一学校开启即启动后台线程)
|
||||
from app.multi_line import any_enabled as _ml_any, start_background as _ml_start
|
||||
if _ml_any():
|
||||
_ml_start(prelogin=True)
|
||||
|
||||
# 后台线程:每 60 秒检测一次地址延迟
|
||||
def _url_monitor():
|
||||
import time
|
||||
from app.url_manager import switch_if_needed
|
||||
from app.session_manager import SessionManager
|
||||
from app.multi_line import is_enabled as ml_enabled
|
||||
while True:
|
||||
time.sleep(60)
|
||||
try:
|
||||
from app.school_manager import list_schools
|
||||
for school in list_schools():
|
||||
switched, old_url, new_url = switch_if_needed(school['id'])
|
||||
if switched and not ml_enabled(school['id']):
|
||||
# 刷新抢课中的用户的 session
|
||||
with app.app_context():
|
||||
SessionManager.batch_refresh_running_users(school_id=school['id'])
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
t = threading.Thread(target=_url_monitor, daemon=True)
|
||||
t.start()
|
||||
|
||||
# 后台线程:每 2 小时检查并刷新所有用户的 session
|
||||
SESSION_REFRESH_INTERVAL = 2 * 3600 # 2 小时
|
||||
|
||||
def _session_refresh_loop():
|
||||
import time
|
||||
import logging
|
||||
logger = logging.getLogger(__name__)
|
||||
from app.session_manager import SessionManager
|
||||
from app.account_manager import AccountManager
|
||||
from app.time_utils import now as bj_now
|
||||
|
||||
# 首次延迟随机 5~30 分钟,避免启动时突发请求
|
||||
first_delay = random.uniform(300, 1800)
|
||||
logger.info(f"[session_refresh] 首次 session 检查延迟 {first_delay:.0f} 秒后执行")
|
||||
time.sleep(first_delay)
|
||||
|
||||
while True:
|
||||
try:
|
||||
now_hour = bj_now().hour
|
||||
# 夜间 00:00~05:00 跳过
|
||||
if 0 <= now_hour < 5:
|
||||
time.sleep(600)
|
||||
continue
|
||||
|
||||
from app.multi_line import is_enabled as ml_enabled, is_xk_mode
|
||||
accounts = AccountManager.get_all_accounts()
|
||||
for acc in accounts:
|
||||
username = acc.get('jwxt_username') or ''
|
||||
if not username:
|
||||
continue
|
||||
acc_school = acc.get('school_id') or 'sdmu'
|
||||
# 选课模式(按学校):该校暂停非核心的全量 session 刷新
|
||||
if is_xk_mode(acc_school):
|
||||
continue
|
||||
# 多线路预热(按学校):本循环只会用"全局线路"校验/重登,
|
||||
# 会给固定了其他线路的用户写错 cookie;该校的预热/保活/回填
|
||||
# 由 multi_line 的 keepalive 线程统一负责,这里按学校让路
|
||||
if ml_enabled(acc_school):
|
||||
continue
|
||||
try:
|
||||
from app.url_manager import push_school, pop_school
|
||||
push_school(acc_school)
|
||||
valid, _ = SessionManager.is_session_valid(username)
|
||||
if not valid:
|
||||
password = acc.get('jwxt_password', '')
|
||||
if password:
|
||||
logger.info(f"[session_refresh] session 已过期,正在刷新: {username}")
|
||||
SessionManager.login_and_save(username, password)
|
||||
except Exception as e:
|
||||
logger.warning(f"[session_refresh] 检查失败 {username}: {e}")
|
||||
finally:
|
||||
pop_school()
|
||||
|
||||
logger.info(f"[session_refresh] 完成一轮 session 检查({len(accounts)} 个用户)")
|
||||
except Exception as e:
|
||||
logger.error(f"[session_refresh] 循环异常: {e}")
|
||||
|
||||
time.sleep(SESSION_REFRESH_INTERVAL)
|
||||
|
||||
t2 = threading.Thread(target=_session_refresh_loop, daemon=True, name="session-refresh")
|
||||
t2.start()
|
||||
|
||||
# 启动邮件解封后台线程
|
||||
from app.ip_manager import start_email_unban_checker
|
||||
start_email_unban_checker(app)
|
||||
|
||||
return app
|
||||
|
||||
|
||||
def _init_admin_user(app):
|
||||
"""初始化管理员账号"""
|
||||
admin = User.query.filter_by(username=app.config['ADMIN_USERNAME']).first()
|
||||
if not admin:
|
||||
admin = User(
|
||||
username=app.config['ADMIN_USERNAME'],
|
||||
is_admin=True,
|
||||
is_active=True
|
||||
)
|
||||
admin.set_password(app.config['ADMIN_PASSWORD'])
|
||||
db.session.add(admin)
|
||||
db.session.commit()
|
||||
print(f"[OK] 管理员账号已创建: {app.config['ADMIN_USERNAME']}")
|
||||
|
||||
|
||||
def _auto_upgrade_schema(app):
|
||||
"""自动给旧数据库补上模型新增的列(兼容 MySQL / SQLite)"""
|
||||
from sqlalchemy import inspect, text
|
||||
from app.models import GrabTask
|
||||
|
||||
with app.app_context():
|
||||
inspector = inspect(db.engine)
|
||||
# 确保新表存在(ai_usage_logs 等)
|
||||
db.create_all()
|
||||
|
||||
# 模型新增的列(只补可空列,避免 NOT NULL 约束冲突)
|
||||
new_columns = {
|
||||
'grab_tasks': {'rules': 'TEXT'},
|
||||
'users': {'ai_daily_limit': 'BIGINT', 'school_id': 'VARCHAR(40)'},
|
||||
'ai_scheduled_tasks': {
|
||||
'repeat_interval': 'BIGINT',
|
||||
'repeat_until': 'DATETIME',
|
||||
'run_count': 'INTEGER',
|
||||
},
|
||||
}
|
||||
for table, columns in new_columns.items():
|
||||
try:
|
||||
existing_cols = {col['name'] for col in inspector.get_columns(table)}
|
||||
except Exception:
|
||||
continue # 表不存在,db.create_all() 会建
|
||||
for col, col_type in columns.items():
|
||||
if col in existing_cols:
|
||||
continue
|
||||
try:
|
||||
db.session.execute(text(f'ALTER TABLE {table} ADD COLUMN {col} {col_type}'))
|
||||
db.session.commit()
|
||||
print(f"[DB] 新增列 {table}.{col} ({col_type})")
|
||||
except Exception as e:
|
||||
print(f"[!] 新增列 {table}.{col} 失败: {e}")
|
||||
db.session.rollback()
|
||||
# 旧版所有账号归属山东管理学院;只填空值,绝不覆盖已注册的新学校。
|
||||
db.session.execute(text("UPDATE users SET school_id = 'sdmu' WHERE school_id IS NULL OR school_id = ''"))
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def _ensure_tailwind_cache(static_path):
|
||||
"""确保 Tailwind CSS 本地缓存存在,优先使用本地文件"""
|
||||
tailwind_path = os.path.join(static_path, 'tailwind.min.css')
|
||||
cdn_url = 'https://cdn.tailwindcss.com/3.4.1'
|
||||
|
||||
# 检查本地缓存是否存在且有效(>100KB)
|
||||
if os.path.exists(tailwind_path) and os.path.getsize(tailwind_path) > 100_000:
|
||||
print(f"[OK] Tailwind CSS 本地缓存已就绪 ({os.path.getsize(tailwind_path)//1024}KB)")
|
||||
return
|
||||
|
||||
# 本地缓存无效,尝试从 CDN 下载
|
||||
print("[*] 正在下载 Tailwind CSS(首次启动)...")
|
||||
for attempt in range(3):
|
||||
try:
|
||||
req = urllib.request.Request(cdn_url, headers={
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
|
||||
})
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
content = resp.read()
|
||||
if len(content) > 100_000:
|
||||
with open(tailwind_path, 'wb') as f:
|
||||
f.write(content)
|
||||
print(f"[OK] Tailwind CSS 已缓存到本地 ({len(content)//1024}KB)")
|
||||
return
|
||||
except Exception as e:
|
||||
print(f"[!] 下载失败(第{attempt+1}次): {e}")
|
||||
if attempt < 2:
|
||||
time.sleep(2)
|
||||
|
||||
print("[!] Tailwind CSS 下载失败,将使用 CDN")
|
||||
@@ -0,0 +1,212 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
账号管理器 - 分离网站账号和教务系统账号
|
||||
|
||||
网站账号:存储在数据库 (User模型)
|
||||
教务系统账号:存储在 accounts.json
|
||||
|
||||
映射关系:通过 user_id 或 username 关联
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import Optional, Dict, List, Tuple
|
||||
|
||||
BASE_DIR = Path(__file__).parent.parent
|
||||
ACCOUNTS_FILE = BASE_DIR / "accounts.json"
|
||||
|
||||
|
||||
def _file_lock_wrapper(method):
|
||||
"""串行化 accounts.json 读改写"""
|
||||
import functools
|
||||
@functools.wraps(method)
|
||||
def wrapper(*args, **kwargs):
|
||||
with AccountManager._file_lock:
|
||||
return method(*args, **kwargs)
|
||||
return wrapper
|
||||
|
||||
|
||||
class AccountManager:
|
||||
"""账号管理器"""
|
||||
|
||||
# 串行化 accounts.json 读改写(注册并发/后台刷新读并发会互相覆盖)
|
||||
_file_lock = threading.Lock()
|
||||
|
||||
@staticmethod
|
||||
def _load_accounts() -> List[Dict]:
|
||||
"""加载所有账号配置;解析失败时备份损坏文件,防止下次保存静默清空全部账号"""
|
||||
if not ACCOUNTS_FILE.exists():
|
||||
return []
|
||||
try:
|
||||
data = json.loads(ACCOUNTS_FILE.read_text(encoding="utf-8"))
|
||||
return data if isinstance(data, list) else []
|
||||
except Exception as e:
|
||||
try:
|
||||
backup = ACCOUNTS_FILE.with_suffix('.json.corrupt')
|
||||
if ACCOUNTS_FILE.exists():
|
||||
backup.write_text(ACCOUNTS_FILE.read_text(encoding="utf-8"), encoding="utf-8")
|
||||
print(f"[account_manager] accounts.json 解析失败({e}),已备份到 {backup.name};返回空列表")
|
||||
except Exception:
|
||||
pass
|
||||
return []
|
||||
|
||||
@staticmethod
|
||||
def _save_accounts(accounts: List[Dict]):
|
||||
"""保存账号配置(原子写,防读到半截)"""
|
||||
import os, tempfile
|
||||
fd, tmp = tempfile.mkstemp(dir=str(ACCOUNTS_FILE.parent), suffix=".tmp")
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||||
json.dump(accounts, f, ensure_ascii=False, indent=2)
|
||||
os.replace(tmp, ACCOUNTS_FILE)
|
||||
except Exception:
|
||||
try:
|
||||
os.unlink(tmp)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
@classmethod
|
||||
def get_jwxt_account(cls, user_id: int = None, username: str = None) -> Optional[Dict]:
|
||||
"""
|
||||
获取教务系统账号
|
||||
|
||||
Args:
|
||||
user_id: 网站用户ID
|
||||
username: 网站用户名(学号)
|
||||
|
||||
Returns:
|
||||
{"username": "...", "password": "..."} 或 None
|
||||
"""
|
||||
accounts = cls._load_accounts()
|
||||
|
||||
for acc in accounts:
|
||||
# 优先匹配 user_id
|
||||
if user_id and acc.get("user_id") == user_id:
|
||||
return {
|
||||
"username": acc.get("jwxt_username", acc.get("username")),
|
||||
"password": acc.get("jwxt_password", acc.get("password"))
|
||||
}
|
||||
# 其次匹配 username
|
||||
if username and acc.get("username") == username:
|
||||
return {
|
||||
"username": acc.get("jwxt_username", acc.get("username")),
|
||||
"password": acc.get("jwxt_password", acc.get("password"))
|
||||
}
|
||||
# 兼容旧格式
|
||||
if username and acc.get("jwxt_username") == username:
|
||||
return {
|
||||
"username": acc.get("jwxt_username"),
|
||||
"password": acc.get("jwxt_password")
|
||||
}
|
||||
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
@_file_lock_wrapper
|
||||
def set_jwxt_account(cls, user_id: int, username: str,
|
||||
jwxt_username: str, jwxt_password: str,
|
||||
jwxt_name: str = "", school_id: str = None) -> bool:
|
||||
"""
|
||||
设置/更新教务系统账号
|
||||
|
||||
Args:
|
||||
user_id: 网站用户ID
|
||||
username: 网站用户名
|
||||
jwxt_username: 教务系统学号
|
||||
jwxt_password: 教务系统密码
|
||||
jwxt_name: 姓名
|
||||
|
||||
Returns:
|
||||
bool: 是否成功
|
||||
"""
|
||||
try:
|
||||
accounts = cls._load_accounts()
|
||||
|
||||
# 查找是否已存在
|
||||
found = False
|
||||
for acc in accounts:
|
||||
if acc.get("user_id") == user_id or acc.get("username") == username:
|
||||
acc["user_id"] = user_id
|
||||
acc["username"] = username
|
||||
acc["jwxt_username"] = jwxt_username
|
||||
acc["jwxt_password"] = jwxt_password
|
||||
if school_id:
|
||||
acc["school_id"] = school_id
|
||||
if jwxt_name:
|
||||
acc["jwxt_name"] = jwxt_name
|
||||
found = True
|
||||
break
|
||||
|
||||
# 不存在则添加
|
||||
if not found:
|
||||
accounts.append({
|
||||
"user_id": user_id,
|
||||
"username": username,
|
||||
"jwxt_username": jwxt_username,
|
||||
"jwxt_password": jwxt_password,
|
||||
"jwxt_name": jwxt_name,
|
||||
"school_id": school_id or 'sdmu'
|
||||
})
|
||||
|
||||
cls._save_accounts(accounts)
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"[ERROR] 保存账号失败: {e}")
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
@_file_lock_wrapper
|
||||
def delete_jwxt_account(cls, user_id: int = None, username: str = None) -> bool:
|
||||
"""删除教务系统账号配置"""
|
||||
try:
|
||||
accounts = cls._load_accounts()
|
||||
|
||||
# 过滤掉要删除的账号
|
||||
new_accounts = [
|
||||
acc for acc in accounts
|
||||
if not (
|
||||
(user_id and acc.get("user_id") == user_id) or
|
||||
(username and acc.get("username") == username)
|
||||
)
|
||||
]
|
||||
|
||||
cls._save_accounts(new_accounts)
|
||||
return len(new_accounts) < len(accounts)
|
||||
except Exception as e:
|
||||
print(f"[ERROR] 删除账号失败: {e}")
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def get_all_accounts(cls) -> List[Dict]:
|
||||
"""获取所有账号配置(管理员用)"""
|
||||
return cls._load_accounts()
|
||||
|
||||
@classmethod
|
||||
def get_jwxt_username(cls, user_id: int = None, username: str = None) -> Optional[str]:
|
||||
"""获取教务系统学号"""
|
||||
account = cls.get_jwxt_account(user_id, username)
|
||||
return account["username"] if account else None
|
||||
|
||||
@classmethod
|
||||
def has_jwxt_account(cls, user_id: int = None, username: str = None) -> bool:
|
||||
"""检查是否配置了教务系统账号"""
|
||||
return cls.get_jwxt_account(user_id, username) is not None
|
||||
|
||||
|
||||
# 便捷函数
|
||||
def get_jwxt_account(user_id: int = None, username: str = None) -> Optional[Dict]:
|
||||
"""获取教务系统账号"""
|
||||
return AccountManager.get_jwxt_account(user_id, username)
|
||||
|
||||
|
||||
def set_jwxt_account(user_id: int, username: str,
|
||||
jwxt_username: str, jwxt_password: str,
|
||||
jwxt_name: str = "", school_id: str = None) -> bool:
|
||||
"""设置教务系统账号"""
|
||||
return AccountManager.set_jwxt_account(
|
||||
user_id, username, jwxt_username, jwxt_password, jwxt_name, school_id
|
||||
)
|
||||
@@ -0,0 +1,182 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
推广联盟管理模块 - 处理推广码验证、佣金计算等
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
from datetime import datetime
|
||||
from typing import Dict, Optional
|
||||
from app.time_utils import now as bj_now
|
||||
|
||||
|
||||
class AffiliateManager:
|
||||
"""推广联盟管理器"""
|
||||
|
||||
AFFILIATES_FILE = os.path.join(os.path.dirname(__file__), '..', 'affiliates.json')
|
||||
|
||||
@classmethod
|
||||
def _load_affiliates(cls) -> Dict:
|
||||
"""加载推广人员数据"""
|
||||
try:
|
||||
if os.path.exists(cls.AFFILIATES_FILE):
|
||||
with open(cls.AFFILIATES_FILE, 'r', encoding='utf-8') as f:
|
||||
return json.load(f)
|
||||
except Exception as e:
|
||||
print(f"加载推广数据失败: {e}")
|
||||
return {}
|
||||
|
||||
@classmethod
|
||||
def _save_affiliates(cls, data: Dict):
|
||||
"""保存推广人员数据"""
|
||||
try:
|
||||
with open(cls.AFFILIATES_FILE, 'w', encoding='utf-8') as f:
|
||||
json.dump(data, f, indent=2, ensure_ascii=False)
|
||||
except Exception as e:
|
||||
print(f"保存推广数据失败: {e}")
|
||||
|
||||
@classmethod
|
||||
def verify_code(cls, code: str) -> Optional[Dict]:
|
||||
"""
|
||||
验证推广码是否有效
|
||||
|
||||
Returns:
|
||||
推广人信息 或 None
|
||||
"""
|
||||
if not code:
|
||||
return None
|
||||
|
||||
affiliates = cls._load_affiliates()
|
||||
code = code.upper().strip()
|
||||
|
||||
if code in affiliates:
|
||||
aff = affiliates[code]
|
||||
return {
|
||||
"valid": True,
|
||||
"name": aff["name"],
|
||||
"code": code,
|
||||
"commission_rate": aff.get("commission_rate", 30),
|
||||
"discount_amount": aff.get("discount_amount", 2)
|
||||
}
|
||||
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def get_affiliate(cls, code: str) -> Optional[Dict]:
|
||||
"""获取推广人信息"""
|
||||
affiliates = cls._load_affiliates()
|
||||
code = code.upper().strip()
|
||||
return affiliates.get(code)
|
||||
|
||||
@classmethod
|
||||
def add_affiliate(cls, code: str, name: str, commission_rate: int = 30, discount_amount: int = 2) -> bool:
|
||||
"""添加推广人"""
|
||||
affiliates = cls._load_affiliates()
|
||||
code = code.upper().strip()
|
||||
|
||||
affiliates[code] = {
|
||||
"name": name,
|
||||
"commission_rate": commission_rate,
|
||||
"discount_amount": discount_amount,
|
||||
"created_at": bj_now().isoformat()
|
||||
}
|
||||
|
||||
cls._save_affiliates(affiliates)
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def update_affiliate(cls, code: str, **kwargs) -> bool:
|
||||
"""更新推广人信息"""
|
||||
affiliates = cls._load_affiliates()
|
||||
code = code.upper().strip()
|
||||
|
||||
if code not in affiliates:
|
||||
return False
|
||||
|
||||
for key, value in kwargs.items():
|
||||
if value is not None:
|
||||
affiliates[code][key] = value
|
||||
|
||||
cls._save_affiliates(affiliates)
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def delete_affiliate(cls, code: str) -> bool:
|
||||
"""删除推广人"""
|
||||
affiliates = cls._load_affiliates()
|
||||
code = code.upper().strip()
|
||||
|
||||
if code in affiliates:
|
||||
del affiliates[code]
|
||||
cls._save_affiliates(affiliates)
|
||||
return True
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def list_affiliates(cls) -> Dict:
|
||||
"""获取所有推广人列表"""
|
||||
return cls._load_affiliates()
|
||||
|
||||
@classmethod
|
||||
def calculate_commission(cls, final_amount: int, commission_rate: int) -> float:
|
||||
"""计算佣金金额"""
|
||||
return round(final_amount * (commission_rate / 100), 2)
|
||||
|
||||
@classmethod
|
||||
def settle_affiliate(cls, code: str, settle_amount: float, note: str = '') -> bool:
|
||||
"""
|
||||
结清推广人佣金
|
||||
|
||||
Args:
|
||||
code: 推广码
|
||||
settle_amount: 结算金额
|
||||
note: 结算备注
|
||||
|
||||
Returns:
|
||||
是否成功
|
||||
"""
|
||||
affiliates = cls._load_affiliates()
|
||||
code = code.upper().strip()
|
||||
|
||||
if code not in affiliates:
|
||||
return False
|
||||
|
||||
# 初始化结算历史
|
||||
if 'settlement_history' not in affiliates[code]:
|
||||
affiliates[code]['settlement_history'] = []
|
||||
|
||||
# 添加结算记录
|
||||
settlement_record = {
|
||||
'settle_amount': settle_amount,
|
||||
'note': note,
|
||||
'settled_at': bj_now().isoformat()
|
||||
}
|
||||
affiliates[code]['settlement_history'].append(settlement_record)
|
||||
|
||||
# 更新最后结算时间和累计结算金额
|
||||
affiliates[code]['last_settled_at'] = bj_now().isoformat()
|
||||
affiliates[code]['total_settled_amount'] = affiliates[code].get('total_settled_amount', 0) + settle_amount
|
||||
|
||||
cls._save_affiliates(affiliates)
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def get_settlement_info(cls, code: str) -> dict:
|
||||
"""
|
||||
获取推广人结算信息
|
||||
|
||||
Returns:
|
||||
结算信息字典
|
||||
"""
|
||||
affiliates = cls._load_affiliates()
|
||||
code = code.upper().strip()
|
||||
|
||||
if code not in affiliates:
|
||||
return None
|
||||
|
||||
aff = affiliates[code]
|
||||
return {
|
||||
'total_settled_amount': aff.get('total_settled_amount', 0),
|
||||
'last_settled_at': aff.get('last_settled_at'),
|
||||
'settlement_history': aff.get('settlement_history', [])
|
||||
}
|
||||
@@ -0,0 +1,446 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""AI 定时任务调度器:到点后自动执行一次用户委托的 AI 指令。
|
||||
|
||||
- 用户在对话中通过 create_scheduled_task 工具创建任务,三种时间模式:
|
||||
绝对时间(scheduled_at)/ 计时器(delay_minutes,从现在往后计时)/
|
||||
重复任务(repeat_minutes 间隔,可选 repeat_until 截止,到期自动结束)。
|
||||
- 后台线程每 10 秒轮询认领到点任务,线程池内跑一次完整 agent loop:
|
||||
写操作自动视为用户已确认(创建任务即明确委托)。
|
||||
- 重复任务每次执行后按锚点推进下一次并写回会话报告,用户取消为止;
|
||||
服务停机错过的时间段自动跳过,不补跑。
|
||||
- 体验优先:执行不受每日 token 限额拦截(超限也让任务跑完自然结束),到任务结束
|
||||
后限额继续生效;token 用量照常入账供管理端查看。
|
||||
- 执行结果写回用户会话,用户打开 AI 对话即可看到代理执行报告。
|
||||
- 服务器停机导致错过的任务:24 小时内补跑,超过的直接标记失败不再执行。
|
||||
"""
|
||||
import time
|
||||
import threading
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.models import db, User, AiConversation, AiConversationMessage, AiScheduledTask
|
||||
from app.time_utils import BJ_TZ
|
||||
|
||||
|
||||
POLL_INTERVAL_SECONDS = 10
|
||||
MAX_WORKERS = 3
|
||||
# 认领后超过该时长仍未结束视为执行中断(服务重启等),标记失败
|
||||
STALE_RUNNING_HOURS = 1
|
||||
# 错过计划时间超过该时长的任务不再补跑
|
||||
STALE_DUE_HOURS = 24
|
||||
MIN_LEAD_SECONDS = 60
|
||||
MAX_HORIZON_DAYS = 90
|
||||
MAX_INSTRUCTION_CHARS = 2000
|
||||
MAX_REPEAT_RUNS = 1000 # 单个重复任务执行次数上限(安全阀)
|
||||
|
||||
# 定时任务执行时注入的无人值守策略:到点即选课窗口,AI 实时查课自主决策。
|
||||
# 核心是防犹豫:多个候选全部创建抢课任务,先到先得,抢到多个由用户自行取舍。
|
||||
EXECUTION_POLICY = """【无人值守执行策略】你正在执行用户预先委托的定时任务,用户不在线:所有写操作自动视为已确认,不要请求确认,也不要调用 ask_user 提问(无人回答),一切依据任务指令自主决策。
|
||||
- 本次要选的是“下学期可选课程”,务必用 search_live_courses 实时查询获取可选课程与教学班 ID;课程索引缓存的是当学期已有课程,与本次选课无关,禁止用它推定。
|
||||
- 严禁犹豫不决:符合用户目标的课程或教学班若有多个候选,全部逐一创建抢课任务(先到先得,抢到多个由用户自行取舍),不要挑选,也不要只创建其中一个。
|
||||
- 实时查询不可用或查不到目标课程时,如实说明原因结束任务,不要编造课程或 ID。
|
||||
- 结束时输出简洁报告:创建了哪些抢课任务(课程/教师/任务ID/状态)、哪些没成及原因。"""
|
||||
|
||||
_app = None
|
||||
_pool = None
|
||||
_started = threading.Event()
|
||||
|
||||
|
||||
def _naive_now() -> datetime:
|
||||
"""当前北京时间(naive,与库内 created_at / scheduled_time 的存储约定一致)。"""
|
||||
return datetime.now(BJ_TZ).replace(tzinfo=None)
|
||||
|
||||
|
||||
def _parse_bj_datetime(text) -> datetime:
|
||||
"""解析北京时间(naive);带时区的 ISO 串自动换算。失败返回 None。"""
|
||||
text = str(text or '').strip()
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
parsed = datetime.fromisoformat(text.replace('Z', '+00:00').replace(' ', 'T', 1))
|
||||
if parsed.tzinfo is not None:
|
||||
parsed = parsed.astimezone(BJ_TZ).replace(tzinfo=None)
|
||||
return parsed
|
||||
except ValueError:
|
||||
pass
|
||||
for fmt in ('%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y/%m/%d %H:%M', '%Y-%m-%d'):
|
||||
try:
|
||||
return datetime.strptime(text, fmt)
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _next_occurrence(task, now) -> datetime:
|
||||
"""重复任务的下一次执行时间:锚定 scheduled_at 推进,跳过错过的时段。"""
|
||||
next_at = task.scheduled_at
|
||||
step = timedelta(seconds=max(int(task.repeat_interval or 0), MIN_LEAD_SECONDS))
|
||||
while next_at <= now:
|
||||
next_at += step
|
||||
return next_at
|
||||
|
||||
|
||||
def create_task(user_id: int, scheduled_at_raw, instruction,
|
||||
conversation_id=None, delay_minutes=None,
|
||||
repeat_minutes=None, repeat_until_raw=None) -> dict:
|
||||
"""创建定时任务(含校验)。供 AI 工具与后续管理接口复用。
|
||||
|
||||
时间模式二选一:scheduled_at 绝对时间 / delay_minutes 计时器(从现在往后计时)。
|
||||
repeat_minutes(分钟)可选:按间隔重复执行,repeat_until 可选截止时间。
|
||||
"""
|
||||
instruction = str(instruction or '').strip()
|
||||
if not instruction:
|
||||
return {'success': False, 'message': '缺少任务指令'}
|
||||
now = _naive_now()
|
||||
|
||||
# 首次执行时间:计时器与绝对时间二选一
|
||||
if delay_minutes is not None and str(scheduled_at_raw or '').strip():
|
||||
return {'success': False, 'message': 'delay_minutes 与 scheduled_at 只能二选一'}
|
||||
if delay_minutes is not None:
|
||||
try:
|
||||
delay = float(delay_minutes)
|
||||
except (TypeError, ValueError):
|
||||
return {'success': False, 'message': 'delay_minutes 必须是数字(分钟)'}
|
||||
if delay * 60 < MIN_LEAD_SECONDS:
|
||||
return {'success': False, 'message': '计时器至少 1 分钟'}
|
||||
if delay > MAX_HORIZON_DAYS * 1440:
|
||||
return {'success': False, 'message': f'计时器不能超过 {MAX_HORIZON_DAYS} 天'}
|
||||
scheduled_at = now + timedelta(minutes=delay)
|
||||
time_desc = f'{delay:g} 分钟后({scheduled_at:%Y-%m-%d %H:%M})'
|
||||
else:
|
||||
scheduled_at = _parse_bj_datetime(scheduled_at_raw)
|
||||
if scheduled_at is None:
|
||||
return {'success': False, 'message': '时间格式无法解析,请使用如 2026-09-15 08:00 的北京时间格式'}
|
||||
if scheduled_at < now + timedelta(seconds=MIN_LEAD_SECONDS):
|
||||
return {'success': False, 'message': '执行时间必须至少在 1 分钟之后'}
|
||||
if scheduled_at > now + timedelta(days=MAX_HORIZON_DAYS):
|
||||
return {'success': False, 'message': f'执行时间不能超过 {MAX_HORIZON_DAYS} 天之后'}
|
||||
time_desc = f'{scheduled_at:%Y-%m-%d %H:%M}'
|
||||
|
||||
# 重复设置
|
||||
repeat_interval = None
|
||||
repeat_until = None
|
||||
if repeat_minutes not in (None, ''):
|
||||
try:
|
||||
minutes = int(float(repeat_minutes))
|
||||
except (TypeError, ValueError):
|
||||
return {'success': False, 'message': 'repeat_minutes 必须是数字(分钟)'}
|
||||
if minutes < 1:
|
||||
return {'success': False, 'message': '重复间隔至少 1 分钟'}
|
||||
if minutes > MAX_HORIZON_DAYS * 1440:
|
||||
return {'success': False, 'message': f'重复间隔不能超过 {MAX_HORIZON_DAYS} 天'}
|
||||
repeat_interval = minutes * 60
|
||||
if str(repeat_until_raw or '').strip():
|
||||
if repeat_interval is None:
|
||||
return {'success': False, 'message': 'repeat_until 需要配合 repeat_minutes 使用'}
|
||||
repeat_until = _parse_bj_datetime(repeat_until_raw)
|
||||
if repeat_until is None:
|
||||
return {'success': False, 'message': 'repeat_until 格式无法解析,请使用如 2026-09-15 08:00 的北京时间格式'}
|
||||
if repeat_until <= scheduled_at:
|
||||
return {'success': False, 'message': '重复截止时间必须晚于首次执行时间'}
|
||||
if repeat_until > now + timedelta(days=MAX_HORIZON_DAYS):
|
||||
return {'success': False, 'message': f'重复截止时间不能超过 {MAX_HORIZON_DAYS} 天之后'}
|
||||
|
||||
task = AiScheduledTask(
|
||||
user_id=user_id,
|
||||
conversation_id=conversation_id,
|
||||
instruction=instruction[:MAX_INSTRUCTION_CHARS],
|
||||
scheduled_at=scheduled_at,
|
||||
repeat_interval=repeat_interval,
|
||||
repeat_until=repeat_until,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
repeat_desc = ''
|
||||
if repeat_interval:
|
||||
repeat_desc = f',每 {repeat_interval // 60} 分钟重复一次'
|
||||
if repeat_until:
|
||||
repeat_desc += f',至 {repeat_until:%Y-%m-%d %H:%M} 自动结束'
|
||||
return {
|
||||
'success': True,
|
||||
'message': f'定时任务已创建,将于 {time_desc} 自动执行{repeat_desc}',
|
||||
'task': task.to_dict(),
|
||||
}
|
||||
|
||||
|
||||
def cancel_own_task(user_id: int, task_id: int) -> dict:
|
||||
task = AiScheduledTask.query.filter_by(id=int(task_id or 0), user_id=user_id).first()
|
||||
if not task:
|
||||
return {'success': False, 'message': '任务不存在或无权取消'}
|
||||
if task.status != AiScheduledTask.STATUS_PENDING:
|
||||
return {'success': False, 'message': '任务已开始执行或已结束,无法取消'}
|
||||
task.status = AiScheduledTask.STATUS_CANCELLED
|
||||
db.session.commit()
|
||||
return {'success': True, 'message': '定时任务已取消', 'task': task.to_dict()}
|
||||
|
||||
|
||||
def init_scheduler(app) -> None:
|
||||
"""启动调度线程与执行线程池(幂等,随 create_app 调用)。"""
|
||||
if _started.is_set():
|
||||
return
|
||||
_started.set()
|
||||
global _app, _pool
|
||||
_app = app
|
||||
_pool = ThreadPoolExecutor(max_workers=MAX_WORKERS, thread_name_prefix='ai-sched')
|
||||
threading.Thread(target=_loop, args=(app,), daemon=True, name='ai-scheduler').start()
|
||||
print('[ai_scheduler] AI 定时任务调度器已启动')
|
||||
|
||||
|
||||
def _loop(app) -> None:
|
||||
while True:
|
||||
try:
|
||||
with app.app_context():
|
||||
run_due_tasks()
|
||||
except Exception:
|
||||
app.logger.exception('AI 定时任务调度轮询失败')
|
||||
time.sleep(POLL_INTERVAL_SECONDS)
|
||||
|
||||
|
||||
def run_due_tasks(wait: bool = False) -> list:
|
||||
"""认领所有到点任务并派发执行。返回本次派发的任务 id 列表。
|
||||
|
||||
wait=True 时阻塞到全部执行完成(冒烟测试用)。
|
||||
"""
|
||||
now = _naive_now()
|
||||
# 恢复中断:认领后长时间未结束的任务(服务重启导致线程丢失)
|
||||
stale_before = now - timedelta(hours=STALE_RUNNING_HOURS)
|
||||
stuck = AiScheduledTask.query.filter(
|
||||
AiScheduledTask.status == AiScheduledTask.STATUS_RUNNING,
|
||||
AiScheduledTask.claimed_at < stale_before,
|
||||
).all()
|
||||
for task in stuck:
|
||||
if task.repeat_interval:
|
||||
# 重复任务:中断的那次视为跳过,推进到下一次(到期则结束)
|
||||
next_at = _next_occurrence(task, now)
|
||||
if task.repeat_until and next_at > task.repeat_until:
|
||||
task.status = AiScheduledTask.STATUS_ENDED
|
||||
task.claimed_at = None
|
||||
task.error = '一次执行中断(服务重启或超时);重复计划已到期自动结束'
|
||||
else:
|
||||
task.scheduled_at = next_at
|
||||
task.status = AiScheduledTask.STATUS_PENDING
|
||||
task.claimed_at = None
|
||||
task.error = '一次执行中断(服务重启或超时),已跳到下一次'
|
||||
else:
|
||||
task.status = AiScheduledTask.STATUS_FAILED
|
||||
task.error = '执行中断(服务重启或超时),请重新创建任务'
|
||||
task.executed_at = now
|
||||
# 错过太久的不补跑
|
||||
missed = AiScheduledTask.query.filter(
|
||||
AiScheduledTask.status == AiScheduledTask.STATUS_PENDING,
|
||||
AiScheduledTask.scheduled_at < now - timedelta(hours=STALE_DUE_HOURS),
|
||||
).all()
|
||||
for task in missed:
|
||||
if task.repeat_interval:
|
||||
next_at = _next_occurrence(task, now)
|
||||
if task.repeat_until and next_at > task.repeat_until:
|
||||
task.status = AiScheduledTask.STATUS_ENDED
|
||||
task.error = '重复计划已到期自动结束'
|
||||
else:
|
||||
task.scheduled_at = next_at
|
||||
task.error = '错过若干次执行(服务器当时未运行),已跳到下一次'
|
||||
else:
|
||||
task.status = AiScheduledTask.STATUS_FAILED
|
||||
task.error = '错过执行时间(服务器当时未运行),已跳过'
|
||||
task.executed_at = now
|
||||
# 认领到点任务(单一线程轮询,先改状态再派发,天然防重复认领)
|
||||
due = AiScheduledTask.query.filter(
|
||||
AiScheduledTask.status == AiScheduledTask.STATUS_PENDING,
|
||||
AiScheduledTask.scheduled_at <= now,
|
||||
).all()
|
||||
dispatched = []
|
||||
for task in due:
|
||||
task.status = AiScheduledTask.STATUS_RUNNING
|
||||
task.claimed_at = now
|
||||
dispatched.append(task.id)
|
||||
if stuck or missed or dispatched:
|
||||
db.session.commit()
|
||||
|
||||
futures = [_pool.submit(_execute, task_id) for task_id in dispatched]
|
||||
if wait:
|
||||
for future in futures:
|
||||
future.result()
|
||||
return dispatched
|
||||
|
||||
|
||||
class _TaskUser:
|
||||
"""执行期间提供给工具的最小用户视图(不跨线程携带 ORM 对象)。"""
|
||||
|
||||
def __init__(self, user, conversation_id=None):
|
||||
self.id = user.id
|
||||
self.conversation_id = conversation_id
|
||||
account = user.get_jwxt_account() or {}
|
||||
self._jwxt_username = str(account.get('username', '') or '')
|
||||
|
||||
def get_jwxt_account(self):
|
||||
if not self._jwxt_username:
|
||||
return None
|
||||
return {'username': self._jwxt_username}
|
||||
|
||||
|
||||
def _execute(task_id: int) -> None:
|
||||
"""在独立线程 + app 上下文里执行一个已认领的任务。"""
|
||||
with _app.app_context():
|
||||
from app.url_manager import push_school, pop_school
|
||||
try:
|
||||
task = db.session.get(AiScheduledTask, task_id)
|
||||
user = db.session.get(User, task.user_id) if task else None
|
||||
if user:
|
||||
push_school(user.school_id)
|
||||
_execute_locked(task_id)
|
||||
except Exception:
|
||||
current_app.logger.exception('AI 定时任务执行异常 #%s', task_id)
|
||||
try:
|
||||
task = db.session.get(AiScheduledTask, task_id)
|
||||
if task is not None and task.status == AiScheduledTask.STATUS_RUNNING:
|
||||
_finish(task, AiScheduledTask.STATUS_FAILED, error='执行过程出现未预期异常')
|
||||
except Exception:
|
||||
current_app.logger.exception('AI 定时任务失败状态回写失败 #%s', task_id)
|
||||
finally:
|
||||
pop_school()
|
||||
|
||||
|
||||
def _execute_locked(task_id: int) -> None:
|
||||
task = db.session.get(AiScheduledTask, task_id)
|
||||
if task is None or task.status != AiScheduledTask.STATUS_RUNNING:
|
||||
return
|
||||
user_row = db.session.get(User, task.user_id)
|
||||
if user_row is None:
|
||||
_finish(task, AiScheduledTask.STATUS_FAILED, error='用户不存在')
|
||||
return
|
||||
|
||||
from app.ai_assistant import stream_chat, get_ai_settings
|
||||
from app.ai_usage import record_usage
|
||||
|
||||
stop = threading.Event()
|
||||
_last_check = [0.0]
|
||||
|
||||
def cancel_check():
|
||||
"""每 3 秒查一次库,用户取消任务或用量超限时中止执行。"""
|
||||
if stop.is_set():
|
||||
return True
|
||||
now_mono = time.monotonic()
|
||||
if now_mono - _last_check[0] >= 3:
|
||||
_last_check[0] = now_mono
|
||||
status = db.session.query(AiScheduledTask.status).filter(
|
||||
AiScheduledTask.id == task_id).scalar()
|
||||
if status == AiScheduledTask.STATUS_CANCELLED:
|
||||
stop.set()
|
||||
return stop.is_set()
|
||||
|
||||
model_name = str(get_ai_settings().get('model') or '')
|
||||
|
||||
def usage_sink(input_tokens, output_tokens):
|
||||
# 体验优先:执行期间超出每日限额也不中断,任务跑完自然结束;
|
||||
# 用量照常入账,限额继续约束之后的交互对话。
|
||||
try:
|
||||
record_usage(task.user_id, model_name, input_tokens, output_tokens)
|
||||
except Exception:
|
||||
current_app.logger.exception('定时任务记录 AI 用量失败 #%s', task_id)
|
||||
|
||||
# 结果写回会话:优先创建任务时的会话,否则用该用户当前会话
|
||||
conversation = None
|
||||
if task.conversation_id:
|
||||
conversation = db.session.get(AiConversation, task.conversation_id)
|
||||
if conversation is None:
|
||||
conversation = AiConversation.query.filter_by(user_id=task.user_id).first()
|
||||
if conversation is None:
|
||||
conversation = AiConversation(user_id=task.user_id)
|
||||
db.session.add(conversation)
|
||||
db.session.flush()
|
||||
if task.conversation_id != conversation.id:
|
||||
task.conversation_id = conversation.id
|
||||
|
||||
now = _naive_now()
|
||||
trigger_note = f'[定时任务自动触发 · 计划 {task.scheduled_at:%Y-%m-%d %H:%M} · 实际 {now:%Y-%m-%d %H:%M}]'
|
||||
db.session.add(AiConversationMessage(
|
||||
conversation_id=conversation.id, role='user',
|
||||
content=f'{trigger_note}\n{task.instruction}'[:4000],
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
recent = conversation.messages.order_by(AiConversationMessage.id.desc()).limit(20).all()
|
||||
messages = [{'role': item.role, 'content': item.content} for item in reversed(recent)]
|
||||
|
||||
output_parts = []
|
||||
error_message = ''
|
||||
for event in stream_chat(
|
||||
_TaskUser(user_row, conversation.id), messages,
|
||||
cancel_check=cancel_check,
|
||||
# 无人值守:创建任务即委托,写操作自动确认;ask_user 无法获得回答
|
||||
confirm=lambda call_id: True,
|
||||
ask=lambda call_id, payload=None: {'unattended': True},
|
||||
usage_sink=usage_sink,
|
||||
extra_system=EXECUTION_POLICY):
|
||||
event_type = event.get('type')
|
||||
if event_type == 'text_delta':
|
||||
output_parts.append(event.get('delta') or '')
|
||||
elif event_type == 'done':
|
||||
output_parts = [event.get('message') or ''.join(output_parts)]
|
||||
elif event_type == 'error':
|
||||
error_message = str(event.get('message') or 'AI 响应异常')
|
||||
|
||||
result_text = ''.join(output_parts).strip()
|
||||
if stop.is_set() and not result_text:
|
||||
_finish(task, AiScheduledTask.STATUS_CANCELLED, error='任务被用户取消,执行中止')
|
||||
return
|
||||
if error_message and not result_text:
|
||||
_finish_or_reschedule(task, AiScheduledTask.STATUS_FAILED, error=error_message[:500])
|
||||
_save_result(conversation.id, f"⏰ 定时任务执行失败:{error_message}")
|
||||
return
|
||||
_finish_or_reschedule(task, AiScheduledTask.STATUS_SUCCESS, result=result_text,
|
||||
error=error_message or None)
|
||||
_save_result(conversation.id, f"⏰ 定时任务执行结果:\n{result_text}")
|
||||
|
||||
|
||||
def _finish_or_reschedule(task, status: str, result: str = None, error: str = None) -> None:
|
||||
"""一次性任务落终态;重复任务记录本次结果后推进到下一次(用户取消除外)。"""
|
||||
if task.repeat_interval and status != AiScheduledTask.STATUS_CANCELLED:
|
||||
_reschedule(task, result=result, error=error)
|
||||
else:
|
||||
_finish(task, status, result=result, error=error)
|
||||
|
||||
|
||||
def _finish(task, status: str, result: str = None, error: str = None) -> None:
|
||||
task.status = status
|
||||
if result is not None:
|
||||
task.result = result[:4000]
|
||||
if error is not None:
|
||||
task.error = error
|
||||
task.run_count = (task.run_count or 0) + 1
|
||||
task.executed_at = _naive_now()
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def _reschedule(task, result: str = None, error: str = None) -> None:
|
||||
"""重复任务:保留本次结果/原因,锚定推进下一次;到期或达次数上限则结束。"""
|
||||
now = _naive_now()
|
||||
task.status = AiScheduledTask.STATUS_PENDING
|
||||
if result is not None:
|
||||
task.result = result[:4000]
|
||||
task.error = error
|
||||
task.run_count = (task.run_count or 0) + 1
|
||||
task.executed_at = now
|
||||
task.claimed_at = None
|
||||
next_at = _next_occurrence(task, now)
|
||||
if (task.repeat_until and next_at > task.repeat_until) or \
|
||||
(task.run_count or 0) >= MAX_REPEAT_RUNS:
|
||||
task.status = AiScheduledTask.STATUS_ENDED
|
||||
task.error = f'{error};' if error else ''
|
||||
task.error += '重复计划已到期自动结束'
|
||||
db.session.commit()
|
||||
return
|
||||
task.scheduled_at = next_at
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def _save_result(conversation_id, text: str) -> None:
|
||||
"""把执行报告作为 assistant 消息写回会话,用户下次打开对话即可看到。"""
|
||||
if not conversation_id or not text:
|
||||
return
|
||||
db.session.add(AiConversationMessage(
|
||||
conversation_id=conversation_id, role='assistant', content=text[:4000],
|
||||
))
|
||||
db.session.commit()
|
||||
@@ -0,0 +1,185 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""AI token 用量统计与每日限额。
|
||||
|
||||
- 每次模型调用完成写入一条 AiUsageLog(输入/输出 token,来自 API 真实 usage)。
|
||||
- 每用户每日上限:users.ai_daily_limit(NULL=用全局默认,0=不限制),
|
||||
全局默认存 SystemConfig(默认 1,000,000 tokens/天)。
|
||||
- 按北京时间零点切天。
|
||||
"""
|
||||
from datetime import datetime, timedelta
|
||||
import json
|
||||
|
||||
from flask import current_app
|
||||
from sqlalchemy import func
|
||||
|
||||
from app.models import db, SystemConfig, AiUsageLog, User
|
||||
from app.time_utils import BJ_TZ
|
||||
|
||||
|
||||
AI_DAILY_LIMIT_KEY = 'ai_daily_token_limit'
|
||||
DEFAULT_DAILY_LIMIT = 1_000_000
|
||||
|
||||
|
||||
def get_default_daily_limit() -> int:
|
||||
"""全局默认每日上限(tokens)。0 表示不限制。"""
|
||||
try:
|
||||
value = int(str(SystemConfig.get(AI_DAILY_LIMIT_KEY, DEFAULT_DAILY_LIMIT) or 0))
|
||||
except (TypeError, ValueError):
|
||||
return DEFAULT_DAILY_LIMIT
|
||||
return max(value, 0)
|
||||
|
||||
|
||||
def set_default_daily_limit(value: int) -> None:
|
||||
SystemConfig.set(AI_DAILY_LIMIT_KEY, str(max(int(value), 0)), 'AI 每日 token 用量默认上限(0=不限制)')
|
||||
|
||||
|
||||
def get_user_daily_limit(user) -> int:
|
||||
"""用户的生效每日上限:个人设置优先(0=不限制),否则全局默认。"""
|
||||
personal = getattr(user, 'ai_daily_limit', None)
|
||||
if personal is not None:
|
||||
return max(int(personal), 0)
|
||||
return get_default_daily_limit()
|
||||
|
||||
|
||||
def _today_start() -> datetime:
|
||||
"""北京时间今天零点(与模型 created_at 的 naive 本地时间对齐)。"""
|
||||
now_bj = datetime.now(BJ_TZ)
|
||||
return now_bj.replace(hour=0, minute=0, second=0, microsecond=0).replace(tzinfo=None)
|
||||
|
||||
|
||||
def record_usage(user_id: int, model: str, input_tokens: int, output_tokens: int) -> None:
|
||||
"""记录一次模型调用的用量。写入失败只记日志,不影响对话。"""
|
||||
try:
|
||||
db.session.add(AiUsageLog(
|
||||
user_id=user_id,
|
||||
model=str(model or '')[:100],
|
||||
input_tokens=max(int(input_tokens or 0), 0),
|
||||
output_tokens=max(int(output_tokens or 0), 0),
|
||||
))
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
current_app.logger.exception('记录 AI 用量失败')
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
def estimate_tokens(text: str) -> int:
|
||||
"""本地分词估算:CJK 字符按 1 token/字,其余按约 4 字符/token。
|
||||
|
||||
服务端未返回 usage 时的兜底,略微高估,用于限额统计足够。
|
||||
"""
|
||||
if not text:
|
||||
return 0
|
||||
non_ascii = sum(1 for ch in text if ord(ch) > 0x7F)
|
||||
ascii_len = len(text) - non_ascii
|
||||
return non_ascii + (ascii_len + 3) // 4
|
||||
|
||||
|
||||
def _estimate_text_value(value) -> int:
|
||||
if value is None:
|
||||
return 0
|
||||
if isinstance(value, str):
|
||||
return estimate_tokens(value)
|
||||
return estimate_tokens(json.dumps(value, ensure_ascii=False, default=str))
|
||||
|
||||
|
||||
def estimate_messages_tokens(messages) -> int:
|
||||
"""估算一组对话消息(dict,chat 协议)的输入 token 数。"""
|
||||
total = 0
|
||||
for message in messages or []:
|
||||
total += 4 # role 等格式开销
|
||||
if isinstance(message, dict):
|
||||
total += _estimate_text_value(message.get('content'))
|
||||
tool_calls = message.get('tool_calls')
|
||||
if tool_calls:
|
||||
total += _estimate_text_value(tool_calls)
|
||||
else:
|
||||
total += _estimate_text_value(getattr(message, 'content', None))
|
||||
return total
|
||||
|
||||
|
||||
def estimate_items_tokens(items) -> int:
|
||||
"""估算 Responses 协议 input_items(dict 或响应输出对象)的输入 token 数。"""
|
||||
total = 0
|
||||
for item in items or []:
|
||||
total += 4
|
||||
if isinstance(item, dict):
|
||||
item_type = str(item.get('type') or '')
|
||||
if item_type == 'function_call':
|
||||
total += estimate_tokens(str(item.get('name') or '') + str(item.get('arguments') or ''))
|
||||
elif item_type == 'function_call_output':
|
||||
total += _estimate_text_value(item.get('output'))
|
||||
else:
|
||||
total += _estimate_text_value(item.get('content'))
|
||||
else:
|
||||
arguments = getattr(item, 'arguments', None)
|
||||
if arguments:
|
||||
total += estimate_tokens(str(arguments))
|
||||
else:
|
||||
total += _estimate_text_value(getattr(item, 'content', None))
|
||||
return total
|
||||
|
||||
|
||||
def get_user_daily_usage(user_id: int):
|
||||
"""返回 (今日已用 tokens, 今日调用次数, 生效上限)。"""
|
||||
used, calls = db.session.query(
|
||||
func.coalesce(func.sum(AiUsageLog.input_tokens + AiUsageLog.output_tokens), 0),
|
||||
func.count(AiUsageLog.id),
|
||||
).filter(
|
||||
AiUsageLog.user_id == user_id,
|
||||
AiUsageLog.created_at >= _today_start(),
|
||||
).one()
|
||||
user = db.session.get(User, user_id)
|
||||
limit = get_user_daily_limit(user) if user else get_default_daily_limit()
|
||||
return int(used or 0), int(calls or 0), limit
|
||||
|
||||
|
||||
def get_all_users_daily_usage():
|
||||
"""管理端用量表:所有用户 + 今日汇总(按用量降序)。"""
|
||||
today = _today_start()
|
||||
rows = db.session.query(
|
||||
AiUsageLog.user_id,
|
||||
func.count(AiUsageLog.id),
|
||||
func.coalesce(func.sum(AiUsageLog.input_tokens), 0),
|
||||
func.coalesce(func.sum(AiUsageLog.output_tokens), 0),
|
||||
).filter(
|
||||
AiUsageLog.created_at >= today,
|
||||
).group_by(AiUsageLog.user_id).all()
|
||||
summary = {r[0]: (int(r[1] or 0), int(r[2] or 0), int(r[3] or 0)) for r in rows}
|
||||
|
||||
users = User.query.order_by(User.id.asc()).all()
|
||||
result = []
|
||||
for user in users:
|
||||
calls, inp, out = summary.get(user.id, (0, 0, 0))
|
||||
limit = get_user_daily_limit(user)
|
||||
result.append({
|
||||
'user_id': user.id,
|
||||
'username': user.username,
|
||||
'jwxt_name': user.jwxt_name or '',
|
||||
'calls': calls,
|
||||
'input_tokens': inp,
|
||||
'output_tokens': out,
|
||||
'total_tokens': inp + out,
|
||||
'daily_limit': limit,
|
||||
'personal_limit': user.ai_daily_limit,
|
||||
})
|
||||
result.sort(key=lambda item: item['total_tokens'], reverse=True)
|
||||
return result
|
||||
|
||||
|
||||
def get_usage_trend(days: int = 7):
|
||||
"""最近 N 天的全站用量趋势(北京时间按天)。"""
|
||||
start = _today_start() - timedelta(days=days - 1)
|
||||
rows = db.session.query(
|
||||
func.date(AiUsageLog.created_at),
|
||||
func.coalesce(func.sum(AiUsageLog.input_tokens), 0),
|
||||
func.coalesce(func.sum(AiUsageLog.output_tokens), 0),
|
||||
).filter(
|
||||
AiUsageLog.created_at >= start,
|
||||
).group_by(func.date(AiUsageLog.created_at)).all()
|
||||
by_date = {str(r[0]): (int(r[1] or 0), int(r[2] or 0)) for r in rows}
|
||||
trend = []
|
||||
for offset in range(days):
|
||||
day = (_today_start() + timedelta(days=offset - days + 1)).date()
|
||||
inp, out = by_date.get(str(day), (0, 0))
|
||||
trend.append({'date': str(day), 'input_tokens': inp, 'output_tokens': out})
|
||||
return trend
|
||||
@@ -0,0 +1,362 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""AI 选课助手的原生 WebSocket 传输层。
|
||||
|
||||
协议(每个 WebSocket 连接处理一条 AI 消息):
|
||||
- 客户端连接后发送 {"type": "chat", "message": "..."}(兼容旧格式 {"message": "..."})。
|
||||
- 服务端推送 text_delta / tool_started / tool_finished / confirmation_required /
|
||||
ask_user / error / done / heartbeat 事件,最后以 stream_end 收尾。
|
||||
- 客户端可随时发送 {"type": "stop"} 取消生成(也会停止待执行的工具)。
|
||||
- confirmation_required 事件要求客户端回传 {"type": "confirm", "call_id": "...",
|
||||
"approved": true/false},写操作只有在确认后才会执行。
|
||||
- ask_user 事件把前端输入框变成选择器,客户端回传 {"type": "ask_answer",
|
||||
"call_id": "...", "selected": [...], "text": "补充说明"},答案作为工具结果返回模型。
|
||||
"""
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
from collections import deque
|
||||
from queue import Empty, Queue
|
||||
|
||||
from flask import current_app
|
||||
from flask_login import current_user
|
||||
|
||||
from app.ai_assistant import stream_chat, get_ai_settings
|
||||
from app.ai_usage import get_user_daily_usage, record_usage
|
||||
from app.models import AiConversation, AiConversationMessage, db
|
||||
|
||||
|
||||
_SENTENCE_ENDINGS = set('。!?!?;;\n')
|
||||
_CLOSING_QUOTES = set('”’》))]}」』')
|
||||
_MAX_TEXT_FRAME = 120
|
||||
_HEARTBEAT_INTERVAL = 15
|
||||
_CONFIRM_TIMEOUT = 180
|
||||
# 计费走管理员共享 API Key:每用户每分钟最多 10 条消息。
|
||||
_RATE_LIMIT_MAX = 10
|
||||
_RATE_LIMIT_WINDOW = 60.0
|
||||
|
||||
_rate_lock = threading.Lock()
|
||||
_rate_hits = {}
|
||||
|
||||
|
||||
def _rate_limit_allow(user_id) -> bool:
|
||||
now = time.monotonic()
|
||||
with _rate_lock:
|
||||
hits = _rate_hits.setdefault(user_id, deque())
|
||||
while hits and now - hits[0] > _RATE_LIMIT_WINDOW:
|
||||
hits.popleft()
|
||||
if len(hits) >= _RATE_LIMIT_MAX:
|
||||
return False
|
||||
hits.append(now)
|
||||
return True
|
||||
|
||||
|
||||
class _DecisionGate:
|
||||
"""等待用户在界面上回应(确认写操作 / 回答 ask_user 选择器)。
|
||||
|
||||
同一时刻只有一个挂起的请求。resolve 的 value 对确认是 bool,
|
||||
对 ask_user 是答案 dict({'selected': [...], 'text': '...'})。
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self._cond = threading.Condition()
|
||||
self._call_id = None
|
||||
self._decision = None
|
||||
self._early = None # (call_id, value):早于等待开始到达的答案(脚本/极速客户端)
|
||||
|
||||
def request(self, call_id: str, timeout: float = _CONFIRM_TIMEOUT) -> bool:
|
||||
"""阻塞等待用户决定;超时、拒绝或连接断开都返回 False。"""
|
||||
decision = self._wait(call_id, timeout)
|
||||
return bool(decision)
|
||||
|
||||
def ask(self, call_id: str, payload=None, timeout: float = _CONFIRM_TIMEOUT):
|
||||
"""阻塞等待用户回答 ask_user;返回答案 dict,超时或连接断开返回 None。
|
||||
|
||||
payload 是向用户展示的提问内容(question/options/multiple),仅为对齐
|
||||
ask(call_id, payload) 的调用约定,答案以 resolve 回传的值为准。
|
||||
"""
|
||||
decision = self._wait(call_id, timeout)
|
||||
return decision if isinstance(decision, dict) else None
|
||||
|
||||
def _wait(self, call_id: str, timeout: float):
|
||||
with self._cond:
|
||||
call_id = str(call_id)
|
||||
self._call_id = call_id
|
||||
self._decision = None
|
||||
# 事件 yield 后答案可能在等待开始前就到,先认领缓冲的早到答案
|
||||
if self._early and self._early[0] == call_id:
|
||||
value, self._early = self._early[1], None
|
||||
self._call_id = None
|
||||
return value
|
||||
decided = self._cond.wait_for(lambda: self._decision is not None, timeout=timeout)
|
||||
self._call_id = None
|
||||
decision, self._decision = self._decision, None
|
||||
return decision if decided else None
|
||||
|
||||
def resolve(self, call_id: str, value) -> None:
|
||||
with self._cond:
|
||||
call_id = str(call_id)
|
||||
if self._call_id == call_id and self._decision is None:
|
||||
self._decision = value
|
||||
self._cond.notify_all()
|
||||
elif self._call_id is None and self._early is None:
|
||||
# 尚无等待者:缓冲给随后 _wait 的同一 call_id 认领
|
||||
self._early = (call_id, value)
|
||||
|
||||
def abandon(self) -> None:
|
||||
"""用户停止或连接断开时结束等待,确认视为拒绝、提问视为无回答。"""
|
||||
with self._cond:
|
||||
if self._decision is None:
|
||||
self._decision = False
|
||||
self._cond.notify_all()
|
||||
|
||||
|
||||
class _UserRef:
|
||||
"""把当前用户固化成纯 Python 对象,避免后台线程访问别的线程的 ORM 会话。"""
|
||||
|
||||
def __init__(self, user, conversation_id=None):
|
||||
self.id = user.id
|
||||
self.school_id = user.school_id or 'sdmu'
|
||||
self.conversation_id = conversation_id
|
||||
account = user.get_jwxt_account() or {}
|
||||
self._jwxt_username = str(account.get('username', '') or '')
|
||||
|
||||
def get_jwxt_account(self):
|
||||
if not self._jwxt_username:
|
||||
return None
|
||||
return {'username': self._jwxt_username}
|
||||
|
||||
|
||||
def _safe_send(ws, payload: dict) -> bool:
|
||||
try:
|
||||
ws.send(json.dumps(payload, ensure_ascii=False))
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _drain_sentence_buffer(buffer: str, force: bool = False):
|
||||
"""把模型 token 聚合成自然句子,返回待发送帧和未完成的尾部。"""
|
||||
frames = []
|
||||
while buffer:
|
||||
cut = -1
|
||||
for index, char in enumerate(buffer):
|
||||
if char in _SENTENCE_ENDINGS:
|
||||
cut = index + 1
|
||||
while cut < len(buffer) and buffer[cut] in _CLOSING_QUOTES:
|
||||
cut += 1
|
||||
break
|
||||
if cut < 0 and len(buffer) >= _MAX_TEXT_FRAME:
|
||||
cut = buffer.rfind(' ', 0, _MAX_TEXT_FRAME + 1)
|
||||
if cut <= 0:
|
||||
cut = _MAX_TEXT_FRAME
|
||||
if cut <= 0:
|
||||
break
|
||||
frames.append(buffer[:cut])
|
||||
buffer = buffer[cut:]
|
||||
if force and buffer:
|
||||
frames.append(buffer)
|
||||
buffer = ''
|
||||
return frames, buffer
|
||||
|
||||
|
||||
def _load_conversation_messages(user, content):
|
||||
conversation = AiConversation.query.filter_by(user_id=user.id).first()
|
||||
if not conversation:
|
||||
conversation = AiConversation(user_id=user.id)
|
||||
db.session.add(conversation)
|
||||
db.session.flush()
|
||||
db.session.add(AiConversationMessage(
|
||||
conversation_id=conversation.id,
|
||||
role='user',
|
||||
content=content[:4000],
|
||||
))
|
||||
db.session.commit()
|
||||
recent = conversation.messages.order_by(AiConversationMessage.id.desc()).limit(20).all()
|
||||
messages = [{'role': item.role, 'content': item.content} for item in reversed(recent)]
|
||||
return conversation, messages
|
||||
|
||||
|
||||
def _save_assistant_message(conversation_id, content: str) -> None:
|
||||
"""保存回答(含被用户停止时的部分内容),避免下一轮对话丢失上下文。"""
|
||||
if not conversation_id or not content:
|
||||
return
|
||||
db.session.add(AiConversationMessage(
|
||||
conversation_id=conversation_id,
|
||||
role='assistant',
|
||||
content=content[:4000],
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def register_ai_websocket(sock):
|
||||
"""注册 /api/ai/chat/ws。"""
|
||||
|
||||
@sock.route('/api/ai/chat/ws')
|
||||
def ai_chat_websocket(ws):
|
||||
if not current_user.is_authenticated:
|
||||
_safe_send(ws, {'type': 'error', 'message': '请先登录后使用 AI 选课助手'})
|
||||
return
|
||||
|
||||
user_id = current_user.id
|
||||
if not _rate_limit_allow(user_id):
|
||||
_safe_send(ws, {'type': 'error', 'message': '发送太频繁了,请稍等一分钟再试'})
|
||||
return
|
||||
|
||||
# 每日 token 限额(limit=0 表示不限制):超限直接拒绝本轮对话。
|
||||
try:
|
||||
used_today, _calls_today, daily_limit = get_user_daily_usage(user_id)
|
||||
except Exception:
|
||||
current_app.logger.exception('读取 AI 每日用量失败')
|
||||
used_today, daily_limit = 0, 0
|
||||
if daily_limit and used_today >= daily_limit:
|
||||
_safe_send(ws, {
|
||||
'type': 'error',
|
||||
'message': f'今日 AI 用量已达上限({used_today:,}/{daily_limit:,} tokens),请明天再试或联系管理员调整',
|
||||
})
|
||||
return
|
||||
|
||||
conversation_id = None
|
||||
gate = _DecisionGate()
|
||||
stop_requested = threading.Event()
|
||||
final_message = ''
|
||||
reader_thread = None
|
||||
|
||||
try:
|
||||
raw_message = ws.receive()
|
||||
data = json.loads(raw_message or '{}')
|
||||
content = str(data.get('message', '')).strip()
|
||||
if not content:
|
||||
_safe_send(ws, {'type': 'error', 'message': '请发送一条消息'})
|
||||
return
|
||||
|
||||
conversation, messages = _load_conversation_messages(current_user, content)
|
||||
conversation_id = conversation.id
|
||||
# 在请求线程内固化用户数据,后台线程不再触碰 ORM 对象。
|
||||
user = _UserRef(current_user, conversation_id=conversation_id)
|
||||
model_name = str(get_ai_settings().get('model') or '')
|
||||
|
||||
def usage_sink(input_tokens, output_tokens):
|
||||
"""每轮模型响应完成后的用量回调:落库,并超限即时停止后续轮次。"""
|
||||
try:
|
||||
record_usage(user_id, model_name, input_tokens, output_tokens)
|
||||
used_now, _c, day_limit = get_user_daily_usage(user_id)
|
||||
if day_limit and used_now >= day_limit:
|
||||
stop_requested.set()
|
||||
gate.abandon()
|
||||
except Exception:
|
||||
current_app.logger.exception('AI 用量记录失败')
|
||||
|
||||
# 模型请求可能长时间没有任何 token。生成器放到后台线程,主线程
|
||||
# 每 15 秒发送一个空心跳,避免 Nginx/负载均衡器误判连接已断开。
|
||||
event_queue = Queue()
|
||||
app = current_app._get_current_object()
|
||||
|
||||
def produce_events():
|
||||
from app.url_manager import push_school, pop_school
|
||||
push_school(user.school_id)
|
||||
try:
|
||||
with app.app_context():
|
||||
for event in stream_chat(
|
||||
user, messages,
|
||||
cancel_check=stop_requested.is_set,
|
||||
confirm=gate.request,
|
||||
usage_sink=usage_sink,
|
||||
ask=gate.ask,
|
||||
):
|
||||
event_queue.put(event)
|
||||
except Exception:
|
||||
current_app.logger.exception('AI WebSocket 流生成失败')
|
||||
event_queue.put({'type': 'error', 'message': 'AI 流式响应异常,请稍后重试'})
|
||||
finally:
|
||||
pop_school()
|
||||
event_queue.put(None)
|
||||
|
||||
threading.Thread(target=produce_events, daemon=True).start()
|
||||
|
||||
def read_control_frames():
|
||||
"""读取客户端控制帧:stop 取消生成,confirm 回传写操作确认。
|
||||
|
||||
simple-websocket 内部线程负责收 socket,receive 只是读缓冲,
|
||||
与主线程的 send 并发是安全的。连接断开同样视为停止,
|
||||
避免后台继续调用模型和执行工具。
|
||||
"""
|
||||
try:
|
||||
while True:
|
||||
raw = ws.receive()
|
||||
if raw is None:
|
||||
break
|
||||
try:
|
||||
control = json.loads(raw)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if control.get('type') == 'stop':
|
||||
stop_requested.set()
|
||||
gate.abandon()
|
||||
break
|
||||
if control.get('type') == 'confirm':
|
||||
gate.resolve(str(control.get('call_id', '')), bool(control.get('approved')))
|
||||
if control.get('type') == 'ask_answer':
|
||||
gate.resolve(str(control.get('call_id', '')), {
|
||||
'selected': control.get('selected') or [],
|
||||
'text': str(control.get('text') or ''),
|
||||
})
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
stop_requested.set()
|
||||
gate.abandon()
|
||||
|
||||
reader_thread = threading.Thread(target=read_control_frames, daemon=True)
|
||||
reader_thread.start()
|
||||
|
||||
text_buffer = ''
|
||||
|
||||
def send_text_frames(force=False):
|
||||
nonlocal text_buffer
|
||||
frames, text_buffer = _drain_sentence_buffer(text_buffer, force=force)
|
||||
for frame in frames:
|
||||
ws.send(json.dumps({'type': 'text_delta', 'delta': frame}, ensure_ascii=False))
|
||||
|
||||
while True:
|
||||
try:
|
||||
event = event_queue.get(timeout=_HEARTBEAT_INTERVAL)
|
||||
except Empty:
|
||||
ws.send(json.dumps({'type': 'heartbeat', 'delta': ''}, ensure_ascii=False))
|
||||
continue
|
||||
if event is None:
|
||||
break
|
||||
if event.get('type') == 'text_delta':
|
||||
delta = event.get('delta', '')
|
||||
final_message += delta
|
||||
text_buffer += delta
|
||||
send_text_frames()
|
||||
elif event.get('type') == 'done':
|
||||
final_message = event.get('message', final_message)
|
||||
send_text_frames(force=True)
|
||||
ws.send(json.dumps(event, ensure_ascii=False))
|
||||
else:
|
||||
# 工具/确认事件前先发完模型上一段文字,保持“输出 → 工具 → 输出”的顺序。
|
||||
send_text_frames(force=True)
|
||||
ws.send(json.dumps(event, ensure_ascii=False))
|
||||
|
||||
send_text_frames(force=True)
|
||||
_save_assistant_message(conversation_id, final_message)
|
||||
reason = 'cancelled' if stop_requested.is_set() else 'complete'
|
||||
# 应用层明确通知客户端:所有文本和工具事件都已发送完毕。
|
||||
_safe_send(ws, {'type': 'stream_end', 'reason': reason})
|
||||
except Exception:
|
||||
current_app.logger.exception('AI WebSocket 对话失败')
|
||||
# 连接中断也保留已生成的部分回答,避免下一轮对话丢失上下文。
|
||||
try:
|
||||
db.session.rollback()
|
||||
_save_assistant_message(conversation_id, final_message)
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
finally:
|
||||
stop_requested.set()
|
||||
gate.abandon()
|
||||
# 等控制帧读取线程随客户端 close 退出(正常情况下客户端收到
|
||||
# stream_end 后立即关闭),保持完整的 close handshake,避免
|
||||
# handler 提前返回导致代理截断连接;超时则交给 flask_sock 收尾。
|
||||
if reader_thread is not None:
|
||||
reader_thread.join(timeout=30)
|
||||
@@ -0,0 +1,97 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Flask应用配置
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
# 基础路径
|
||||
BASE_DIR = Path(__file__).parent.parent
|
||||
APP_DIR = BASE_DIR / "app"
|
||||
LOG_DIR = BASE_DIR / "logs"
|
||||
|
||||
# 确保目录存在
|
||||
LOG_DIR.mkdir(exist_ok=True)
|
||||
|
||||
from app.settings import BASE_URLS
|
||||
|
||||
|
||||
def _load_or_create_secret_key() -> str:
|
||||
"""SECRET_KEY 未设环境变量时,自动生成并持久化到 .secret_key。
|
||||
不再回退到公开常量(否则任何人可伪造 Flask session cookie)。"""
|
||||
key_file = BASE_DIR / '.secret_key'
|
||||
try:
|
||||
if key_file.exists():
|
||||
k = key_file.read_text(encoding='utf-8').strip()
|
||||
if k:
|
||||
return k
|
||||
import secrets
|
||||
k = secrets.token_hex(32)
|
||||
key_file.write_text(k, encoding='utf-8')
|
||||
return k
|
||||
except Exception:
|
||||
import secrets
|
||||
return secrets.token_hex(32)
|
||||
|
||||
|
||||
class Config:
|
||||
"""基础配置类"""
|
||||
|
||||
# Flask基础配置
|
||||
SECRET_KEY = os.environ.get('SECRET_KEY') or _load_or_create_secret_key()
|
||||
|
||||
# 数据库配置
|
||||
# 支持 MySQL(生产推荐)和 SQLite(开发/默认)
|
||||
# MySQL 示例: mysql+pymysql://user:pass@localhost:3306/sdmu?charset=utf8mb4
|
||||
# 环境变量 DATABASE_URL 优先;未设置时回退 SQLite
|
||||
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
|
||||
f'sqlite:///{BASE_DIR / "app.db"}'
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||
# 连接池(MySQL 场景下避免连接耗尽)
|
||||
SQLALCHEMY_POOL_SIZE = 10
|
||||
SQLALCHEMY_POOL_RECYCLE = 3600 # 1 小时回收连接,避免 MySQL wait_timeout 断连
|
||||
|
||||
# 会话配置
|
||||
PERMANENT_SESSION_LIFETIME = 86400 # 24小时
|
||||
|
||||
# 教务系统配置(运行时以 url_manager.get_base_url() 为准)
|
||||
# 以下仅作 Environment 覆盖回退,实际由 app.settings.BASE_URLS 接管
|
||||
BASE_URL = os.environ.get('JWXT_BASE_URL') or BASE_URLS[0]
|
||||
GNMKDM = "N253512"
|
||||
|
||||
# 抢课引擎配置
|
||||
MAX_CONCURRENT_TASKS = 10 # 最大并发抢课任务数
|
||||
RETRY_INTERVAL = 0.5 # 抢课重试间隔(秒)
|
||||
MAX_RETRIES = 100 # 最大重试次数
|
||||
|
||||
# 日志配置
|
||||
LOG_LEVEL = os.environ.get('LOG_LEVEL') or 'INFO'
|
||||
LOG_FILE = LOG_DIR / "app.log"
|
||||
|
||||
# 管理员账号 (生产环境应从数据库读取)
|
||||
ADMIN_USERNAME = os.environ.get('ADMIN_USERNAME') or 'admin'
|
||||
ADMIN_PASSWORD = os.environ.get('ADMIN_PASSWORD') or 'admin123'
|
||||
|
||||
# 支付FM配置
|
||||
PAY_BASE_URL = os.environ.get('PAY_BASE_URL') or 'https://jwxt.bansonic.top'
|
||||
|
||||
|
||||
class DevelopmentConfig(Config):
|
||||
"""开发环境配置"""
|
||||
DEBUG = True
|
||||
LOG_LEVEL = 'DEBUG'
|
||||
|
||||
|
||||
class ProductionConfig(Config):
|
||||
"""生产环境配置"""
|
||||
DEBUG = False
|
||||
LOG_LEVEL = 'WARNING'
|
||||
|
||||
|
||||
# 配置映射
|
||||
config = {
|
||||
'development': DevelopmentConfig,
|
||||
'production': ProductionConfig,
|
||||
'default': DevelopmentConfig
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
GeoLite2-City 数据库下载/更新工具
|
||||
|
||||
用法:
|
||||
# 新版 API(推荐,需 Account ID + License Key)
|
||||
python download_geolite2.py --account-id 1395316 --license-key YOUR_KEY
|
||||
|
||||
# 旧版 API(仅 License Key,老账号可用)
|
||||
python download_geolite2.py --license-key YOUR_KEY
|
||||
|
||||
# 通过环境变量配置
|
||||
MAXMIND_ACCOUNT_ID=1395316 MAXMIND_LICENSE_KEY=xxx python download_geolite2.py
|
||||
|
||||
# 无 Key,走社区镜像(无需注册)
|
||||
python download_geolite2.py
|
||||
|
||||
# 强制重新下载
|
||||
python download_geolite2.py --license-key YOUR_KEY --force
|
||||
|
||||
获取 License Key:
|
||||
1. 注册 https://www.maxmind.com/en/geolite2/signup
|
||||
2. 登录后进入 Account → Manage License Keys → Generate
|
||||
3. 免费账号即可,每月更新一次数据库
|
||||
4. 新版 API 需要 Account ID(登录后在账号概览页可见)
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import time
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
# 数据库存放路径(项目根目录)
|
||||
DB_PATH = Path(__file__).parent.parent / "GeoLite2-City.mmdb"
|
||||
# 记录上次更新时间的文件
|
||||
STAMP_PATH = DB_PATH.with_suffix(".mmdb.update_stamp")
|
||||
# 更新间隔:7 天
|
||||
UPDATE_INTERVAL_DAYS = 7
|
||||
|
||||
# MaxMind 官方下载端点
|
||||
# 新版 API(permalink,需基本认证 account_id:license_key,返回 tar.gz)
|
||||
NEW_API_URL = "https://download.maxmind.com/geoip/databases/GeoLite2-City/download"
|
||||
# 旧版 API(query param 传 license_key,返回 zip)
|
||||
OLD_API_URL = "https://download.maxmind.com/app/geoip_download"
|
||||
|
||||
# 备用镜像(社区维护,无需 License Key)
|
||||
# linklet-io/GeoLite.mmdb 的 download 分支有完整的 City/ASN/Country mmdb
|
||||
# 通过 GitHub API 获取(raw.githubusercontent 在国内常超时,API 更稳)
|
||||
MIRROR_REPO = "linklet-io/GeoLite.mmdb"
|
||||
MIRROR_BRANCH = "download"
|
||||
MIRROR_FILE = "GeoLite2-City.mmdb"
|
||||
|
||||
|
||||
def _download_with_license_key(license_key: str, account_id: str = "") -> bool:
|
||||
"""用 MaxMind 官方 API 下载
|
||||
新版 API:基本认证 (account_id, license_key),返回 tar.gz(推荐)
|
||||
旧版 API:query param 传 license_key,返回 zip(老账号兼容)
|
||||
"""
|
||||
import requests
|
||||
|
||||
# 先试新版 API(有 account_id 时优先)
|
||||
if account_id:
|
||||
print(f"[GeoLite2] 从 MaxMind 官方下载(新版 API, account={account_id})...")
|
||||
try:
|
||||
resp = requests.get(
|
||||
NEW_API_URL,
|
||||
params={"suffix": "tar.gz"},
|
||||
auth=(account_id, license_key),
|
||||
timeout=120,
|
||||
stream=True,
|
||||
)
|
||||
if resp.status_code == 200:
|
||||
return _save_tarball(resp, source="官方新版API")
|
||||
else:
|
||||
body = resp.text[:200]
|
||||
print(f"[GeoLite2] 新版 API 返回 {resp.status_code}: {body}")
|
||||
except Exception as e:
|
||||
print(f"[GeoLite2] 新版 API 异常: {e}")
|
||||
|
||||
# 降级到旧版 API
|
||||
print(f"[GeoLite2] 从 MaxMind 官方下载(旧版 API)...")
|
||||
params = {
|
||||
"edition_id": "GeoLite2-City",
|
||||
"license_key": license_key,
|
||||
"suffix": "zip",
|
||||
}
|
||||
try:
|
||||
resp = requests.get(OLD_API_URL, params=params, timeout=120, stream=True)
|
||||
if resp.status_code != 200:
|
||||
body = resp.text[:200]
|
||||
print(f"[GeoLite2] 旧版 API 返回 {resp.status_code}: {body}")
|
||||
return False
|
||||
return _save_zip(resp.content, source="官方旧版API")
|
||||
except Exception as e:
|
||||
print(f"[GeoLite2] 下载失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def _save_tarball(resp, source: str = "") -> bool:
|
||||
"""保存 tar.gz 响应,提取 .mmdb 文件"""
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(suffix=".tar.gz", delete=False) as f:
|
||||
for chunk in resp.iter_content(chunk_size=65536):
|
||||
f.write(chunk)
|
||||
tar_path = f.name
|
||||
|
||||
with tarfile.open(tar_path, "r:gz") as tf:
|
||||
mmdb_members = [m for m in tf.getmembers() if m.name.endswith(".mmdb")]
|
||||
if not mmdb_members:
|
||||
print(f"[GeoLite2] tar.gz 内未找到 .mmdb 文件")
|
||||
os.unlink(tar_path)
|
||||
return False
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
tf.extract(mmdb_members[0], tmpdir)
|
||||
src = Path(tmpdir) / mmdb_members[0].name
|
||||
_atomic_replace(src, DB_PATH)
|
||||
|
||||
os.unlink(tar_path)
|
||||
_write_stamp()
|
||||
size_mb = DB_PATH.stat().st_size / (1024 * 1024)
|
||||
print(f"[GeoLite2] 下载完成({source}): {DB_PATH} ({size_mb:.1f} MB)")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"[GeoLite2] 保存 tar.gz 失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def _save_zip(content: bytes, source: str = "") -> bool:
|
||||
"""保存 zip 内容,提取 .mmdb 文件"""
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(suffix=".zip", delete=False) as f:
|
||||
f.write(content)
|
||||
zip_path = f.name
|
||||
|
||||
with zipfile.ZipFile(zip_path, "r") as zf:
|
||||
mmdb_files = [n for n in zf.namelist() if n.endswith(".mmdb")]
|
||||
if not mmdb_files:
|
||||
print("[GeoLite2] zip 内未找到 .mmdb 文件")
|
||||
os.unlink(zip_path)
|
||||
return False
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
zf.extract(mmdb_files[0], tmpdir)
|
||||
src = Path(tmpdir) / mmdb_files[0]
|
||||
_atomic_replace(src, DB_PATH)
|
||||
|
||||
os.unlink(zip_path)
|
||||
_write_stamp()
|
||||
size_mb = DB_PATH.stat().st_size / (1024 * 1024)
|
||||
print(f"[GeoLite2] 下载完成({source}): {DB_PATH} ({size_mb:.1f} MB)")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"[GeoLite2] 保存 zip 失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def _atomic_replace(src: Path, dst: Path):
|
||||
"""原子替换目标文件"""
|
||||
tmp_target = str(dst) + ".tmp"
|
||||
src.replace(tmp_target)
|
||||
if dst.exists():
|
||||
os.unlink(str(dst))
|
||||
os.rename(tmp_target, str(dst))
|
||||
|
||||
|
||||
def _download_from_mirror() -> bool:
|
||||
"""从 GitHub 社区镜像下载(无需 License Key,直接下载 .mmdb)
|
||||
使用 GitHub API 获取 raw download_url,比直接访问 raw.githubusercontent.com 更稳
|
||||
"""
|
||||
import base64
|
||||
import requests
|
||||
|
||||
api_url = f"https://api.github.com/repos/{MIRROR_REPO}/contents/{MIRROR_FILE}?ref={MIRROR_BRANCH}"
|
||||
print(f"[GeoLite2] 尝试镜像: {MIRROR_REPO}/{MIRROR_BRANCH}/{MIRROR_FILE}")
|
||||
try:
|
||||
resp = requests.get(api_url, timeout=30, headers={"Accept": "application/vnd.github.v3+json"})
|
||||
if resp.status_code != 200:
|
||||
print(f"[GeoLite2] GitHub API 返回 {resp.status_code}: {resp.text[:200]}")
|
||||
return False
|
||||
info = resp.json()
|
||||
size = info.get("size", 0)
|
||||
download_url = info.get("download_url")
|
||||
encoding = info.get("encoding", "")
|
||||
content_b64 = info.get("content", "")
|
||||
|
||||
if not download_url and not content_b64:
|
||||
print(f"[GeoLite2] GitHub API 未返回下载链接或内容")
|
||||
return False
|
||||
|
||||
print(f"[GeoLite2] 镜像文件大小: {size / (1024*1024):.1f} MB")
|
||||
|
||||
# 方式1: 直接从 download_url 下载(raw.githubusercontent.com,国内可能超时)
|
||||
if download_url:
|
||||
print(f"[GeoLite2] 尝试 raw 直链...")
|
||||
try:
|
||||
raw_resp = requests.get(download_url, timeout=120, stream=True,
|
||||
headers={"User-Agent": "geoip-downloader/1.0"})
|
||||
if raw_resp.status_code == 200:
|
||||
return _save_raw_stream(raw_resp)
|
||||
print(f"[GeoLite2] raw 直链返回 {raw_resp.status_code}")
|
||||
except Exception as e:
|
||||
print(f"[GeoLite2] raw 直链失败: {e}")
|
||||
|
||||
# 方式2: 从 API 返回的 base64 content 解码(GitHub API 对 >1MB 文件不返回 content)
|
||||
if content_b64 and encoding == "base64":
|
||||
print(f"[GeoLite2] 尝试 API base64 内容...")
|
||||
try:
|
||||
raw = base64.b64decode(content_b64)
|
||||
tmp_target = str(DB_PATH) + ".tmp"
|
||||
with open(tmp_target, "wb") as f:
|
||||
f.write(raw)
|
||||
_atomic_replace(Path(tmp_target), DB_PATH)
|
||||
_write_stamp()
|
||||
size_mb = DB_PATH.stat().st_size / (1024 * 1024)
|
||||
print(f"[GeoLite2] 镜像下载完成: {DB_PATH} ({size_mb:.1f} MB)")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"[GeoLite2] base64 解码失败: {e}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"[GeoLite2] 镜像下载失败: {e}")
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def _save_raw_stream(resp) -> bool:
|
||||
"""保存流式响应到文件"""
|
||||
tmp_target = str(DB_PATH) + ".tmp"
|
||||
try:
|
||||
with open(tmp_target, "wb") as f:
|
||||
for chunk in resp.iter_content(chunk_size=65536):
|
||||
f.write(chunk)
|
||||
# 校验大小(GeoLite2-City 至少 30MB)
|
||||
size = Path(tmp_target).stat().st_size
|
||||
if size < 30_000_000:
|
||||
print(f"[GeoLite2] 下载文件过小 ({size} bytes),可能损坏,已丢弃")
|
||||
os.unlink(tmp_target)
|
||||
return False
|
||||
_atomic_replace(Path(tmp_target), DB_PATH)
|
||||
_write_stamp()
|
||||
size_mb = DB_PATH.stat().st_size / (1024 * 1024)
|
||||
print(f"[GeoLite2] 镜像下载完成: {DB_PATH} ({size_mb:.1f} MB)")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"[GeoLite2] 保存失败: {e}")
|
||||
if Path(tmp_target).exists():
|
||||
os.unlink(tmp_target)
|
||||
return False
|
||||
|
||||
|
||||
def _write_stamp():
|
||||
"""记录更新时间戳"""
|
||||
STAMP_PATH.write_text(str(int(time.time())), encoding="utf-8")
|
||||
|
||||
|
||||
def _needs_update() -> bool:
|
||||
"""判断是否需要更新(不存在或超过 7 天)"""
|
||||
if not DB_PATH.exists():
|
||||
return True
|
||||
if not STAMP_PATH.exists():
|
||||
return True
|
||||
try:
|
||||
last = int(STAMP_PATH.read_text(encoding="utf-8").strip())
|
||||
age_days = (time.time() - last) / 86400
|
||||
return age_days >= UPDATE_INTERVAL_DAYS
|
||||
except Exception:
|
||||
return True
|
||||
|
||||
|
||||
def download(license_key: str = "", account_id: str = "", force: bool = False) -> bool:
|
||||
"""
|
||||
下载/更新 GeoLite2-City 数据库
|
||||
|
||||
Args:
|
||||
license_key: MaxMind License Key(为空则尝试镜像)
|
||||
account_id: MaxMind Account ID(新版 API 需要,登录后在账号概览页可见)
|
||||
force: 是否强制重新下载
|
||||
|
||||
Returns:
|
||||
bool: 是否成功
|
||||
"""
|
||||
if not force and DB_PATH.exists() and not _needs_update():
|
||||
size_mb = DB_PATH.stat().st_size / (1024 * 1024)
|
||||
print(f"[GeoLite2] 数据库已是最新,跳过下载 ({size_mb:.1f} MB)")
|
||||
return True
|
||||
|
||||
# 优先用 License Key 下载
|
||||
if license_key:
|
||||
if _download_with_license_key(license_key, account_id):
|
||||
return True
|
||||
print("[GeoLite2] 官方下载失败,尝试镜像...")
|
||||
|
||||
# 降级到镜像
|
||||
if _download_from_mirror():
|
||||
return True
|
||||
|
||||
print("[GeoLite2] 所有下载方式均失败")
|
||||
print(" → 请注册 MaxMind 免费账号获取 License Key:")
|
||||
print(" https://www.maxmind.com/en/geolite2/signup")
|
||||
print(" → 然后运行: python app/download_geolite2.py --account-id YOUR_ID --license-key YOUR_KEY")
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="GeoLite2-City 数据库下载工具")
|
||||
parser.add_argument("--account-id", default=os.environ.get("MAXMIND_ACCOUNT_ID", ""),
|
||||
help="MaxMind Account ID(新版 API 需要,也可通过 MAXMIND_ACCOUNT_ID 环境变量配置)")
|
||||
parser.add_argument("--license-key", default=os.environ.get("MAXMIND_LICENSE_KEY", ""),
|
||||
help="MaxMind License Key(也可通过 MAXMIND_LICENSE_KEY 环境变量配置)")
|
||||
parser.add_argument("--force", action="store_true", help="强制重新下载")
|
||||
args = parser.parse_args()
|
||||
|
||||
success = download(license_key=args.license_key, account_id=args.account_id, force=args.force)
|
||||
sys.exit(0 if success else 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,714 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
抢课引擎 - 持续抢课直到成功
|
||||
|
||||
功能:
|
||||
1. 持续抢课 - 一直抢课直到抢上为止,每个请求间隔2秒
|
||||
2. 自动刷新Session - Session过期时自动调用update_session.py刷新
|
||||
3. 实时日志 - 抢课过程实时记录日志
|
||||
4. 并发抢课 - 多线程并发执行多个抢课任务
|
||||
"""
|
||||
import threading
|
||||
import time
|
||||
import json
|
||||
import logging
|
||||
import subprocess
|
||||
import sys
|
||||
from typing import Dict, Optional, Callable
|
||||
|
||||
from flask import current_app
|
||||
from app.time_utils import now as bj_now
|
||||
|
||||
# 导入选课API
|
||||
import sys as system_module
|
||||
from pathlib import Path
|
||||
system_module.path.insert(0, str(Path(__file__).parent.parent))
|
||||
from app.xk_api import CourseAPI
|
||||
|
||||
from app.models import db, GrabTask, GrabLog, User
|
||||
from app.session_manager import SessionManager
|
||||
from app.account_manager import AccountManager
|
||||
|
||||
# 配置日志
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(levelname)s - %(message)s'
|
||||
)
|
||||
from app.settings import (
|
||||
GRAB_INTERVAL_DAY_MIN, GRAB_INTERVAL_DAY_MAX,
|
||||
GRAB_INTERVAL_NIGHT_MIN, GRAB_INTERVAL_NIGHT_MAX,
|
||||
GRAB_TIME_A_START, GRAB_TIME_A_END,
|
||||
SESSION_RETRY_INTERVAL,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ── 随机抢课间隔(模拟人为) ──
|
||||
import random
|
||||
|
||||
def _grab_sleep():
|
||||
"""根据当前时间返回随机抢课间隔秒数"""
|
||||
hour = bj_now().hour
|
||||
if GRAB_TIME_A_START <= hour < GRAB_TIME_A_END:
|
||||
sec = random.uniform(GRAB_INTERVAL_DAY_MIN, GRAB_INTERVAL_DAY_MAX)
|
||||
else:
|
||||
sec = random.uniform(GRAB_INTERVAL_NIGHT_MIN, GRAB_INTERVAL_NIGHT_MAX)
|
||||
time.sleep(sec)
|
||||
|
||||
# 常量配置
|
||||
|
||||
class GrabEngine:
|
||||
"""
|
||||
抢课引擎 - 核心调度器
|
||||
|
||||
特点:
|
||||
- 持续抢课直到成功(间隔2秒)
|
||||
- Session过期自动刷新
|
||||
- 并发执行多个任务
|
||||
"""
|
||||
|
||||
_instance = None
|
||||
_lock = threading.Lock()
|
||||
|
||||
def __new__(cls):
|
||||
"""单例模式"""
|
||||
if cls._instance is None:
|
||||
with cls._lock:
|
||||
if cls._instance is None:
|
||||
cls._instance = super().__new__(cls)
|
||||
cls._instance._initialized = False
|
||||
return cls._instance
|
||||
|
||||
def __init__(self):
|
||||
if self._initialized:
|
||||
return
|
||||
|
||||
self._initialized = True
|
||||
self.running_tasks: Dict[int, threading.Event] = {} # task_id -> stop_event
|
||||
self._refresh_locks: Dict[int, threading.Lock] = {}
|
||||
self.scheduler_thread = None
|
||||
self.is_running = False
|
||||
self.app = None
|
||||
|
||||
def init_app(self, app):
|
||||
"""初始化Flask应用"""
|
||||
self.app = app
|
||||
|
||||
def start(self):
|
||||
"""启动抢课引擎"""
|
||||
if self.is_running:
|
||||
return
|
||||
|
||||
self.is_running = True
|
||||
|
||||
# 将所有任务上限改为 0(不限次数)
|
||||
try:
|
||||
with self.app.app_context():
|
||||
GrabTask.query.update({GrabTask.max_retries: 0}, synchronize_session=False)
|
||||
db.session.commit()
|
||||
except Exception as e:
|
||||
logger.error(f"[INIT] 重置任务次数失败: {e}")
|
||||
|
||||
# 恢复上次未完成的任务(服务器重启后)
|
||||
try:
|
||||
with self.app.app_context():
|
||||
unfinished = GrabTask.query.filter(
|
||||
GrabTask.status.in_([GrabTask.STATUS_RUNNING, GrabTask.STATUS_PENDING])
|
||||
).all()
|
||||
for task in unfinished:
|
||||
if task.status == GrabTask.STATUS_RUNNING:
|
||||
# 重启前正在跑的,标记回 pending 重新提交
|
||||
task.status = GrabTask.STATUS_PENDING
|
||||
db.session.commit()
|
||||
# 立即任务恢复执行;定时任务保留原定时刻,交由调度器触发。
|
||||
# 过去这里一律 immediate=True,会让服务器重启提前触发定时任务。
|
||||
self.submit_task(task.id, immediate=(task.task_type == GrabTask.TYPE_IMMEDIATE))
|
||||
logger.info(f"[RECOVER] 恢复任务 #{task.id}: {task.course_name}")
|
||||
except Exception as e:
|
||||
logger.error(f"[RECOVER] 恢复任务失败: {e}")
|
||||
|
||||
self.scheduler_thread = threading.Thread(target=self._scheduler_loop, daemon=True)
|
||||
self.scheduler_thread.start()
|
||||
logger.info("[OK] 抢课引擎已启动")
|
||||
|
||||
def stop(self):
|
||||
"""停止抢课引擎"""
|
||||
self.is_running = False
|
||||
|
||||
# 停止所有运行中的任务
|
||||
for task_id, stop_event in list(self.running_tasks.items()):
|
||||
stop_event.set()
|
||||
logger.info(f"[STOP] 停止任务 #{task_id}")
|
||||
|
||||
logger.info("[STOP] 抢课引擎已停止")
|
||||
|
||||
def _scheduler_loop(self):
|
||||
"""调度器主循环 - 检查并执行定时任务"""
|
||||
logger.info("[INFO] 调度器已启动")
|
||||
|
||||
while self.is_running:
|
||||
try:
|
||||
with self.app.app_context():
|
||||
# naive 北京时间:scheduled_time 入库时已归一化为 naive(见 /tasks/create)
|
||||
now = bj_now().replace(tzinfo=None)
|
||||
|
||||
# 查找待执行的定时任务
|
||||
pending_tasks = GrabTask.query.filter(
|
||||
GrabTask.task_type == GrabTask.TYPE_SCHEDULED,
|
||||
GrabTask.status == GrabTask.STATUS_PENDING,
|
||||
GrabTask.scheduled_time <= now
|
||||
).all()
|
||||
|
||||
for task in pending_tasks:
|
||||
logger.info(f"[SCHEDULE] 触发定时任务 #{task.id}: {task.course_name}")
|
||||
self._execute_task_async(task.id)
|
||||
|
||||
# 每秒检查一次
|
||||
time.sleep(1)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"调度器错误: {e}")
|
||||
time.sleep(5)
|
||||
|
||||
def submit_task(self, task_id: int, immediate: bool = False) -> bool:
|
||||
"""
|
||||
提交抢课任务
|
||||
|
||||
Args:
|
||||
task_id: 任务ID
|
||||
immediate: 是否立即执行(忽略定时设置)
|
||||
|
||||
Returns:
|
||||
bool: 是否成功提交
|
||||
"""
|
||||
with self.app.app_context():
|
||||
task = GrabTask.query.get(task_id)
|
||||
if not task:
|
||||
logger.error(f"[ERROR] 任务 #{task_id} 不存在")
|
||||
return False
|
||||
|
||||
if task.status == GrabTask.STATUS_RUNNING:
|
||||
logger.warning(f"[WARN] 任务 #{task_id} 已在运行中")
|
||||
return False
|
||||
|
||||
if immediate or task.task_type == GrabTask.TYPE_IMMEDIATE:
|
||||
# 立即执行
|
||||
return self._execute_task_async(task_id)
|
||||
else:
|
||||
# 定时任务,等待调度器执行
|
||||
logger.info(f"[PENDING] 任务 #{task_id} 已加入定时队列,将在 {task.scheduled_time} 执行")
|
||||
return True
|
||||
|
||||
def _execute_task_async(self, task_id: int) -> bool:
|
||||
"""为每个任务开辟一个独立线程"""
|
||||
stop_event = threading.Event()
|
||||
self.running_tasks[task_id] = stop_event
|
||||
|
||||
t = threading.Thread(target=self._grab_course_worker, args=(task_id, stop_event), daemon=True)
|
||||
t.start()
|
||||
return True
|
||||
|
||||
def _try_refresh_session(self, user) -> bool:
|
||||
"""
|
||||
尝试刷新用户Session(带每用户互斥锁,防止并发重复刷新)
|
||||
|
||||
Returns:
|
||||
bool: 是否刷新成功
|
||||
"""
|
||||
# 每用户互斥锁:同一时间只有一个线程能刷新该用户的 session
|
||||
lock = self._refresh_locks.setdefault(user.id, threading.Lock())
|
||||
if not lock.acquire(blocking=False):
|
||||
logger.info(f"[SESSION] 用户 {user.username} 的Session正在刷新中,跳过本次")
|
||||
return False
|
||||
try:
|
||||
logger.info(f"[SESSION] 尝试自动刷新用户 {user.username} 的Session")
|
||||
|
||||
# 检测是否是密码到期,先重置密码
|
||||
from app.account_manager import AccountManager
|
||||
jwxt_acc = AccountManager.get_jwxt_account(user_id=user.id, username=user.username)
|
||||
if jwxt_acc:
|
||||
pw_result = SessionManager.reset_password_expiry(
|
||||
jwxt_acc['username'], jwxt_acc['password']
|
||||
)
|
||||
if pw_result.get('success'):
|
||||
logger.info(f"密码已过期,已自动重置密码(用户 {user.id})")
|
||||
|
||||
# 使用SessionManager刷新
|
||||
result = SessionManager.refresh_session(user, force=True)
|
||||
|
||||
if result['success']:
|
||||
logger.info(f"[SESSION] Session刷新成功")
|
||||
return True
|
||||
else:
|
||||
logger.error(f"[SESSION] Session刷新失败: {result['message']}")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[SESSION] Session刷新异常: {e}")
|
||||
return False
|
||||
finally:
|
||||
lock.release()
|
||||
|
||||
def _grab_course_worker(self, task_id: int, stop_event: threading.Event):
|
||||
"""
|
||||
抢课工作线程 - 持续抢课直到成功
|
||||
|
||||
核心逻辑:
|
||||
1. 持续尝试选课,直到成功或任务被取消
|
||||
2. 每次请求间隔2秒
|
||||
3. Session过期时自动刷新
|
||||
"""
|
||||
with self.app.app_context():
|
||||
task = GrabTask.query.get(task_id)
|
||||
if not task:
|
||||
return
|
||||
|
||||
# 更新任务状态为运行中
|
||||
task.status = GrabTask.STATUS_RUNNING
|
||||
task.started_at = bj_now()
|
||||
db.session.commit()
|
||||
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_INFO,
|
||||
f"[START] 开始抢课: {task.course_name}",
|
||||
{'course_id': task.course_id})
|
||||
|
||||
# 获取用户和教务系统账号
|
||||
user = task.user
|
||||
jwxt_acc = AccountManager.get_jwxt_account(
|
||||
user_id=user.id, username=user.username
|
||||
)
|
||||
|
||||
if not jwxt_acc:
|
||||
task.status = GrabTask.STATUS_FAILED
|
||||
task.result_message = "未配置教务系统账号"
|
||||
task.completed_at = bj_now()
|
||||
db.session.commit()
|
||||
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_ERROR,
|
||||
f"[ERROR] 未配置教务系统账号")
|
||||
|
||||
if task_id in self.running_tasks:
|
||||
del self.running_tasks[task_id]
|
||||
return
|
||||
|
||||
jwxt_username = jwxt_acc['username']
|
||||
jwxt_password = jwxt_acc['password']
|
||||
|
||||
# 用户固定了线路 → 本线程所有请求走该线路(与其 session 文件匹配)
|
||||
from app.url_manager import push_school, pop_school
|
||||
from app.multi_line import get_user_line_url
|
||||
_line_url = get_user_line_url(jwxt_username, user.school_id)
|
||||
push_school(user.school_id, _line_url)
|
||||
if _line_url:
|
||||
logger.info(f"[LINE] 任务 #{task_id} 使用用户固定线路: {_line_url}")
|
||||
|
||||
# rules 结构校验:坏 rules 会让每轮循环抛异常、每 5 秒重试到选课结束
|
||||
try:
|
||||
_rules_obj = json.loads(task.rules) if task.rules else None
|
||||
if _rules_obj is not None and (
|
||||
not isinstance(_rules_obj, dict)
|
||||
or not isinstance(_rules_obj.get("on_has_vacancy", []), list)
|
||||
):
|
||||
raise ValueError("rules 必须为对象且 on_has_vacancy 必须为数组")
|
||||
except Exception as e:
|
||||
task.status = GrabTask.STATUS_FAILED
|
||||
task.result_message = f"抢课规则配置错误: {e}"
|
||||
task.completed_at = bj_now()
|
||||
db.session.commit()
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_ERROR,
|
||||
f"[ERROR] {task.result_message}")
|
||||
return
|
||||
|
||||
retry_count = 0
|
||||
success = False
|
||||
last_message = ""
|
||||
session_refreshed = False
|
||||
dropped_any = False
|
||||
dropped_courses = []
|
||||
try:
|
||||
# ── 回退辅助函数:抢课失败后把之前退的课加回来 ──
|
||||
def _fallback_readd(api, task, rules, task_id):
|
||||
if not dropped_courses:
|
||||
return
|
||||
for dc in dropped_courses:
|
||||
name = dc.get('course_name', '未知课程')
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_INFO,
|
||||
f"[FALLBACK] 尝试恢复「{name}」...")
|
||||
try:
|
||||
re_result = api.add_course(
|
||||
jxb_id=dc.get('jxb_id', ''),
|
||||
do_jxb_id=dc.get('do_jxb_id', ''),
|
||||
kch_id=dc.get('kch_id', ''),
|
||||
jxbzls=dc.get('jxbzls', '0'),
|
||||
kklxdm=dc.get('kklxdm', ''),
|
||||
kcmc=name,
|
||||
)
|
||||
if re_result.get('success'):
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_SUCCESS,
|
||||
f"[FALLBACK] 已恢复「{name}」✅")
|
||||
elif '已选' in (re_result.get('message', '') or ''):
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_INFO,
|
||||
f"[FALLBACK] 「{name}」已在选课列表中,无需恢复")
|
||||
else:
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_WARNING,
|
||||
f"[FALLBACK] 恢复「{name}」失败: {re_result.get('message', '')}")
|
||||
except Exception as e:
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_ERROR,
|
||||
f"[FALLBACK] 恢复「{name}」异常: {e}")
|
||||
time.sleep(1)
|
||||
|
||||
while not stop_event.is_set() and not success:
|
||||
retry_count += 1
|
||||
task.retry_count = retry_count
|
||||
db.session.commit()
|
||||
|
||||
|
||||
# 每轮重置规则状态
|
||||
rules_failed = False
|
||||
dropped_any = False
|
||||
dropped_courses = []
|
||||
|
||||
try:
|
||||
api = CourseAPI(jwxt_username)
|
||||
|
||||
# ── 阶段1:监控余量(不直接选课) ──
|
||||
jxb_result = api.get_jxb_list(
|
||||
kch_id=task.kch_id or "",
|
||||
cxbj="0",
|
||||
fxbj="0",
|
||||
kklxdm=task.kklxdm or "",
|
||||
)
|
||||
|
||||
if not jxb_result.get("success"):
|
||||
err_msg = jxb_result.get('message', '') or ''
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_WARNING,
|
||||
"[WATCH] 查询余量失败: " + err_msg)
|
||||
|
||||
# 检测是否 Session 过期
|
||||
is_session_error = (
|
||||
'session' in err_msg.lower() or
|
||||
'登录' in err_msg or
|
||||
'过期' in err_msg or
|
||||
'302' in err_msg or
|
||||
'901' in err_msg or
|
||||
'响应非 JSON' in err_msg or
|
||||
'非法访问' in err_msg or
|
||||
'无功能权限' in err_msg or
|
||||
'密码已到期' in err_msg
|
||||
)
|
||||
if is_session_error:
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_WARNING,
|
||||
"[SESSION] 监控阶段检测到Session过期,尝试自动刷新...")
|
||||
if self._try_refresh_session(user):
|
||||
session_refreshed = True
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_INFO,
|
||||
"[SESSION] Session刷新成功,继续监控")
|
||||
time.sleep(SESSION_RETRY_INTERVAL)
|
||||
continue
|
||||
else:
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_WARNING,
|
||||
"[SESSION] Session刷新失败,稍后重试")
|
||||
time.sleep(SESSION_RETRY_INTERVAL)
|
||||
continue
|
||||
|
||||
time.sleep(5)
|
||||
continue
|
||||
|
||||
# 在当前课程的所有教学班中找到目标 jxb
|
||||
target_jxb = None
|
||||
for jxb in jxb_result.get("jxbs", []):
|
||||
if jxb.get("jxb_id") == task.course_id:
|
||||
target_jxb = jxb
|
||||
break
|
||||
|
||||
if not target_jxb:
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_WARNING,
|
||||
"[WATCH] 未找到目标教学班,5秒后重试")
|
||||
time.sleep(5)
|
||||
continue
|
||||
|
||||
yxzrs_str = target_jxb.get("yxzrs", "0") or "0"
|
||||
jxbrl_str = target_jxb.get("jxbrl", "0") or "0"
|
||||
try:
|
||||
yxzrs = int(yxzrs_str)
|
||||
jxbrl = int(jxbrl_str)
|
||||
except (ValueError, TypeError):
|
||||
yxzrs, jxbrl = 0, 0
|
||||
|
||||
# 更新实时人数(供前端展示)
|
||||
task.class_info = f"{yxzrs}/{jxbrl}"
|
||||
db.session.commit()
|
||||
|
||||
if jxbrl > 0 and yxzrs >= jxbrl:
|
||||
# 满了:按设置间隔看余量
|
||||
if retry_count <= 5 or retry_count % 6 == 1:
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_INFO,
|
||||
"[WATCH] 余量 " + str(yxzrs) + "/" + str(jxbrl) + ",继续监控中...")
|
||||
_grab_sleep()
|
||||
continue
|
||||
|
||||
# ── 阶段2:有余量,执行自定义规则(如退课) ──
|
||||
rules = json.loads(task.rules) if task.rules else None
|
||||
if rules and rules.get("on_has_vacancy"):
|
||||
for rule in rules["on_has_vacancy"]:
|
||||
action = rule.get("action", "")
|
||||
if action == "drop_course":
|
||||
drop_jxb_id = rule.get("jxb_id", "")
|
||||
drop_do_jxb_id = rule.get("do_jxb_id", "")
|
||||
drop_kch_id = rule.get("kch_id", "")
|
||||
drop_name = rule.get("course_name", "未知课程")
|
||||
drop_jxbzls = rule.get("jxbzls", "0")
|
||||
drop_kklxdm = rule.get("kklxdm", "")
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_INFO,
|
||||
f"[RULE] 退课「{drop_name}」...")
|
||||
drop_result = api.drop_course(
|
||||
jxb_id=drop_jxb_id,
|
||||
do_jxb_id=drop_do_jxb_id,
|
||||
kch_id=drop_kch_id,
|
||||
)
|
||||
if drop_result.get('success'):
|
||||
dropped_any = True
|
||||
dropped_courses.append({
|
||||
'jxb_id': drop_jxb_id,
|
||||
'do_jxb_id': drop_do_jxb_id,
|
||||
'kch_id': drop_kch_id,
|
||||
'jxbzls': drop_jxbzls,
|
||||
'kklxdm': drop_kklxdm,
|
||||
'course_name': drop_name,
|
||||
})
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_SUCCESS,
|
||||
f"[RULE] 退课「{drop_name}」成功")
|
||||
time.sleep(1)
|
||||
else:
|
||||
msg = drop_result.get('message', '退课失败')
|
||||
# 如果课程已经不在选课列表(已被退过),视为跳过而非失败
|
||||
if any(kw in msg for kw in ('未选', '不存在', '不可退', '未在')):
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_INFO,
|
||||
f"[RULE] 「{drop_name}」已不在选课列表,跳过")
|
||||
else:
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_WARNING,
|
||||
f"[RULE] 退课「{drop_name}」失败: {msg}")
|
||||
rules_failed = True
|
||||
break
|
||||
elif action == "wait":
|
||||
seconds = rule.get("seconds", 2)
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_INFO,
|
||||
f"[RULE] 等待 {seconds} 秒...")
|
||||
time.sleep(seconds)
|
||||
|
||||
if rules_failed:
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_INFO,
|
||||
"[RULE] 前置操作失败,切回监控重试")
|
||||
time.sleep(2)
|
||||
continue
|
||||
|
||||
# ── 阶段3:选课 ──
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_INFO,
|
||||
"[GRAB] 检测到余量,开始选课!")
|
||||
result = api.add_course(
|
||||
jxb_id=task.course_id,
|
||||
do_jxb_id=target_jxb.get("do_jxb_id") or task.do_jxb_id or "",
|
||||
kch_id=task.kch_id or "",
|
||||
jxbzls=task.jxbzls or "0",
|
||||
kklxdm=task.kklxdm or "",
|
||||
kcmc=task.course_name or "",
|
||||
)
|
||||
|
||||
if result.get('success'):
|
||||
success = True
|
||||
last_message = result.get('message', '') or '选课成功!'
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_SUCCESS,
|
||||
"[SUCCESS] 抢课成功!" + last_message,
|
||||
{'retry_count': retry_count, 'result': result})
|
||||
break
|
||||
else:
|
||||
last_message = result.get('message', '') or '未知错误'
|
||||
|
||||
# 已选 → 视为成功
|
||||
if '已选' in last_message or '重复' in last_message:
|
||||
success = True
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_SUCCESS,
|
||||
"[SUCCESS] 课程已在选课列表中",
|
||||
{'retry_count': retry_count, 'result': result})
|
||||
break
|
||||
|
||||
# 被别人抢先了 → 切回监控继续等
|
||||
# (只匹配明确的"无余量/余量不足/容量",避免普通错误含"余量"被误判)
|
||||
if '无余量' in last_message or '余量不足' in last_message or '容量' in last_message:
|
||||
if dropped_any:
|
||||
# 已退课但抢课失败 —— 紧急回退:先把刚退的课抢回来
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_WARNING,
|
||||
"[GRAB] ⚠️ 已退课但被抢先了,尝试恢复已退课程...",
|
||||
{'retry_count': retry_count})
|
||||
_fallback_readd(api, task, rules, task_id)
|
||||
# 回退完成后继续监控,下次循环再试
|
||||
time.sleep(1)
|
||||
continue
|
||||
else:
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_WARNING,
|
||||
"[GRAB] 被抢先了(" + last_message + "),切回监控",
|
||||
{'retry_count': retry_count})
|
||||
time.sleep(1)
|
||||
continue
|
||||
|
||||
# Session 过期 → 自动刷新
|
||||
is_session_error = (
|
||||
'session' in last_message.lower() or
|
||||
'登录' in last_message or
|
||||
'过期' in last_message or
|
||||
'302' in last_message or
|
||||
'901' in last_message or
|
||||
'响应非 JSON' in last_message or
|
||||
'非法访问' in last_message or
|
||||
'无功能权限' in last_message or
|
||||
'密码已到期' in last_message
|
||||
)
|
||||
if is_session_error:
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_WARNING,
|
||||
"[SESSION] Session可能已过期,尝试自动刷新...",
|
||||
{'retry_count': retry_count, 'message': last_message})
|
||||
|
||||
if self._try_refresh_session(user):
|
||||
session_refreshed = True
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_INFO,
|
||||
"[SESSION] Session刷新成功,继续抢课")
|
||||
time.sleep(SESSION_RETRY_INTERVAL)
|
||||
continue
|
||||
else:
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_WARNING,
|
||||
"[SESSION] Session刷新失败,稍后重试")
|
||||
time.sleep(SESSION_RETRY_INTERVAL)
|
||||
continue
|
||||
|
||||
# 其他错误(冲突、学分已满等)
|
||||
if dropped_any:
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_WARNING,
|
||||
"[GRAB] 已退课但选课失败(" + last_message + "),尝试恢复已退课程...")
|
||||
_fallback_readd(api, task, rules, task_id)
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_WARNING,
|
||||
"[GRAB] 选课失败(" + last_message + "),切回监控重试",
|
||||
{'retry_count': retry_count})
|
||||
time.sleep(3)
|
||||
|
||||
except FileNotFoundError as e:
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_WARNING,
|
||||
"[SESSION] Session文件不存在,尝试自动刷新...")
|
||||
|
||||
if self._try_refresh_session(user):
|
||||
session_refreshed = True
|
||||
time.sleep(SESSION_RETRY_INTERVAL)
|
||||
continue
|
||||
else:
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_WARNING,
|
||||
"[SESSION] Session刷新失败,稍后重试")
|
||||
time.sleep(SESSION_RETRY_INTERVAL)
|
||||
continue
|
||||
|
||||
except Exception as e:
|
||||
logger.exception("抢课任务 #" + str(task_id) + " 异常")
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_ERROR,
|
||||
"[ERROR] 抢课异常: " + str(e),
|
||||
{'retry_count': retry_count})
|
||||
time.sleep(5)
|
||||
|
||||
# 更新任务状态
|
||||
if success:
|
||||
task.status = GrabTask.STATUS_SUCCESS
|
||||
task.result_message = f"抢课成功!{last_message}"
|
||||
elif stop_event.is_set():
|
||||
# 取消前若已退课,必须先尝试恢复,否则学生的课就丢了
|
||||
if dropped_any:
|
||||
try:
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_WARNING,
|
||||
"[FALLBACK] 任务取消但检测到已退课程,尝试恢复...",
|
||||
{'retry_count': retry_count})
|
||||
_fallback_readd(CourseAPI(jwxt_username), task, rules, task_id)
|
||||
except Exception as e:
|
||||
logger.warning(f"任务 #{task_id} 取消时恢复已退课程失败: {e}")
|
||||
task.status = GrabTask.STATUS_CANCELLED
|
||||
task.result_message = "任务被取消"
|
||||
elif dropped_any:
|
||||
task.status = GrabTask.STATUS_FAILED
|
||||
task.result_message = f"已退课但抢课失败: {last_message}(已退课程无法自动恢复,请手动处理)"
|
||||
else:
|
||||
task.status = GrabTask.STATUS_FAILED
|
||||
task.result_message = f"抢课失败: {last_message}"
|
||||
|
||||
task.completed_at = bj_now()
|
||||
db.session.commit()
|
||||
|
||||
self._add_log(task_id, task.user_id,
|
||||
GrabLog.LEVEL_SUCCESS if success else GrabLog.LEVEL_ERROR,
|
||||
f"[END] 任务结束: {task.result_message}",
|
||||
{'total_retries': retry_count, 'final_status': task.status})
|
||||
|
||||
except Exception as e:
|
||||
logger.exception(f"抢课任务 #{task_id} 严重异常")
|
||||
task.status = GrabTask.STATUS_FAILED
|
||||
task.result_message = f"执行异常: {str(e)}"
|
||||
task.completed_at = bj_now()
|
||||
db.session.commit()
|
||||
|
||||
self._add_log(task_id, task.user_id, GrabLog.LEVEL_ERROR,
|
||||
f"[ERROR] 执行异常: {str(e)}")
|
||||
|
||||
finally:
|
||||
# 清理
|
||||
try:
|
||||
pop_school()
|
||||
except Exception:
|
||||
pass
|
||||
if task_id in self.running_tasks:
|
||||
del self.running_tasks[task_id]
|
||||
|
||||
def cancel_task(self, task_id: int) -> bool:
|
||||
"""取消抢课任务"""
|
||||
with self.app.app_context():
|
||||
task = GrabTask.query.get(task_id)
|
||||
if not task:
|
||||
return False
|
||||
|
||||
if task.status == GrabTask.STATUS_RUNNING:
|
||||
# 停止运行中的任务
|
||||
if task_id in self.running_tasks:
|
||||
self.running_tasks[task_id].set()
|
||||
return True
|
||||
else:
|
||||
# 线程已不存在但状态可能已被 worker 更新(如成功/失败),重新检查
|
||||
db.session.refresh(task)
|
||||
if task.status != GrabTask.STATUS_RUNNING:
|
||||
# worker 已经处理完毕,无需操作
|
||||
return True
|
||||
task.status = GrabTask.STATUS_CANCELLED
|
||||
task.completed_at = bj_now()
|
||||
task.result_message = "任务已取消(线程已结束)"
|
||||
db.session.commit()
|
||||
return True
|
||||
elif task.status == GrabTask.STATUS_PENDING:
|
||||
# 取消待执行的任务
|
||||
task.status = GrabTask.STATUS_CANCELLED
|
||||
task.completed_at = bj_now()
|
||||
task.result_message = "任务已取消"
|
||||
db.session.commit()
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def _add_log(self, task_id: int, user_id: int, level: str, message: str, detail: dict = None):
|
||||
"""添加日志记录"""
|
||||
try:
|
||||
log = GrabLog(
|
||||
task_id=task_id,
|
||||
user_id=user_id,
|
||||
level=level,
|
||||
message=message,
|
||||
detail=json.dumps(detail, ensure_ascii=False) if detail else None
|
||||
)
|
||||
db.session.add(log)
|
||||
db.session.commit()
|
||||
except Exception as e:
|
||||
logger.error(f"添加日志失败: {e}")
|
||||
|
||||
# 全局抢课引擎实例
|
||||
grab_engine = GrabEngine()
|
||||
@@ -0,0 +1,886 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
IP管理模块
|
||||
- IP地理位置查询(geoip2 本地库,HTTP API 降级)
|
||||
- 中国IP检测
|
||||
- IP封禁/解封
|
||||
- 登录频率限制
|
||||
- 访问日志记录
|
||||
- 邮件解封指令解析
|
||||
"""
|
||||
import calendar
|
||||
import ipaddress
|
||||
import logging
|
||||
import re
|
||||
import smtplib
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from email.mime.text import MIMEText
|
||||
from typing import Optional, Tuple
|
||||
|
||||
import requests as http_requests
|
||||
from app.time_utils import now as bj_now, to_iso, BJ_TZ
|
||||
from app.settings import BASE_DIR
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Flask app 实例引用(用于后台线程的 app_context)
|
||||
_app_instance = None
|
||||
|
||||
# ── geoip2 本地库(GeoLite2)──
|
||||
# 延迟导入,避免未安装 geoip2 时整个模块无法加载
|
||||
_geoip_reader = None
|
||||
_geoip_reader_lock = threading.Lock()
|
||||
# 优先 City 库(含省市),没有则用 Country 库(仅国家,足够做中国IP判断)
|
||||
_GEOLITE_CITY_PATH = BASE_DIR / "GeoLite2-City.mmdb"
|
||||
_GEOLITE_COUNTRY_PATH = BASE_DIR / "GeoLite2-Country.mmdb"
|
||||
# 标记是否已打印过下载提示,避免每请求重复
|
||||
_geoip_warned = False
|
||||
|
||||
|
||||
def _get_geoip_reader():
|
||||
"""惰性加载 geoip2 本地库,优先 City 库,降级 Country 库,返回 reader 或 None"""
|
||||
global _geoip_reader, _geoip_warned
|
||||
if _geoip_reader is not None:
|
||||
return _geoip_reader
|
||||
with _geoip_reader_lock:
|
||||
if _geoip_reader is not None:
|
||||
return _geoip_reader
|
||||
try:
|
||||
import geoip2.database
|
||||
# 优先 City 库
|
||||
if _GEOLITE_CITY_PATH.exists():
|
||||
_geoip_reader = geoip2.database.Reader(str(_GEOLITE_CITY_PATH))
|
||||
logger.info(f"[ip_manager] GeoLite2 本地库已加载: {_GEOLITE_CITY_PATH.name}(City)")
|
||||
return _geoip_reader
|
||||
# 降级 Country 库(仅国家信息,足够做中国IP判断)
|
||||
if _GEOLITE_COUNTRY_PATH.exists():
|
||||
_geoip_reader = geoip2.database.Reader(str(_GEOLITE_COUNTRY_PATH))
|
||||
logger.info(f"[ip_manager] GeoLite2 本地库已加载: {_GEOLITE_COUNTRY_PATH.name}(Country,无省市)")
|
||||
return _geoip_reader
|
||||
# 两个库都没有
|
||||
if not _geoip_warned:
|
||||
_geoip_warned = True
|
||||
logger.warning(
|
||||
f"[ip_manager] 未找到 GeoLite2 库(City 或 Country)\n"
|
||||
f" 期望路径: {_GEOLITE_CITY_PATH} 或 {_GEOLITE_COUNTRY_PATH}\n"
|
||||
" IP 地理查询将降级到 HTTP API(延迟高、有并发瓶颈)\n"
|
||||
" 下载方式: python app/download_geolite2.py --account-id YOUR_ID --license-key YOUR_KEY"
|
||||
)
|
||||
return None
|
||||
except ImportError:
|
||||
if not _geoip_warned:
|
||||
_geoip_warned = True
|
||||
logger.warning("[ip_manager] geoip2 未安装,IP 查询降级到 HTTP API(pip install geoip2)")
|
||||
return None
|
||||
except Exception as e:
|
||||
if not _geoip_warned:
|
||||
_geoip_warned = True
|
||||
logger.warning(f"[ip_manager] GeoLite2 加载失败: {e},IP 查询降级到 HTTP API")
|
||||
return None
|
||||
|
||||
|
||||
def warmup_geoip_reader():
|
||||
"""启动时预热 GeoLite2 库(由 run.py 在 app.run 前调用)"""
|
||||
_get_geoip_reader()
|
||||
|
||||
|
||||
# geoip 本地查询结果缓存,避免重复查询
|
||||
_geo_cache: dict = {}
|
||||
_geo_cache_lock = threading.Lock()
|
||||
_GEO_CACHE_TTL = 3600 # 1小时
|
||||
|
||||
|
||||
def _utc_to_timestamp(dt: Optional[datetime]) -> Optional[int]:
|
||||
"""
|
||||
将 datetime 转为 Unix 时间戳(秒)
|
||||
支持 naive 和 aware datetime,自动识别时区
|
||||
"""
|
||||
if dt is None:
|
||||
return None
|
||||
if dt.tzinfo is None:
|
||||
# naive datetime,视为北京时间
|
||||
dt = dt.replace(tzinfo=BJ_TZ)
|
||||
return int(dt.timestamp())
|
||||
|
||||
|
||||
def _ensure_aware(dt: Optional[datetime]) -> Optional[datetime]:
|
||||
"""将 naive datetime 转换为 aware datetime(北京时间)"""
|
||||
if dt is None:
|
||||
return None
|
||||
if dt.tzinfo is None:
|
||||
return dt.replace(tzinfo=BJ_TZ)
|
||||
return dt
|
||||
|
||||
|
||||
def _set_app(app):
|
||||
"""由 ip_middleware 在 init 时调用,存储 app 引用"""
|
||||
global _app_instance
|
||||
_app_instance = app
|
||||
|
||||
|
||||
def _get_real_ip(request) -> str:
|
||||
"""从请求中获取真实IP。
|
||||
Nginx 覆盖 XFF 后由 ProxyFix(x_for=1) 写入 remote_addr,这里直接用
|
||||
remote_addr——不再信任裸 X-Forwarded-For/X-Real-IP 头(客户端可伪造,
|
||||
会被用来绕过封禁/伪造他人 IP)。"""
|
||||
return request.remote_addr or '127.0.0.1'
|
||||
|
||||
|
||||
def query_ip_geo(ip: str) -> dict:
|
||||
"""
|
||||
查询IP地理位置
|
||||
优先级:本地 geoip2 库(微秒级) → HTTP API 降级(ip-api.com/ipinfo.io/freeipapi)
|
||||
返回结构:
|
||||
{
|
||||
'country': 'CN', # 国家代码
|
||||
'country_name': '中国',
|
||||
'region': '山东',
|
||||
'city': '济南',
|
||||
'isp': 'China Unicom',
|
||||
'lat': 36.67,
|
||||
'lon': 116.99,
|
||||
'success': True
|
||||
}
|
||||
"""
|
||||
# 本地/私有IP直接返回中国
|
||||
try:
|
||||
addr = ipaddress.ip_address(ip)
|
||||
if addr.is_private or addr.is_loopback or addr.is_unspecified:
|
||||
return {
|
||||
'country': 'CN', 'country_name': '中国(本地)',
|
||||
'region': '本地', 'city': '本地',
|
||||
'isp': 'Local', 'lat': 0, 'lon': 0, 'success': True
|
||||
}
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# 查缓存
|
||||
now = time.time()
|
||||
with _geo_cache_lock:
|
||||
if ip in _geo_cache:
|
||||
entry, ts = _geo_cache[ip]
|
||||
if now - ts < _GEO_CACHE_TTL:
|
||||
return entry
|
||||
|
||||
result = {'country': '', 'country_name': '', 'region': '', 'city': '',
|
||||
'isp': '', 'lat': 0, 'lon': 0, 'success': False}
|
||||
|
||||
# 1. 优先使用本地 geoip2 库(微秒级,无网络开销)
|
||||
reader = _get_geoip_reader()
|
||||
if reader is not None:
|
||||
try:
|
||||
# City 库有 city() 方法,Country 库只有 country() 方法
|
||||
db_type = getattr(reader.metadata(), 'database_type', '')
|
||||
if 'City' in db_type:
|
||||
resp = reader.city(ip)
|
||||
result = {
|
||||
'country': resp.country.iso_code or '',
|
||||
'country_name': resp.country.name or '',
|
||||
'region': (resp.subdivisions.most_specific.name or '') if resp.subdivisions.most_specific else '',
|
||||
'city': resp.city.name or '',
|
||||
'isp': '', # City 库不含 ISP,需 ASN 库;留空
|
||||
'lat': resp.location.latitude or 0,
|
||||
'lon': resp.location.longitude or 0,
|
||||
'success': True
|
||||
}
|
||||
else:
|
||||
# Country 库只有国家信息,省市/经纬度留空(足够做中国IP判断)
|
||||
resp = reader.country(ip)
|
||||
result = {
|
||||
'country': resp.country.iso_code or '',
|
||||
'country_name': resp.country.name or '',
|
||||
'region': '', 'city': '', 'isp': '',
|
||||
'lat': 0, 'lon': 0,
|
||||
'success': True
|
||||
}
|
||||
except Exception:
|
||||
pass # 本地库查不到(如内网 IP 段),降级 HTTP
|
||||
|
||||
# 2. 本地库不可用或查不到,降级到 HTTP API
|
||||
if not result['success']:
|
||||
# 2a. ip-api.com(HTTPS + HTTP 降级)
|
||||
for scheme in ('https', 'http'):
|
||||
try:
|
||||
resp_data = http_requests.get(
|
||||
f'{scheme}://ip-api.com/json/{ip}',
|
||||
params={'lang': 'zh-CN', 'fields': 'status,country,countryCode,regionName,city,isp,lat,lon,query'},
|
||||
timeout=(2, 5)
|
||||
)
|
||||
data = resp_data.json()
|
||||
if data.get('status') == 'success':
|
||||
result = {
|
||||
'country': data.get('countryCode', ''),
|
||||
'country_name': data.get('country', ''),
|
||||
'region': data.get('regionName', ''),
|
||||
'city': data.get('city', ''),
|
||||
'isp': data.get('isp', ''),
|
||||
'lat': data.get('lat', 0),
|
||||
'lon': data.get('lon', 0),
|
||||
'success': True
|
||||
}
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
# 2b. ip-api 失败时,尝试备用 API(ipinfo.io)
|
||||
if not result['success']:
|
||||
for scheme in ('https', 'http'):
|
||||
try:
|
||||
resp_data = http_requests.get(
|
||||
f'{scheme}://ipinfo.io/{ip}/json',
|
||||
timeout=(2, 5)
|
||||
)
|
||||
data = resp_data.json()
|
||||
if 'country' in data:
|
||||
result = {
|
||||
'country': data.get('country', ''),
|
||||
'country_name': '',
|
||||
'region': data.get('region', ''),
|
||||
'city': data.get('city', ''),
|
||||
'isp': data.get('org', ''),
|
||||
'lat': 0,
|
||||
'lon': 0,
|
||||
'success': True
|
||||
}
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
# 2c. ipinfo 也失败,尝试 freeipapi
|
||||
if not result['success']:
|
||||
for scheme in ('https', 'http'):
|
||||
try:
|
||||
resp_data = http_requests.get(
|
||||
f'{scheme}://freeipapi.com/api/json/{ip}',
|
||||
timeout=(2, 5)
|
||||
)
|
||||
data = resp_data.json()
|
||||
if data.get('statusCode') == 200:
|
||||
result = {
|
||||
'country': data.get('countryCode', ''),
|
||||
'country_name': data.get('countryName', ''),
|
||||
'region': data.get('regionName', ''),
|
||||
'city': data.get('cityName', ''),
|
||||
'isp': '',
|
||||
'lat': 0,
|
||||
'lon': 0,
|
||||
'success': True
|
||||
}
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
with _geo_cache_lock:
|
||||
_geo_cache[ip] = (result, now)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def is_china_ip(ip: str) -> Tuple[bool, dict]:
|
||||
"""
|
||||
判断是否是中国IP(含港澳台)
|
||||
返回 (is_china: bool, geo_info: dict)
|
||||
"""
|
||||
geo = query_ip_geo(ip)
|
||||
# 中国大陆 + 港澳台
|
||||
china_codes = {'CN', 'HK', 'MO', 'TW'}
|
||||
return geo.get('country', '') in china_codes, geo
|
||||
|
||||
|
||||
# ==================== 封禁管理 ====================
|
||||
|
||||
def parse_ban_duration(duration_str: Optional[str]) -> Optional[datetime]:
|
||||
"""
|
||||
解析封禁时长字符串,返回到期时间(None=永久)
|
||||
支持: 1h, 1d, 1w, 1m, permanent/forever/None
|
||||
"""
|
||||
if not duration_str or duration_str.lower() in ('permanent', 'forever', 'perm', '永久'):
|
||||
return None # 永久
|
||||
|
||||
duration_str = duration_str.strip().lower()
|
||||
now = bj_now()
|
||||
|
||||
m = re.match(r'^(\d+)([hdwm])$', duration_str)
|
||||
if not m:
|
||||
return None
|
||||
|
||||
num, unit = int(m.group(1)), m.group(2)
|
||||
if unit == 'h':
|
||||
return now + timedelta(hours=num)
|
||||
elif unit == 'd':
|
||||
return now + timedelta(days=num)
|
||||
elif unit == 'w':
|
||||
return now + timedelta(weeks=num)
|
||||
elif unit == 'm':
|
||||
return now + timedelta(days=num * 30)
|
||||
return None
|
||||
|
||||
|
||||
def ban_ip(ip_or_cidr: str, reason: str = '', duration_str: Optional[str] = None,
|
||||
ban_type: str = 'ip', created_by: str = 'admin') -> dict:
|
||||
"""
|
||||
封禁一个IP/CIDR/国家代码
|
||||
duration_str: None=永久, '1h'=1小时, '1d'=1天, '1w'=1周, '1m'=1个月
|
||||
"""
|
||||
from app.models import db, IPBan
|
||||
|
||||
expires_at = parse_ban_duration(duration_str)
|
||||
is_permanent = (expires_at is None)
|
||||
|
||||
# 检查是否已存在
|
||||
existing = IPBan.query.filter_by(ban_type=ban_type, value=ip_or_cidr).first()
|
||||
if existing:
|
||||
existing.reason = reason or existing.reason
|
||||
existing.is_permanent = is_permanent
|
||||
existing.expires_at = expires_at
|
||||
existing.created_by = created_by
|
||||
existing.created_at = bj_now()
|
||||
db.session.commit()
|
||||
_invalidate_ban_cache()
|
||||
return {'success': True, 'message': f'已更新封禁: {ip_or_cidr}', 'id': existing.id}
|
||||
|
||||
ban = IPBan(
|
||||
ban_type=ban_type,
|
||||
value=ip_or_cidr,
|
||||
reason=reason,
|
||||
is_permanent=is_permanent,
|
||||
expires_at=expires_at,
|
||||
created_by=created_by
|
||||
)
|
||||
db.session.add(ban)
|
||||
db.session.commit()
|
||||
_invalidate_ban_cache()
|
||||
logger.info(f"[ip_manager] 封禁 {ban_type}:{ip_or_cidr} 原因={reason} 到期={expires_at} 操作={created_by}")
|
||||
return {'success': True, 'message': f'封禁成功: {ip_or_cidr}', 'id': ban.id}
|
||||
|
||||
|
||||
def unban_ip(ip_or_cidr: str, ban_type: str = 'ip') -> dict:
|
||||
"""解封IP/CIDR/国家代码"""
|
||||
from app.models import db, IPBan, LoginAttempt
|
||||
|
||||
bans = IPBan.query.filter_by(ban_type=ban_type, value=ip_or_cidr).all()
|
||||
if not bans:
|
||||
return {'success': False, 'message': f'未找到封禁记录: {ip_or_cidr}'}
|
||||
|
||||
for ban in bans:
|
||||
db.session.delete(ban)
|
||||
|
||||
# 解封时清除该IP的失败登录记录,防止解封后立即又被封
|
||||
LoginAttempt.query.filter_by(ip=ip_or_cidr).delete()
|
||||
|
||||
db.session.commit()
|
||||
_invalidate_ban_cache()
|
||||
logger.info(f"[ip_manager] 解封 {ban_type}:{ip_or_cidr},已清除登录失败记录")
|
||||
return {'success': True, 'message': f'解封成功: {ip_or_cidr}'}
|
||||
|
||||
|
||||
# ── is_ip_banned 内存缓存 ──
|
||||
# 缓存 (ip, country) → (is_banned, reason, expires_at, cached_ts)
|
||||
_ban_cache: dict = {}
|
||||
_ban_cache_lock = threading.Lock()
|
||||
_BAN_CACHE_TTL = 10 # 秒,封禁状态变化后最多 10 秒生效
|
||||
|
||||
|
||||
def _invalidate_ban_cache():
|
||||
"""清除全部封禁缓存(封禁/解封操作后调用)"""
|
||||
with _ban_cache_lock:
|
||||
_ban_cache.clear()
|
||||
|
||||
|
||||
def is_ip_banned(ip: str, country: str = '') -> Tuple[bool, str, Optional[datetime]]:
|
||||
"""
|
||||
检查IP是否被封禁
|
||||
返回 (is_banned: bool, reason: str, expires_at: Optional[datetime])
|
||||
带 10 秒内存缓存,封禁状态变化后最多 10 秒生效
|
||||
"""
|
||||
from app.models import IPBan
|
||||
|
||||
now = bj_now()
|
||||
cache_key = (ip, country.upper())
|
||||
|
||||
# 查缓存
|
||||
now_ts = time.time()
|
||||
with _ban_cache_lock:
|
||||
entry = _ban_cache.get(cache_key)
|
||||
if entry is not None:
|
||||
is_banned, reason, expires_at, cached_ts = entry
|
||||
if now_ts - cached_ts < _BAN_CACHE_TTL:
|
||||
return is_banned, reason, expires_at
|
||||
|
||||
# 缓存未命中,查数据库
|
||||
result_banned = False
|
||||
result_reason = ''
|
||||
result_expires = None
|
||||
|
||||
# 1. 检查精确IP封禁
|
||||
exact = IPBan.query.filter_by(ban_type='ip', value=ip).first()
|
||||
if exact and (exact.is_permanent or (exact.expires_at and _ensure_aware(exact.expires_at) > now)):
|
||||
result_banned = True
|
||||
result_reason = exact.reason or 'IP已被封禁'
|
||||
result_expires = None if exact.is_permanent else exact.expires_at
|
||||
|
||||
# 2. 检查CIDR段封禁
|
||||
if not result_banned:
|
||||
cidr_bans = IPBan.query.filter_by(ban_type='cidr').all()
|
||||
try:
|
||||
client_addr = ipaddress.ip_address(ip)
|
||||
for ban in cidr_bans:
|
||||
if not (ban.is_permanent or (ban.expires_at and _ensure_aware(ban.expires_at) > now)):
|
||||
continue
|
||||
try:
|
||||
network = ipaddress.ip_network(ban.value, strict=False)
|
||||
if client_addr in network:
|
||||
result_banned = True
|
||||
result_reason = ban.reason or f'IP段 {ban.value} 已被封禁'
|
||||
result_expires = None if ban.is_permanent else ban.expires_at
|
||||
break
|
||||
except ValueError:
|
||||
pass
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# 3. 检查国家封禁
|
||||
if not result_banned and country:
|
||||
country_ban = IPBan.query.filter_by(ban_type='country', value=country.upper()).first()
|
||||
if country_ban and (country_ban.is_permanent or (country_ban.expires_at and _ensure_aware(country_ban.expires_at) > now)):
|
||||
result_banned = True
|
||||
result_reason = country_ban.reason or f'地区 {country} 已被限制访问'
|
||||
result_expires = None if country_ban.is_permanent else country_ban.expires_at
|
||||
|
||||
# 写缓存
|
||||
with _ban_cache_lock:
|
||||
_ban_cache[cache_key] = (result_banned, result_reason, result_expires, now_ts)
|
||||
|
||||
return result_banned, result_reason, result_expires
|
||||
|
||||
|
||||
# ==================== 访问日志 ====================
|
||||
|
||||
# 异步写日志队列,避免每次请求都同步写DB
|
||||
_log_queue = []
|
||||
_log_lock = threading.Lock()
|
||||
_LOG_BATCH_SIZE = 50
|
||||
_last_flush = time.time()
|
||||
|
||||
|
||||
def record_access(ip: str, geo: dict, method: str, path: str,
|
||||
status_code: int = 0, user_agent: str = '',
|
||||
blocked: bool = False, block_reason: str = ''):
|
||||
"""记录访问日志(批量异步写入)"""
|
||||
entry = {
|
||||
'ip': ip,
|
||||
'country': geo.get('country', ''),
|
||||
'region': geo.get('region', ''),
|
||||
'city': geo.get('city', ''),
|
||||
'isp': geo.get('isp', ''),
|
||||
'method': method,
|
||||
'path': path[:500] if path else '',
|
||||
'status_code': status_code,
|
||||
'user_agent': user_agent[:500] if user_agent else '',
|
||||
'blocked': blocked,
|
||||
'block_reason': block_reason,
|
||||
'created_at': bj_now()
|
||||
}
|
||||
with _log_lock:
|
||||
_log_queue.append(entry)
|
||||
should_flush = len(_log_queue) >= _LOG_BATCH_SIZE
|
||||
|
||||
if should_flush:
|
||||
_flush_logs()
|
||||
|
||||
|
||||
def _flush_logs():
|
||||
"""将队列中的日志批量写入数据库"""
|
||||
global _last_flush
|
||||
with _log_lock:
|
||||
if not _log_queue:
|
||||
return
|
||||
batch = _log_queue[:]
|
||||
_log_queue.clear()
|
||||
_last_flush = time.time()
|
||||
|
||||
try:
|
||||
from app.models import db, IPAccessLog
|
||||
app = _app_instance
|
||||
if app is None:
|
||||
logger.warning("[ip_manager] Flask app 未初始化,跳过日志写入")
|
||||
return
|
||||
with app.app_context():
|
||||
for entry in batch:
|
||||
log = IPAccessLog(**entry)
|
||||
db.session.add(log)
|
||||
db.session.commit()
|
||||
except Exception as e:
|
||||
logger.warning(f"[ip_manager] 写访问日志失败: {e}")
|
||||
|
||||
|
||||
def flush_logs_if_needed():
|
||||
"""定期刷新(在每次请求后调用)"""
|
||||
global _last_flush
|
||||
if time.time() - _last_flush > 10: # 超过10秒就刷一次
|
||||
threading.Thread(target=_flush_logs, daemon=True).start()
|
||||
|
||||
|
||||
# ==================== 登录频率限制 ====================
|
||||
|
||||
def check_login_rate_limit(ip: str, window_minutes: int = 10, max_attempts: int = 10) -> Tuple[bool, str]:
|
||||
"""
|
||||
检查登录频率限制
|
||||
window_minutes: 时间窗口(分钟)
|
||||
max_attempts: 窗口内最大失败次数
|
||||
返回 (is_limited: bool, message: str)
|
||||
"""
|
||||
from app.models import db, LoginAttempt, IPBan
|
||||
|
||||
now = bj_now()
|
||||
window_start = now - timedelta(minutes=window_minutes)
|
||||
|
||||
# 统计窗口内失败次数
|
||||
fail_count = LoginAttempt.query.filter(
|
||||
LoginAttempt.ip == ip,
|
||||
LoginAttempt.success == False,
|
||||
LoginAttempt.created_at >= window_start
|
||||
).count()
|
||||
|
||||
if fail_count >= max_attempts:
|
||||
# 自动封禁1小时
|
||||
existing = IPBan.query.filter_by(ban_type='ip', value=ip).first()
|
||||
if not existing:
|
||||
ban_ip(ip, reason=f'登录失败频率超限({window_minutes}分钟内失败{fail_count}次)',
|
||||
duration_str='1h', created_by='auto')
|
||||
logger.warning(f"[ip_manager] 自动封禁IP {ip}(登录失败{fail_count}次/{window_minutes}分钟)")
|
||||
return True, f'登录尝试过于频繁,已被临时封禁1小时'
|
||||
|
||||
return False, ''
|
||||
|
||||
|
||||
def record_login_attempt(ip: str, username: str, success: bool):
|
||||
"""记录一次登录尝试"""
|
||||
from app.models import db, LoginAttempt
|
||||
|
||||
attempt = LoginAttempt(ip=ip, username=username, success=success)
|
||||
db.session.add(attempt)
|
||||
db.session.commit()
|
||||
|
||||
# 清理7天前的记录
|
||||
cutoff = bj_now() - timedelta(days=7)
|
||||
LoginAttempt.query.filter(LoginAttempt.created_at < cutoff).delete()
|
||||
db.session.commit()
|
||||
|
||||
|
||||
# ==================== 邮件解封指令 ====================
|
||||
|
||||
def parse_unban_email_command(subject: str) -> Optional[dict]:
|
||||
"""
|
||||
解析邮件解封指令
|
||||
格式: unban [ip|all] [duration]
|
||||
例如:
|
||||
unban => 解封所有IP,1小时后重新封禁
|
||||
unban 1.2.3.4 1d => 解封IP 1.2.3.4,封禁1天后再封
|
||||
unban 1.2.3.4 => 永久解封
|
||||
unban all => 解封所有(永久)
|
||||
unban all 1h => 解封所有IP,1小时后重新封禁
|
||||
unban 1.2.3.4 1h => 短暂解封1小时(解封后1小时重新封禁)
|
||||
返回 None 或 {'ip': ..., 'duration': ...}
|
||||
"""
|
||||
subject = subject.strip()
|
||||
# 匹配 unban 后面可选的 ip/all 和 duration
|
||||
m = re.match(r'^unban(?:\s+(\S+))?(?:\s+(\S+))?$', subject, re.IGNORECASE)
|
||||
if not m:
|
||||
return None
|
||||
|
||||
ip_val = m.group(1).strip() if m.group(1) else None
|
||||
duration = m.group(2).strip() if m.group(2) else None
|
||||
|
||||
# 如果只有 unban 没有参数,默认解封所有IP 1小时
|
||||
if ip_val is None:
|
||||
return {'ip': 'all', 'duration': '1h'}
|
||||
|
||||
return {'ip': ip_val, 'duration': duration}
|
||||
|
||||
|
||||
def check_unban_emails(app, processed_ids=None, max_age_seconds=60, save_callback=None):
|
||||
"""
|
||||
检查邮箱中的解封指令(IMAP)
|
||||
在独立线程中定期调用
|
||||
Args:
|
||||
app: Flask应用实例
|
||||
processed_ids: 已处理的邮件ID集合
|
||||
max_age_seconds: 超过此秒数的邮件将被忽略
|
||||
save_callback: 保存已处理ID的回调函数
|
||||
"""
|
||||
import os
|
||||
from email.utils import parsedate_to_datetime
|
||||
|
||||
if processed_ids is None:
|
||||
processed_ids = set()
|
||||
current_time = time.time()
|
||||
newly_processed = set()
|
||||
import imaplib
|
||||
import email as email_lib
|
||||
from email.header import decode_header
|
||||
|
||||
mail = None
|
||||
try:
|
||||
email_cfg = _load_email_config()
|
||||
if not email_cfg:
|
||||
return
|
||||
smtp_server, email_addr, password = email_cfg
|
||||
# QQ邮箱IMAP服务器
|
||||
imap_server = smtp_server.replace('smtp.', 'imap.')
|
||||
|
||||
mail = imaplib.IMAP4_SSL(imap_server, timeout=20) # 无超时会挂死整轮检查
|
||||
mail.login(email_addr, password)
|
||||
mail.select('INBOX')
|
||||
|
||||
# 搜索所有邮件,主题包含 unban(已读的也要处理)
|
||||
_, msgs = mail.search(None, 'SUBJECT "unban"')
|
||||
msg_ids = msgs[0].split()
|
||||
|
||||
if not msg_ids:
|
||||
return # finally 统一 logout
|
||||
|
||||
with app.app_context():
|
||||
for msg_id in msg_ids:
|
||||
msg_id_str = msg_id.decode() if isinstance(msg_id, bytes) else msg_id
|
||||
|
||||
_, data = mail.fetch(msg_id, '(RFC822)')
|
||||
raw = data[0][1]
|
||||
msg = email_lib.message_from_bytes(raw)
|
||||
|
||||
# 去重键用 Message-ID:IMAP 序列号跨会话会漂移(删信/新信),
|
||||
# 曾导致新解封指令的序列号恰好命中历史记录而被静默跳过
|
||||
dedup_id = (msg.get('Message-ID') or '').strip() or f'seq-{msg_id_str}'
|
||||
if dedup_id in processed_ids:
|
||||
continue
|
||||
|
||||
# 检查邮件发送时间,超过60秒忽略
|
||||
date_header = msg.get('Date', '')
|
||||
try:
|
||||
if date_header:
|
||||
email_time = parsedate_to_datetime(date_header)
|
||||
email_timestamp = email_time.timestamp()
|
||||
if current_time - email_timestamp > max_age_seconds:
|
||||
logger.info(f"[ip_manager] 忽略超时邮件: {msg_id_str} ({(current_time - email_timestamp):.0f}秒前)")
|
||||
newly_processed.add(dedup_id)
|
||||
continue
|
||||
except Exception:
|
||||
pass # 无法解析时间则不跳过
|
||||
|
||||
# 解码主题
|
||||
subject_raw = msg.get('Subject', '')
|
||||
subject_parts = decode_header(subject_raw)
|
||||
subject = ''
|
||||
for part, enc in subject_parts:
|
||||
if isinstance(part, bytes):
|
||||
subject += part.decode(enc or 'utf-8', errors='replace')
|
||||
else:
|
||||
subject += part
|
||||
|
||||
# 检查发件人是否是自己(安全验证)
|
||||
sender = msg.get('From', '')
|
||||
if email_addr not in sender:
|
||||
logger.info(f"[ip_manager] 忽略非本人邮件解封指令: from={sender}")
|
||||
# 标记为已读但不处理
|
||||
mail.store(msg_id, '+FLAGS', '\\Seen')
|
||||
newly_processed.add(dedup_id)
|
||||
continue
|
||||
|
||||
cmd = parse_unban_email_command(subject)
|
||||
if not cmd:
|
||||
mail.store(msg_id, '+FLAGS', '\\Seen')
|
||||
newly_processed.add(dedup_id)
|
||||
continue
|
||||
|
||||
# 标记为已处理
|
||||
newly_processed.add(dedup_id)
|
||||
|
||||
ip_val = cmd['ip']
|
||||
duration = cmd['duration']
|
||||
|
||||
if ip_val.lower() == 'all':
|
||||
# 解封所有
|
||||
from app.models import db, IPBan
|
||||
if duration:
|
||||
# 短暂解封:将所有封禁临时推迟 duration
|
||||
expires = parse_ban_duration(duration)
|
||||
if expires is None and duration.lower() not in ('permanent', 'forever', 'perm', '永久'):
|
||||
logger.warning(f"[ip_manager] 时长 '{duration}' 无法解析,按永久解封处理")
|
||||
bans = IPBan.query.filter_by(ban_type='ip').all()
|
||||
for b in bans:
|
||||
b.expires_at = expires
|
||||
b.is_permanent = False
|
||||
db.session.commit()
|
||||
logger.info(f"[ip_manager] 邮件指令:短暂解封所有IP,{duration}后恢复")
|
||||
else:
|
||||
IPBan.query.filter_by(ban_type='ip').delete()
|
||||
db.session.commit()
|
||||
logger.info(f"[ip_manager] 邮件指令:永久解封所有IP")
|
||||
else:
|
||||
if duration:
|
||||
# 短暂解封:将该IP封禁到期时间设为 duration 后
|
||||
from app.models import db, IPBan
|
||||
expires = parse_ban_duration(duration)
|
||||
if expires is None and duration.lower() not in ('permanent', 'forever', 'perm', '永久'):
|
||||
logger.warning(f"[ip_manager] 时长 '{duration}' 无法解析,IP {ip_val} 按永久解封处理")
|
||||
unban_ip(ip_val)
|
||||
mail.store(msg_id, '+FLAGS', '\\Seen')
|
||||
continue
|
||||
ban = IPBan.query.filter_by(ban_type='ip', value=ip_val).first()
|
||||
if ban:
|
||||
ban.expires_at = expires
|
||||
ban.is_permanent = False
|
||||
db.session.commit()
|
||||
logger.info(f"[ip_manager] 邮件指令:短暂解封IP {ip_val},{duration}后恢复")
|
||||
else:
|
||||
unban_ip(ip_val)
|
||||
logger.info(f"[ip_manager] 邮件指令:永久解封IP {ip_val}")
|
||||
|
||||
mail.store(msg_id, '+FLAGS', '\\Seen')
|
||||
|
||||
# 保存已处理的邮件ID
|
||||
if save_callback and newly_processed:
|
||||
all_ids = processed_ids | newly_processed
|
||||
save_callback(all_ids)
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"[ip_manager] 检查解封邮件失败: {e}")
|
||||
finally:
|
||||
if mail:
|
||||
try:
|
||||
mail.logout()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _load_email_config():
|
||||
"""读取 email.txt 配置"""
|
||||
import os
|
||||
email_file = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'email.txt')
|
||||
try:
|
||||
with open(email_file, encoding='utf-8') as f:
|
||||
lines = [l.strip() for l in f.readlines() if l.strip()]
|
||||
if len(lines) >= 3:
|
||||
return lines[0], lines[1], lines[2]
|
||||
except Exception as e:
|
||||
logger.warning(f"[ip_manager] 读取email.txt失败: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def start_email_unban_checker(app, interval_seconds: int = 60):
|
||||
"""启动邮件解封检查后台线程(每60秒检查一次)"""
|
||||
import os
|
||||
import json
|
||||
from email.utils import parsedate_to_datetime
|
||||
|
||||
# 已处理邮件ID存储文件
|
||||
processed_file = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'processed_unban_emails.json')
|
||||
max_age_seconds = 120 # 超过 2×轮询间隔 的邮件忽略(防 IMAP 卡顿时误丢解封指令)
|
||||
|
||||
def _load_processed():
|
||||
try:
|
||||
if os.path.exists(processed_file):
|
||||
with open(processed_file, 'r', encoding='utf-8') as f:
|
||||
return set(json.load(f))
|
||||
except:
|
||||
pass
|
||||
return set()
|
||||
|
||||
def _save_processed(ids):
|
||||
try:
|
||||
with open(processed_file, 'w', encoding='utf-8') as f:
|
||||
json.dump(list(ids), f)
|
||||
except:
|
||||
pass
|
||||
|
||||
def _worker():
|
||||
time.sleep(10) # 延迟10秒启动
|
||||
while True:
|
||||
try:
|
||||
processed_ids = _load_processed()
|
||||
check_unban_emails(app, processed_ids, max_age_seconds, _save_processed)
|
||||
except Exception as e:
|
||||
logger.warning(f"[ip_manager] 邮件解封检查异常: {e}")
|
||||
time.sleep(interval_seconds)
|
||||
|
||||
t = threading.Thread(target=_worker, daemon=True, name='email-unban-checker')
|
||||
t.start()
|
||||
logger.info("[ip_manager] 邮件解封检查线程已启动")
|
||||
|
||||
|
||||
# ==================== 统计 ====================
|
||||
|
||||
def get_ip_stats(hours: int = 24) -> dict:
|
||||
"""获取IP访问统计"""
|
||||
from app.models import db, IPAccessLog
|
||||
from sqlalchemy import func
|
||||
|
||||
cutoff = bj_now() - timedelta(hours=hours)
|
||||
|
||||
# 总访问量
|
||||
total = IPAccessLog.query.filter(IPAccessLog.created_at >= cutoff).count()
|
||||
blocked = IPAccessLog.query.filter(
|
||||
IPAccessLog.created_at >= cutoff,
|
||||
IPAccessLog.blocked == True
|
||||
).count()
|
||||
|
||||
# 按国家分组
|
||||
by_country = db.session.query(
|
||||
IPAccessLog.country,
|
||||
func.count(IPAccessLog.id).label('count')
|
||||
).filter(
|
||||
IPAccessLog.created_at >= cutoff
|
||||
).group_by(IPAccessLog.country).order_by(func.count(IPAccessLog.id).desc()).limit(20).all()
|
||||
|
||||
# 按省份分组(中国)
|
||||
by_region = db.session.query(
|
||||
IPAccessLog.region,
|
||||
func.count(IPAccessLog.id).label('count')
|
||||
).filter(
|
||||
IPAccessLog.created_at >= cutoff,
|
||||
IPAccessLog.country == 'CN'
|
||||
).group_by(IPAccessLog.region).order_by(func.count(IPAccessLog.id).desc()).limit(20).all()
|
||||
|
||||
# Top IP
|
||||
top_ips = db.session.query(
|
||||
IPAccessLog.ip,
|
||||
IPAccessLog.country,
|
||||
IPAccessLog.region,
|
||||
IPAccessLog.city,
|
||||
func.count(IPAccessLog.id).label('count')
|
||||
).filter(
|
||||
IPAccessLog.created_at >= cutoff
|
||||
).group_by(IPAccessLog.ip).order_by(func.count(IPAccessLog.id).desc()).limit(20).all()
|
||||
|
||||
# 按小时分布(最近24h)
|
||||
by_hour = db.session.query(
|
||||
func.date_format(IPAccessLog.created_at, '%H').label('hour'),
|
||||
func.count(IPAccessLog.id).label('count')
|
||||
).filter(
|
||||
IPAccessLog.created_at >= cutoff
|
||||
).group_by(func.date_format(IPAccessLog.created_at, '%H')).all()
|
||||
|
||||
|
||||
# 活跃封禁数(在 Python 侧计算比较时间,避免 naive/aware datetime 问题)
|
||||
from app.models import IPBan
|
||||
ban_cutoff = bj_now() + timedelta(hours=8)
|
||||
active_bans = IPBan.query.filter(
|
||||
(IPBan.is_permanent == True) |
|
||||
(IPBan.expires_at.isnot(None) & (IPBan.expires_at > ban_cutoff))
|
||||
).count()
|
||||
|
||||
return {
|
||||
'total': total,
|
||||
'blocked': blocked,
|
||||
'active_bans': active_bans,
|
||||
'unique_ips': db.session.query(func.count(func.distinct(IPAccessLog.ip))).filter(
|
||||
IPAccessLog.created_at >= cutoff).scalar() or 0,
|
||||
'by_country': [{'country': r.country or '未知', 'count': r.count} for r in by_country],
|
||||
'by_region': [{'region': r.region or '未知', 'count': r.count} for r in by_region],
|
||||
'top_ips': [{'ip': r.ip, 'country': r.country, 'region': r.region,
|
||||
'city': r.city, 'count': r.count} for r in top_ips],
|
||||
'by_hour': [{'hour': r.hour, 'count': r.count} for r in by_hour],
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
IP访问控制中间件
|
||||
- 拦截非中国IP
|
||||
- 拦截已封禁IP
|
||||
- 记录访问日志
|
||||
跳过静态资源、/blocked、/api/admin/ip/unban_temp 等路由
|
||||
"""
|
||||
import logging
|
||||
from flask import request, render_template, g
|
||||
|
||||
from app.ip_manager import (
|
||||
_get_real_ip, query_ip_geo, is_china_ip, is_ip_banned,
|
||||
record_access, flush_logs_if_needed, _set_app, _utc_to_timestamp
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 不做IP检测的路径前缀
|
||||
_SKIP_PREFIXES = (
|
||||
'/static/',
|
||||
'/blocked',
|
||||
'/favicon.ico',
|
||||
'/notify', # 支付平台回调:来源 IP 不可控(可能境外/数据中心),不能被 IP 风控拦截
|
||||
)
|
||||
|
||||
# 不记日志的路径(太频繁)
|
||||
_NO_LOG_PREFIXES = (
|
||||
'/static/',
|
||||
'/favicon.ico',
|
||||
)
|
||||
|
||||
|
||||
def _should_skip(path: str) -> bool:
|
||||
return any(path.startswith(p) for p in _SKIP_PREFIXES)
|
||||
|
||||
|
||||
def _should_log(path: str) -> bool:
|
||||
return not any(path.startswith(p) for p in _NO_LOG_PREFIXES)
|
||||
|
||||
|
||||
def init_ip_middleware(app):
|
||||
"""注册IP中间件到Flask应用"""
|
||||
_set_app(app)
|
||||
|
||||
@app.before_request
|
||||
def ip_guard():
|
||||
path = request.path
|
||||
if _should_skip(path):
|
||||
return None
|
||||
|
||||
ip = _get_real_ip(request)
|
||||
g.client_ip = ip # 挂到g上,路由层可以直接用
|
||||
|
||||
# 查询地理位置(带缓存)
|
||||
geo = query_ip_geo(ip)
|
||||
g.client_geo = geo
|
||||
|
||||
country = geo.get('country', '')
|
||||
g.client_country = country
|
||||
|
||||
# 1. 检查是否已被封禁
|
||||
banned, ban_reason, expires_at = is_ip_banned(ip, country)
|
||||
if banned:
|
||||
if _should_log(path):
|
||||
record_access(ip, geo, request.method, path,
|
||||
status_code=403,
|
||||
user_agent=request.headers.get('User-Agent', ''),
|
||||
blocked=True, block_reason=ban_reason)
|
||||
flush_logs_if_needed()
|
||||
return render_template('blocked.html',
|
||||
ip=ip,
|
||||
reason=ban_reason,
|
||||
expires_at=_utc_to_timestamp(expires_at) if expires_at else None,
|
||||
block_type='banned'), 403
|
||||
|
||||
# 2. 检查是否中国IP(仅在启用中国限制时)
|
||||
try:
|
||||
from app.models import SystemConfig
|
||||
china_only = SystemConfig.get('enable_china_only', 'true').lower() == 'true'
|
||||
except Exception:
|
||||
china_only = True
|
||||
|
||||
if china_only:
|
||||
china, _ = is_china_ip(ip)
|
||||
# 保守策略:geo查询失败也当作非中国IP处理(拦截未知来源)
|
||||
if not china:
|
||||
if _should_log(path):
|
||||
record_access(ip, geo, request.method, path,
|
||||
status_code=403,
|
||||
user_agent=request.headers.get('User-Agent', ''),
|
||||
blocked=True, block_reason='非中国IP')
|
||||
flush_logs_if_needed()
|
||||
return render_template('blocked.html',
|
||||
ip=ip,
|
||||
reason='检测到您的IP来自境外,本服务仅对中国大陆用户开放',
|
||||
block_type='foreign'), 403
|
||||
|
||||
# 3. 正常放行,记录访问日志
|
||||
if _should_log(path):
|
||||
record_access(ip, geo, request.method, path,
|
||||
user_agent=request.headers.get('User-Agent', ''),
|
||||
blocked=False)
|
||||
|
||||
return None
|
||||
|
||||
@app.after_request
|
||||
def after_ip_log(response):
|
||||
"""更新日志状态码 + 定期刷新"""
|
||||
flush_logs_if_needed()
|
||||
return response
|
||||
|
||||
logger.info("[ip_middleware] IP访问控制中间件已注册")
|
||||
@@ -0,0 +1,447 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
教务系统登录脚本 - 使用 ddddocr 识别验证码
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
import re
|
||||
import requests
|
||||
import ddddocr
|
||||
from pathlib import Path
|
||||
import json
|
||||
import base64
|
||||
from Crypto.PublicKey import RSA
|
||||
from Crypto.Cipher import PKCS1_v1_5
|
||||
from Crypto import Random
|
||||
|
||||
# 从统一配置读取默认地址(运行时动态获取当前最优地址)
|
||||
from app.url_manager import get_base_url
|
||||
|
||||
|
||||
# OCR 模型加载耗时(数百 ms~秒级),模块级单例复用
|
||||
_OCR_SINGLETON = None
|
||||
|
||||
|
||||
def _get_ocr():
|
||||
global _OCR_SINGLETON
|
||||
if _OCR_SINGLETON is None:
|
||||
_OCR_SINGLETON = ddddocr.DdddOcr()
|
||||
return _OCR_SINGLETON
|
||||
|
||||
|
||||
class JWXTLogin:
|
||||
"""教务系统登录类"""
|
||||
|
||||
def __init__(self, base_url=None):
|
||||
"""
|
||||
初始化
|
||||
:param base_url: 教务系统基础URL,默认从 settings.BASE_URL 读取
|
||||
"""
|
||||
self.base_url = (base_url or get_base_url()).rstrip('/')
|
||||
from app.school_manager import list_schools, requires_captcha
|
||||
from app.url_manager import current_school_id
|
||||
active_school = current_school_id()
|
||||
if active_school:
|
||||
self.requires_captcha = requires_captcha(active_school)
|
||||
else:
|
||||
self.requires_captcha = next((s.get('requires_captcha', True)
|
||||
for s in list_schools() if self.base_url in s['urls']), True)
|
||||
from urllib.parse import urlparse
|
||||
parsed = urlparse(self.base_url)
|
||||
self._origin = f"{parsed.scheme}://{parsed.netloc}"
|
||||
self.session = requests.Session()
|
||||
self.ocr = _get_ocr() if self.requires_captcha else None
|
||||
|
||||
# 设置请求头
|
||||
self.session.headers.update({
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
|
||||
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
|
||||
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
|
||||
})
|
||||
|
||||
def get_captcha(self):
|
||||
"""
|
||||
获取验证码图片
|
||||
:return: 验证码图片内容和图片URL
|
||||
"""
|
||||
captcha_url = f"{self.base_url}/kaptcha"
|
||||
params = {'time': int(time.time() * 1000)}
|
||||
|
||||
response = self.session.get(captcha_url, params=params, timeout=(5, 15))
|
||||
response.raise_for_status()
|
||||
|
||||
return response.content, f"{captcha_url}?{params['time']}"
|
||||
|
||||
def get_rsa_public_key(self):
|
||||
"""
|
||||
获取RSA公钥
|
||||
:return: modulus, exponent
|
||||
"""
|
||||
url = f"{self.base_url}/xtgl/login_getPublicKey.html"
|
||||
params = {'time': int(time.time() * 1000)}
|
||||
|
||||
response = self.session.get(url, params=params, timeout=(5, 15))
|
||||
response.raise_for_status()
|
||||
|
||||
data = response.json()
|
||||
return data['modulus'], data['exponent']
|
||||
|
||||
def rsa_encrypt_password(self, password, modulus, exponent):
|
||||
"""
|
||||
使用RSA公钥加密密码
|
||||
:param password: 明文密码
|
||||
:param modulus: RSA模数
|
||||
:param exponent: RSA指数
|
||||
:return: Base64编码的加密密码
|
||||
"""
|
||||
# 将base64的modulus和exponent转换为数字
|
||||
modulus_int = int.from_bytes(base64.b64decode(modulus), byteorder='big')
|
||||
exponent_int = int.from_bytes(base64.b64decode(exponent), byteorder='big')
|
||||
|
||||
# 创建RSA公钥对象
|
||||
key = RSA.construct((modulus_int, exponent_int))
|
||||
|
||||
# 加密密码
|
||||
cipher = PKCS1_v1_5.new(key)
|
||||
encrypted_password = cipher.encrypt(password.encode('utf-8'))
|
||||
|
||||
# 转换为base64
|
||||
return base64.b64encode(encrypted_password).decode('utf-8')
|
||||
|
||||
def recognize_captcha(self, image_data):
|
||||
"""
|
||||
使用 ddddocr 识别验证码
|
||||
:param image_data: 验证码图片二进制数据
|
||||
:return: (识别结果, 耗时ms)
|
||||
"""
|
||||
try:
|
||||
t0 = time.perf_counter()
|
||||
result = self.ocr.classification(image_data)
|
||||
ms = int((time.perf_counter() - t0) * 1000)
|
||||
return result, ms
|
||||
except Exception as e:
|
||||
print(f"验证码识别失败: {e}")
|
||||
return None, 0
|
||||
|
||||
@staticmethod
|
||||
def _validate_captcha_format(code):
|
||||
"""
|
||||
校验验证码格式:必须为6位字母+数字组合
|
||||
:param code: OCR 识别结果
|
||||
:return: True 格式正确, False 格式错误
|
||||
"""
|
||||
if not code:
|
||||
return False
|
||||
import re
|
||||
return bool(re.fullmatch(r'[a-zA-Z0-9]{6}', code))
|
||||
|
||||
def login(self, username, password, captcha_code=None):
|
||||
"""
|
||||
登录教务系统(单次尝试,不含重试)
|
||||
:param username: 用户名
|
||||
:param password: 密码
|
||||
:param captcha_code: 验证码(如果为None则自动获取并识别)
|
||||
:return: {
|
||||
'success': bool,
|
||||
'message': str,
|
||||
'ocr_ms': int, # OCR 识别耗时(ms)
|
||||
'total_ms': int, # 登录总耗时(ms)
|
||||
'steps': { # 各步骤耗时(ms)
|
||||
'get_page_ms': int,
|
||||
'captcha_ms': int,
|
||||
'get_rsa_ms': int,
|
||||
'encrypt_ms': int,
|
||||
'post_login_ms': int,
|
||||
}
|
||||
}
|
||||
"""
|
||||
t_start = time.perf_counter()
|
||||
steps = {}
|
||||
|
||||
# 先访问登录页面获取csrftoken(必须在获取验证码之前,否则登录页会刷新验证码session)
|
||||
print("正在获取登录页面...")
|
||||
t0 = time.perf_counter()
|
||||
login_page_url = f"{self.base_url}/xtgl/login_slogin.html"
|
||||
response = self.session.get(login_page_url, timeout=(5, 15))
|
||||
steps['get_page_ms'] = int((time.perf_counter() - t0) * 1000)
|
||||
|
||||
# 如果没有提供验证码,则自动获取并识别(必须在访问登录页之后)
|
||||
ocr_ms = 0
|
||||
if captcha_code is None and self.requires_captcha:
|
||||
max_ocr_retries = 2
|
||||
for ocr_attempt in range(1, max_ocr_retries + 1):
|
||||
print(f"正在获取验证码 (第{ocr_attempt}次)...")
|
||||
t0 = time.perf_counter()
|
||||
captcha_img, _ = self.get_captcha()
|
||||
steps['captcha_ms'] = int((time.perf_counter() - t0) * 1000)
|
||||
|
||||
print(f"正在识别验证码...")
|
||||
raw_code, ocr_ms = self.recognize_captcha(captcha_img)
|
||||
print(f"识别到的验证码: {raw_code}")
|
||||
|
||||
if not raw_code:
|
||||
print(f"验证码识别失败,准备重试...")
|
||||
continue
|
||||
|
||||
if self._validate_captcha_format(raw_code):
|
||||
captcha_code = raw_code
|
||||
print(f"验证码格式校验通过: {captcha_code}")
|
||||
break
|
||||
else:
|
||||
print(f"验证码格式异常(期望6位字母数字,实际={len(raw_code) if raw_code else 0}位'{raw_code}'), 重新识别...")
|
||||
captcha_code = None
|
||||
|
||||
if not captcha_code:
|
||||
return {
|
||||
'success': False,
|
||||
'message': f'验证码识别失败(已尝试{max_ocr_retries}次OCR)',
|
||||
'ocr_ms': ocr_ms,
|
||||
'total_ms': int((time.perf_counter() - t_start) * 1000),
|
||||
'steps': steps,
|
||||
}
|
||||
else:
|
||||
steps['captcha_ms'] = 0
|
||||
|
||||
# 从页面中提取csrftoken
|
||||
csrftoken_match = re.search(r'<input[^>]*name="csrftoken"[^>]*value="([^"]+)"', response.text)
|
||||
csrftoken = csrftoken_match.group(1) if csrftoken_match else ''
|
||||
|
||||
# 获取RSA公钥并加密密码
|
||||
print("正在获取RSA公钥...")
|
||||
t0 = time.perf_counter()
|
||||
modulus, exponent = self.get_rsa_public_key()
|
||||
steps['get_rsa_ms'] = int((time.perf_counter() - t0) * 1000)
|
||||
|
||||
print("正在加密密码...")
|
||||
t0 = time.perf_counter()
|
||||
encrypted_password = self.rsa_encrypt_password(password, modulus, exponent)
|
||||
steps['encrypt_ms'] = int((time.perf_counter() - t0) * 1000)
|
||||
print("密码加密完成")
|
||||
|
||||
# 构造登录表单数据
|
||||
login_url = f"{self.base_url}/xtgl/login_slogin.html"
|
||||
data = {
|
||||
'yhm': username,
|
||||
'mm': encrypted_password, # 使用加密后的密码
|
||||
'yzm': captcha_code or '',
|
||||
'csrftoken': csrftoken,
|
||||
'language': 'zh_CN',
|
||||
'dlmmsfknt': '0',
|
||||
'ydappsfbldlzt': '0',
|
||||
'yzcskz': '-1',
|
||||
'mmsfjm': '1', # 密码需要加密
|
||||
'mmsrddcshkzfs': '0',
|
||||
'dlsbsdsj': '3',
|
||||
}
|
||||
|
||||
# 添加时间戳
|
||||
login_url_with_time = f"{login_url}?time={int(time.time() * 1000)}"
|
||||
|
||||
print(f"正在登录用户: {username}")
|
||||
t0 = time.perf_counter()
|
||||
response = self.session.post(
|
||||
login_url_with_time,
|
||||
data=data,
|
||||
allow_redirects=False,
|
||||
timeout=(5, 15)
|
||||
)
|
||||
steps['post_login_ms'] = int((time.perf_counter() - t0) * 1000)
|
||||
total_ms = int((time.perf_counter() - t_start) * 1000)
|
||||
|
||||
# 检查是否登录成功
|
||||
# 注意: 服务器可能返回二次重定向,第一跳是登录页,第二跳才是首页
|
||||
if response.status_code == 302:
|
||||
location = response.headers.get('Location', '')
|
||||
print(f"第一跳重定向到: {location}")
|
||||
# 直接成功的标志
|
||||
if 'index_initMenu.html' in location or 'auth_loginSuccess.html' in location:
|
||||
print("[OK] 登录成功!")
|
||||
return {'success': True, 'message': '登录成功', 'ocr_ms': ocr_ms, 'total_ms': total_ms, 'steps': steps}
|
||||
# 第一跳回到登录页,可能是二次重定向(实际已登录)
|
||||
if 'login_slogin.html' in location or location.endswith('/login_slogin.html'):
|
||||
# 跟随第二跳,看是否跳到首页
|
||||
# 注意:Location 已经包含 /jwglxt path,所以用 origin(不含路径)拼接
|
||||
second_url = location if location.startswith('http') else f"{self._origin}{location}"
|
||||
r2 = self.session.get(second_url, allow_redirects=False, timeout=(5, 15))
|
||||
location2 = r2.headers.get('Location', '')
|
||||
print(f"第二跳重定向到: {location2}")
|
||||
if 'index_initMenu.html' in location2 or 'auth_loginSuccess.html' in location2:
|
||||
print("[OK] 登录成功! (二次重定向)")
|
||||
return {'success': True, 'message': '登录成功', 'ocr_ms': ocr_ms, 'total_ms': total_ms, 'steps': steps}
|
||||
print(f"[FAIL] 登录失败,重定向到: {location}")
|
||||
return {'success': False, 'message': f'登录失败: {location}', 'ocr_ms': ocr_ms, 'total_ms': total_ms, 'steps': steps}
|
||||
elif response.status_code == 200:
|
||||
print("[FAIL] 登录失败,返回了登录页面")
|
||||
# 尝试查找错误信息
|
||||
if '用户名或密码不正确' in response.text:
|
||||
msg = '用户名或密码不正确'
|
||||
elif '验证码错误' in response.text or '验证码不正确' in response.text:
|
||||
msg = '验证码错误'
|
||||
elif '密码已到期' in response.text or '修改密码' in response.text or '密码过期' in response.text:
|
||||
# 密码到期:重试无意义,标记 stop_retry 让上层立即终止
|
||||
msg = '密码已到期,请修改密码后重试'
|
||||
print(f"错误: {msg}")
|
||||
return {'success': False, 'message': msg, 'stop_retry': True,
|
||||
'ocr_ms': ocr_ms, 'total_ms': total_ms, 'steps': steps}
|
||||
else:
|
||||
msg = '登录失败'
|
||||
print(f"错误: {msg}")
|
||||
return {'success': False, 'message': msg, 'ocr_ms': ocr_ms, 'total_ms': total_ms, 'steps': steps}
|
||||
else:
|
||||
print(f"[FAIL] 登录失败,状态码: {response.status_code}")
|
||||
return {'success': False, 'message': f'登录失败(状态码{response.status_code})', 'ocr_ms': ocr_ms, 'total_ms': total_ms, 'steps': steps}
|
||||
|
||||
def login_with_retry(self, username, password, max_retries=3):
|
||||
"""
|
||||
登录教务系统(含重试)
|
||||
:param username: 用户名
|
||||
:param password: 密码
|
||||
:param max_retries: 最大重试次数
|
||||
:return: {
|
||||
'success': bool,
|
||||
'message': str,
|
||||
'timing': {
|
||||
'attempts': int, # 尝试次数
|
||||
'total_ms': int, # 总耗时
|
||||
'ocr_ms': int, # 最后一次OCR耗时
|
||||
'ocr_avg_ms': int, # 平均OCR耗时(attempts>1时有值)
|
||||
}
|
||||
}
|
||||
"""
|
||||
t_start = time.perf_counter()
|
||||
ocr_times = []
|
||||
|
||||
for attempt in range(1, max_retries + 1):
|
||||
print(f"\n尝试第 {attempt}/{max_retries} 次登录...")
|
||||
result = self.login(username, password)
|
||||
|
||||
if result.get('ocr_ms'):
|
||||
ocr_times.append(result['ocr_ms'])
|
||||
|
||||
if result['success']:
|
||||
total_ms = int((time.perf_counter() - t_start) * 1000)
|
||||
return {
|
||||
'success': True,
|
||||
'message': result['message'],
|
||||
'timing': {
|
||||
'attempts': attempt,
|
||||
'total_ms': total_ms,
|
||||
'ocr_ms': result['ocr_ms'],
|
||||
'ocr_avg_ms': int(sum(ocr_times) / len(ocr_times)) if len(ocr_times) > 1 else 0,
|
||||
}
|
||||
}
|
||||
|
||||
if attempt < max_retries:
|
||||
print(f"第 {attempt} 次登录失败: {result['message']}, 正在重试...")
|
||||
|
||||
total_ms = int((time.perf_counter() - t_start) * 1000)
|
||||
return {
|
||||
'success': False,
|
||||
'message': f'登录失败(已尝试{max_retries}次): {result["message"]}',
|
||||
'timing': {
|
||||
'attempts': max_retries,
|
||||
'total_ms': total_ms,
|
||||
'ocr_ms': ocr_times[-1] if ocr_times else 0,
|
||||
'ocr_avg_ms': int(sum(ocr_times) / len(ocr_times)) if len(ocr_times) > 1 else 0,
|
||||
}
|
||||
}
|
||||
|
||||
def save_session(self):
|
||||
"""
|
||||
保存会话信息到文件
|
||||
"""
|
||||
# 保存 Cookie 到文件
|
||||
with open(COOKIE_JAR_FILE, 'w') as f:
|
||||
for cookie in self.session.cookies:
|
||||
f.write(f"{cookie.name}={cookie.value}\n")
|
||||
|
||||
# 保存会话信息到 JSON 文件
|
||||
session_info = {
|
||||
'cookies': dict(self.session.cookies),
|
||||
'headers': dict(self.session.headers),
|
||||
}
|
||||
|
||||
with open(SESSION_FILE, 'w', encoding='utf-8') as f:
|
||||
json.dump(session_info, f, ensure_ascii=False, indent=2)
|
||||
|
||||
print(f"会话已保存到 {SESSION_FILE} 和 {COOKIE_JAR_FILE}")
|
||||
|
||||
def load_session(self):
|
||||
"""
|
||||
从文件加载会话信息
|
||||
:return: 是否加载成功
|
||||
"""
|
||||
if not os.path.exists(SESSION_FILE):
|
||||
print(f"会话文件不存在: {SESSION_FILE}")
|
||||
return False
|
||||
|
||||
try:
|
||||
with open(SESSION_FILE, 'r', encoding='utf-8') as f:
|
||||
session_info = json.load(f)
|
||||
|
||||
# 恢复 cookies
|
||||
self.session.cookies.update(session_info.get('cookies', {}))
|
||||
|
||||
print("会话加载成功")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"会话加载失败: {e}")
|
||||
return False
|
||||
|
||||
def test_session(self):
|
||||
"""
|
||||
测试会话是否有效
|
||||
:return: 会话是否有效
|
||||
"""
|
||||
test_url = f"{self.base_url}/xtgl/index_initMenu.html"
|
||||
try:
|
||||
response = self.session.get(test_url, allow_redirects=False, timeout=(5, 15))
|
||||
return response.status_code == 200
|
||||
except:
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
print("=" * 50)
|
||||
print("教务系统登录脚本")
|
||||
print("=" * 50)
|
||||
|
||||
# 创建登录实例
|
||||
login = JWXTLogin()
|
||||
|
||||
# 尝试加载已有会话
|
||||
if os.path.exists(SESSION_FILE):
|
||||
print("\n检测到已有会话文件,正在测试...")
|
||||
if login.load_session():
|
||||
if login.test_session():
|
||||
print("[OK] 会话有效,无需重新登录")
|
||||
return
|
||||
else:
|
||||
print("[FAIL] 会话已失效,需要重新登录")
|
||||
|
||||
# 输入用户名和密码
|
||||
username = input("\n请输入用户名: ").strip()
|
||||
password = input("请输入密码: ").strip()
|
||||
|
||||
if not username or not password:
|
||||
print("用户名和密码不能为空!")
|
||||
return
|
||||
|
||||
# 登录(含重试)
|
||||
result = login.login_with_retry(username, password, max_retries=3)
|
||||
|
||||
if result['success']:
|
||||
login.save_session()
|
||||
t = result['timing']
|
||||
print(f"\n[OK] 登录完成! 尝试 {t['attempts']} 次, 总耗时 {t['total_ms']}ms")
|
||||
if t['ocr_avg_ms']:
|
||||
print(f"OCR 平均耗时: {t['ocr_avg_ms']}ms")
|
||||
else:
|
||||
print(f"\n[FAIL] {result['message']}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,189 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
SQLite → MySQL 数据迁移脚本
|
||||
|
||||
用法:
|
||||
# 先装依赖
|
||||
pip install pymysql
|
||||
|
||||
# 确保 MySQL 已建库(utf8mb4)
|
||||
# CREATE DATABASE sdmu CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
# 执行迁移(环境变量配置目标 MySQL)
|
||||
MYSQL_HOST=localhost MYSQL_PORT=3306 MYSQL_USER=root MYSQL_PASSWORD=xxx MYSQL_DB=sdmu \
|
||||
python3 app/migrate_to_mysql.py
|
||||
|
||||
# 或用命令行参数
|
||||
python3 app/migrate_to_mysql.py --host localhost --port 3306 --user root --password xxx --db sdmu
|
||||
|
||||
# --dry-run 只打印不写
|
||||
python3 app/migrate_to_mysql.py --host ... --dry-run
|
||||
|
||||
注意:
|
||||
本脚本直接用 SQLAlchemy 连 MySQL 建表+插数据,不走 create_app(),
|
||||
不会启动抢课引擎等后台线程,可安全运行。
|
||||
建表依赖 app/models.py 里的模型定义(仅取 db 元数据,不初始化应用)。
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# 添加项目路径
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent))
|
||||
|
||||
|
||||
def _build_mysql_uri(host, port, user, password, db):
|
||||
"""构造 MySQL 连接串"""
|
||||
return f"mysql+pymysql://{user}:{password}@{host}:{port}/{db}?charset=utf8mb4"
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="SQLite → MySQL 数据迁移")
|
||||
parser.add_argument('--host', default=os.environ.get('MYSQL_HOST', 'localhost'))
|
||||
parser.add_argument('--port', type=int, default=int(os.environ.get('MYSQL_PORT', '3306')))
|
||||
parser.add_argument('--user', default=os.environ.get('MYSQL_USER', 'root'))
|
||||
parser.add_argument('--password', default=os.environ.get('MYSQL_PASSWORD', ''))
|
||||
parser.add_argument('--db', default=os.environ.get('MYSQL_DB', 'sdmu'))
|
||||
parser.add_argument('--sqlite', default=str(Path(__file__).parent.parent / 'app.db'),
|
||||
help='SQLite 文件路径(默认 app.db)')
|
||||
parser.add_argument('--dry-run', action='store_true', help='只读不写,打印每表行数')
|
||||
parser.add_argument('--batch-size', type=int, default=500, help='批量插入大小')
|
||||
args = parser.parse_args()
|
||||
|
||||
# ===== 0. 在导入 app 之前设好 DATABASE_URL,避免 config 读到 SQLite =====
|
||||
mysql_uri = _build_mysql_uri(args.host, args.port, args.user, args.password, args.db)
|
||||
os.environ['DATABASE_URL'] = mysql_uri
|
||||
|
||||
from sqlalchemy import create_engine, MetaData, select, text
|
||||
|
||||
# ===== 1. 读 SQLite =====
|
||||
sqlite_uri = f"sqlite:///{args.sqlite}"
|
||||
if not Path(args.sqlite).exists():
|
||||
print(f"[ERROR] SQLite 文件不存在: {args.sqlite}")
|
||||
sys.exit(1)
|
||||
|
||||
print(f"[1/4] 读取 SQLite: {args.sqlite}")
|
||||
sqlite_engine = create_engine(sqlite_uri, echo=False)
|
||||
sqlite_meta = MetaData()
|
||||
sqlite_meta.reflect(bind=sqlite_engine)
|
||||
|
||||
tables = sorted(sqlite_meta.tables.keys())
|
||||
print(f" 发现 {len(tables)} 张表: {', '.join(tables)}")
|
||||
|
||||
# 先读全部数据到内存
|
||||
all_data = {}
|
||||
for table_name in tables:
|
||||
table = sqlite_meta.tables[table_name]
|
||||
with sqlite_engine.connect() as conn:
|
||||
rows = conn.execute(select(table)).fetchall()
|
||||
all_data[table_name] = [dict(row._mapping) for row in rows]
|
||||
print(f" {table_name}: {len(all_data[table_name])} 行")
|
||||
|
||||
if args.dry_run:
|
||||
print("\n[dry-run] 只读模式,不写入 MySQL")
|
||||
total = sum(len(v) for v in all_data.values())
|
||||
print(f"[dry-run] 共 {total} 行待迁移")
|
||||
return
|
||||
|
||||
# ===== 2. 连 MySQL 并建表 =====
|
||||
print(f"\n[2/4] 连接 MySQL: {args.host}:{args.port}/{args.db}")
|
||||
try:
|
||||
mysql_engine = create_engine(mysql_uri, echo=False)
|
||||
with mysql_engine.connect() as conn:
|
||||
conn.execute(text("SELECT 1"))
|
||||
except Exception as e:
|
||||
print(f"[ERROR] 连接 MySQL 失败: {e}")
|
||||
print(" 请确认:")
|
||||
print(" 1. MySQL 已启动")
|
||||
print(f" 2. 数据库 {args.db} 已创建(utf8mb4)")
|
||||
print(" CREATE DATABASE sdmu CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;")
|
||||
print(" 3. 用户名密码正确")
|
||||
sys.exit(1)
|
||||
|
||||
# 用模型定义建表(只导入 models 注册表结构,不调 create_app)
|
||||
print(" 建表(先删旧表)...")
|
||||
from app.models import db
|
||||
# 先删旧表(上次迁移可能建了字段长度不够的表)
|
||||
db.metadata.drop_all(mysql_engine)
|
||||
# 用模型注册的 metadata 在 MySQL 上建表
|
||||
db.metadata.create_all(mysql_engine)
|
||||
|
||||
# 读取 MySQL 表结构
|
||||
mysql_meta = MetaData()
|
||||
mysql_meta.reflect(bind=mysql_engine)
|
||||
mysql_tables = mysql_meta.tables
|
||||
|
||||
# ===== 3. 批量插入数据 =====
|
||||
print(f"\n[3/4] 迁移数据(batch_size={args.batch_size})")
|
||||
|
||||
# 临时禁用外键检查,避免插入顺序问题
|
||||
with mysql_engine.connect() as conn:
|
||||
conn.execute(text("SET FOREIGN_KEY_CHECKS = 0"))
|
||||
|
||||
for table_name in tables:
|
||||
if table_name not in mysql_tables:
|
||||
print(f" [SKIP] {table_name}: MySQL 无此表")
|
||||
continue
|
||||
|
||||
rows = all_data[table_name]
|
||||
if not rows:
|
||||
print(f" [SKIP] {table_name}: 无数据")
|
||||
continue
|
||||
|
||||
table = mysql_tables[table_name]
|
||||
inserted = 0
|
||||
for i in range(0, len(rows), args.batch_size):
|
||||
batch = rows[i:i + args.batch_size]
|
||||
try:
|
||||
with mysql_engine.begin() as conn:
|
||||
conn.execute(table.insert(), batch)
|
||||
inserted += len(batch)
|
||||
except Exception as e:
|
||||
# 批量失败,逐行插入跳过重复
|
||||
print(f" [WARN] {table_name} 批次 {i} 失败: {e},尝试逐行...")
|
||||
for row in batch:
|
||||
try:
|
||||
with mysql_engine.begin() as conn:
|
||||
conn.execute(table.insert(), [row])
|
||||
inserted += 1
|
||||
except Exception:
|
||||
continue # 跳过重复/冲突行
|
||||
|
||||
print(f" {table_name}: 插入 {inserted}/{len(rows)} 行")
|
||||
|
||||
# 恢复外键检查
|
||||
with mysql_engine.connect() as conn:
|
||||
conn.execute(text("SET FOREIGN_KEY_CHECKS = 1"))
|
||||
|
||||
# ===== 4. 校验行数 =====
|
||||
print(f"\n[4/4] 校验行数")
|
||||
all_ok = True
|
||||
for table_name in tables:
|
||||
if table_name not in mysql_tables:
|
||||
continue
|
||||
table = mysql_tables[table_name]
|
||||
with mysql_engine.connect() as conn:
|
||||
result = conn.execute(select(table))
|
||||
mysql_rows = result.fetchall()
|
||||
mysql_count = len(mysql_rows)
|
||||
sqlite_count = len(all_data[table_name])
|
||||
status = "OK" if mysql_count == sqlite_count else "MISMATCH"
|
||||
if status != "OK":
|
||||
all_ok = False
|
||||
print(f" {table_name}: SQLite={sqlite_count} MySQL={mysql_count} [{status}]")
|
||||
|
||||
print("\n[完成] 迁移结束")
|
||||
if not all_ok:
|
||||
print(" [WARN] 部分表行数不一致,请检查")
|
||||
print(" 下一步: 设 DATABASE_URL 环境变量指向 MySQL,重启应用")
|
||||
print(f" export DATABASE_URL='{mysql_uri}'")
|
||||
|
||||
# 关闭 engine
|
||||
mysql_engine.dispose()
|
||||
sqlite_engine.dispose()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,449 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
数据库模型定义
|
||||
"""
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from werkzeug.security import generate_password_hash, check_password_hash
|
||||
from app.time_utils import now as _now, to_iso
|
||||
import json
|
||||
|
||||
db = SQLAlchemy()
|
||||
|
||||
|
||||
class User(db.Model):
|
||||
"""用户模型 - 网站账号(与教务系统账号分离)"""
|
||||
__tablename__ = 'users'
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
username = db.Column(db.String(20), unique=True, nullable=False, index=True, comment='网站登录用户名')
|
||||
password_hash = db.Column(db.String(256), nullable=False, comment='网站登录密码哈希')
|
||||
|
||||
# 教务系统账号信息(仅存储学号和姓名,密码在 accounts.json)
|
||||
jwxt_username = db.Column(db.String(20), nullable=True, comment='教务系统学号')
|
||||
jwxt_name = db.Column(db.String(50), nullable=True, comment='姓名')
|
||||
school_id = db.Column(db.String(40), nullable=True, default='sdmu', comment='注册时选择的学校,不允许修改')
|
||||
|
||||
# Session状态
|
||||
session_status = db.Column(db.String(20), default='unknown', comment='session状态: valid/invalid/unknown')
|
||||
session_updated_at = db.Column(db.DateTime, nullable=True, comment='session最后更新时间')
|
||||
session_error_msg = db.Column(db.Text, nullable=True, comment='session错误信息')
|
||||
|
||||
is_admin = db.Column(db.Boolean, default=False, comment='是否管理员')
|
||||
created_at = db.Column(db.DateTime, default=_now, comment='创建时间')
|
||||
last_login = db.Column(db.DateTime, nullable=True, comment='最后登录时间')
|
||||
is_active = db.Column(db.Boolean, default=True, comment='是否激活')
|
||||
# AI 每日 token 用量上限(输入+输出)。NULL=用全局默认值,0=不限制
|
||||
ai_daily_limit = db.Column(db.BigInteger, nullable=True, comment='AI 每日 token 上限:NULL=全局默认,0=不限制')
|
||||
|
||||
# 关联关系
|
||||
tasks = db.relationship('GrabTask', backref='user', lazy='dynamic', cascade='all, delete-orphan')
|
||||
logs = db.relationship('GrabLog', backref='user', lazy='dynamic', cascade='all, delete-orphan')
|
||||
|
||||
def set_password(self, password):
|
||||
"""设置网站登录密码"""
|
||||
self.password_hash = generate_password_hash(password)
|
||||
|
||||
def check_password(self, password):
|
||||
"""验证网站登录密码"""
|
||||
if self.password_hash is None:
|
||||
return False
|
||||
return check_password_hash(self.password_hash, password)
|
||||
|
||||
def get_id(self):
|
||||
"""Flask-Login 必需的方法"""
|
||||
return str(self.id)
|
||||
|
||||
@property
|
||||
def is_authenticated(self):
|
||||
return True
|
||||
|
||||
@property
|
||||
def is_anonymous(self):
|
||||
return False
|
||||
|
||||
def get_jwxt_account(self):
|
||||
"""获取教务系统账号(从 accounts.json)"""
|
||||
from app.account_manager import get_jwxt_account
|
||||
return get_jwxt_account(user_id=self.id, username=self.username)
|
||||
|
||||
def has_jwxt_account(self):
|
||||
"""检查是否配置了教务系统账号"""
|
||||
return self.get_jwxt_account() is not None
|
||||
|
||||
def to_dict(self):
|
||||
"""转换为字典"""
|
||||
return {
|
||||
'id': self.id,
|
||||
'username': self.username,
|
||||
'jwxt_username': self.jwxt_username,
|
||||
'jwxt_name': self.jwxt_name,
|
||||
'school_id': self.school_id or 'sdmu',
|
||||
'has_jwxt_account': self.has_jwxt_account(),
|
||||
'session_status': self.session_status,
|
||||
'session_updated_at': to_iso(self.session_updated_at),
|
||||
'session_error_msg': self.session_error_msg,
|
||||
'is_admin': self.is_admin,
|
||||
'created_at': to_iso(self.created_at),
|
||||
'last_login': to_iso(self.last_login),
|
||||
'is_active': self.is_active
|
||||
}
|
||||
|
||||
def to_dict_admin(self):
|
||||
"""管理员查看的完整信息"""
|
||||
data = self.to_dict()
|
||||
jwxt_acc = self.get_jwxt_account()
|
||||
data['has_jwxt_password'] = jwxt_acc is not None
|
||||
return data
|
||||
|
||||
|
||||
class GrabTask(db.Model):
|
||||
"""抢课任务模型"""
|
||||
__tablename__ = 'grab_tasks'
|
||||
|
||||
# 任务状态
|
||||
STATUS_PENDING = 'pending' # 待执行
|
||||
STATUS_RUNNING = 'running' # 执行中
|
||||
STATUS_SUCCESS = 'success' # 成功
|
||||
STATUS_FAILED = 'failed' # 失败
|
||||
STATUS_CANCELLED = 'cancelled' # 已取消
|
||||
STATUS_EXPIRED = 'expired' # 已过期
|
||||
|
||||
# 任务类型
|
||||
TYPE_IMMEDIATE = 'immediate' # 立即抢课
|
||||
TYPE_SCHEDULED = 'scheduled' # 定时抢课
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, index=True)
|
||||
|
||||
# 课程信息
|
||||
course_name = db.Column(db.String(100), nullable=False, comment='课程名称')
|
||||
course_id = db.Column(db.String(50), nullable=False, comment='课程ID(jxb_id)')
|
||||
teacher_name = db.Column(db.String(50), nullable=True, comment='教师姓名')
|
||||
credit = db.Column(db.String(10), nullable=True, comment='学分')
|
||||
class_info = db.Column(db.String(100), nullable=True, comment='班级信息')
|
||||
|
||||
# 抢课所需完整参数(对齐 xk_api.py)
|
||||
do_jxb_id = db.Column(db.String(500), nullable=True, comment='加密ID/志愿场次ID')
|
||||
kch_id = db.Column(db.String(50), nullable=True, comment='课程号ID')
|
||||
jxbzls = db.Column(db.String(10), default='0', comment='教学班总量/志愿序号')
|
||||
kklxdm = db.Column(db.String(10), nullable=True, comment='课程类型代码')
|
||||
|
||||
# 自定义规则(JSON: {"on_has_vacancy": [{"action": "drop_course", ...}]})
|
||||
rules = db.Column(db.Text, nullable=True, comment='自定义规则(JSON)')
|
||||
|
||||
# 任务配置
|
||||
task_type = db.Column(db.String(20), default=TYPE_IMMEDIATE, comment='任务类型')
|
||||
scheduled_time = db.Column(db.DateTime, nullable=True, comment='定时执行时间')
|
||||
|
||||
# 任务状态
|
||||
status = db.Column(db.String(20), default=STATUS_PENDING, index=True, comment='任务状态')
|
||||
retry_count = db.Column(db.Integer, default=0, comment='重试次数')
|
||||
max_retries = db.Column(db.Integer, default=100, comment='最大重试次数')
|
||||
|
||||
# 执行结果
|
||||
result_message = db.Column(db.Text, nullable=True, comment='结果消息')
|
||||
started_at = db.Column(db.DateTime, nullable=True, comment='开始时间')
|
||||
completed_at = db.Column(db.DateTime, nullable=True, comment='完成时间')
|
||||
|
||||
# 时间戳
|
||||
created_at = db.Column(db.DateTime, default=_now, comment='创建时间')
|
||||
updated_at = db.Column(db.DateTime, default=_now, onupdate=_now, comment='更新时间')
|
||||
|
||||
# 关联关系
|
||||
logs = db.relationship('GrabLog', backref='task', lazy='dynamic', cascade='all, delete-orphan')
|
||||
|
||||
def to_dict(self):
|
||||
"""转换为字典"""
|
||||
return {
|
||||
'id': self.id,
|
||||
'user_id': self.user_id,
|
||||
'username': self.user.username if self.user else None,
|
||||
'course_name': self.course_name,
|
||||
'course_id': self.course_id,
|
||||
'teacher_name': self.teacher_name,
|
||||
'credit': self.credit,
|
||||
'class_info': self.class_info,
|
||||
'do_jxb_id': self.do_jxb_id,
|
||||
'kch_id': self.kch_id,
|
||||
'jxbzls': self.jxbzls,
|
||||
'kklxdm': self.kklxdm,
|
||||
'rules': json.loads(self.rules) if self.rules else None,
|
||||
'task_type': self.task_type,
|
||||
'scheduled_time': to_iso(self.scheduled_time),
|
||||
'status': self.status,
|
||||
'retry_count': self.retry_count,
|
||||
'max_retries': self.max_retries,
|
||||
'result_message': self.result_message,
|
||||
'started_at': to_iso(self.started_at),
|
||||
'completed_at': to_iso(self.completed_at),
|
||||
'created_at': to_iso(self.created_at),
|
||||
'updated_at': to_iso(self.updated_at)
|
||||
}
|
||||
|
||||
|
||||
class GrabLog(db.Model):
|
||||
"""抢课日志模型"""
|
||||
__tablename__ = 'grab_logs'
|
||||
|
||||
# 日志级别
|
||||
LEVEL_INFO = 'info'
|
||||
LEVEL_WARNING = 'warning'
|
||||
LEVEL_ERROR = 'error'
|
||||
LEVEL_SUCCESS = 'success'
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
task_id = db.Column(db.Integer, db.ForeignKey('grab_tasks.id'), nullable=False, index=True)
|
||||
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, index=True)
|
||||
|
||||
# 日志内容
|
||||
level = db.Column(db.String(20), default=LEVEL_INFO, comment='日志级别')
|
||||
message = db.Column(db.Text, nullable=False, comment='日志消息')
|
||||
detail = db.Column(db.Text, nullable=True, comment='详细内容(JSON)')
|
||||
|
||||
# 时间戳
|
||||
created_at = db.Column(db.DateTime, default=_now, comment='创建时间')
|
||||
|
||||
def to_dict(self):
|
||||
"""转换为字典"""
|
||||
return {
|
||||
'id': self.id,
|
||||
'task_id': self.task_id,
|
||||
'user_id': self.user_id,
|
||||
'username': self.user.username if self.user else None,
|
||||
'level': self.level,
|
||||
'message': self.message,
|
||||
'detail': self.detail,
|
||||
'created_at': to_iso(self.created_at)
|
||||
}
|
||||
|
||||
|
||||
class AiConversation(db.Model):
|
||||
"""每个网站账号的一条选课 AI 会话。"""
|
||||
__tablename__ = 'ai_conversations'
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, unique=True, index=True)
|
||||
created_at = db.Column(db.DateTime, default=_now, nullable=False)
|
||||
updated_at = db.Column(db.DateTime, default=_now, onupdate=_now, nullable=False)
|
||||
|
||||
messages = db.relationship(
|
||||
'AiConversationMessage', backref='conversation', lazy='dynamic',
|
||||
cascade='all, delete-orphan'
|
||||
)
|
||||
|
||||
|
||||
class AiConversationMessage(db.Model):
|
||||
"""AI 会话文本。工具调用参数与 API Key 均不写入此表。"""
|
||||
__tablename__ = 'ai_conversation_messages'
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
conversation_id = db.Column(db.Integer, db.ForeignKey('ai_conversations.id'), nullable=False, index=True)
|
||||
role = db.Column(db.String(16), nullable=False, comment='user / assistant')
|
||||
content = db.Column(db.Text, nullable=False)
|
||||
created_at = db.Column(db.DateTime, default=_now, nullable=False)
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
'id': self.id,
|
||||
'role': self.role,
|
||||
'content': self.content,
|
||||
'created_at': to_iso(self.created_at),
|
||||
}
|
||||
|
||||
|
||||
class AiUsageLog(db.Model):
|
||||
"""AI 每次模型调用的 token 用量(输入/输出),用于管理端统计与每日限额。"""
|
||||
__tablename__ = 'ai_usage_logs'
|
||||
__table_args__ = (
|
||||
db.Index('idx_ai_usage_user_time', 'user_id', 'created_at'),
|
||||
)
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, index=True)
|
||||
model = db.Column(db.String(100), nullable=True, comment='模型名')
|
||||
input_tokens = db.Column(db.BigInteger, nullable=False, default=0)
|
||||
output_tokens = db.Column(db.BigInteger, nullable=False, default=0)
|
||||
created_at = db.Column(db.DateTime, default=_now, nullable=False)
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
'id': self.id,
|
||||
'user_id': self.user_id,
|
||||
'model': self.model,
|
||||
'input_tokens': self.input_tokens,
|
||||
'output_tokens': self.output_tokens,
|
||||
'created_at': to_iso(self.created_at),
|
||||
}
|
||||
|
||||
|
||||
class AiScheduledTask(db.Model):
|
||||
"""AI 定时任务:到点后由调度器自动、无人值守地执行一次用户委托的 AI 指令。
|
||||
|
||||
执行期间写操作自动视为用户已确认(创建任务即委托);用量照常记录,
|
||||
但执行不受每日限额中断(体验优先)。
|
||||
"""
|
||||
__tablename__ = 'ai_scheduled_tasks'
|
||||
__table_args__ = (
|
||||
db.Index('idx_ai_sched_due', 'status', 'scheduled_at'),
|
||||
)
|
||||
|
||||
STATUS_PENDING = 'pending'
|
||||
STATUS_RUNNING = 'running'
|
||||
STATUS_SUCCESS = 'success'
|
||||
STATUS_FAILED = 'failed'
|
||||
STATUS_CANCELLED = 'cancelled'
|
||||
STATUS_ENDED = 'ended' # 重复任务到期/达次数上限自动结束
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, index=True)
|
||||
conversation_id = db.Column(db.Integer, nullable=True, comment='结果写回的会话')
|
||||
instruction = db.Column(db.Text, nullable=False, comment='到点要执行的完整指令')
|
||||
scheduled_at = db.Column(db.DateTime, nullable=False, comment='下次执行时间(北京时间)')
|
||||
repeat_interval = db.Column(db.BigInteger, nullable=True, comment='重复间隔(秒),NULL=一次性')
|
||||
repeat_until = db.Column(db.DateTime, nullable=True, comment='重复截止时间,到期自动结束')
|
||||
run_count = db.Column(db.Integer, nullable=True, comment='已执行次数')
|
||||
status = db.Column(db.String(20), default=STATUS_PENDING, nullable=False, index=True)
|
||||
result = db.Column(db.Text, nullable=True, comment='AI 最终输出(重复任务为最近一次)')
|
||||
error = db.Column(db.String(500), nullable=True, comment='失败/取消原因')
|
||||
created_at = db.Column(db.DateTime, default=_now, nullable=False)
|
||||
claimed_at = db.Column(db.DateTime, nullable=True, comment='调度器认领时间,用于中断恢复')
|
||||
executed_at = db.Column(db.DateTime, nullable=True)
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
'id': self.id,
|
||||
'user_id': self.user_id,
|
||||
'conversation_id': self.conversation_id,
|
||||
'instruction': self.instruction,
|
||||
'scheduled_at': to_iso(self.scheduled_at),
|
||||
'repeat_interval': self.repeat_interval,
|
||||
'repeat_until': to_iso(self.repeat_until),
|
||||
'run_count': self.run_count or 0,
|
||||
'status': self.status,
|
||||
'result': self.result,
|
||||
'error': self.error,
|
||||
'created_at': to_iso(self.created_at),
|
||||
'executed_at': to_iso(self.executed_at),
|
||||
}
|
||||
|
||||
|
||||
class SystemConfig(db.Model):
|
||||
"""系统配置模型"""
|
||||
__tablename__ = 'system_configs'
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
key = db.Column(db.String(50), unique=True, nullable=False, comment='配置键')
|
||||
value = db.Column(db.Text, nullable=True, comment='配置值')
|
||||
description = db.Column(db.String(200), nullable=True, comment='配置说明')
|
||||
updated_at = db.Column(db.DateTime, default=_now, onupdate=_now)
|
||||
|
||||
# ── 内存缓存(每请求热路径,避免频繁查 SQLite)──
|
||||
_config_cache: dict = {}
|
||||
_config_cache_lock = None # 延迟初始化(db.Model 定义阶段 threading 还没导入)
|
||||
_CONFIG_CACHE_TTL = 30 # 秒
|
||||
|
||||
@staticmethod
|
||||
def get(key, default=None):
|
||||
"""获取配置值(带 30 秒内存缓存)"""
|
||||
import time as _time
|
||||
import threading as _threading
|
||||
if SystemConfig._config_cache_lock is None:
|
||||
SystemConfig._config_cache_lock = _threading.Lock()
|
||||
|
||||
now = _time.time()
|
||||
with SystemConfig._config_cache_lock:
|
||||
entry = SystemConfig._config_cache.get(key)
|
||||
if entry is not None:
|
||||
value, ts = entry
|
||||
if now - ts < SystemConfig._CONFIG_CACHE_TTL:
|
||||
return value if value is not None else default
|
||||
|
||||
config = SystemConfig.query.filter_by(key=key).first()
|
||||
value = config.value if config else None
|
||||
with SystemConfig._config_cache_lock:
|
||||
SystemConfig._config_cache[key] = (value, now)
|
||||
return value if value is not None else default
|
||||
|
||||
@staticmethod
|
||||
def set(key, value, description=None):
|
||||
"""设置配置值(同时清除缓存)"""
|
||||
config = SystemConfig.query.filter_by(key=key).first()
|
||||
if config:
|
||||
config.value = value
|
||||
else:
|
||||
config = SystemConfig(key=key, value=value, description=description)
|
||||
db.session.add(config)
|
||||
db.session.commit()
|
||||
# 清除该 key 的缓存
|
||||
import threading as _threading
|
||||
if SystemConfig._config_cache_lock is None:
|
||||
SystemConfig._config_cache_lock = _threading.Lock()
|
||||
with SystemConfig._config_cache_lock:
|
||||
SystemConfig._config_cache.pop(key, None)
|
||||
|
||||
|
||||
class IPBan(db.Model):
|
||||
"""IP封禁模型"""
|
||||
__tablename__ = 'ip_bans'
|
||||
|
||||
# 封禁类型
|
||||
TYPE_IP = 'ip' # 单个IP
|
||||
TYPE_CIDR = 'cidr' # IP段 (CIDR)
|
||||
TYPE_COUNTRY = 'country' # 国家/地区代码
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
ban_type = db.Column(db.String(20), default=TYPE_IP, nullable=False, comment='封禁类型: ip/cidr/country')
|
||||
value = db.Column(db.String(100), nullable=False, index=True, comment='封禁值: IP/CIDR/国家代码')
|
||||
reason = db.Column(db.String(200), nullable=True, comment='封禁原因')
|
||||
is_permanent = db.Column(db.Boolean, default=False, comment='是否永久封禁')
|
||||
expires_at = db.Column(db.DateTime, nullable=True, comment='解封时间(NULL=永久)')
|
||||
created_at = db.Column(db.DateTime, default=_now, comment='创建时间')
|
||||
created_by = db.Column(db.String(50), nullable=True, comment='操作者(admin/auto)')
|
||||
|
||||
|
||||
class IPAccessLog(db.Model):
|
||||
"""IP访问日志模型"""
|
||||
__tablename__ = 'ip_access_logs'
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
ip = db.Column(db.String(50), nullable=False, index=True, comment='访问IP')
|
||||
country = db.Column(db.String(10), nullable=True, comment='国家代码')
|
||||
region = db.Column(db.String(50), nullable=True, comment='省/州')
|
||||
city = db.Column(db.String(50), nullable=True, comment='城市')
|
||||
isp = db.Column(db.String(100), nullable=True, comment='运营商')
|
||||
method = db.Column(db.String(10), nullable=True, comment='HTTP方法')
|
||||
path = db.Column(db.String(500), nullable=True, comment='请求路径')
|
||||
status_code = db.Column(db.Integer, nullable=True, comment='响应状态码')
|
||||
user_agent = db.Column(db.String(500), nullable=True, comment='UserAgent')
|
||||
blocked = db.Column(db.Boolean, default=False, comment='是否被拦截')
|
||||
block_reason = db.Column(db.String(100), nullable=True, comment='拦截原因')
|
||||
created_at = db.Column(db.DateTime, default=_now, index=True, comment='访问时间')
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
'id': self.id,
|
||||
'ip': self.ip,
|
||||
'country': self.country,
|
||||
'region': self.region,
|
||||
'city': self.city,
|
||||
'isp': self.isp,
|
||||
'method': self.method,
|
||||
'path': self.path,
|
||||
'status_code': self.status_code,
|
||||
'user_agent': self.user_agent,
|
||||
'blocked': self.blocked,
|
||||
'block_reason': self.block_reason,
|
||||
'created_at': to_iso(self.created_at)
|
||||
}
|
||||
|
||||
|
||||
class LoginAttempt(db.Model):
|
||||
"""登录尝试记录(用于频率限制)"""
|
||||
__tablename__ = 'login_attempts'
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
ip = db.Column(db.String(50), nullable=False, index=True, comment='来源IP')
|
||||
username = db.Column(db.String(50), nullable=True, comment='尝试的用户名')
|
||||
success = db.Column(db.Boolean, default=False, comment='是否成功')
|
||||
created_at = db.Column(db.DateTime, default=_now, index=True, comment='时间')
|
||||
@@ -0,0 +1,668 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
多线路 Session 管理器
|
||||
|
||||
背景:
|
||||
教务系统 3 条入口线路(公网域名 + 2 个内网 IP)是 3 个独立后端,
|
||||
session(cookie)跨线路不通用。原方案:线路拥堵切换后强刷 session
|
||||
(OCR 登录,慢)。本模块改为:提前在每条线路上都养好 session,
|
||||
切换线路时只做本地文件复制(毫秒级),不再临时登录。
|
||||
|
||||
功能:
|
||||
1. 多线路开关(管理端):开启后后台为所有账号在每条线路上预登录
|
||||
2. 保活线程:定期心跳检查每条线路的 session,过期自动重登
|
||||
3. 秒切:线路切换时把目标线路的预热 session 原子写入当前生效的
|
||||
sessions/{username}.json,先换文件再切 URL
|
||||
4. 用户线路偏好:用户可固定某条线路(auto = 跟随全局智能切换)
|
||||
5. 选课模式(管理端):开启后暂停非核心后台任务、拦截非核心查询
|
||||
|
||||
配置持久化:BASE_DIR / multi_line_config.json
|
||||
预热 session 文件:sessions/{username}@{线路tag}.json(格式与现有 session 文件一致)
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import logging
|
||||
import tempfile
|
||||
import threading
|
||||
import concurrent.futures
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from app.settings import BASE_URLS, SESSION_DIR, BASE_DIR
|
||||
from app.school_manager import DEFAULT_SCHOOL_ID, school_urls, school_for_username, session_key, list_schools
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
CONFIG_FILE = BASE_DIR / "multi_line_config.json"
|
||||
|
||||
# ── 默认配置 ──
|
||||
DEFAULT_CONFIG = {
|
||||
"multi_line_enabled": False, # [已废弃] 旧版全局开关,仅用于一次性迁移到 schools
|
||||
"xk_mode": False, # [已废弃] 旧版全局开关,仅用于一次性迁移到 schools
|
||||
"user_preferences": {}, # {session_key(jwxt_username): line_tag},"auto" 或缺省=跟随全局
|
||||
"schools": {}, # {school_id: {"multi_line_enabled": bool, "xk_mode": bool}} 按学校开关
|
||||
}
|
||||
|
||||
# 预热 session 有效则跳过重登的心跳间隔(秒)
|
||||
KEEPALIVE_INTERVAL = 20 * 60
|
||||
# 延迟测量间隔(秒):多线路开启期间每分钟测一轮
|
||||
LATENCY_INTERVAL = 60
|
||||
# 登录重试次数
|
||||
PRELOGIN_RETRIES = 5
|
||||
|
||||
_config_lock = threading.Lock()
|
||||
_config: Dict = {}
|
||||
_latency_cache: Dict[str, Optional[float]] = {} # tag -> 秒(None=不可达)
|
||||
_latency_lock = threading.Lock()
|
||||
_latency_ts: float = 0.0 # 上次测量的时间戳
|
||||
|
||||
_keepalive_thread: Optional[threading.Thread] = None
|
||||
_latency_thread: Optional[threading.Thread] = None
|
||||
_keepalive_stop = threading.Event()
|
||||
|
||||
|
||||
# ══════════════════════════════════════════════════════════
|
||||
# 线路注册
|
||||
# ══════════════════════════════════════════════════════════
|
||||
|
||||
def line_tag(url: str) -> str:
|
||||
"""线路标识:取 URL 的 host 部分(如 jwxt.sdmu.edu.cn / 10.224.2.186)"""
|
||||
from urllib.parse import urlparse
|
||||
return urlparse(url).netloc or url
|
||||
|
||||
|
||||
def get_lines(school_id=DEFAULT_SCHOOL_ID) -> List[Dict]:
|
||||
"""所有线路 [{tag, url}]"""
|
||||
return [{"tag": line_tag(u), "url": u.rstrip('/')} for u in school_urls(school_id)]
|
||||
|
||||
|
||||
def url_by_tag(tag: str, school_id=DEFAULT_SCHOOL_ID) -> Optional[str]:
|
||||
for u in school_urls(school_id):
|
||||
if line_tag(u) == tag:
|
||||
return u.rstrip('/')
|
||||
return None
|
||||
|
||||
|
||||
# ══════════════════════════════════════════════════════════
|
||||
# 配置读写(JSON 文件持久化,无数据库迁移)
|
||||
# ══════════════════════════════════════════════════════════
|
||||
|
||||
def _resolve_school(school_id=None) -> str:
|
||||
"""显式参数优先,其次线程绑定的学校(请求/抢课线程),最后默认学校"""
|
||||
if school_id:
|
||||
return str(school_id)
|
||||
try:
|
||||
from app.url_manager import current_school_id
|
||||
return current_school_id() or DEFAULT_SCHOOL_ID
|
||||
except Exception:
|
||||
return DEFAULT_SCHOOL_ID
|
||||
|
||||
|
||||
def _migrate_global_flags(cfg: Dict):
|
||||
"""旧版全局开关一次性迁移为按学校配置:各学校继承迁移时刻的全局值,行为无缝延续"""
|
||||
if not isinstance(cfg.get("schools"), dict):
|
||||
cfg["schools"] = {}
|
||||
legacy_ml = cfg.get("multi_line_enabled")
|
||||
legacy_xk = cfg.get("xk_mode")
|
||||
if legacy_ml is None and legacy_xk is None:
|
||||
return # 已是按学校配置(或全新安装)
|
||||
try:
|
||||
from app.school_manager import list_schools
|
||||
school_ids = [s['id'] for s in list_schools()]
|
||||
except Exception:
|
||||
school_ids = [DEFAULT_SCHOOL_ID]
|
||||
for sid in school_ids:
|
||||
flags = cfg["schools"].setdefault(sid, {})
|
||||
if legacy_ml is not None and "multi_line_enabled" not in flags:
|
||||
flags["multi_line_enabled"] = bool(legacy_ml)
|
||||
if legacy_xk is not None and "xk_mode" not in flags:
|
||||
flags["xk_mode"] = bool(legacy_xk)
|
||||
# 固化迁移结果,防止每次启动重复继承
|
||||
for key in ("multi_line_enabled", "xk_mode"):
|
||||
cfg.pop(key, None)
|
||||
try:
|
||||
_atomic_write_json(CONFIG_FILE, cfg)
|
||||
logger.info("[multi_line] 旧版全局开关已迁移为按学校配置")
|
||||
except Exception as e:
|
||||
logger.warning(f"[multi_line] 开关迁移写入失败: {e}")
|
||||
|
||||
|
||||
def _load_config() -> Dict:
|
||||
global _config
|
||||
with _config_lock:
|
||||
if _config:
|
||||
return _config
|
||||
# 深拷贝默认值,避免嵌套 dict 被 setdefault 污染模块级常量
|
||||
cfg = json.loads(json.dumps(DEFAULT_CONFIG))
|
||||
try:
|
||||
if CONFIG_FILE and CONFIG_FILE.exists():
|
||||
data = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
|
||||
if isinstance(data, dict):
|
||||
cfg.update(data)
|
||||
except Exception as e:
|
||||
logger.warning(f"[multi_line] 配置读取失败,用默认值: {e}")
|
||||
_migrate_global_flags(cfg)
|
||||
_config = cfg
|
||||
return _config
|
||||
|
||||
|
||||
def _save_config():
|
||||
with _config_lock:
|
||||
try:
|
||||
if CONFIG_FILE and _config:
|
||||
_atomic_write_json(CONFIG_FILE, _config)
|
||||
except Exception as e:
|
||||
logger.error(f"[multi_line] 配置保存失败: {e}")
|
||||
|
||||
|
||||
def is_enabled(school_id=None) -> bool:
|
||||
"""该校是否开启了多线路 Session 预热(school_id 缺省时取线程绑定学校)"""
|
||||
flags = _load_config().get("schools", {}).get(_resolve_school(school_id)) or {}
|
||||
return bool(flags.get("multi_line_enabled"))
|
||||
|
||||
|
||||
def is_xk_mode(school_id=None) -> bool:
|
||||
"""该校是否开启了选课模式(school_id 缺省时取线程绑定学校)"""
|
||||
flags = _load_config().get("schools", {}).get(_resolve_school(school_id)) or {}
|
||||
return bool(flags.get("xk_mode"))
|
||||
|
||||
|
||||
def any_enabled() -> bool:
|
||||
"""是否任一学校开启了多线路预热(决定后台线程是否需要存活)"""
|
||||
schools = _load_config().get("schools", {})
|
||||
return any(bool(f.get("multi_line_enabled")) for f in schools.values())
|
||||
|
||||
|
||||
def set_enabled(enabled: bool, school_id=None) -> Dict:
|
||||
school_id = _resolve_school(school_id)
|
||||
_load_config()
|
||||
with _config_lock:
|
||||
flags = _config.setdefault("schools", {}).setdefault(school_id, {})
|
||||
flags["multi_line_enabled"] = bool(enabled)
|
||||
_save_config()
|
||||
if enabled:
|
||||
# 只预热该校账号(prelogin_all 内部按 school_id 过滤)
|
||||
start_background(prelogin=True, prelogin_school=school_id)
|
||||
elif not any_enabled():
|
||||
_keepalive_stop.set()
|
||||
return {"multi_line_enabled": bool(enabled), "school_id": school_id}
|
||||
|
||||
|
||||
def set_xk_mode(enabled: bool, school_id=None):
|
||||
school_id = _resolve_school(school_id)
|
||||
_load_config()
|
||||
with _config_lock:
|
||||
flags = _config.setdefault("schools", {}).setdefault(school_id, {})
|
||||
flags["xk_mode"] = bool(enabled)
|
||||
_save_config()
|
||||
|
||||
|
||||
# ══════════════════════════════════════════════════════════
|
||||
# 用户线路偏好
|
||||
# ══════════════════════════════════════════════════════════
|
||||
|
||||
def get_user_preference(jwxt_username: str, school_id=None) -> str:
|
||||
"""返回用户固定线路 tag;'auto' 或未设置 = 跟随全局"""
|
||||
prefs = _load_config().get("user_preferences", {})
|
||||
return prefs.get(session_key(jwxt_username, school_id), "auto")
|
||||
|
||||
|
||||
def set_user_preference(jwxt_username: str, tag: str):
|
||||
with _config_lock:
|
||||
prefs = _config.setdefault("user_preferences", {})
|
||||
key = session_key(jwxt_username)
|
||||
if tag in ("auto", "", None):
|
||||
prefs.pop(key, None)
|
||||
else:
|
||||
prefs[key] = tag
|
||||
_save_config()
|
||||
|
||||
|
||||
def get_user_line_url(jwxt_username: str, school_id=None) -> Optional[str]:
|
||||
"""用户固定线路对应的 URL;auto/未设置返回 None(用全局线路)"""
|
||||
tag = get_user_preference(jwxt_username, school_id)
|
||||
if tag == "auto":
|
||||
return None
|
||||
return url_by_tag(tag, school_id or school_for_username(jwxt_username))
|
||||
|
||||
|
||||
# ══════════════════════════════════════════════════════════
|
||||
# 预热 session 文件操作
|
||||
# ══════════════════════════════════════════════════════════
|
||||
|
||||
def _line_session_file(username: str, tag: str) -> Path:
|
||||
return SESSION_DIR / f"{session_key(username)}@{tag}.json"
|
||||
|
||||
|
||||
def _active_session_file(username: str) -> Path:
|
||||
return SESSION_DIR / f"{session_key(username)}.json"
|
||||
|
||||
|
||||
def _read_session(path: Path) -> Optional[Dict]:
|
||||
try:
|
||||
if not path.exists():
|
||||
return None
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
if data.get("cookies"):
|
||||
return data
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def _atomic_write_json(path: Path, data: Dict):
|
||||
"""原子写入,避免抢课线程读到半截文件"""
|
||||
fd, tmp = tempfile.mkstemp(dir=str(path.parent), suffix=".tmp")
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=2)
|
||||
os.replace(tmp, path)
|
||||
except Exception:
|
||||
try:
|
||||
os.unlink(tmp)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
def _is_session_valid_on(url: str, cookies: Dict, timeout: int = 8) -> bool:
|
||||
"""检查一份 cookie 在指定线路上是否有效(302=跳登录页=过期)"""
|
||||
import requests
|
||||
try:
|
||||
s = requests.Session()
|
||||
s.cookies.update(cookies)
|
||||
r = s.get(url.rstrip('/') + "/xtgl/index_initMenu.html",
|
||||
allow_redirects=False, timeout=timeout)
|
||||
return r.status_code == 200
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
# ══════════════════════════════════════════════════════════
|
||||
# 预登录(预热)
|
||||
# ══════════════════════════════════════════════════════════
|
||||
|
||||
def _promote_if_serving(username: str, tag: str, url: str):
|
||||
"""
|
||||
若该线路正是当前"服务"此用户的线路,把刚登录的新 cookie 同步进生效文件。
|
||||
|
||||
背景:正方系统同账号重复登录会挤掉旧 session。预热/保活在某条线路上重登时,
|
||||
如果该线路正在服务用户(auto 且=全局当前线路,或用户固定了该线路),
|
||||
生效文件里的旧 session 就会被踢掉——必须同步替换,否则用户请求全挂,
|
||||
且 keepalive 与 SessionManager 会互相踢对方的 session 形成死循环。
|
||||
"""
|
||||
pref = get_user_preference(username)
|
||||
if pref == tag:
|
||||
serving = True
|
||||
elif pref in ('auto', '', None):
|
||||
from app.url_manager import get_global_base_url
|
||||
serving = (line_tag(get_global_base_url(school_for_username(username))) == tag)
|
||||
else:
|
||||
serving = False
|
||||
if serving:
|
||||
_swap_active_session(username, tag, url)
|
||||
logger.info(f"[multi_line] 重登同步生效 session: {username}@{tag}")
|
||||
|
||||
|
||||
def _login_on_line(username: str, password: str, url: str, tag: str,
|
||||
max_retries: int = PRELOGIN_RETRIES) -> Dict:
|
||||
"""在指定线路上登录并把 session 存到 {username}@{tag}.json"""
|
||||
from app.jwxt_login import JWXTLogin
|
||||
|
||||
if not password:
|
||||
return {"username": username, "tag": tag, "success": False,
|
||||
"message": "无密码(accounts.json 未配置)"}
|
||||
|
||||
login = JWXTLogin(base_url=url)
|
||||
last_err = ""
|
||||
for attempt in range(1, max_retries + 1):
|
||||
try:
|
||||
result = login.login(username, password)
|
||||
if result.get("success", False) if isinstance(result, dict) else result:
|
||||
data = {
|
||||
"cookies": dict(login.session.cookies),
|
||||
"headers": dict(login.session.headers),
|
||||
}
|
||||
_atomic_write_json(_line_session_file(username, tag), data)
|
||||
_promote_if_serving(username, tag, url)
|
||||
return {"username": username, "tag": tag, "success": True}
|
||||
last_err = (result.get("message", "") if isinstance(result, dict) else "") or "登录失败"
|
||||
except Exception as e:
|
||||
last_err = str(e)
|
||||
if attempt < max_retries:
|
||||
time.sleep(0.5)
|
||||
login = JWXTLogin(base_url=url)
|
||||
return {"username": username, "tag": tag, "success": False, "message": last_err}
|
||||
|
||||
|
||||
def prewarm_user(username: str, password: str, force: bool = False,
|
||||
only_tags: Optional[List[str]] = None, school_id=None) -> List[Dict]:
|
||||
"""为一个账号在所有线路上预热 session(3 线路并发,线路间互不阻塞)"""
|
||||
results = []
|
||||
school_id = school_id or school_for_username(username)
|
||||
lines = [l for l in get_lines(school_id) if not only_tags or l["tag"] in only_tags]
|
||||
|
||||
def _warm(line):
|
||||
from app.url_manager import push_school, pop_school
|
||||
push_school(school_id)
|
||||
try:
|
||||
url, tag = line["url"], line["tag"]
|
||||
data = _read_session(_line_session_file(username, tag))
|
||||
if data and not force and _is_session_valid_on(url, data.get("cookies", {})):
|
||||
return {"username": username, "tag": tag, "success": True, "skipped": True}
|
||||
return _login_on_line(username, password, url, tag)
|
||||
finally:
|
||||
pop_school()
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=len(lines)) as ex:
|
||||
futures = [ex.submit(_warm, l) for l in lines]
|
||||
for fut in concurrent.futures.as_completed(futures):
|
||||
try:
|
||||
results.append(fut.result())
|
||||
except Exception as e:
|
||||
results.append({"success": False, "message": str(e)})
|
||||
return results
|
||||
|
||||
|
||||
def prelogin_all(force: bool = False, progress_callback=None,
|
||||
school_id: Optional[str] = None) -> Dict:
|
||||
"""
|
||||
批量预热账号(账号串行限速防风控,单账号的线路间并发)。
|
||||
school_id 指定学校 → 只预热该校账号(管理端"该校全量预热")
|
||||
缺省 → 只预热已开启多线路预热的学校的账号
|
||||
"""
|
||||
from app.account_manager import AccountManager
|
||||
|
||||
accounts = AccountManager.get_all_accounts()
|
||||
summary = {"total": 0, "ok": 0, "failed": 0, "details": []}
|
||||
for i, acc in enumerate(accounts, 1):
|
||||
username = acc.get("jwxt_username") or acc.get("username") or ""
|
||||
password = acc.get("jwxt_password") or acc.get("password") or ""
|
||||
if not username:
|
||||
continue
|
||||
acc_school = acc.get('school_id') or DEFAULT_SCHOOL_ID
|
||||
if school_id:
|
||||
if acc_school != school_id:
|
||||
continue
|
||||
elif not is_enabled(acc_school):
|
||||
continue # 该校未开启多线路预热
|
||||
summary["total"] += 1
|
||||
res = prewarm_user(username, password, force=force, school_id=acc_school)
|
||||
ok = all(r.get("success") for r in res) if res else False
|
||||
summary["ok" if ok else "failed"] += 1
|
||||
summary["details"].append({"username": username, "lines": res})
|
||||
if progress_callback:
|
||||
try:
|
||||
progress_callback(summary["total"], summary["total"] + 1, username, ok, res)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.3) # 账号间限速
|
||||
logger.info(f"[multi_line] 预热完成: {summary['ok']}/{summary['total']} 成功"
|
||||
+ (f" (school={school_id})" if school_id else ""))
|
||||
return summary
|
||||
|
||||
|
||||
# ══════════════════════════════════════════════════════════
|
||||
# 秒切(换文件代替重登)
|
||||
# ══════════════════════════════════════════════════════════
|
||||
|
||||
def _swap_active_session(username: str, tag: str, url: str) -> bool:
|
||||
"""把 {username}@{tag}.json 的 cookies 原子写入生效的 {username}.json"""
|
||||
data = _read_session(_line_session_file(username, tag))
|
||||
if not data:
|
||||
return False
|
||||
headers = data.get("headers") or {}
|
||||
headers["Referer"] = url + "/xtgl/index_initMenu.html"
|
||||
data["headers"] = headers
|
||||
try:
|
||||
_atomic_write_json(_active_session_file(username), data)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"[multi_line] 换文件失败 {username}@{tag}: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def prewarm_switch(new_url: str, school_id=DEFAULT_SCHOOL_ID) -> Dict:
|
||||
"""
|
||||
全局线路切换的秒切入口(由 url_manager.switch_if_needed 在 set_base_url 之前调用):
|
||||
1. 校验目标线路可用
|
||||
2. 对每个账号:把目标线路的预热 session 原子写入生效文件
|
||||
(用户固定了其他线路的跳过,保持其偏好)
|
||||
多线路未开启(该校)时为 no-op。
|
||||
"""
|
||||
if not is_enabled(school_id):
|
||||
return {"skipped": "disabled"}
|
||||
|
||||
tag = line_tag(new_url)
|
||||
from app.account_manager import AccountManager
|
||||
accounts = AccountManager.get_all_accounts()
|
||||
|
||||
swapped, missing = 0, 0
|
||||
for acc in accounts:
|
||||
username = acc.get("jwxt_username") or acc.get("username") or ""
|
||||
if not username:
|
||||
continue
|
||||
if (acc.get('school_id') or DEFAULT_SCHOOL_ID) != school_id:
|
||||
continue
|
||||
from app.url_manager import push_school, pop_school
|
||||
push_school(school_id)
|
||||
try:
|
||||
# 用户固定了别的线路 → 不动他的生效文件
|
||||
pref = get_user_preference(username)
|
||||
if pref != "auto" and pref != tag:
|
||||
continue
|
||||
if _swap_active_session(username, tag, new_url.rstrip('/')):
|
||||
swapped += 1
|
||||
else:
|
||||
missing += 1
|
||||
finally:
|
||||
pop_school()
|
||||
|
||||
logger.info(f"[multi_line] 秒切到 {tag}: 换文件 {swapped} 个, 缺预热 {missing} 个")
|
||||
return {"swapped": swapped, "missing": missing, "tag": tag}
|
||||
|
||||
|
||||
def activate_user_line(username: str, tag: str) -> Dict:
|
||||
"""
|
||||
用户选择线路:把他生效的 {username}.json 换成目标线路的预热 session。
|
||||
返回 {'success': bool, 'message': str}
|
||||
"""
|
||||
url = url_by_tag(tag, school_for_username(username))
|
||||
if not url:
|
||||
return {"success": False, "message": f"未知线路: {tag}"}
|
||||
if not is_enabled(school_for_username(username)):
|
||||
return {"success": False, "message": "多线路模式未开启"}
|
||||
|
||||
data = _read_session(_line_session_file(username, tag))
|
||||
if not data:
|
||||
return {"success": False, "message": "该线路暂无预热 session,请稍后再试或联系管理员预热"}
|
||||
if not _is_session_valid_on(url, data.get("cookies", {})):
|
||||
return {"success": False, "message": "该线路预热 session 已失效,正在等待自动补登"}
|
||||
|
||||
if _swap_active_session(username, tag, url):
|
||||
set_user_preference(username, tag)
|
||||
return {"success": True, "message": f"已切换到线路 {tag}"}
|
||||
return {"success": False, "message": "切换失败(文件写入错误)"}
|
||||
|
||||
|
||||
# ══════════════════════════════════════════════════════════
|
||||
# 延迟测量与状态
|
||||
# ══════════════════════════════════════════════════════════
|
||||
|
||||
def refresh_latency():
|
||||
"""并发测量所有线路延迟,写入缓存"""
|
||||
global _latency_ts
|
||||
from app.url_manager import measure_latency
|
||||
try:
|
||||
urls = list({u for school in list_schools() for u in school['urls']})
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=len(urls)) as ex:
|
||||
fut_to_tag = {ex.submit(measure_latency, u): line_tag(u) for u in urls}
|
||||
for fut in concurrent.futures.as_completed(fut_to_tag, timeout=10):
|
||||
tag = fut_to_tag[fut]
|
||||
try:
|
||||
with _latency_lock:
|
||||
_latency_cache[tag] = fut.result()
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
_latency_ts = time.time() # 即使超时也更新,避免状态页永远"测速中"
|
||||
|
||||
|
||||
def get_latency(tag: str) -> Optional[float]:
|
||||
with _latency_lock:
|
||||
return _latency_cache.get(tag)
|
||||
|
||||
|
||||
def _ensure_latency_fresh(max_age: float = 60):
|
||||
"""缓存超过 max_age 秒则刷新一次。任一学校开启了多线路时由测速线程每 60s 维护,
|
||||
请求线程不做同步测量(避免阻塞请求最坏 5~6s),只有全部关闭才现场补测。"""
|
||||
if time.time() - _latency_ts < max_age:
|
||||
return
|
||||
if any_enabled():
|
||||
return
|
||||
try:
|
||||
refresh_latency()
|
||||
except Exception as e:
|
||||
logger.warning(f"[multi_line] 延迟测量失败: {e}")
|
||||
|
||||
|
||||
def get_status(school_id=DEFAULT_SCHOOL_ID) -> Dict:
|
||||
"""管理端状态视图"""
|
||||
# 注意:用全局地址而非 get_base_url()——本函数常在带线程级线路覆盖的
|
||||
# 请求线程里被调用,get_base_url() 会返回调用者自己的固定线路
|
||||
from app.url_manager import get_global_base_url
|
||||
from app.account_manager import AccountManager
|
||||
|
||||
# 缓存过期就现场测一轮,避免一直显示"测速中"
|
||||
_ensure_latency_fresh()
|
||||
|
||||
cfg = _load_config()
|
||||
current = get_global_base_url(school_id)
|
||||
n_accounts = sum(1 for acc in AccountManager.get_all_accounts()
|
||||
if (acc.get('school_id') or DEFAULT_SCHOOL_ID) == school_id)
|
||||
|
||||
lines = []
|
||||
for l in get_lines(school_id):
|
||||
prefix = '' if school_id == DEFAULT_SCHOOL_ID else f'{school_id}__'
|
||||
warmed = sum(1 for f in SESSION_DIR.glob(f"*@{l['tag']}.json")
|
||||
if f.name.startswith(prefix) and
|
||||
(school_id != DEFAULT_SCHOOL_ID or '__' not in f.name.split('@')[0]))
|
||||
lines.append({
|
||||
"tag": l["tag"],
|
||||
"url": l["url"],
|
||||
"latency": get_latency(l["tag"]),
|
||||
"is_current": l["url"] == current.rstrip('/'),
|
||||
"prewarmed": warmed,
|
||||
})
|
||||
|
||||
return {
|
||||
"multi_line_enabled": is_enabled(school_id),
|
||||
"xk_mode": is_xk_mode(school_id),
|
||||
"school_id": school_id,
|
||||
"current_line": line_tag(current),
|
||||
"current_url": current,
|
||||
"accounts": n_accounts,
|
||||
"lines": lines,
|
||||
"user_preferences": dict(cfg.get("user_preferences", {})),
|
||||
}
|
||||
|
||||
|
||||
# ══════════════════════════════════════════════════════════
|
||||
# 后台线程
|
||||
# ══════════════════════════════════════════════════════════
|
||||
|
||||
def _latency_loop():
|
||||
"""延迟测量:多线路开启期间每 60 秒测一轮,供管理端/用户端展示与智能切换参考"""
|
||||
refresh_latency() # 启动先测一轮,别让页面等 20 分钟才见数值
|
||||
while not _keepalive_stop.is_set():
|
||||
_keepalive_stop.wait(LATENCY_INTERVAL)
|
||||
# 所有学校都关闭预热后彻底退出
|
||||
if not any_enabled():
|
||||
break
|
||||
try:
|
||||
refresh_latency()
|
||||
except Exception as e:
|
||||
logger.warning(f"[multi_line] 延迟测量失败: {e}")
|
||||
|
||||
|
||||
def _backfill_active(username: str):
|
||||
"""
|
||||
回填生效文件:用户"应服务线路"(固定偏好,或 auto=全局当前线路)的预热
|
||||
session 有效,但生效文件在该线路上无效(如缺预热被跳过秒切、或旧线路
|
||||
cookie 残留)→ 用预热文件回填,避免错误配置持续到下一次全局切换。
|
||||
"""
|
||||
url = get_user_line_url(username)
|
||||
if url is None:
|
||||
from app.url_manager import get_global_base_url
|
||||
url = get_global_base_url(school_for_username(username))
|
||||
tag = line_tag(url)
|
||||
active = _read_session(_active_session_file(username))
|
||||
if active and _is_session_valid_on(url, active.get("cookies", {})):
|
||||
return # 生效文件本来就正常
|
||||
data = _read_session(_line_session_file(username, tag))
|
||||
if data and _is_session_valid_on(url, data.get("cookies", {})):
|
||||
_swap_active_session(username, tag, url)
|
||||
logger.info(f"[multi_line] 回填生效 session: {username}@{tag}")
|
||||
|
||||
|
||||
def _keepalive_loop():
|
||||
"""保活:定期心跳所有已开启预热学校的线路预热 session,过期的重登"""
|
||||
logger.info("[multi_line] 保活线程已启动")
|
||||
while not _keepalive_stop.is_set():
|
||||
_keepalive_stop.wait(KEEPALIVE_INTERVAL)
|
||||
if not any_enabled():
|
||||
break
|
||||
try:
|
||||
from app.account_manager import AccountManager
|
||||
for acc in AccountManager.get_all_accounts():
|
||||
if _keepalive_stop.is_set() or not any_enabled():
|
||||
break
|
||||
username = acc.get("jwxt_username") or acc.get("username") or ""
|
||||
password = acc.get("jwxt_password") or acc.get("password") or ""
|
||||
if not username:
|
||||
continue
|
||||
acc_school = acc.get('school_id') or DEFAULT_SCHOOL_ID
|
||||
if not is_enabled(acc_school):
|
||||
continue # 该校未开启预热,不消耗登录次数
|
||||
if not password:
|
||||
# 无密码账号:keepalive 无法补登,仅提示(其生效 session
|
||||
# 只能靠用户自己的请求级 with_session_retry 自救)
|
||||
logger.warning(f"[multi_line] 账号 {username} 无密码,跳过保活(无法自动补登)")
|
||||
continue
|
||||
# 只补登失效的线路(prewarm_user 内部会先校验,有效则跳过)
|
||||
try:
|
||||
from app.url_manager import push_school, pop_school
|
||||
push_school(acc_school)
|
||||
prewarm_user(username, password, force=False, school_id=acc_school)
|
||||
_backfill_active(username)
|
||||
except Exception as e:
|
||||
logger.warning(f"[multi_line] 保活 {username} 失败: {e}")
|
||||
finally:
|
||||
pop_school()
|
||||
time.sleep(0.2)
|
||||
except Exception as e:
|
||||
logger.error(f"[multi_line] 保活循环异常: {e}")
|
||||
logger.info("[multi_line] 保活线程已退出")
|
||||
|
||||
|
||||
def start_background(prelogin: bool = False, prelogin_school: Optional[str] = None):
|
||||
"""启动保活/测速线程;prelogin=True 时先做一轮预热(后台执行不阻塞)
|
||||
prelogin_school 指定时只预热该校,否则预热所有已开启预热的学校"""
|
||||
global _keepalive_thread, _latency_thread
|
||||
# 无条件 clear:处理"关闭后几秒内重新开启"——旧线程可能还活着但已收到停止信号,
|
||||
# clear 后它们会继续正常工作;若已退出则重新拉起
|
||||
_keepalive_stop.clear()
|
||||
|
||||
if not (_keepalive_thread and _keepalive_thread.is_alive()):
|
||||
_keepalive_thread = threading.Thread(target=_keepalive_loop, daemon=True, name="multi-line-keepalive")
|
||||
_keepalive_thread.start()
|
||||
|
||||
if not (_latency_thread and _latency_thread.is_alive()):
|
||||
_latency_thread = threading.Thread(target=_latency_loop, daemon=True, name="multi-line-latency")
|
||||
_latency_thread.start()
|
||||
|
||||
if prelogin:
|
||||
threading.Thread(target=prelogin_all, kwargs={'school_id': prelogin_school},
|
||||
daemon=True, name="multi-line-prelogin").start()
|
||||
@@ -0,0 +1,813 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
支付管理模块 - 处理订单、支付回调、邮件发送等
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import random
|
||||
import threading
|
||||
import hashlib
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
import smtplib
|
||||
from email.mime.text import MIMEText
|
||||
from email.mime.multipart import MIMEMultipart
|
||||
from pathlib import Path
|
||||
|
||||
from app.ticket_manager import TicketManager
|
||||
from app.time_utils import now as bj_now
|
||||
|
||||
# 支付FM配置
|
||||
# 注意:API地址请联系支付FM获取
|
||||
MERCHANT_NUM = os.environ.get('PAY_MERCHANT_NUM', "611986525303226368")
|
||||
PAY_SECRET = os.environ.get('PAY_SECRET', "cb5af747dc4fb12a8542935f2f765155")
|
||||
# 注意:以上默认值已进过 git 历史,建议尽快在支付FM后台轮换密钥并改用环境变量
|
||||
PAY_API_URL = "https://api-4ndv48ogy5fk.zhifu.fm.it88168.com/api/startOrder"
|
||||
|
||||
# 支付FM基础URL(通过 get_pay_base_url() 动态获取)
|
||||
def get_pay_base_url():
|
||||
"""获取支付FM基础URL,从配置文件读取"""
|
||||
try:
|
||||
from flask import current_app
|
||||
return current_app.config.get('PAY_BASE_URL', 'https://jwxt.bansonic.top')
|
||||
except:
|
||||
return 'https://jwxt.bansonic.top'
|
||||
|
||||
def get_notify_url():
|
||||
return f"{get_pay_base_url()}/notify"
|
||||
|
||||
def get_return_url():
|
||||
return f"{get_pay_base_url()}/return"
|
||||
|
||||
# 价格配置
|
||||
PRICE_CONFIG = {
|
||||
"default": {
|
||||
"single": 20, # 原价
|
||||
"quantity_discount": { # 批量折扣比例
|
||||
2: 0.05, # 2份以上 5%折扣
|
||||
6: 0.15, # 6份以上 15%折扣
|
||||
16: 0.25 # 16份以上 25%折扣
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# 提前预约折扣配置(与前端保持一致)
|
||||
PREBOOK_DISCOUNTS = [
|
||||
(150, 0.60), # 150天以上,减60%(8元)
|
||||
(120, 0.50), # 120天以上,减50%(10元)
|
||||
(90, 0.40), # 90天以上,减40%(12元)
|
||||
(60, 0.30), # 60天以上,减30%(14元)
|
||||
(30, 0.20), # 30天以上,减20%(16元)
|
||||
(14, 0.10), # 14天以上,减10%(18元)
|
||||
(0, 0.00), # 当天,无折扣(20元)
|
||||
]
|
||||
|
||||
def calculate_price(quantity: int, days_in_advance: int, invite_code: str = None) -> dict:
|
||||
"""计算价格(与前端算法保持一致)
|
||||
|
||||
Args:
|
||||
quantity: 购买数量
|
||||
days_in_advance: 提前预约天数
|
||||
invite_code: 邀请码(可选)
|
||||
|
||||
Returns:
|
||||
价格详情字典
|
||||
"""
|
||||
from app.affiliate_manager import AffiliateManager
|
||||
|
||||
base_price = 20
|
||||
|
||||
# 计算提前预约折扣
|
||||
time_discount = 0
|
||||
for min_days, discount in PREBOOK_DISCOUNTS:
|
||||
if days_in_advance >= min_days:
|
||||
time_discount = discount
|
||||
break
|
||||
|
||||
# 计算批量折扣
|
||||
bulk_discount = 0
|
||||
for min_qty, discount in sorted(PRICE_CONFIG["default"]["quantity_discount"].items(), reverse=True):
|
||||
if quantity >= min_qty:
|
||||
bulk_discount = discount
|
||||
break
|
||||
|
||||
# 计算邀请码折扣和佣金
|
||||
invite_discount = 0
|
||||
commission_rate = 0
|
||||
commission_amount = 0
|
||||
affiliate_name = None
|
||||
invite_discount_per_unit = 0
|
||||
|
||||
if invite_code:
|
||||
aff_info = AffiliateManager.verify_code(invite_code)
|
||||
if aff_info:
|
||||
invite_discount_per_unit = aff_info['discount_amount']
|
||||
commission_rate = aff_info['commission_rate']
|
||||
affiliate_name = aff_info['name']
|
||||
invite_discount = invite_discount_per_unit * quantity
|
||||
|
||||
# 计算最终价格
|
||||
unit_price = round(base_price * (1 - time_discount))
|
||||
subtotal = unit_price * quantity * (1 - bulk_discount)
|
||||
total = round(subtotal - invite_discount)
|
||||
per_person = round(total / quantity) if quantity > 0 else 0
|
||||
|
||||
# 计算佣金(基于实际支付金额)
|
||||
if commission_rate > 0:
|
||||
commission_amount = round(total * commission_rate / 100, 2)
|
||||
|
||||
return {
|
||||
"base_price": base_price,
|
||||
"unit_price": unit_price,
|
||||
"quantity": quantity,
|
||||
"days_in_advance": days_in_advance,
|
||||
"time_discount": time_discount,
|
||||
"time_discount_amount": round(base_price * time_discount) * quantity,
|
||||
"bulk_discount": bulk_discount,
|
||||
"bulk_discount_amount": round(unit_price * quantity * bulk_discount),
|
||||
"invite_discount": invite_discount,
|
||||
"invite_discount_per_unit": invite_discount_per_unit,
|
||||
"invite_code": invite_code.upper() if invite_code else None,
|
||||
"affiliate_name": affiliate_name,
|
||||
"commission_rate": commission_rate,
|
||||
"commission_amount": commission_amount,
|
||||
"subtotal": round(subtotal),
|
||||
"total": total,
|
||||
"per_person": per_person,
|
||||
"original_amount": base_price * quantity,
|
||||
"final_amount": max(1, total) # 最低1元
|
||||
}
|
||||
|
||||
|
||||
def _file_locked(method):
|
||||
"""装饰器:串行化 JSON 文件读-改-写,防并发双花/互相覆盖"""
|
||||
import functools
|
||||
@functools.wraps(method)
|
||||
def wrapper(*args, **kwargs):
|
||||
with PaymentManager._file_lock:
|
||||
return method(*args, **kwargs)
|
||||
return wrapper
|
||||
|
||||
|
||||
class PaymentManager:
|
||||
"""支付管理器"""
|
||||
|
||||
# 串行化 payments.json 的"读-改-写"全过程,防并发双花/互相覆盖
|
||||
_file_lock = threading.RLock() # RLock:锁内调用同类的其他加锁方法(如 use_ticket→verify_ticket)不会自死锁
|
||||
|
||||
@classmethod
|
||||
def _get_file_path(cls) -> str:
|
||||
"""获取支付数据文件路径"""
|
||||
return os.path.join(os.path.dirname(__file__), '..', 'payments.json')
|
||||
|
||||
@classmethod
|
||||
def _load_data(cls) -> Dict:
|
||||
"""加载支付数据"""
|
||||
file_path = cls._get_file_path()
|
||||
if os.path.exists(file_path):
|
||||
try:
|
||||
with open(file_path, 'r', encoding='utf-8') as f:
|
||||
return json.load(f)
|
||||
except (json.JSONDecodeError, IOError):
|
||||
pass
|
||||
return {
|
||||
'orders': [], # 订单列表
|
||||
'affiliates': {}, # 推广人员
|
||||
'orders_by_affiliate': {} # 按推广人员统计的订单
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def _save_data(cls, data: Dict):
|
||||
"""保存支付数据"""
|
||||
file_path = cls._get_file_path()
|
||||
with open(file_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=2)
|
||||
|
||||
@classmethod
|
||||
def generate_order_id(cls) -> str:
|
||||
"""生成订单号(含 secrets 随机段,防枚举遍历他人订单)"""
|
||||
import secrets
|
||||
return f"SDMU{int(time.time())}{secrets.token_hex(4).upper()}"
|
||||
|
||||
@classmethod
|
||||
def md5_sign(cls, text: str) -> str:
|
||||
"""MD5签名"""
|
||||
return hashlib.md5(text.encode('utf-8')).hexdigest().lower()
|
||||
|
||||
@classmethod
|
||||
def verify_pay_sign(cls, data: dict) -> bool:
|
||||
"""验证支付FM回调签名
|
||||
|
||||
支付FM回调参数:
|
||||
- merchantNum: 商户号
|
||||
- orderNo: 订单号
|
||||
- amount: 金额
|
||||
- notifyUrl: 通知URL
|
||||
- sign: 签名
|
||||
"""
|
||||
try:
|
||||
# 获取必要参数(支持多种可能的参数名)
|
||||
merchant_num = data.get('merchantNum') or data.get('merchant_num')
|
||||
order_no = data.get('orderNo') or data.get('order_no') or data.get('order_id')
|
||||
amount = data.get('amount') or data.get('actualPayAmount') or data.get('pay_amount')
|
||||
notify_url = data.get('notifyUrl') or data.get('notify_url') or get_notify_url()
|
||||
sign = data.get('sign')
|
||||
|
||||
if not all([merchant_num, order_no, amount, sign]):
|
||||
print(f"[支付回调] 缺少必要参数: merchant_num={merchant_num}, order_no={order_no}, amount={amount}, sign={sign}")
|
||||
return False
|
||||
|
||||
# 构建签名字符串(按照支付FM规则)
|
||||
sign_str = f"{merchant_num}{order_no}{amount}{notify_url}{PAY_SECRET}"
|
||||
expected_sign = cls.md5_sign(sign_str)
|
||||
|
||||
# 不打印 sign_str(内含 PAY_SECRET,会落日志)
|
||||
print(f"[支付回调] 签名验证: expected={expected_sign}, actual={sign}")
|
||||
|
||||
return expected_sign == sign
|
||||
except Exception as e:
|
||||
print(f"[支付回调] 签名验证异常: {e}")
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
@_file_locked
|
||||
def create_order(cls, email: str, quantity: int, invite_code: Optional[str] = None, days_in_advance: int = 0) -> Tuple[bool, str, Dict]:
|
||||
"""创建订单 - 与前端价格算法保持一致
|
||||
|
||||
Args:
|
||||
email: 用户邮箱
|
||||
quantity: 购买数量
|
||||
invite_code: 邀请码(可选)
|
||||
days_in_advance: 提前预约天数
|
||||
|
||||
Returns:
|
||||
success, message, order_data
|
||||
"""
|
||||
from app.affiliate_manager import AffiliateManager
|
||||
|
||||
# 验证邮箱格式
|
||||
if not re.match(r'^[\w\.-]+@[\w\.-]+$', email):
|
||||
return False, "邮箱格式不正确", {}
|
||||
|
||||
# 使用统一的价格计算函数(与前端一致)
|
||||
price_info = calculate_price(quantity, days_in_advance, invite_code)
|
||||
|
||||
# 验证邀请码并获取折扣信息
|
||||
invite_discount_per_unit = 0
|
||||
commission_rate = 0
|
||||
affiliate_name = None
|
||||
|
||||
if invite_code:
|
||||
aff_info = AffiliateManager.verify_code(invite_code)
|
||||
if aff_info:
|
||||
invite_discount_per_unit = aff_info['discount_amount']
|
||||
commission_rate = aff_info['commission_rate']
|
||||
affiliate_name = aff_info['name']
|
||||
invite_code = aff_info['code'] # 使用标准化的大写代码
|
||||
|
||||
# 生成订单号
|
||||
order_id = cls.generate_order_id()
|
||||
|
||||
# 保存订单
|
||||
data = cls._load_data()
|
||||
|
||||
# 检查订单号是否已存在
|
||||
for order in data['orders']:
|
||||
if order['order_id'] == order_id:
|
||||
return False, "订单号已存在,请重试", {}
|
||||
|
||||
# 计算订单过期时间(5分钟后)
|
||||
order_expires_at = (bj_now() + timedelta(minutes=5)).isoformat()
|
||||
|
||||
order_data = {
|
||||
"order_id": order_id,
|
||||
"email": email,
|
||||
"quantity": quantity,
|
||||
"days_in_advance": days_in_advance,
|
||||
"amount": price_info["original_amount"], # 原价
|
||||
"final_amount": price_info["final_amount"], # 实际支付价格
|
||||
"invite_code": invite_code,
|
||||
"invite_discount_per_unit": invite_discount_per_unit,
|
||||
"invite_discount_total": price_info["invite_discount"],
|
||||
"affiliate_name": affiliate_name,
|
||||
"status": "pending", # pending, paid, processed, cancelled, expired, refunded
|
||||
"commission_status": "pending" if invite_code else None, # 佣金状态
|
||||
"ticket_codes": [],
|
||||
"created_at": bj_now().isoformat(),
|
||||
"expires_at": order_expires_at, # 订单过期时间(5分钟后)
|
||||
"cancel_reason": None, # 取消原因
|
||||
"commission_rate": commission_rate,
|
||||
"commission_amount": price_info["commission_amount"] if invite_code else 0,
|
||||
# 详细价格分解(方便调试和展示)
|
||||
"price_breakdown": {
|
||||
"base_price": price_info["base_price"],
|
||||
"unit_price": price_info["unit_price"],
|
||||
"time_discount": price_info["time_discount"],
|
||||
"time_discount_amount": price_info["time_discount_amount"],
|
||||
"bulk_discount": price_info["bulk_discount"],
|
||||
"bulk_discount_amount": price_info["bulk_discount_amount"],
|
||||
}
|
||||
}
|
||||
|
||||
data['orders'].append(order_data)
|
||||
cls._save_data(data)
|
||||
|
||||
return True, "订单创建成功", order_data
|
||||
|
||||
@classmethod
|
||||
def get_order(cls, order_id: str) -> Optional[Dict]:
|
||||
"""获取订单信息"""
|
||||
data = cls._load_data()
|
||||
for order in data['orders']:
|
||||
if order['order_id'] == order_id:
|
||||
return order
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def is_order_expired(cls, order_id: str) -> bool:
|
||||
"""检查订单是否已过期
|
||||
|
||||
Args:
|
||||
order_id: 订单号
|
||||
|
||||
Returns:
|
||||
True 如果订单已过期或被取消
|
||||
"""
|
||||
order = cls.get_order(order_id)
|
||||
if not order:
|
||||
return True
|
||||
|
||||
status = order.get('status', 'pending')
|
||||
|
||||
# 如果订单已被取消或过期,直接返回
|
||||
if status in ['cancelled', 'expired', 'refunded', 'failed', 'paid', 'processed']:
|
||||
return status in ['cancelled', 'expired']
|
||||
|
||||
# 检查是否超过5分钟过期时间
|
||||
expires_at = order.get('expires_at')
|
||||
if expires_at:
|
||||
try:
|
||||
expire_time = datetime.fromisoformat(expires_at)
|
||||
if bj_now() > expire_time:
|
||||
# 自动标记为过期
|
||||
cls.update_order_status(order_id, 'expired')
|
||||
return True
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def get_order_status(cls, order_id: str) -> Dict:
|
||||
"""获取订单状态(包含过期信息)
|
||||
|
||||
Args:
|
||||
order_id: 订单号
|
||||
|
||||
Returns:
|
||||
包含状态信息的字典
|
||||
"""
|
||||
order = cls.get_order(order_id)
|
||||
if not order:
|
||||
return {
|
||||
'exists': False,
|
||||
'expired': True,
|
||||
'status': 'not_found',
|
||||
'message': '订单不存在'
|
||||
}
|
||||
|
||||
status = order.get('status', 'pending')
|
||||
expires_at = order.get('expires_at')
|
||||
remaining_seconds = 0
|
||||
is_expired = False
|
||||
|
||||
if status == 'pending' and expires_at:
|
||||
try:
|
||||
expire_time = datetime.fromisoformat(expires_at)
|
||||
remaining = (expire_time - bj_now()).total_seconds()
|
||||
if remaining <= 0:
|
||||
is_expired = True
|
||||
remaining_seconds = 0
|
||||
else:
|
||||
remaining_seconds = int(remaining)
|
||||
except (ValueError, TypeError):
|
||||
is_expired = True
|
||||
|
||||
return {
|
||||
'exists': True,
|
||||
'status': status,
|
||||
'is_expired': is_expired or status in ['cancelled', 'expired'],
|
||||
'remaining_seconds': remaining_seconds,
|
||||
'expires_at': expires_at,
|
||||
'cancel_reason': order.get('cancel_reason'),
|
||||
'can_cancel': status == 'pending' and not is_expired
|
||||
}
|
||||
|
||||
@classmethod
|
||||
@_file_locked
|
||||
def cancel_order(cls, order_id: str, reason: str = '用户主动取消') -> Tuple[bool, str]:
|
||||
"""取消订单
|
||||
|
||||
Args:
|
||||
order_id: 订单号
|
||||
reason: 取消原因
|
||||
|
||||
Returns:
|
||||
success, message
|
||||
"""
|
||||
data = cls._load_data()
|
||||
order_found = False
|
||||
|
||||
for order in data['orders']:
|
||||
if order['order_id'] == order_id:
|
||||
order_found = True
|
||||
old_status = order.get('status', 'pending')
|
||||
|
||||
# 只有 pending 状态的订单可以取消
|
||||
if old_status not in ['pending']:
|
||||
return False, f"订单状态为 {old_status},无法取消"
|
||||
|
||||
# 检查是否已过期
|
||||
expires_at = order.get('expires_at')
|
||||
if expires_at:
|
||||
try:
|
||||
expire_time = datetime.fromisoformat(expires_at)
|
||||
if bj_now() > expire_time:
|
||||
return False, "订单已过期,无法取消"
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
order['status'] = 'cancelled'
|
||||
order['cancel_reason'] = reason
|
||||
order['cancelled_at'] = bj_now().isoformat()
|
||||
break
|
||||
|
||||
if not order_found:
|
||||
return False, "订单不存在"
|
||||
|
||||
cls._save_data(data)
|
||||
return True, "订单已取消"
|
||||
|
||||
@classmethod
|
||||
@_file_locked
|
||||
def update_order_status(cls, order_id: str, status: str, platform_order_no: str = None,
|
||||
actual_pay_amount: str = None) -> Tuple[bool, str]:
|
||||
"""更新订单状态(支付回调时调用)
|
||||
|
||||
Args:
|
||||
order_id: 订单号
|
||||
status: 状态 (paid, failed, refunded等)
|
||||
platform_order_no: 支付平台订单号
|
||||
actual_pay_amount: 实际支付金额
|
||||
|
||||
Returns:
|
||||
success, message
|
||||
"""
|
||||
data = cls._load_data()
|
||||
order_found = False
|
||||
|
||||
for order in data['orders']:
|
||||
if order['order_id'] == order_id:
|
||||
order_found = True
|
||||
old_status = order.get('status', 'pending')
|
||||
|
||||
if status == "paid":
|
||||
# 支付成功
|
||||
order['status'] = 'paid'
|
||||
order['paid_at'] = bj_now().isoformat()
|
||||
|
||||
if platform_order_no:
|
||||
order['platform_order_no'] = platform_order_no
|
||||
|
||||
if actual_pay_amount:
|
||||
try:
|
||||
order['actual_pay_amount'] = float(actual_pay_amount)
|
||||
except:
|
||||
pass
|
||||
|
||||
# 如果是推广订单,设置佣金状态为待支付
|
||||
if order.get('invite_code'):
|
||||
order['commission_status'] = 'pending'
|
||||
|
||||
elif status == "failed":
|
||||
order['status'] = 'failed'
|
||||
order['failed_at'] = bj_now().isoformat()
|
||||
|
||||
elif status == "refunded":
|
||||
order['status'] = 'refunded'
|
||||
order['refunded_at'] = bj_now().isoformat()
|
||||
|
||||
# 如果已支付佣金,需要扣除
|
||||
if order.get('commission_status') == 'paid':
|
||||
order['commission_status'] = 'refunded'
|
||||
|
||||
break
|
||||
|
||||
if not order_found:
|
||||
return False, "订单不存在"
|
||||
|
||||
cls._save_data(data)
|
||||
return True, f"订单状态更新为 {status}"
|
||||
|
||||
@classmethod
|
||||
def process_paid_order(cls, order_id: str, expiry_days: int = 180) -> Tuple[bool, str, List[str]]:
|
||||
"""处理已支付订单:生成注册码并发送邮件
|
||||
|
||||
Args:
|
||||
order_id: 订单号
|
||||
expiry_days: 有效期天数
|
||||
|
||||
Returns:
|
||||
success, message, ticket_codes
|
||||
"""
|
||||
with cls._file_lock:
|
||||
data = cls._load_data()
|
||||
order = None
|
||||
|
||||
for o in data['orders']:
|
||||
if o['order_id'] == order_id:
|
||||
order = o
|
||||
break
|
||||
|
||||
if not order:
|
||||
return False, "订单不存在", []
|
||||
|
||||
if order['status'] != 'paid':
|
||||
return False, f"订单状态不是已支付: {order['status']}", []
|
||||
|
||||
# 已经处理过
|
||||
if order.get('ticket_codes') and len(order['ticket_codes']) > 0:
|
||||
return True, "订单已处理过", order['ticket_codes']
|
||||
|
||||
# 生成注册码
|
||||
quantity = order.get('quantity', 1)
|
||||
ticket_codes = []
|
||||
|
||||
for i in range(quantity):
|
||||
# 使用新的带横线格式
|
||||
code = TicketManager.generate_ticket(
|
||||
max_uses=1,
|
||||
expiry_days=expiry_days,
|
||||
created_by=f"order_{order_id}"
|
||||
)
|
||||
ticket_codes.append(code)
|
||||
|
||||
# 更新订单
|
||||
order['ticket_codes'] = ticket_codes
|
||||
order['status'] = 'processed'
|
||||
order['processed_at'] = bj_now().isoformat()
|
||||
order['expiry_days'] = expiry_days
|
||||
|
||||
cls._save_data(data)
|
||||
|
||||
# 发送邮件(最多重试 3 次;仍失败则订单标记 email_failed,可人工重发)
|
||||
email_success, email_msg = False, ""
|
||||
for attempt in range(1, 4):
|
||||
try:
|
||||
email_success, email_msg = cls.send_ticket_email(
|
||||
order['email'],
|
||||
ticket_codes,
|
||||
order_id,
|
||||
expiry_days
|
||||
)
|
||||
except Exception as mail_err:
|
||||
email_msg = str(mail_err)
|
||||
if email_success:
|
||||
break
|
||||
print(f"[支付回调] 邮件发送失败(第{attempt}/3次): {email_msg}")
|
||||
time.sleep(2)
|
||||
if not email_success:
|
||||
try:
|
||||
with cls._file_lock:
|
||||
data = cls._load_data()
|
||||
for o in data['orders']:
|
||||
if o['order_id'] == order_id:
|
||||
o['email_status'] = 'failed'
|
||||
o['email_error'] = email_msg
|
||||
cls._save_data(data)
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
return True, f"注册码生成成功但邮件发送失败(已重试3次): {email_msg}", ticket_codes
|
||||
|
||||
return True, "注册码已生成并发送到邮箱", ticket_codes
|
||||
|
||||
@classmethod
|
||||
def get_orders(cls, status: str = "all") -> List[Dict]:
|
||||
"""获取订单列表
|
||||
|
||||
Args:
|
||||
status: 订单状态 (all, pending, paid, processed, failed, refunded)
|
||||
|
||||
Returns:
|
||||
订单列表
|
||||
"""
|
||||
data = cls._load_data()
|
||||
orders = data['orders']
|
||||
|
||||
if status != "all":
|
||||
orders = [order for order in orders if order['status'] == status]
|
||||
|
||||
# 按创建时间倒序排序
|
||||
orders.sort(key=lambda x: x.get('created_at', ''), reverse=True)
|
||||
return orders
|
||||
|
||||
@classmethod
|
||||
def load_email_config(cls) -> Optional[Dict]:
|
||||
"""从email.txt加载邮箱配置"""
|
||||
try:
|
||||
config_file = Path("email.txt")
|
||||
if not config_file.exists():
|
||||
# 创建默认配置模板
|
||||
with open(config_file, 'w', encoding='utf-8') as f:
|
||||
f.write("smtp.qq.com\n")
|
||||
f.write("your_qq_email@qq.com\n")
|
||||
f.write("your_authorization_code\n")
|
||||
return None
|
||||
|
||||
with open(config_file, 'r', encoding='utf-8') as f:
|
||||
lines = [line.strip() for line in f.readlines() if line.strip()]
|
||||
if len(lines) >= 3:
|
||||
return {
|
||||
"smtp_server": lines[0],
|
||||
"email": lines[1],
|
||||
"password": lines[2]
|
||||
}
|
||||
return None
|
||||
except Exception as e:
|
||||
print(f"读取邮箱配置失败: {e}")
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def send_ticket_email(cls, to_email: str, ticket_codes: List[str],
|
||||
order_id: str, expiry_days: int = 7) -> Tuple[bool, str]:
|
||||
"""发送卡密邮件到用户邮箱
|
||||
|
||||
Args:
|
||||
to_email: 收件人邮箱
|
||||
ticket_codes: 注册码列表
|
||||
order_id: 订单号
|
||||
expiry_days: 有效期天数
|
||||
|
||||
Returns:
|
||||
success, message
|
||||
"""
|
||||
try:
|
||||
config = cls.load_email_config()
|
||||
if not config:
|
||||
return False, "邮箱配置不存在,请先配置email.txt文件"
|
||||
|
||||
# 构建邮件内容
|
||||
subject = f"SDMU抢课助手 - 您的注册码 (订单: {order_id})"
|
||||
|
||||
# HTML内容
|
||||
html_content = f"""
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>SDMU抢课助手 - 注册码</title>
|
||||
<style>
|
||||
body {{ font-family: Arial, sans-serif; line-height: 1.6; color: #333; }}
|
||||
.container {{ max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #ddd; border-radius: 5px; }}
|
||||
.header {{ background-color: #4CAF50; color: white; padding: 10px 20px; border-radius: 5px 5px 0 0; }}
|
||||
.content {{ padding: 20px; }}
|
||||
.code {{ font-family: monospace; font-size: 18px; background-color: #f5f5f5; padding: 10px; border-radius: 3px; margin: 10px 0; }}
|
||||
.important {{ color: #d32f2f; font-weight: bold; }}
|
||||
.footer {{ margin-top: 20px; padding-top: 20px; border-top: 1px solid #ddd; font-size: 12px; color: #777; }}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>SDMU抢课助手 - 注册码</h1>
|
||||
</div>
|
||||
<div class="content">
|
||||
<p>您好!</p>
|
||||
<p>感谢您购买SDMU抢课助手,以下是您的注册码:</p>
|
||||
|
||||
<h3>订单信息:</h3>
|
||||
<ul>
|
||||
<li>订单号:{order_id}</li>
|
||||
<li>注册码数量:{len(ticket_codes)} 个</li>
|
||||
<li>有效期:{expiry_days} 天</li>
|
||||
</ul>
|
||||
|
||||
<h3>注册码:</h3>
|
||||
"""
|
||||
|
||||
for i, code in enumerate(ticket_codes, 1):
|
||||
html_content += f'<div class="code">{code}</div>'
|
||||
|
||||
# 添加登录地址
|
||||
html_content += f"""
|
||||
<h3>使用说明:</h3>
|
||||
<ol>
|
||||
<li>访问:<a href="https://jwxt.bansonic.top">https://jwxt.bansonic.top</a></li>
|
||||
<li>点击右上角"注册"按钮</li>
|
||||
<li>输入用户名、密码和上面的注册码</li>
|
||||
<li>登录后即可开始使用</li>
|
||||
</ol>
|
||||
|
||||
<p class="important">重要提示:</p>
|
||||
<ul>
|
||||
<li>每个注册码只能使用一次</li>
|
||||
<li>请妥善保管您的注册码,不要泄露给他人</li>
|
||||
<li>注册码到期后将被自动回收</li>
|
||||
</ul>
|
||||
|
||||
<p>如有问题,请联系客服。</p>
|
||||
</div>
|
||||
<div class="footer">
|
||||
<p>SDMU抢课助手</p>
|
||||
<p>此为自动发送邮件,请勿回复</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
# 创建邮件
|
||||
msg = MIMEMultipart('alternative')
|
||||
msg['Subject'] = subject
|
||||
msg['From'] = config['email']
|
||||
msg['To'] = to_email
|
||||
|
||||
# 添加HTML版本
|
||||
html_part = MIMEText(html_content, 'html', 'utf-8')
|
||||
msg.attach(html_part)
|
||||
|
||||
# 发送邮件
|
||||
with smtplib.SMTP_SSL(config['smtp_server'], 465) as server:
|
||||
server.login(config['email'], config['password'])
|
||||
server.send_message(msg)
|
||||
|
||||
return True, "邮件发送成功"
|
||||
|
||||
except Exception as e:
|
||||
return False, f"邮件发送失败: {str(e)}"
|
||||
|
||||
@classmethod
|
||||
def get_order_stats(cls) -> Dict:
|
||||
"""获取订单统计信息"""
|
||||
data = cls._load_data()
|
||||
orders = data['orders']
|
||||
|
||||
stats = {
|
||||
'total': len(orders),
|
||||
'pending': 0,
|
||||
'paid': 0,
|
||||
'processed': 0,
|
||||
'failed': 0,
|
||||
'refunded': 0,
|
||||
'total_amount': 0,
|
||||
'total_final_amount': 0,
|
||||
'total_commission': 0
|
||||
}
|
||||
|
||||
for order in orders:
|
||||
status = order.get('status', 'pending')
|
||||
if status in stats:
|
||||
stats[status] += 1
|
||||
|
||||
stats['total_amount'] += order.get('amount', 0)
|
||||
stats['total_final_amount'] += order.get('final_amount', 0)
|
||||
stats['total_commission'] += order.get('commission_amount', 0)
|
||||
|
||||
return stats
|
||||
|
||||
@classmethod
|
||||
def create_payment_params(cls, order_id: str, pay_type: str = "alipay") -> Dict:
|
||||
"""创建支付参数
|
||||
|
||||
Args:
|
||||
order_id: 订单号
|
||||
pay_type: 支付类型 (alipay, wechat)
|
||||
|
||||
Returns:
|
||||
支付参数
|
||||
"""
|
||||
order = cls.get_order(order_id)
|
||||
if not order:
|
||||
return {}
|
||||
|
||||
# 计算签名
|
||||
sign_str = f"{MERCHANT_NUM}{order_id}{order['final_amount']}{get_notify_url()}{PAY_SECRET}"
|
||||
sign = cls.md5_sign(sign_str)
|
||||
|
||||
return_url = f"{get_return_url()}?orderNo={order_id}"
|
||||
|
||||
return {
|
||||
"merchantNum": MERCHANT_NUM,
|
||||
"orderNo": order_id,
|
||||
"amount": str(order['final_amount']),
|
||||
"notifyUrl": get_notify_url(),
|
||||
"returnUrl": return_url,
|
||||
"payType": pay_type,
|
||||
"sign": sign,
|
||||
"returnType": "page",
|
||||
"subject": f"SDMU抢课助手 x{order['quantity']}份"
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
"""School configuration, persisted independently of the user database."""
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from app.settings import BASE_DIR, BASE_URLS
|
||||
|
||||
DEFAULT_SCHOOL_ID = 'sdmu'
|
||||
CONFIG_FILE = BASE_DIR / 'schools.json'
|
||||
# 上传的学校图标(统一转 64x64 PNG),按学校标识存放
|
||||
ICON_DIR = BASE_DIR / 'uploads' / 'school_icons'
|
||||
ICON_MAX_BYTES = 1024 * 1024
|
||||
ICON_MAX_SIDE = 1024
|
||||
_lock = threading.RLock()
|
||||
|
||||
# 课表查询来源:auto=网页版优先失败回退Mobile,web=网页版接口,mobile=正方APP接口
|
||||
KBCX_SOURCES = ('auto', 'web', 'mobile')
|
||||
|
||||
|
||||
def _default():
|
||||
return {'id': DEFAULT_SCHOOL_ID, 'name': '山东管理学院',
|
||||
'urls': list(BASE_URLS), 'requires_captcha': True,
|
||||
'kbcx_source': 'auto'}
|
||||
|
||||
|
||||
def list_schools():
|
||||
with _lock:
|
||||
try:
|
||||
schools = json.loads(CONFIG_FILE.read_text(encoding='utf-8'))
|
||||
if isinstance(schools, list) and schools:
|
||||
return schools
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
return [_default()]
|
||||
|
||||
|
||||
def get_school(school_id):
|
||||
return next((s for s in list_schools() if s['id'] == school_id), None)
|
||||
|
||||
|
||||
def school_urls(school_id):
|
||||
school = get_school(school_id) or get_school(DEFAULT_SCHOOL_ID)
|
||||
return list(school['urls']) if school else list(BASE_URLS)
|
||||
|
||||
|
||||
def requires_captcha(school_id):
|
||||
school = get_school(school_id) or get_school(DEFAULT_SCHOOL_ID)
|
||||
return school.get('requires_captcha', True) if school else True
|
||||
|
||||
|
||||
def school_abbr(school_id=None):
|
||||
"""学校品牌缩写:配置的 abbr 优先,否则取学校标识大写;未知学校退回标识大写"""
|
||||
school = get_school(school_id)
|
||||
if school is None and school_id and school_id != DEFAULT_SCHOOL_ID:
|
||||
return str(school_id).upper()
|
||||
school = school or get_school(DEFAULT_SCHOOL_ID)
|
||||
if not school:
|
||||
return str(school_id or DEFAULT_SCHOOL_ID).upper()
|
||||
abbr = str(school.get('abbr') or '').strip()
|
||||
return (abbr or school.get('id') or DEFAULT_SCHOOL_ID).upper()
|
||||
|
||||
|
||||
def school_favicon(school_id=None):
|
||||
"""学校 ICO 图标地址(未配置返回 None)"""
|
||||
school = get_school(school_id)
|
||||
return ((school or {}).get('favicon') or '').strip() or None
|
||||
|
||||
|
||||
def save_school_icon(school_id, file_storage) -> str:
|
||||
"""
|
||||
接收上传的图片,校验后统一转成 64x64 PNG,以版本化文件名原子写入
|
||||
uploads/school_icons/{school_id}_{时间戳}.png,返回 favicon URL。
|
||||
版本化文件名避免覆盖正被读取的旧文件(Windows 下覆盖打开中的文件会失败),
|
||||
旧版本在保存成功后尽力清理。
|
||||
"""
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
data = file_storage.read()
|
||||
if not data:
|
||||
raise ValueError('未读取到图片内容')
|
||||
if len(data) > ICON_MAX_BYTES:
|
||||
raise ValueError('图片不能超过 1MB')
|
||||
try:
|
||||
img = Image.open(io.BytesIO(data))
|
||||
img.load()
|
||||
except Exception:
|
||||
raise ValueError('无法识别的图片文件,请上传 PNG/JPG/GIF/WebP/ICO 图片')
|
||||
img = ImageOps.exif_transpose(img).convert('RGBA')
|
||||
w, h = img.size
|
||||
if w == 0 or h == 0:
|
||||
raise ValueError('图片尺寸无效')
|
||||
if max(w, h) > ICON_MAX_SIDE:
|
||||
raise ValueError(f'图片尺寸过大(最长边不超过 {ICON_MAX_SIDE}px)')
|
||||
# 居中裁正方形(favicon 需要方形)
|
||||
side = min(w, h)
|
||||
img = img.crop(((w - side) // 2, (h - side) // 2, (w + side) // 2, (h + side) // 2))
|
||||
if side > 64:
|
||||
img = img.resize((64, 64), Image.LANCZOS)
|
||||
|
||||
ICON_DIR.mkdir(parents=True, exist_ok=True)
|
||||
version = int(time.time() * 1000) # 毫秒级,连续上传也不同名
|
||||
target = ICON_DIR / f'{school_id}_{version}.png'
|
||||
fd, tmp = tempfile.mkstemp(dir=str(ICON_DIR), suffix='.tmp')
|
||||
try:
|
||||
with os.fdopen(fd, 'wb') as f:
|
||||
img.save(f, 'PNG')
|
||||
os.replace(tmp, target)
|
||||
finally:
|
||||
if os.path.exists(tmp):
|
||||
try:
|
||||
os.unlink(tmp)
|
||||
except OSError:
|
||||
pass
|
||||
_cleanup_old_icons(school_id, keep=target.name)
|
||||
return f'/uploads/school_icons/{target.name}'
|
||||
|
||||
|
||||
def _cleanup_old_icons(school_id: str, keep: str):
|
||||
"""清理同校旧版本图标;被占用的文件(正在被请求)留待下次清理"""
|
||||
try:
|
||||
for f in ICON_DIR.glob(f'{school_id}_*.png'):
|
||||
if f.name != keep:
|
||||
try:
|
||||
f.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def clear_school_icon(school_id):
|
||||
"""删除该校上传的图标文件,并把配置里的 favicon 一并清空"""
|
||||
_cleanup_old_icons(school_id, keep='')
|
||||
school = get_school(school_id)
|
||||
if school and (school.get('favicon') or '').startswith('/uploads/'):
|
||||
merged = dict(school)
|
||||
merged['favicon'] = ''
|
||||
save_school(merged)
|
||||
|
||||
|
||||
def kbcx_source(school_id):
|
||||
"""该校课表查询使用的接口来源(auto/web/mobile)"""
|
||||
school = get_school(school_id) or get_school(DEFAULT_SCHOOL_ID)
|
||||
source = school.get('kbcx_source', 'auto') if school else 'auto'
|
||||
return source if source in KBCX_SOURCES else 'auto'
|
||||
|
||||
|
||||
def save_school(payload):
|
||||
"""Validate and atomically replace one school's configuration."""
|
||||
school_id = str(payload.get('id') or '').strip()
|
||||
name = str(payload.get('name') or '').strip()
|
||||
urls = payload.get('urls')
|
||||
if not school_id or len(school_id) > 40 or not all(c.isascii() and (c.isalnum() or c in '_-') for c in school_id):
|
||||
raise ValueError('学校标识只能包含英文字母、数字、下划线和连字符')
|
||||
if not name or len(name) > 100:
|
||||
raise ValueError('学校名称不能为空且不能超过100字')
|
||||
if not isinstance(urls, list) or not urls or len(urls) > 20:
|
||||
raise ValueError('每所学校须配置1至20条线路')
|
||||
clean_urls = []
|
||||
for value in urls:
|
||||
url = str(value).strip().rstrip('/')
|
||||
parsed = urlparse(url)
|
||||
if parsed.scheme not in ('http', 'https') or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment:
|
||||
raise ValueError('线路必须是有效的 http/https 教务系统基础地址')
|
||||
if url not in clean_urls:
|
||||
clean_urls.append(url)
|
||||
if len({urlparse(url).netloc for url in clean_urls}) != len(clean_urls):
|
||||
raise ValueError('同一学校的线路主机名不能重复')
|
||||
kbcx = str(payload.get('kbcx_source') or 'auto').strip()
|
||||
if kbcx not in KBCX_SOURCES:
|
||||
raise ValueError('课表来源只能是 auto、web 或 mobile')
|
||||
abbr = str(payload.get('abbr') or '').strip()
|
||||
if abbr and (len(abbr) > 12 or not all(c.isascii() and c.isalnum() for c in abbr)):
|
||||
raise ValueError('学校缩写只能是英文字母或数字(不超过12个字符)')
|
||||
if 'favicon' in payload:
|
||||
favicon = str(payload.get('favicon') or '').strip()
|
||||
else:
|
||||
# favicon 由图标上传/清除端点独立管理,常规保存不携带时保留原值
|
||||
existing = get_school(school_id)
|
||||
favicon = str((existing or {}).get('favicon') or '').strip()
|
||||
if favicon:
|
||||
if favicon.startswith('/'):
|
||||
# 站内路径(上传图标生成,如 /uploads/school_icons/qdc.png?v=1)
|
||||
if len(favicon) > 500 or '..' in favicon:
|
||||
raise ValueError('学校 ICO 地址无效')
|
||||
else:
|
||||
parsed = urlparse(favicon)
|
||||
if parsed.scheme not in ('http', 'https') or not parsed.netloc or len(favicon) > 500:
|
||||
raise ValueError('学校 ICO 必须是有效的 http/https 图片地址')
|
||||
school = {'id': school_id, 'name': name, 'urls': clean_urls,
|
||||
'requires_captcha': bool(payload.get('requires_captcha', True)),
|
||||
'kbcx_source': kbcx, 'abbr': abbr, 'favicon': favicon}
|
||||
with _lock:
|
||||
schools = list_schools()
|
||||
for index, existing in enumerate(schools):
|
||||
if existing['id'] == school_id:
|
||||
schools[index] = school
|
||||
break
|
||||
else:
|
||||
schools.append(school)
|
||||
fd, temporary = tempfile.mkstemp(dir=CONFIG_FILE.parent, suffix='.tmp')
|
||||
try:
|
||||
with os.fdopen(fd, 'w', encoding='utf-8') as stream:
|
||||
json.dump(schools, stream, ensure_ascii=False, indent=2)
|
||||
os.replace(temporary, CONFIG_FILE)
|
||||
finally:
|
||||
if os.path.exists(temporary):
|
||||
os.unlink(temporary)
|
||||
return school
|
||||
|
||||
|
||||
def school_for_username(jwxt_username):
|
||||
"""Background workers resolve the school from accounts.json without Flask context."""
|
||||
from app.url_manager import current_school_id
|
||||
active = current_school_id()
|
||||
if active:
|
||||
return active
|
||||
from app.account_manager import AccountManager
|
||||
for account in AccountManager.get_all_accounts():
|
||||
if account.get('jwxt_username') == jwxt_username:
|
||||
return account.get('school_id') or DEFAULT_SCHOOL_ID
|
||||
return DEFAULT_SCHOOL_ID
|
||||
|
||||
|
||||
def session_key(jwxt_username, school_id=None):
|
||||
from app.url_manager import current_school_id
|
||||
school_id = school_id or current_school_id() or DEFAULT_SCHOOL_ID
|
||||
return jwxt_username if school_id == DEFAULT_SCHOOL_ID else f'{school_id}__{jwxt_username}'
|
||||
@@ -0,0 +1,542 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Session管理工具类
|
||||
负责检测、刷新和管理教务系统Session
|
||||
|
||||
账号分离设计:
|
||||
- 网站账号:存储在数据库 (User模型)
|
||||
- 教务系统账号:存储在 accounts.json
|
||||
"""
|
||||
import json
|
||||
import time
|
||||
import base64
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from app.time_utils import now as bj_now
|
||||
|
||||
import requests
|
||||
from Crypto.PublicKey import RSA
|
||||
from Crypto.Cipher import PKCS1_v1_5
|
||||
|
||||
from app.jwxt_login import JWXTLogin
|
||||
from app.account_manager import AccountManager
|
||||
|
||||
from app.settings import SESSION_DIR
|
||||
from app.url_manager import get_base_url
|
||||
SESSION_DIR.mkdir(exist_ok=True)
|
||||
|
||||
class SessionManager:
|
||||
"""Session管理器"""
|
||||
|
||||
@staticmethod
|
||||
def get_session_file(username):
|
||||
"""获取session文件路径"""
|
||||
from app.school_manager import session_key
|
||||
return SESSION_DIR / f"{session_key(username)}.json"
|
||||
|
||||
@staticmethod
|
||||
def _save_session_atomic(username, data, login_base_url=None):
|
||||
"""
|
||||
原子保存 session 文件,并处理多线路错配:
|
||||
登录耗时数秒(OCR 重试),期间全局线路可能已切换、或用户固定了其他
|
||||
线路——此时这份 cookie 不能覆盖生效文件(会造成 cookie 与请求线路
|
||||
错配),改写入对应线路的预热文件,由 multi_line 统一调度。
|
||||
|
||||
本方法可能在无学校上下文的后台线程被调用,先按账号绑定学校,
|
||||
否则 session 文件命名会落到默认学校(多学校场景错写文件)。
|
||||
"""
|
||||
data_json = json.dumps(data, ensure_ascii=False, indent=2)
|
||||
from app.url_manager import push_school, pop_school
|
||||
from app.school_manager import school_for_username
|
||||
acc_school = school_for_username(username)
|
||||
push_school(acc_school)
|
||||
try:
|
||||
target = SessionManager.get_session_file(username)
|
||||
try:
|
||||
from app import multi_line as ml
|
||||
if ml.is_enabled(acc_school) and login_base_url:
|
||||
login_tag = ml.line_tag(login_base_url)
|
||||
pref = ml.get_user_preference(username, acc_school)
|
||||
if pref in ('auto', '', None):
|
||||
from app.url_manager import get_global_base_url
|
||||
serving_tag = ml.line_tag(get_global_base_url(acc_school))
|
||||
else:
|
||||
serving_tag = pref
|
||||
if login_tag != serving_tag:
|
||||
ml._atomic_write_json(ml._line_session_file(username, login_tag), data)
|
||||
logging.getLogger(__name__).info(
|
||||
f"[session_manager] 登录线路({login_tag})与生效线路({serving_tag})不一致,"
|
||||
f"cookie 已写入预热文件,不覆盖生效 session"
|
||||
)
|
||||
return
|
||||
except ImportError:
|
||||
pass
|
||||
# 原子写入生效文件(避免抢课线程读到半截 JSON)
|
||||
try:
|
||||
from app import multi_line as ml
|
||||
ml._atomic_write_json(target, data)
|
||||
except Exception:
|
||||
target.write_text(data_json, encoding="utf-8")
|
||||
finally:
|
||||
pop_school()
|
||||
|
||||
@staticmethod
|
||||
def is_session_valid(username):
|
||||
"""
|
||||
检查session是否有效
|
||||
返回: (is_valid, error_msg)
|
||||
"""
|
||||
import requests
|
||||
|
||||
session_file = SessionManager.get_session_file(username)
|
||||
if not session_file.exists():
|
||||
return False, "Session文件不存在"
|
||||
|
||||
try:
|
||||
data = json.loads(session_file.read_text(encoding="utf-8"))
|
||||
s = requests.Session()
|
||||
s.cookies.update(data.get("cookies", {}))
|
||||
r = s.get(get_base_url() + "/xtgl/index_initMenu.html",
|
||||
allow_redirects=False, timeout=8)
|
||||
|
||||
if r.status_code == 200:
|
||||
return True, None
|
||||
if r.status_code == 302 and 'login' in (r.headers.get('Location') or ''):
|
||||
return False, "Session已过期(302到登录页)"
|
||||
# 5xx/网关错误等不算 session 过期(避免上游抖动触发无谓重登)
|
||||
return False, f"教务系统响应异常 (HTTP {r.status_code})"
|
||||
except Exception as e:
|
||||
return False, f"检查Session时出错: {str(e)}"
|
||||
|
||||
@staticmethod
|
||||
def login_and_save(username, password, max_retries=10):
|
||||
"""
|
||||
登录并保存session
|
||||
返回: (success, error_msg, timing_dict_or_None)
|
||||
"""
|
||||
# 固定本次登录所用线路:重试期间全局线路可能切换,登录与写文件必须同线路
|
||||
login_base_url = get_base_url()
|
||||
login = JWXTLogin(base_url=login_base_url)
|
||||
ocr_times = []
|
||||
|
||||
for attempt in range(1, max_retries + 1):
|
||||
try:
|
||||
result = login.login(username, password)
|
||||
if result.get('stop_retry'):
|
||||
# 密码到期等不可恢复错误:立即终止,避免白打剩余重试
|
||||
timing = {'attempts': attempt, 'ocr_ms': result.get('ocr_ms', 0)}
|
||||
return False, result.get('message', '登录失败(不可恢复)'), timing
|
||||
success = result.get('success', False)
|
||||
|
||||
if result.get('ocr_ms'):
|
||||
ocr_times.append(result['ocr_ms'])
|
||||
|
||||
if success:
|
||||
# 保存session
|
||||
data = {
|
||||
"cookies": dict(login.session.cookies),
|
||||
"headers": dict(login.session.headers),
|
||||
}
|
||||
SessionManager._save_session_atomic(username, data, login_base_url)
|
||||
timing = {
|
||||
'attempts': attempt,
|
||||
'ocr_ms': result.get('ocr_ms', 0),
|
||||
'ocr_avg_ms': int(sum(ocr_times) / len(ocr_times)) if len(ocr_times) > 1 else 0,
|
||||
}
|
||||
return True, None, timing
|
||||
else:
|
||||
if attempt < max_retries:
|
||||
time.sleep(0.5)
|
||||
login = JWXTLogin(base_url=login_base_url)
|
||||
except Exception as e:
|
||||
if attempt < max_retries:
|
||||
time.sleep(0.5)
|
||||
login = JWXTLogin(base_url=login_base_url)
|
||||
else:
|
||||
timing = {
|
||||
'attempts': attempt,
|
||||
'ocr_ms': ocr_times[-1] if ocr_times else 0,
|
||||
'ocr_avg_ms': int(sum(ocr_times) / len(ocr_times)) if len(ocr_times) > 1 else 0,
|
||||
}
|
||||
return False, f"登录异常: {str(e)}", timing
|
||||
|
||||
timing = {
|
||||
'attempts': max_retries,
|
||||
'ocr_ms': ocr_times[-1] if ocr_times else 0,
|
||||
'ocr_avg_ms': int(sum(ocr_times) / len(ocr_times)) if len(ocr_times) > 1 else 0,
|
||||
}
|
||||
return False, f"登录失败,已尝试{max_retries}次", timing
|
||||
|
||||
@staticmethod
|
||||
def refresh_session(user, force=False):
|
||||
"""
|
||||
刷新指定用户的session(自动从 accounts.json 获取密码)
|
||||
|
||||
Args:
|
||||
user: User模型对象
|
||||
force: 是否强制刷新(忽略当前session是否有效)
|
||||
|
||||
返回: {
|
||||
'success': bool,
|
||||
'status': 'valid'/'refreshed'/'failed',
|
||||
'message': str,
|
||||
'error': str or None
|
||||
}
|
||||
"""
|
||||
# 获取教务系统账号
|
||||
jwxt_acc = AccountManager.get_jwxt_account(user_id=user.id, username=user.username)
|
||||
|
||||
if not jwxt_acc:
|
||||
return {
|
||||
'success': False,
|
||||
'status': 'failed',
|
||||
'message': '未配置教务系统账号',
|
||||
'error': 'no_account'
|
||||
}
|
||||
|
||||
username = jwxt_acc['username']
|
||||
password = jwxt_acc['password']
|
||||
|
||||
# 如果不是强制刷新,先检查当前session
|
||||
if not force:
|
||||
is_valid, error_msg = SessionManager.is_session_valid(username)
|
||||
if is_valid:
|
||||
# 更新状态
|
||||
user.session_status = 'valid'
|
||||
user.session_updated_at = bj_now()
|
||||
user.session_error_msg = None
|
||||
return {
|
||||
'success': True,
|
||||
'status': 'valid',
|
||||
'message': 'Session仍然有效',
|
||||
'error': None
|
||||
}
|
||||
|
||||
# 执行登录
|
||||
success, error_msg, timing = SessionManager.login_and_save(
|
||||
username, password, max_retries=10
|
||||
)
|
||||
|
||||
if success:
|
||||
user.session_status = 'valid'
|
||||
user.session_updated_at = bj_now()
|
||||
user.session_error_msg = None
|
||||
return {
|
||||
'success': True,
|
||||
'status': 'refreshed',
|
||||
'message': 'Session刷新成功',
|
||||
'error': None,
|
||||
'timing': timing or {},
|
||||
}
|
||||
else:
|
||||
user.session_status = 'invalid'
|
||||
user.session_error_msg = error_msg
|
||||
return {
|
||||
'success': False,
|
||||
'status': 'failed',
|
||||
'message': error_msg,
|
||||
'error': 'login_failed',
|
||||
'timing': timing or {},
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def refresh_session_with_password(user, password, force=False):
|
||||
"""
|
||||
使用明文密码刷新session(用于用户主动刷新)
|
||||
|
||||
返回: {
|
||||
'success': bool,
|
||||
'status': 'valid'/'refreshed'/'failed',
|
||||
'message': str,
|
||||
'error': str or None
|
||||
}
|
||||
"""
|
||||
username = user.jwxt_username or user.username
|
||||
|
||||
# 如果不是强制刷新,先检查当前session
|
||||
if not force:
|
||||
is_valid, error_msg = SessionManager.is_session_valid(username)
|
||||
if is_valid:
|
||||
user.session_status = 'valid'
|
||||
user.session_updated_at = bj_now()
|
||||
user.session_error_msg = None
|
||||
return {
|
||||
'success': True,
|
||||
'status': 'valid',
|
||||
'message': 'Session仍然有效',
|
||||
'error': None
|
||||
}
|
||||
|
||||
# 执行登录
|
||||
success, error_msg, timing = SessionManager.login_and_save(
|
||||
username, password, max_retries=10
|
||||
)
|
||||
|
||||
if success:
|
||||
user.session_status = 'valid'
|
||||
user.session_updated_at = bj_now()
|
||||
user.session_error_msg = None
|
||||
return {
|
||||
'success': True,
|
||||
'status': 'refreshed',
|
||||
'message': 'Session刷新成功',
|
||||
'error': None,
|
||||
'timing': timing or {},
|
||||
}
|
||||
else:
|
||||
user.session_status = 'invalid'
|
||||
user.session_error_msg = error_msg
|
||||
return {
|
||||
'success': False,
|
||||
'status': 'failed',
|
||||
'message': error_msg,
|
||||
'error': 'login_failed',
|
||||
'timing': timing or {},
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def reset_password_expiry(username, password):
|
||||
"""
|
||||
密码到期时,通过提交相同密码来刷新有效期。
|
||||
使用当前 session(即使有"无功能权限",cookies 仍有效)调用密码重置 API。
|
||||
|
||||
Args:
|
||||
username: 教务系统学号
|
||||
password: 教务系统密码(明文)
|
||||
|
||||
Returns:
|
||||
{'success': True/False, 'message': str}
|
||||
"""
|
||||
sf = SessionManager.get_session_file(username)
|
||||
if not sf.exists():
|
||||
return {'success': False, 'message': 'Session 文件不存在,无法重置密码'}
|
||||
|
||||
try:
|
||||
data = json.loads(sf.read_text(encoding='utf-8'))
|
||||
except Exception as e:
|
||||
return {'success': False, 'message': f'Session 文件解析失败: {e}'}
|
||||
|
||||
s = requests.Session()
|
||||
s.cookies.update(data.get('cookies', {}))
|
||||
s.headers.update({
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
'Referer': f'{get_base_url()}/xtgl/index_initMenu.html',
|
||||
})
|
||||
|
||||
try:
|
||||
# 1. 获取 RSA 公钥
|
||||
r = s.get(f"{get_base_url()}/xtgl/login_getPublicKey.html",
|
||||
params={"time": int(time.time() * 1000)}, timeout=10)
|
||||
r.raise_for_status()
|
||||
d = r.json()
|
||||
|
||||
# 2. RSA 加密密码
|
||||
modulus_int = int.from_bytes(base64.b64decode(d['modulus']), byteorder='big')
|
||||
exponent_int = int.from_bytes(base64.b64decode(d['exponent']), byteorder='big')
|
||||
key = RSA.construct((modulus_int, exponent_int))
|
||||
cipher = PKCS1_v1_5.new(key)
|
||||
encrypted = cipher.encrypt(password.encode('utf-8'))
|
||||
enc_pwd = base64.b64encode(encrypted).decode('utf-8')
|
||||
|
||||
# 3. 提交密码重置(旧密码=新密码,刷新有效期)
|
||||
r2 = s.post(
|
||||
f"{get_base_url()}/xtgl/mmgl_xgRsaMm.html",
|
||||
data={"ymm": enc_pwd, "mm": enc_pwd, "doType": "save"},
|
||||
timeout=15
|
||||
)
|
||||
if "成功" in r2.text:
|
||||
return {'success': True, 'message': '密码有效期已刷新'}
|
||||
else:
|
||||
return {'success': False, 'message': f'密码重置接口返回异常: {r2.text[:200]}'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'message': f'密码重置失败: {e}'}
|
||||
|
||||
@staticmethod
|
||||
def test_login(username, password, max_attempts=10):
|
||||
"""
|
||||
测试登录,用于注册时验证账号密码
|
||||
|
||||
返回: (success, message)
|
||||
"""
|
||||
login = JWXTLogin(base_url=get_base_url())
|
||||
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
result = login.login(username, password)
|
||||
if result.get('success'):
|
||||
return True, "登录验证成功"
|
||||
else:
|
||||
if attempt < max_attempts:
|
||||
time.sleep(0.3)
|
||||
login = JWXTLogin(base_url=get_base_url())
|
||||
except Exception as e:
|
||||
if attempt < max_attempts:
|
||||
time.sleep(0.3)
|
||||
login = JWXTLogin(base_url=get_base_url())
|
||||
else:
|
||||
return False, f"验证异常: {str(e)}"
|
||||
|
||||
return False, "账号或密码错误,请检查教务系统账号信息"
|
||||
|
||||
@staticmethod
|
||||
def batch_refresh(users, force=False, progress_callback=None):
|
||||
"""
|
||||
批量刷新session(自动从 accounts.json 获取密码)
|
||||
|
||||
Args:
|
||||
users: User对象列表
|
||||
force: 是否强制刷新
|
||||
progress_callback: 进度回调函数(user, result)
|
||||
|
||||
返回: {
|
||||
'total': int,
|
||||
'valid': int,
|
||||
'refreshed': int,
|
||||
'failed': int,
|
||||
'no_account': int,
|
||||
'details': list
|
||||
}
|
||||
"""
|
||||
results = {
|
||||
'total': len(users),
|
||||
'valid': 0,
|
||||
'refreshed': 0,
|
||||
'failed': 0,
|
||||
'no_account': 0,
|
||||
'details': []
|
||||
}
|
||||
|
||||
for user in users:
|
||||
# 获取教务系统账号
|
||||
jwxt_acc = AccountManager.get_jwxt_account(
|
||||
user_id=user.id, username=user.username
|
||||
)
|
||||
|
||||
if not jwxt_acc:
|
||||
result = {
|
||||
'user_id': user.id,
|
||||
'username': user.username,
|
||||
'status': 'no_account',
|
||||
'message': '未配置教务系统账号'
|
||||
}
|
||||
results['no_account'] += 1
|
||||
results['failed'] += 1
|
||||
else:
|
||||
# 执行刷新
|
||||
result = SessionManager.refresh_session(user, force=force)
|
||||
result['user_id'] = user.id
|
||||
result['username'] = user.username
|
||||
|
||||
if result['status'] == 'valid':
|
||||
results['valid'] += 1
|
||||
elif result['status'] == 'refreshed':
|
||||
results['refreshed'] += 1
|
||||
else:
|
||||
results['failed'] += 1
|
||||
|
||||
results['details'].append(result)
|
||||
|
||||
if progress_callback:
|
||||
progress_callback(user, result)
|
||||
|
||||
time.sleep(0.2) # 避免请求过快
|
||||
|
||||
return results
|
||||
|
||||
@staticmethod
|
||||
def batch_refresh_running_users(db_session=None, school_id=None):
|
||||
"""
|
||||
刷新所有正在抢课中的用户的 session(一级优先)。
|
||||
用于 URL 切换后立即执行。
|
||||
|
||||
返回: {
|
||||
'total': int,
|
||||
'refreshed': int,
|
||||
'failed': int,
|
||||
'details': list
|
||||
}
|
||||
"""
|
||||
from app.models import GrabTask, User
|
||||
|
||||
# 查询有运行中抢课任务的用户
|
||||
query = User.query.join(GrabTask).filter(
|
||||
GrabTask.status == GrabTask.STATUS_RUNNING
|
||||
)
|
||||
if school_id:
|
||||
query = query.filter(User.school_id == school_id)
|
||||
running_users = query.all()
|
||||
|
||||
results = {
|
||||
'total': len(running_users),
|
||||
'refreshed': 0,
|
||||
'failed': 0,
|
||||
'details': []
|
||||
}
|
||||
|
||||
for user in running_users:
|
||||
from app.url_manager import push_school, pop_school
|
||||
push_school(user.school_id)
|
||||
try:
|
||||
result = SessionManager.refresh_session(user, force=True)
|
||||
finally:
|
||||
pop_school()
|
||||
result['user_id'] = user.id
|
||||
result['username'] = user.username
|
||||
|
||||
if result['status'] == 'refreshed':
|
||||
results['refreshed'] += 1
|
||||
else:
|
||||
results['failed'] += 1
|
||||
|
||||
results['details'].append(result)
|
||||
time.sleep(0.2) # 避免请求过快
|
||||
|
||||
if running_users:
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.info(
|
||||
f"[session_manager] 已刷新 {results['refreshed']}/{results['total']} "
|
||||
f"个抢课中的用户 session"
|
||||
)
|
||||
|
||||
return results
|
||||
|
||||
@staticmethod
|
||||
def ensure_session_valid(user, auto_refresh=True):
|
||||
"""
|
||||
确保用户session有效,如果过期则自动刷新
|
||||
|
||||
Args:
|
||||
user: User模型对象
|
||||
auto_refresh: 是否自动刷新
|
||||
|
||||
返回: (is_valid, error_msg)
|
||||
"""
|
||||
# 获取教务系统账号
|
||||
jwxt_acc = AccountManager.get_jwxt_account(
|
||||
user_id=user.id, username=user.username
|
||||
)
|
||||
|
||||
if not jwxt_acc:
|
||||
return False, "未配置教务系统账号"
|
||||
|
||||
username = jwxt_acc['username']
|
||||
|
||||
# 检查session
|
||||
is_valid, error_msg = SessionManager.is_session_valid(username)
|
||||
|
||||
if is_valid:
|
||||
return True, None
|
||||
|
||||
# 需要刷新
|
||||
if not auto_refresh:
|
||||
return False, error_msg
|
||||
|
||||
# 自动刷新
|
||||
result = SessionManager.refresh_session(user, force=True)
|
||||
|
||||
if result['success']:
|
||||
return True, None
|
||||
else:
|
||||
return False, result['message']
|
||||
@@ -0,0 +1,33 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
统一配置中心 — 所有全局常量集中管理
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
# ── 项目路径 ──
|
||||
BASE_DIR = Path(__file__).parent.parent
|
||||
SESSION_DIR = BASE_DIR / "sessions"
|
||||
ACCOUNTS_FILE = BASE_DIR / "accounts.json"
|
||||
|
||||
# 确保目录存在
|
||||
SESSION_DIR.mkdir(exist_ok=True)
|
||||
|
||||
# ── 教务系统(多地址,自动按延迟切换)──
|
||||
BASE_URLS = [
|
||||
"https://jwxt.sdmu.edu.cn/jwglxt",
|
||||
"http://10.224.2.186/jwglxt",
|
||||
"http://10.224.2.164/jwglxt",
|
||||
]
|
||||
GNMKDM = "N253512"
|
||||
|
||||
# ── 抢课引擎 ──
|
||||
# 抢课间隔(秒),随机范围 [min, max],模拟人为操作
|
||||
# 分两个时段分别设置,按小时(24h制)切换
|
||||
GRAB_INTERVAL_DAY_MIN = 1 # 时段A 最小间隔(秒)
|
||||
GRAB_INTERVAL_DAY_MAX = 2 # 时段A 最大间隔(秒)
|
||||
GRAB_INTERVAL_NIGHT_MIN = 2 # 时段B 最小间隔(秒)
|
||||
GRAB_INTERVAL_NIGHT_MAX = 3 # 时段B 最大间隔(秒)
|
||||
GRAB_TIME_A_START = 8 # 时段A 开始(小时)
|
||||
GRAB_TIME_A_END = 23 # 时段A 结束(小时),其余时间为时段B
|
||||
SESSION_RETRY_INTERVAL = 5 # Session刷新后重试间隔(秒)
|
||||
|
After Width: | Height: | Size: 95 KiB |
|
After Width: | Height: | Size: 95 KiB |
|
After Width: | Height: | Size: 100 KiB |
|
After Width: | Height: | Size: 2.9 MiB |
|
After Width: | Height: | Size: 2.9 MiB |
|
After Width: | Height: | Size: 95 KiB |
|
After Width: | Height: | Size: 79 KiB |
|
After Width: | Height: | Size: 91 KiB |
|
After Width: | Height: | Size: 91 KiB |
@@ -0,0 +1,311 @@
|
||||
// SDMU 教务助手 · Hero 粒子背景引擎
|
||||
// 基于 Three.js,滚动驱动相机/场景变换
|
||||
|
||||
(() => {
|
||||
if (typeof THREE === 'undefined') {
|
||||
console.warn('Three.js not loaded; skipping hero particles.');
|
||||
return;
|
||||
}
|
||||
|
||||
const canvas = document.getElementById('hero-particles');
|
||||
if (!canvas) return;
|
||||
|
||||
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true });
|
||||
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
|
||||
renderer.setSize(canvas.clientWidth, canvas.clientHeight);
|
||||
renderer.setClearColor(0x000000, 0);
|
||||
|
||||
const scene = new THREE.Scene();
|
||||
const camera = new THREE.PerspectiveCamera(60, canvas.clientWidth / canvas.clientHeight, 0.1, 2000);
|
||||
camera.position.z = 600;
|
||||
|
||||
const isDark = () => document.documentElement.classList.contains('dark');
|
||||
|
||||
const palettes = {
|
||||
light: {
|
||||
accent: '#E6A23C',
|
||||
primary: '#111111',
|
||||
muted: '#111111',
|
||||
bg: '#F5F2EA'
|
||||
},
|
||||
dark: {
|
||||
accent: '#E6A23C',
|
||||
primary: '#ffffff',
|
||||
muted: '#ffffff',
|
||||
bg: '#0a0a0a'
|
||||
}
|
||||
};
|
||||
|
||||
let currentPalette = isDark() ? palettes.dark : palettes.light;
|
||||
const colorAccent = new THREE.Color(currentPalette.accent);
|
||||
const colorPrimary = new THREE.Color(currentPalette.primary);
|
||||
const colorMuted = new THREE.Color(currentPalette.muted);
|
||||
const colorLight = new THREE.Color(currentPalette.bg);
|
||||
|
||||
const COUNT = 2200;
|
||||
const pos = new Float32Array(COUNT * 3);
|
||||
const colors = new Float32Array(COUNT * 3);
|
||||
const sizes = new Float32Array(COUNT);
|
||||
const phases = new Float32Array(COUNT);
|
||||
|
||||
for (let i = 0; i < COUNT; i++) {
|
||||
const r = Math.pow(Math.random(), 0.55) * 760;
|
||||
const a = Math.random() * Math.PI * 2;
|
||||
const y = (Math.random() - 0.5) * 360;
|
||||
|
||||
pos[i * 3] = Math.cos(a) * r;
|
||||
pos[i * 3 + 1] = y;
|
||||
pos[i * 3 + 2] = Math.sin(a) * r;
|
||||
phases[i] = Math.random() * Math.PI * 2;
|
||||
|
||||
const roll = Math.random();
|
||||
const c = roll > 0.95 ? colorAccent : colorPrimary;
|
||||
colors[i * 3] = c.r;
|
||||
colors[i * 3 + 1] = c.g;
|
||||
colors[i * 3 + 2] = c.b;
|
||||
sizes[i] = Math.random() * 2.6 + 1.2;
|
||||
}
|
||||
|
||||
const geo = new THREE.BufferGeometry();
|
||||
geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
|
||||
geo.setAttribute('color', new THREE.BufferAttribute(colors, 3));
|
||||
geo.setAttribute('size', new THREE.BufferAttribute(sizes, 1));
|
||||
geo.setAttribute('phase', new THREE.BufferAttribute(phases, 1));
|
||||
|
||||
const mat = new THREE.ShaderMaterial({
|
||||
uniforms: {
|
||||
uTime: { value: 0 },
|
||||
uPixelRatio: { value: Math.min(window.devicePixelRatio, 2) },
|
||||
uMouse: { value: new THREE.Vector3(0, 0, 0) }
|
||||
},
|
||||
vertexShader: `
|
||||
attribute float size;
|
||||
attribute vec3 color;
|
||||
attribute float phase;
|
||||
varying vec3 vColor;
|
||||
uniform float uTime;
|
||||
uniform float uPixelRatio;
|
||||
uniform vec3 uMouse;
|
||||
void main() {
|
||||
vec3 p = position;
|
||||
float t = uTime * 0.6 + phase;
|
||||
p.y += sin(t + position.x * 0.012) * 8.0;
|
||||
p.x += cos(t * 0.7 + position.z * 0.012) * 5.0;
|
||||
p.z += sin(t * 0.5 + position.y * 0.015) * 4.0;
|
||||
float mouseDist = length(p - uMouse);
|
||||
float mouseGlow = smoothstep(120.0, 0.0, mouseDist);
|
||||
vColor = color + vec3(mouseGlow * 0.35);
|
||||
vec4 mv = modelViewMatrix * vec4(p, 1.0);
|
||||
gl_PointSize = size * uPixelRatio * (300.0 / -mv.z) * (1.0 + mouseGlow * 1.2);
|
||||
gl_Position = projectionMatrix * mv;
|
||||
}
|
||||
`,
|
||||
fragmentShader: `
|
||||
varying vec3 vColor;
|
||||
void main() {
|
||||
float d = length(gl_PointCoord - 0.5);
|
||||
if (d > 0.5) discard;
|
||||
float alpha = 1.0 - d * 2.2;
|
||||
gl_FragColor = vec4(vColor, alpha * 0.85);
|
||||
}
|
||||
`,
|
||||
transparent: true,
|
||||
depthWrite: false,
|
||||
blending: THREE.NormalBlending
|
||||
});
|
||||
|
||||
const points = new THREE.Points(geo, mat);
|
||||
scene.add(points);
|
||||
|
||||
// Subtle connection lines
|
||||
const MAX_LINKS = 1800;
|
||||
const linkPos = new Float32Array(MAX_LINKS * 6);
|
||||
const linkColors = new Float32Array(MAX_LINKS * 6);
|
||||
const linkGeo = new THREE.BufferGeometry();
|
||||
linkGeo.setAttribute('position', new THREE.BufferAttribute(linkPos, 3));
|
||||
linkGeo.setAttribute('color', new THREE.BufferAttribute(linkColors, 3));
|
||||
const linkMat = new THREE.LineBasicMaterial({
|
||||
vertexColors: true,
|
||||
transparent: true,
|
||||
opacity: 0.12,
|
||||
blending: THREE.NormalBlending,
|
||||
depthWrite: false
|
||||
});
|
||||
const linkMesh = new THREE.LineSegments(linkGeo, linkMat);
|
||||
scene.add(linkMesh);
|
||||
|
||||
const RM = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
const FINE = window.matchMedia('(hover: hover) and (pointer: fine)').matches;
|
||||
|
||||
let mouseWorld = new THREE.Vector3(0, 0, 0);
|
||||
let raycaster = new THREE.Raycaster();
|
||||
let mousePlane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
|
||||
let mouseV = new THREE.Vector2();
|
||||
let mouseX = 0, mouseY = 0;
|
||||
|
||||
if (FINE) {
|
||||
window.addEventListener('pointermove', (e) => {
|
||||
mouseX = (e.clientX / window.innerWidth - 0.5) * 2;
|
||||
mouseY = (e.clientY / window.innerHeight - 0.5) * 2;
|
||||
mouseV.set((e.clientX / window.innerWidth) * 2 - 1, -(e.clientY / window.innerHeight) * 2 + 1);
|
||||
raycaster.setFromCamera(mouseV, camera);
|
||||
const hit = new THREE.Vector3();
|
||||
raycaster.ray.intersectPlane(mousePlane, hit);
|
||||
if (hit) mouseWorld.copy(hit);
|
||||
}, { passive: true });
|
||||
}
|
||||
|
||||
// Scroll-driven transform: map scroll progress to camera/scene motion
|
||||
let scrollProgress = 0;
|
||||
function updateScroll() {
|
||||
const docH = document.documentElement.scrollHeight - window.innerHeight;
|
||||
scrollProgress = docH > 0 ? Math.min(window.scrollY / docH, 1) : 0;
|
||||
}
|
||||
window.addEventListener('scroll', updateScroll, { passive: true });
|
||||
updateScroll();
|
||||
|
||||
let isVisible = true;
|
||||
const visObs = new IntersectionObserver((entries) => {
|
||||
isVisible = entries[0].isIntersecting;
|
||||
}, { threshold: 0 });
|
||||
visObs.observe(canvas);
|
||||
|
||||
const tempColor = new THREE.Color();
|
||||
const cellSize = 70;
|
||||
const grid = new Map();
|
||||
|
||||
function updateLinks() {
|
||||
grid.clear();
|
||||
for (let i = 0; i < COUNT; i++) {
|
||||
const x = pos[i * 3], y = pos[i * 3 + 1], z = pos[i * 3 + 2];
|
||||
const key = `${Math.floor(x / cellSize)},${Math.floor(y / cellSize)},${Math.floor(z / cellSize)}`;
|
||||
if (!grid.has(key)) grid.set(key, []);
|
||||
grid.get(key).push(i);
|
||||
}
|
||||
|
||||
let linkIdx = 0;
|
||||
const linkThreshold = 92;
|
||||
const linkThresholdSq = linkThreshold * linkThreshold;
|
||||
|
||||
for (let i = 0; i < COUNT; i++) {
|
||||
if (linkIdx >= MAX_LINKS) break;
|
||||
const ix = pos[i * 3], iy = pos[i * 3 + 1], iz = pos[i * 3 + 2];
|
||||
const cx = Math.floor(ix / cellSize), cy = Math.floor(iy / cellSize), cz = Math.floor(iz / cellSize);
|
||||
|
||||
for (let dx = -1; dx <= 1; dx++) {
|
||||
for (let dy = -1; dy <= 1; dy++) {
|
||||
for (let dz = -1; dz <= 1; dz++) {
|
||||
const key = `${cx + dx},${cy + dy},${cz + dz}`;
|
||||
const cell = grid.get(key);
|
||||
if (!cell) continue;
|
||||
for (const j of cell) {
|
||||
if (j <= i) continue;
|
||||
if (linkIdx >= MAX_LINKS) break;
|
||||
const jx = pos[j * 3], jy = pos[j * 3 + 1], jz = pos[j * 3 + 2];
|
||||
const dx_ = ix - jx, dy_ = iy - jy, dz_ = iz - jz;
|
||||
const distSq = dx_ * dx_ + dy_ * dy_ + dz_ * dz_;
|
||||
if (distSq < linkThresholdSq) {
|
||||
const alpha = 1.0 - Math.sqrt(distSq) / linkThreshold;
|
||||
linkPos[linkIdx * 6] = ix;
|
||||
linkPos[linkIdx * 6 + 1] = iy;
|
||||
linkPos[linkIdx * 6 + 2] = iz;
|
||||
linkPos[linkIdx * 6 + 3] = jx;
|
||||
linkPos[linkIdx * 6 + 4] = jy;
|
||||
linkPos[linkIdx * 6 + 5] = jz;
|
||||
tempColor.setRGB(colors[i * 3], colors[i * 3 + 1], colors[i * 3 + 2]);
|
||||
tempColor.lerp(colorLight, 1.0 - alpha);
|
||||
linkColors[linkIdx * 6] = tempColor.r;
|
||||
linkColors[linkIdx * 6 + 1] = tempColor.g;
|
||||
linkColors[linkIdx * 6 + 2] = tempColor.b;
|
||||
linkColors[linkIdx * 6 + 3] = tempColor.r;
|
||||
linkColors[linkIdx * 6 + 4] = tempColor.g;
|
||||
linkColors[linkIdx * 6 + 5] = tempColor.b;
|
||||
linkIdx++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
linkGeo.setDrawRange(0, linkIdx * 2);
|
||||
linkGeo.attributes.position.needsUpdate = true;
|
||||
linkGeo.attributes.color.needsUpdate = true;
|
||||
}
|
||||
|
||||
updateLinks();
|
||||
|
||||
// Theme change detection
|
||||
const themeObs = new MutationObserver(() => {
|
||||
const p = isDark() ? palettes.dark : palettes.light;
|
||||
colorAccent.set(p.accent);
|
||||
colorPrimary.set(p.primary);
|
||||
colorMuted.set(p.muted);
|
||||
colorLight.set(p.bg);
|
||||
for (let i = 0; i < COUNT; i++) {
|
||||
const roll = Math.random();
|
||||
const c = roll > 0.88 ? colorAccent : roll > 0.42 ? colorPrimary : colorMuted;
|
||||
colors[i * 3] = c.r;
|
||||
colors[i * 3 + 1] = c.g;
|
||||
colors[i * 3 + 2] = c.b;
|
||||
}
|
||||
geo.attributes.color.needsUpdate = true;
|
||||
updateLinks();
|
||||
});
|
||||
themeObs.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
|
||||
|
||||
function resize() {
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const w = rect.width;
|
||||
const h = rect.height;
|
||||
camera.aspect = w / h;
|
||||
camera.updateProjectionMatrix();
|
||||
renderer.setSize(w, h);
|
||||
mat.uniforms.uPixelRatio.value = Math.min(window.devicePixelRatio, 2);
|
||||
updateLinks();
|
||||
}
|
||||
window.addEventListener('resize', resize);
|
||||
|
||||
let rafId = null;
|
||||
function loop(t) {
|
||||
if (!isVisible) {
|
||||
rafId = requestAnimationFrame(loop);
|
||||
return;
|
||||
}
|
||||
|
||||
if (RM) {
|
||||
mat.uniforms.uTime.value = 0;
|
||||
camera.position.set(0, 0, 600);
|
||||
camera.lookAt(0, 0, 0);
|
||||
renderer.render(scene, camera);
|
||||
return;
|
||||
}
|
||||
|
||||
const time = t * 0.001;
|
||||
mat.uniforms.uTime.value = time;
|
||||
mat.uniforms.uMouse.value.copy(mouseWorld);
|
||||
|
||||
// Scroll-driven motion
|
||||
const ease = 1 - Math.pow(1 - scrollProgress, 3);
|
||||
points.rotation.y = time * 0.045 + ease * Math.PI * 0.5;
|
||||
points.rotation.x = Math.sin(time * 0.08) * 0.04 + ease * 0.15;
|
||||
linkMesh.rotation.y = points.rotation.y;
|
||||
linkMesh.rotation.x = points.rotation.x;
|
||||
|
||||
camera.position.z = 600 - ease * 400;
|
||||
camera.position.x = mouseX * 30 + ease * 80;
|
||||
camera.position.y = -mouseY * 20 - ease * 60;
|
||||
camera.lookAt(0, 0, 0);
|
||||
|
||||
renderer.render(scene, camera);
|
||||
rafId = requestAnimationFrame(loop);
|
||||
}
|
||||
|
||||
if (RM) {
|
||||
renderer.render(scene, camera);
|
||||
} else {
|
||||
rafId = requestAnimationFrame(loop);
|
||||
}
|
||||
|
||||
console.log('SDMU hero particles mounted. dark:', isDark(), 'RM:', RM);
|
||||
})();
|
||||
@@ -0,0 +1,487 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
|
||||
{% block title %}学业情况 - {{ brand_name }}{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
@keyframes fadeSlideIn {
|
||||
from { opacity: 0; transform: translateY(6px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.row-animate { animation: fadeSlideIn 0.35s ease both; }
|
||||
|
||||
/* 树节点 */
|
||||
.tree-node { transition: all 0.15s ease; }
|
||||
.tree-node:hover { background: rgba(0,0,0,0.02); }
|
||||
.dark .tree-node:hover { background: rgba(255,255,255,0.03); }
|
||||
|
||||
.tree-toggle { cursor: pointer; user-select: none; }
|
||||
|
||||
.tree-children { overflow: hidden; transition: max-height 0.3s ease; }
|
||||
.tree-children.collapsed { max-height: 0 !important; }
|
||||
|
||||
.depth-0 { border-left: 3px solid #22c55e; }
|
||||
.depth-1 { border-left: 2px solid #818cf8; }
|
||||
.depth-2 { border-left: 2px solid #94a3b8; }
|
||||
.depth-3 { border-left: 1px solid #cbd5e1; }
|
||||
.dark .depth-3 { border-left-color: #475569; }
|
||||
|
||||
/* 进度条 */
|
||||
.progress-track { height: 5px; border-radius: 3px; background: #e5e7eb; overflow: hidden; }
|
||||
.dark .progress-track { background: #374151; }
|
||||
.progress-fill { height: 100%; border-radius: 3px; transition: width 0.5s ease; }
|
||||
.progress-fill.ok { background: #22c55e; }
|
||||
.progress-fill.warn { background: #f59e0b; }
|
||||
.progress-fill.danger { background: #ef4444; }
|
||||
|
||||
/* 课程表 */
|
||||
.course-row { transition: background 0.15s; }
|
||||
.course-row:hover { background: rgba(0,0,0,0.02); }
|
||||
.dark .course-row:hover { background: rgba(255,255,255,0.03); }
|
||||
|
||||
.badge-pass { background: #dcfce7; color: #15803d; }
|
||||
.badge-fail { background: #fef3c7; color: #92400e; }
|
||||
.badge-progress { background: #dbeafe; color: #1d4ed8; }
|
||||
.dark .badge-pass { background: #14532d; color: #86efac; }
|
||||
.dark .badge-fail { background: #451a03; color: #fcd34d; }
|
||||
.dark .badge-progress { background: #1e3a5f; color: #93c5fd; }
|
||||
|
||||
/* 统计卡片 */
|
||||
.stat-card {
|
||||
background: linear-gradient(135deg, rgba(79,70,229,0.04), rgba(99,102,241,0.01));
|
||||
border: 1px solid rgba(99,102,241,0.1);
|
||||
}
|
||||
.dark .stat-card {
|
||||
background: linear-gradient(135deg, rgba(129,140,248,0.08), rgba(165,180,252,0.02));
|
||||
border-color: rgba(129,140,248,0.15);
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
<!-- 标题区 -->
|
||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-5">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/>
|
||||
</svg>
|
||||
学业情况
|
||||
</h2>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-0.5">培养方案完成度分析</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<button onclick="toggleAll(true)"
|
||||
class="px-3 py-1.5 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 text-xs hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors">
|
||||
全部展开
|
||||
</button>
|
||||
<button onclick="toggleAll(false)"
|
||||
class="px-3 py-1.5 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 text-xs hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors">
|
||||
全部收起
|
||||
</button>
|
||||
<button onclick="refresh()"
|
||||
class="px-4 py-1.5 rounded-lg bg-indigo-600 text-white text-xs font-medium hover:bg-indigo-700 transition-colors flex items-center gap-1.5">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 摘要卡片 -->
|
||||
<div id="summaryCards" class="hidden grid grid-cols-2 md:grid-cols-5 gap-3 mb-5 row-animate">
|
||||
<div class="stat-card rounded-xl p-3.5">
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400">学生姓名</p>
|
||||
<p id="summaryName" class="font-semibold text-base mt-0.5">--</p>
|
||||
</div>
|
||||
<div class="stat-card rounded-xl p-3.5">
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400">GPA</p>
|
||||
<p id="summaryGpa" class="font-bold text-xl text-indigo-600 dark:text-indigo-400 mt-0.5">--</p>
|
||||
</div>
|
||||
<div class="stat-card rounded-xl p-3.5">
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400">已获 / 要求</p>
|
||||
<p id="summaryCredits" class="font-semibold text-base mt-0.5">--</p>
|
||||
</div>
|
||||
<div class="stat-card rounded-xl p-3.5">
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400">课程进度</p>
|
||||
<p id="summaryCourses" class="font-semibold text-base mt-0.5">--</p>
|
||||
</div>
|
||||
<div class="stat-card rounded-xl p-3.5">
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400">统计时间</p>
|
||||
<p id="summaryTime" class="text-xs text-gray-400 dark:text-gray-500 mt-0.5">--</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 图表 -->
|
||||
<div id="chartsRow" class="hidden grid grid-cols-1 md:grid-cols-2 gap-4 mb-5 row-animate">
|
||||
<div class="glass rounded-2xl p-4">
|
||||
<h4 class="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">整体完成度</h4>
|
||||
<div id="gaugeChart" style="height: 240px; width: 100%;"></div>
|
||||
</div>
|
||||
<div class="glass rounded-2xl p-4">
|
||||
<h4 class="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">各类别学分</h4>
|
||||
<div id="levelChart" style="height: 240px;"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 加载 -->
|
||||
<div id="loadingIndicator" class="text-center py-16">
|
||||
<div class="w-9 h-9 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
|
||||
<p class="text-gray-400 dark:text-gray-500 text-sm">正在查询学业情况,数据较多请稍候…</p>
|
||||
</div>
|
||||
|
||||
<!-- 错误 -->
|
||||
<div id="errorMessage" class="glass rounded-2xl p-5 mb-4 text-center hidden">
|
||||
<p id="errorText" class="text-red-500 text-sm"></p>
|
||||
</div>
|
||||
|
||||
<!-- 树形结构 -->
|
||||
<div id="dataContainer" class="hidden">
|
||||
<div class="glass rounded-2xl overflow-hidden divide-y divide-gray-100 dark:divide-gray-800">
|
||||
<div id="treeRoot"></div>
|
||||
</div>
|
||||
<div id="emptyState" class="glass rounded-2xl p-12 text-center hidden">
|
||||
<p class="text-gray-400 dark:text-gray-500">暂无学业情况数据</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script src="{{ url_for('static', filename='echarts.min.js') }}"></script>
|
||||
<script>
|
||||
async function initSession() {
|
||||
try { await fetch('/api/jwxt/ping'); return true; }
|
||||
catch(e) { console.warn('[Session] ping fail:', e); return false; }
|
||||
}
|
||||
function isDark() { return document.documentElement.classList.contains('dark'); }
|
||||
|
||||
let _expandedAll = true;
|
||||
|
||||
// ── 渲染树节点 ──────────────────────────────────────────────────
|
||||
function renderNode(node, depth) {
|
||||
const hasChildren = node.children && node.children.length > 0;
|
||||
const earned = node.earned_credits || 0;
|
||||
const required = node.required_credits || 0;
|
||||
const missing = Math.max(0, required - earned);
|
||||
const passed = node.passed;
|
||||
|
||||
const pct = required > 0 ? Math.min(100, Math.round((earned / required) * 100)) : (passed ? 100 : 0);
|
||||
const progressClass = pct >= 100 ? 'ok' : (pct >= 60 ? 'warn' : 'danger');
|
||||
|
||||
const nodeId = node.id;
|
||||
const childrenId = 'children-' + nodeId;
|
||||
const coursePanelId = 'courses-' + nodeId;
|
||||
|
||||
// 深度样式
|
||||
const textClass = depth === 0 ? 'text-base font-bold' : depth === 1 ? 'text-sm font-semibold' : 'text-sm';
|
||||
const indent = Math.min(depth, 3);
|
||||
|
||||
const chevronHtml = hasChildren ? `
|
||||
<svg class="tree-chevron w-4 h-4 flex-shrink-0 text-gray-400 transition-transform duration-200"
|
||||
xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<polyline points="6 9 12 15 18 9"/>
|
||||
</svg>` : '<span class="w-4 flex-shrink-0"></span>';
|
||||
|
||||
// 状态徽章
|
||||
let badgeHtml = '';
|
||||
if (required > 0) {
|
||||
if (pct >= 100) badgeHtml = '<span class="px-2 py-0.5 rounded-full text-xs font-medium badge-pass flex-shrink-0">已完成</span>';
|
||||
else if (earned > 0) badgeHtml = '<span class="px-2 py-0.5 rounded-full text-xs font-medium badge-progress flex-shrink-0">进行中</span>';
|
||||
else badgeHtml = '<span class="px-2 py-0.5 rounded-full text-xs font-medium badge-fail flex-shrink-0">未开始</span>';
|
||||
}
|
||||
|
||||
// 学分文字:要求学分:X 获得学分:Y 未获得学分:Z
|
||||
const creditText = required > 0
|
||||
? `要求学分:${required.toFixed(1)} 获得学分:${earned.toFixed(1)} 未获得学分:${missing.toFixed(1)}`
|
||||
: (earned > 0 ? `获得学分:${earned.toFixed(1)}` : '');
|
||||
|
||||
// 进度条
|
||||
const progressHtml = required > 0 ? `
|
||||
<div class="flex items-center gap-2 flex-shrink-0" style="min-width:90px">
|
||||
<div class="progress-track flex-1"><div class="progress-fill ${progressClass}" style="width:${pct}%"></div></div>
|
||||
<span class="text-xs text-gray-400 dark:text-gray-500 w-9 text-right">${pct}%</span>
|
||||
</div>` : '';
|
||||
|
||||
// 课程展开按钮
|
||||
const expandBtnHtml = `
|
||||
<button onclick="loadCourses('${nodeId}', '${coursePanelId}', this)"
|
||||
class="flex-shrink-0 text-xs text-indigo-500 dark:text-indigo-400 hover:text-indigo-700 dark:hover:text-indigo-300 font-medium flex items-center gap-1 px-2 py-0.5 rounded hover:bg-indigo-50 dark:hover:bg-indigo-900/20 transition-colors"
|
||||
title="查看课程明细">
|
||||
<span class="course-count-${nodeId}">课程</span>
|
||||
<svg class="course-chevron-${nodeId} w-3 h-3 transition-transform" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg>
|
||||
</button>`;
|
||||
|
||||
const clickHandler = hasChildren ? `onclick="toggleNode('${childrenId}', this)"` : '';
|
||||
const toggleClass = hasChildren ? 'tree-toggle' : '';
|
||||
|
||||
const html = `
|
||||
<div class="tree-node depth-${depth}">
|
||||
<div class="${toggleClass} flex items-center gap-2 py-2.5 px-4" style="padding-left:${0.75 + indent * 1.25}rem" ${clickHandler}>
|
||||
${chevronHtml}
|
||||
<div class="flex-1 min-w-0">
|
||||
<span class="${textClass}">${escHtml(node.name)}</span>
|
||||
${creditText ? `<span class="text-xs text-gray-400 dark:text-gray-500 ml-2">${creditText}</span>` : ''}
|
||||
</div>
|
||||
${progressHtml}
|
||||
${badgeHtml}
|
||||
${!hasChildren ? expandBtnHtml : ''}
|
||||
</div>
|
||||
<div id="${coursePanelId}" class="hidden px-4 pb-3" style="padding-left:${2 + indent * 1.25}rem"></div>
|
||||
${hasChildren ? `<div id="${childrenId}" class="tree-children" style="max-height:10000px">${node.children.map(c => renderNode(c, depth + 1)).join('')}</div>` : ''}
|
||||
</div>`;
|
||||
return html;
|
||||
}
|
||||
|
||||
function escHtml(s) { return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); }
|
||||
|
||||
// ── 展开/收起子节点 ────────────────────────────────────────────
|
||||
function toggleNode(childrenId, el) {
|
||||
const container = document.getElementById(childrenId);
|
||||
if (!container) return;
|
||||
const chevron = el.querySelector('.tree-chevron');
|
||||
if (container.classList.contains('collapsed')) {
|
||||
container.classList.remove('collapsed');
|
||||
container.style.maxHeight = '10000px';
|
||||
if (chevron) chevron.style.transform = 'rotate(0deg)';
|
||||
} else {
|
||||
container.classList.add('collapsed');
|
||||
container.style.maxHeight = '0px';
|
||||
if (chevron) chevron.style.transform = 'rotate(-90deg)';
|
||||
}
|
||||
}
|
||||
|
||||
function toggleAll(expand) {
|
||||
_expandedAll = expand;
|
||||
document.querySelectorAll('.tree-children').forEach(el => {
|
||||
if (expand) { el.classList.remove('collapsed'); el.style.maxHeight = '10000px'; }
|
||||
else { el.classList.add('collapsed'); el.style.maxHeight = '0px'; }
|
||||
});
|
||||
document.querySelectorAll('.tree-chevron').forEach(el => {
|
||||
el.style.transform = expand ? 'rotate(0deg)' : 'rotate(-90deg)';
|
||||
});
|
||||
}
|
||||
|
||||
// ── 加载课程明细 ──────────────────────────────────────────────
|
||||
async function loadCourses(nodeId, panelId, btn) {
|
||||
const panel = document.getElementById(panelId);
|
||||
if (!panel) return;
|
||||
const chevron = btn.querySelector('svg');
|
||||
|
||||
// 已展开则收起
|
||||
if (!panel.classList.contains('hidden') && panel.innerHTML) {
|
||||
panel.classList.add('hidden');
|
||||
if (chevron) chevron.style.transform = 'rotate(0deg)';
|
||||
return;
|
||||
}
|
||||
// 已加载过则展示
|
||||
if (panel.innerHTML) {
|
||||
panel.classList.remove('hidden');
|
||||
if (chevron) chevron.style.transform = 'rotate(180deg)';
|
||||
return;
|
||||
}
|
||||
|
||||
// 显示加载
|
||||
panel.innerHTML = '<div class="text-xs text-gray-400 py-2">加载中…</div>';
|
||||
panel.classList.remove('hidden');
|
||||
if (chevron) chevron.style.transform = 'rotate(180deg)';
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/jwxt/academic-status/courses?xfyqjd_id=${encodeURIComponent(nodeId)}`);
|
||||
const data = await res.json();
|
||||
if (!data.success) {
|
||||
panel.innerHTML = `<div class="text-xs text-red-400 py-2">${escHtml(data.message || '加载失败')}</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
// 更新按钮计数
|
||||
const countEl = document.querySelector(`.course-count-${nodeId}`);
|
||||
if (countEl) countEl.textContent = `共 ${data.total} 门 通过 ${data.passed} 门`;
|
||||
|
||||
if (!data.courses || !data.courses.length) {
|
||||
if (countEl) countEl.textContent = '共 0 门';
|
||||
panel.innerHTML = '<div class="text-xs text-gray-400 py-1">该节点暂无课程</div>';
|
||||
setTimeout(() => { panel.classList.add('hidden'); if (chevron) chevron.style.transform = 'rotate(0deg)'; }, 1200);
|
||||
return;
|
||||
}
|
||||
|
||||
// 排序:已修(有成绩)在前,在修次之,未修最后
|
||||
const sorted = [...data.courses].sort((a, b) => {
|
||||
const aScore = a.cj && a.cj !== '未开放' ? 0 : a.kczt === 1 ? 1 : 2;
|
||||
const bScore = b.cj && b.cj !== '未开放' ? 0 : b.kczt === 1 ? 1 : 2;
|
||||
return aScore - bScore;
|
||||
});
|
||||
|
||||
// 渲染课程表
|
||||
const rows = sorted.map((c, i) => {
|
||||
const grade = c.cj || (c.kczt === 1 ? '在修' : '未修');
|
||||
const gpa = c.jd != null ? c.jd : '--';
|
||||
const statusCls = c.cj && c.cj !== '未开放' ? 'badge-pass' : c.kczt === 1 ? 'badge-progress' : 'badge-fail';
|
||||
return `
|
||||
<tr class="course-row" style="animation: fadeSlideIn ${0.1 + i * 0.02}s ease both">
|
||||
<td class="py-1.5 pr-4 text-xs text-gray-500 w-6">${i + 1}</td>
|
||||
<td class="py-1.5 pr-4 text-sm truncate max-w-[200px]" title="${escHtml(c.kcmc)}">${escHtml(c.kcmc)}</td>
|
||||
<td class="py-1.5 pr-4 text-xs text-gray-400 w-10 text-right">${c.xf || '--'}</td>
|
||||
<td class="py-1.5 pr-4 text-xs font-medium w-12 text-right">${escHtml(String(grade))}</td>
|
||||
<td class="py-1.5 pr-4 text-xs text-gray-500 w-10 text-right">${gpa}</td>
|
||||
<td class="py-1.5 pr-4 text-xs text-gray-400 whitespace-nowrap">${c.xnmc || ''} ${c.xqmmc || ''}</td>
|
||||
<td class="py-1.5 pr-4 text-xs text-gray-400 truncate max-w-[100px]">${escHtml(c.kcxz || '')}</td>
|
||||
<td class="py-1.5 text-xs"><span class="px-1.5 py-0.5 rounded text-xs ${statusCls}">${c.cj && c.cj !== '未开放' ? '已修' : c.kczt === 1 ? '在修' : '未修'}</span></td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
|
||||
panel.innerHTML = `
|
||||
<div class="border-t border-gray-100 dark:border-gray-800 mt-1 pt-2">
|
||||
<div class="text-xs text-gray-400 mb-2">共 ${data.total} 门,通过 ${data.passed} 门</div>
|
||||
<div class="overflow-x-auto -mx-2">
|
||||
<table class="w-full text-left">
|
||||
<thead>
|
||||
<tr class="text-xs text-gray-400 dark:text-gray-500 border-b border-gray-100 dark:border-gray-800">
|
||||
<th class="py-1.5 pr-4 font-normal w-6">#</th>
|
||||
<th class="py-1.5 pr-4 font-normal">课程名称</th>
|
||||
<th class="py-1.5 pr-4 font-normal w-10 text-right">学分</th>
|
||||
<th class="py-1.5 pr-4 font-normal w-12 text-right">成绩</th>
|
||||
<th class="py-1.5 pr-4 font-normal w-10 text-right">绩点</th>
|
||||
<th class="py-1.5 pr-4 font-normal whitespace-nowrap">学期</th>
|
||||
<th class="py-1.5 pr-4 font-normal">类别</th>
|
||||
<th class="py-1.5 font-normal w-12">状态</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>${rows}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>`;
|
||||
} catch (e) {
|
||||
panel.innerHTML = `<div class="text-xs text-red-400 py-2">网络错误: ${escHtml(e.message)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
// ── ECharts ──────────────────────────────────────────────────
|
||||
let gaugeChart = null, levelChart = null;
|
||||
|
||||
function renderGaugeChart(pct) {
|
||||
const dom = document.getElementById('gaugeChart');
|
||||
if (!dom) return;
|
||||
const dark = isDark();
|
||||
if (!gaugeChart) gaugeChart = echarts.init(dom);
|
||||
gaugeChart.setOption({
|
||||
series: [{
|
||||
type: 'gauge', startAngle: 200, endAngle: -20, center: ['50%', '60%'], radius: '85%',
|
||||
min: 0, max: 100,
|
||||
axisLine: { lineStyle: { width: 14, color: [[0.55, '#ef4444'], [0.8, '#f59e0b'], [1, '#22c55e']] }},
|
||||
pointer: { length: '60%', width: 5, itemStyle: { color: dark ? '#d1d5db' : '#374151' } },
|
||||
axisTick: { show: false }, splitLine: { show: false },
|
||||
axisLabel: { color: dark ? '#9ca3af' : '#6b7280', fontSize: 10, distance: -25 },
|
||||
detail: { valueAnimation: true, fontSize: 26, fontWeight: 'bold', color: dark ? '#f9fafb' : '#111827', formatter: '{value}%', offsetCenter: [0, '62%'] },
|
||||
data: [{ value: pct }]
|
||||
}]
|
||||
}, { notMerge: true });
|
||||
gaugeChart.resize();
|
||||
}
|
||||
|
||||
function renderLevelChart(tree) {
|
||||
const dom = document.getElementById('levelChart');
|
||||
if (!dom) return;
|
||||
const dark = isDark();
|
||||
const categories = tree.map(root => ({
|
||||
name: root.name, earned: root.earned_credits || 0, required: root.required_credits || 0,
|
||||
}));
|
||||
if (!categories.length) return;
|
||||
const names = categories.map(c => c.name);
|
||||
if (!levelChart) levelChart = echarts.init(dom);
|
||||
levelChart.setOption({
|
||||
tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' }, formatter: p => {
|
||||
const c = categories[p[0].dataIndex];
|
||||
return `${c.name}<br/>已获: ${c.earned} / 要求: ${c.required}`;
|
||||
}},
|
||||
grid: { left: '3%', right: '5%', top: 8, bottom: 8, containLabel: true },
|
||||
xAxis: { type: 'value', name: '学分', nameTextStyle: { color: dark ? '#9ca3af' : '#6b7280', fontSize: 10 }, axisLabel: { color: dark ? '#9ca3af' : '#6b7280', fontSize: 10 } },
|
||||
yAxis: { type: 'category', data: names, axisLabel: { color: dark ? '#9ca3af' : '#6b7280', fontSize: 10, width: 70, overflow: 'truncate' }, inverse: true },
|
||||
series: [
|
||||
{ name: '要求', type: 'bar', data: categories.map(c => c.required), itemStyle: { color: dark ? '#374151' : '#e5e7eb', borderRadius: [0,5,5,0] }, barGap: '-100%', z: 1 },
|
||||
{ name: '已获', type: 'bar', data: categories.map(c => c.earned), itemStyle: { color: dark ? '#818cf8' : '#4f46e5', borderRadius: [0,5,5,0] }, z: 2 },
|
||||
]
|
||||
}, { notMerge: true });
|
||||
levelChart.resize();
|
||||
}
|
||||
|
||||
function renderCharts(tree, rootCredits) {
|
||||
document.getElementById('chartsRow').classList.remove('hidden');
|
||||
const pct = rootCredits.required > 0 ? Math.min(100, Math.round((rootCredits.earned / rootCredits.required) * 100)) : 0;
|
||||
renderGaugeChart(pct);
|
||||
renderLevelChart(tree);
|
||||
}
|
||||
|
||||
function setupDarkObserver() {
|
||||
new MutationObserver(() => {
|
||||
if (gaugeChart) { gaugeChart.dispose(); gaugeChart = null; }
|
||||
if (levelChart) { levelChart.dispose(); levelChart = null; }
|
||||
const tree = window._lastTree, c = window._lastCredits;
|
||||
if (tree && tree.length) renderCharts(tree, c);
|
||||
}).observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
|
||||
}
|
||||
window.addEventListener('resize', () => { if (gaugeChart) gaugeChart.resize(); if (levelChart) levelChart.resize(); });
|
||||
|
||||
// ── 数据加载 ──────────────────────────────────────────────────
|
||||
async function refresh() {
|
||||
document.getElementById('loadingIndicator').classList.remove('hidden');
|
||||
document.getElementById('errorMessage').classList.add('hidden');
|
||||
document.getElementById('dataContainer').classList.add('hidden');
|
||||
document.getElementById('summaryCards').classList.add('hidden');
|
||||
document.getElementById('chartsRow').classList.add('hidden');
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/academic-status');
|
||||
const data = await res.json();
|
||||
document.getElementById('loadingIndicator').classList.add('hidden');
|
||||
|
||||
if (!data.success) {
|
||||
document.getElementById('errorText').textContent = data.message || '查询失败';
|
||||
document.getElementById('errorMessage').classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
|
||||
const tree = data.tree || [];
|
||||
if (!tree.length) {
|
||||
document.getElementById('dataContainer').classList.remove('hidden');
|
||||
document.getElementById('emptyState').classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
|
||||
// 摘要
|
||||
document.getElementById('summaryName').textContent = data.student_name || '--';
|
||||
document.getElementById('summaryGpa').textContent = data.gpa || '--';
|
||||
document.getElementById('summaryTime').textContent = data.stat_time || '--';
|
||||
|
||||
const root = tree[0];
|
||||
let rootCredits = { earned: 0, required: 0 };
|
||||
if (root) {
|
||||
rootCredits = { earned: root.earned_credits || 0, required: root.required_credits || 0 };
|
||||
document.getElementById('summaryCredits').textContent = `${rootCredits.earned} / ${rootCredits.required}`;
|
||||
const pct = rootCredits.required > 0 ? Math.round((rootCredits.earned / rootCredits.required) * 100) : 0;
|
||||
document.getElementById('summaryCourses').textContent = `${pct}%`;
|
||||
}
|
||||
|
||||
document.getElementById('summaryCards').classList.remove('hidden');
|
||||
|
||||
// 渲染树
|
||||
document.getElementById('treeRoot').innerHTML = tree.map(n => renderNode(n, 0)).join('');
|
||||
document.getElementById('emptyState').classList.add('hidden');
|
||||
document.getElementById('dataContainer').classList.remove('hidden');
|
||||
|
||||
window._lastTree = tree;
|
||||
window._lastCredits = rootCredits;
|
||||
renderCharts(tree, rootCredits);
|
||||
|
||||
} catch (e) {
|
||||
document.getElementById('loadingIndicator').classList.add('hidden');
|
||||
document.getElementById('errorText').textContent = '网络错误: ' + e.message;
|
||||
document.getElementById('errorMessage').classList.remove('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
initSession().then(() => { setupDarkObserver(); refresh(); });
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,467 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
|
||||
{% block title %}学业预警 - {{ brand_name }}{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
@keyframes fadeSlideIn {
|
||||
from { opacity: 0; transform: translateY(8px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.row-animate { animation: fadeSlideIn 0.3s ease both; }
|
||||
|
||||
.category-panel {
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
.category-panel .toggle-icon {
|
||||
transition: transform 0.2s ease;
|
||||
}
|
||||
.category-panel.open .toggle-icon {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
.course-table {
|
||||
transition: max-height 0.3s ease;
|
||||
overflow: hidden;
|
||||
}
|
||||
.course-table.collapsed {
|
||||
max-height: 0 !important;
|
||||
}
|
||||
.course-table.expanded {
|
||||
max-height: 2000px;
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
<!-- Header -->
|
||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 list-item-enter" style="animation-delay: 0ms;">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>
|
||||
<line x1="12" y1="9" x2="12" y2="13"/>
|
||||
<line x1="12" y1="17" x2="12.01" y2="17"/>
|
||||
</svg>
|
||||
学业预警查询
|
||||
</h2>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">按教学计划分类展示修读情况与学分预警</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Filter Bar -->
|
||||
<div class="glass rounded-2xl p-4 mb-6 list-item-enter max-w-5xl mx-auto" style="animation-delay: 50ms;">
|
||||
<div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3 items-end">
|
||||
<div class="w-full">
|
||||
<label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">学院</label>
|
||||
<select id="filter_jg_id" class="w-full rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 px-3 py-2 text-sm">
|
||||
<option value="">加载中...</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="w-full">
|
||||
<label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">年级</label>
|
||||
<select id="filter_njdm_id" class="w-full rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 px-3 py-2 text-sm">
|
||||
<option value="">加载中...</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="flex-1 min-w-[200px]">
|
||||
<label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">专业</label>
|
||||
<select id="filter_zyh_id" class="w-full rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 px-3 py-2 text-sm">
|
||||
<option value="">加载中...</option>
|
||||
</select>
|
||||
</div>
|
||||
<button id="searchBtn" onclick="doSearch()"
|
||||
class="px-5 py-2 rounded-lg bg-black dark:bg-white text-white dark:text-black text-sm font-medium hover:opacity-85 transition-opacity whitespace-nowrap flex-shrink-0"
|
||||
disabled>
|
||||
查询
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Loading -->
|
||||
<div id="loadingIndicator" class="text-center py-12 hidden">
|
||||
<div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
|
||||
<p class="text-gray-500 dark:text-gray-400">正在查询学业预警...</p>
|
||||
</div>
|
||||
|
||||
<!-- 图表区 -->
|
||||
<div id="chartsRow" class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6 hidden">
|
||||
<div class="glass rounded-2xl p-4">
|
||||
<h3 class="text-sm font-semibold text-gray-600 dark:text-gray-400 mb-3">各类别学分完成度</h3>
|
||||
<div id="creditBarChart" class="h-80"></div>
|
||||
</div>
|
||||
<div class="glass rounded-2xl p-4">
|
||||
<h3 class="text-sm font-semibold text-gray-600 dark:text-gray-400 mb-3">课程状态分布</h3>
|
||||
<div id="courseStatusChart" class="h-64"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Error -->
|
||||
<div id="errorMessage" class="glass rounded-2xl p-6 mb-4 text-center hidden">
|
||||
<p id="errorText" class="text-red-500"></p>
|
||||
</div>
|
||||
|
||||
<!-- Results -->
|
||||
<div id="dataContainer" class="hidden space-y-4"></div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script src="{{ url_for('static', filename='echarts.min.js') }}"></script>
|
||||
<script>
|
||||
let paramsReady = false;
|
||||
let creditBarChart = null;
|
||||
let courseStatusChart = null;
|
||||
|
||||
// ── 深色模式 ──
|
||||
function isDarkMode() { return document.documentElement.classList.contains('dark'); }
|
||||
|
||||
// ── Session 健康检查 ──
|
||||
async function initSession() {
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/ping');
|
||||
const data = await res.json();
|
||||
if (!data.success) { console.warn('Session ping 失败:', data.message); return false; }
|
||||
if (data.refreshed) console.log('🔄 Session 已自动刷新');
|
||||
return true;
|
||||
} catch (e) { console.error('Session ping 异常:', e); return false; }
|
||||
}
|
||||
|
||||
// ── Init: load dropdowns ──
|
||||
async function loadParams() {
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/academic-warning/params');
|
||||
const data = await res.json();
|
||||
if (!data.success || !data.selects) {
|
||||
throw new Error(data.message || '获取下拉框参数失败');
|
||||
}
|
||||
fillSelect('filter_jg_id', data.selects.jg_id);
|
||||
fillSelect('filter_njdm_id', data.selects.njdm_id);
|
||||
fillSelect('filter_zyh_id', data.selects.zyh_id);
|
||||
paramsReady = true;
|
||||
document.getElementById('searchBtn').disabled = false;
|
||||
// Auto query on load
|
||||
doSearch();
|
||||
} catch (e) {
|
||||
document.getElementById('errorText').textContent = '加载参数失败: ' + e.message;
|
||||
document.getElementById('errorMessage').classList.remove('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
function fillSelect(id, selectData) {
|
||||
const el = document.getElementById(id);
|
||||
if (!selectData || !selectData.options) {
|
||||
el.innerHTML = '<option value="">--</option>';
|
||||
return;
|
||||
}
|
||||
const defaultVal = selectData.default || '';
|
||||
el.innerHTML = selectData.options.map(o =>
|
||||
`<option value="${escAttr(o.value)}" ${o.value === defaultVal ? 'selected' : ''}>${escHtml(o.label)}</option>`
|
||||
).join('');
|
||||
}
|
||||
|
||||
// ── Search ──
|
||||
async function doSearch() {
|
||||
if (!paramsReady) return;
|
||||
showLoading();
|
||||
|
||||
const jg_id = document.getElementById('filter_jg_id').value;
|
||||
const njdm_id = document.getElementById('filter_njdm_id').value;
|
||||
const zyh_id = document.getElementById('filter_zyh_id').value;
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
if (jg_id) params.append('jg_id', jg_id);
|
||||
if (njdm_id) params.append('njdm_id', njdm_id);
|
||||
if (zyh_id) params.append('zyh_id', zyh_id);
|
||||
|
||||
const res = await fetch('/api/jwxt/academic-warning?' + params.toString());
|
||||
const data = await res.json();
|
||||
hideLoading();
|
||||
|
||||
if (!data.success) {
|
||||
showError(data.message || '查询失败');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!data.items || !data.items.length) {
|
||||
showEmpty('暂无学业预警数据');
|
||||
return;
|
||||
}
|
||||
|
||||
renderCategories(data.items);
|
||||
} catch (e) {
|
||||
hideLoading();
|
||||
showError('网络错误: ' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Render ──
|
||||
function renderCategories(items) {
|
||||
const container = document.getElementById('dataContainer');
|
||||
container.classList.remove('hidden');
|
||||
container.innerHTML = '';
|
||||
|
||||
items.forEach((item, idx) => {
|
||||
const kcList = item.kcList || [];
|
||||
const name = item.xfyqjdmc || item.fxfyqjdMc || `分类 ${idx + 1}`;
|
||||
const minCredit = item.yqzdxf || '0';
|
||||
const earnedCredit = '--'; // 教务数据中可能没有
|
||||
const hasCourses = kcList.length > 0;
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = `glass rounded-2xl overflow-hidden category-panel ${hasCourses ? 'open' : ''} row-animate`;
|
||||
card.style.animationDelay = (idx * 50) + 'ms';
|
||||
|
||||
card.innerHTML = `
|
||||
<div class="px-5 py-4 flex justify-between items-center cursor-pointer hover:bg-gray-50/30 dark:hover:bg-gray-800/20 transition-colors"
|
||||
onclick="toggleCategory(this)">
|
||||
<div>
|
||||
<h3 class="font-semibold text-base">${escHtml(name)}</h3>
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
|
||||
要求最低 <span class="font-medium text-black dark:text-white">${escHtml(minCredit)}</span> 学分
|
||||
${kcList.length > 0 ? ' · ' + kcList.length + ' 门课程' : ''}
|
||||
</p>
|
||||
</div>
|
||||
${hasCourses ? `
|
||||
<svg class="toggle-icon w-5 h-5 text-gray-400 flex-shrink-0" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
|
||||
<path fill-rule="evenodd" d="M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z" clip-rule="evenodd"/>
|
||||
</svg>` : ''}
|
||||
</div>
|
||||
${hasCourses ? `
|
||||
<div class="course-table expanded overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead>
|
||||
<tr class="border-t border-b border-gray-100 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-800/30">
|
||||
<th class="text-left py-2.5 px-4 font-medium text-gray-600 dark:text-gray-400 text-xs">课程号</th>
|
||||
<th class="text-left py-2.5 px-4 font-medium text-gray-600 dark:text-gray-400 text-xs">课程名称</th>
|
||||
<th class="text-center py-2.5 px-4 font-medium text-gray-600 dark:text-gray-400 text-xs">学分</th>
|
||||
<th class="text-left py-2.5 px-4 font-medium text-gray-600 dark:text-gray-400 text-xs">建议修读</th>
|
||||
<th class="text-left py-2.5 px-4 font-medium text-gray-600 dark:text-gray-400 text-xs">实际修读</th>
|
||||
<th class="text-center py-2.5 px-4 font-medium text-gray-600 dark:text-gray-400 text-xs">必修</th>
|
||||
<th class="text-center py-2.5 px-4 font-medium text-gray-600 dark:text-gray-400 text-xs">成绩</th>
|
||||
<th class="text-center py-2.5 px-4 font-medium text-gray-600 dark:text-gray-400 text-xs">状态</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${kcList.map(course => renderCourseRow(course)).join('')}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>` : ''}
|
||||
`;
|
||||
container.appendChild(card);
|
||||
});
|
||||
|
||||
// 渲染图表
|
||||
const chartsRow = document.getElementById('chartsRow');
|
||||
chartsRow.classList.remove('hidden');
|
||||
renderCreditBarChart(items);
|
||||
renderCourseStatusChart(items);
|
||||
setupDarkObserver(items);
|
||||
}
|
||||
|
||||
function renderCourseRow(c) {
|
||||
// Format semester strings
|
||||
const planSem = c.jyxdxnmc && c.jyxdxqmc ? `${c.jyxdxnmc} ${c.jyxdxqmc}` : '--';
|
||||
const actualSem = c.xnmc && c.xqmc ? `${c.xnmc} ${c.xqmc}` : '--';
|
||||
const isRequired = c.jgpxzd === '1' ? '必修' : '选修';
|
||||
const score = c.cj || '--';
|
||||
const scoreClass = getScoreClass(score);
|
||||
const status = getStatusBadge(c);
|
||||
|
||||
return `
|
||||
<tr class="border-b border-gray-50 dark:border-gray-800/30 hover:bg-gray-50/30 dark:hover:bg-gray-800/20 transition-colors">
|
||||
<td class="py-2 px-4 text-xs text-gray-500 dark:text-gray-400 font-mono">${escHtml(c.kch || '--')}</td>
|
||||
<td class="py-2 px-4 text-sm">${escHtml(c.kcmc || '--')}</td>
|
||||
<td class="py-2 px-4 text-center text-xs">${escHtml(c.xf || '--')}</td>
|
||||
<td class="py-2 px-4 text-xs text-gray-500">${escHtml(planSem)}</td>
|
||||
<td class="py-2 px-4 text-xs text-gray-500">${escHtml(actualSem)}</td>
|
||||
<td class="py-2 px-4 text-center text-xs">${isRequired}</td>
|
||||
<td class="py-2 px-4 text-center text-sm font-medium ${scoreClass}">${score}</td>
|
||||
<td class="py-2 px-4 text-center">${status}</td>
|
||||
</tr>
|
||||
`;
|
||||
}
|
||||
|
||||
function getScoreClass(score) {
|
||||
const n = parseFloat(score);
|
||||
if (isNaN(n)) return 'text-gray-400';
|
||||
if (n >= 90) return 'text-green-600 dark:text-green-400';
|
||||
if (n >= 80) return 'text-blue-600 dark:text-blue-400';
|
||||
if (n >= 70) return 'text-yellow-600 dark:text-yellow-400';
|
||||
if (n >= 60) return 'text-orange-500 dark:text-orange-400';
|
||||
return 'text-red-600 dark:text-red-400';
|
||||
}
|
||||
|
||||
function getStatusBadge(c) {
|
||||
const tdbj = c.tdbj;
|
||||
const bfzcj = c.bfzcj;
|
||||
const xnmc = c.xnmc;
|
||||
|
||||
if (tdbj === '1') {
|
||||
return '<span class="inline-block px-2 py-0.5 rounded text-xs bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400">退课</span>';
|
||||
}
|
||||
if (bfzcj === null && xnmc !== null) {
|
||||
return '<span class="inline-block px-2 py-0.5 rounded text-xs bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400">已修</span>';
|
||||
}
|
||||
if (bfzcj !== null && parseFloat(bfzcj) < 60) {
|
||||
return '<span class="inline-block px-2 py-0.5 rounded text-xs bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-400">不及格</span>';
|
||||
}
|
||||
if (bfzcj === null && xnmc === null) {
|
||||
return '<span class="inline-block px-2 py-0.5 rounded text-xs bg-gray-100 dark:bg-gray-800 text-gray-500">未修</span>';
|
||||
}
|
||||
if (bfzcj !== null && parseFloat(bfzcj) >= 60) {
|
||||
return '<span class="inline-block px-2 py-0.5 rounded text-xs bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400">通过</span>';
|
||||
}
|
||||
return '--';
|
||||
}
|
||||
|
||||
// ── Toggle category ──
|
||||
function toggleCategory(header) {
|
||||
const panel = header.parentElement;
|
||||
const table = panel.querySelector('.course-table');
|
||||
if (!table) return;
|
||||
|
||||
panel.classList.toggle('open');
|
||||
if (panel.classList.contains('open')) {
|
||||
table.classList.remove('collapsed');
|
||||
table.classList.add('expanded');
|
||||
} else {
|
||||
table.classList.add('collapsed');
|
||||
table.classList.remove('expanded');
|
||||
}
|
||||
}
|
||||
|
||||
// ── Helpers ──
|
||||
function showLoading() {
|
||||
document.getElementById('loadingIndicator').classList.remove('hidden');
|
||||
document.getElementById('errorMessage').classList.add('hidden');
|
||||
document.getElementById('dataContainer').classList.add('hidden');
|
||||
}
|
||||
function hideLoading() {
|
||||
document.getElementById('loadingIndicator').classList.add('hidden');
|
||||
}
|
||||
function showError(msg) {
|
||||
document.getElementById('errorText').textContent = msg;
|
||||
document.getElementById('errorMessage').classList.remove('hidden');
|
||||
}
|
||||
function showEmpty(msg) {
|
||||
document.getElementById('dataContainer').classList.remove('hidden');
|
||||
document.getElementById('dataContainer').innerHTML = `
|
||||
<div class="glass rounded-2xl p-12 text-center">
|
||||
<p class="text-gray-500 dark:text-gray-400 text-lg">${escHtml(msg)}</p>
|
||||
</div>`;
|
||||
}
|
||||
function escHtml(s) {
|
||||
if (s == null) return '';
|
||||
return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
||||
}
|
||||
function escAttr(s) {
|
||||
if (s == null) return '';
|
||||
return String(s).replace(/&/g, '"').replace(/</g, '<').replace(/>/g, '>');
|
||||
}
|
||||
|
||||
// ── 各类别学分完成度柱状图 ──
|
||||
function renderCreditBarChart(items) {
|
||||
const container = document.getElementById('creditBarChart');
|
||||
if (!container) return;
|
||||
if (!creditBarChart) creditBarChart = echarts.init(container);
|
||||
|
||||
const categories = [];
|
||||
const requiredCredits = [];
|
||||
const dark = isDarkMode();
|
||||
|
||||
items.forEach(item => {
|
||||
const name = (item.xfyqjdmc || item.fxfyqjdMc || '未知').substring(0, 8);
|
||||
const minCredit = parseFloat(item.yqzdxf) || 0;
|
||||
categories.push(name);
|
||||
requiredCredits.push(minCredit);
|
||||
});
|
||||
|
||||
creditBarChart.setOption({
|
||||
tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
|
||||
legend: { data: ['要求学分'], top: 0, textStyle: { fontSize: 11, color: dark ? '#9ca3af' : '#6b7280' } },
|
||||
grid: { left: '3%', right: '4%', bottom: '3%', top: '15%', containLabel: true },
|
||||
xAxis: { type: 'value', name: '学分', nameTextStyle: { fontSize: 11 } },
|
||||
yAxis: { type: 'category', data: categories, axisLabel: { fontSize: 10 }, inverse: true },
|
||||
series: [{
|
||||
name: '要求学分', type: 'bar', data: requiredCredits,
|
||||
itemStyle: {
|
||||
color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
|
||||
{ offset: 0, color: dark ? '#60a5fa' : '#3b82f6' },
|
||||
{ offset: 1, color: dark ? '#34d399' : '#10b981' }
|
||||
])
|
||||
},
|
||||
barMaxWidth: 28,
|
||||
label: { show: true, position: 'right', fontSize: 11, color: dark ? '#9ca3af' : '#6b7280' }
|
||||
}]
|
||||
}, true);
|
||||
}
|
||||
|
||||
// ── 课程状态饼图 ──
|
||||
function renderCourseStatusChart(items) {
|
||||
const container = document.getElementById('courseStatusChart');
|
||||
if (!container) return;
|
||||
if (!courseStatusChart) courseStatusChart = echarts.init(container);
|
||||
|
||||
const statusCount = { '已修/通过': 0, '未修': 0, '不及格': 0, '退课': 0 };
|
||||
items.forEach(item => {
|
||||
(item.kcList || []).forEach(c => {
|
||||
if (c.tdbj === '1') { statusCount['退课']++; return; }
|
||||
if (c.bfzcj === null && c.xnmc === null) { statusCount['未修']++; return; }
|
||||
if (c.bfzcj !== null && parseFloat(c.bfzcj) < 60) { statusCount['不及格']++; return; }
|
||||
statusCount['已修/通过']++;
|
||||
});
|
||||
});
|
||||
|
||||
const entries = Object.entries(statusCount).filter(([, v]) => v > 0);
|
||||
const dark = isDarkMode();
|
||||
const colorMap = {
|
||||
'已修/通过': dark ? '#34d399' : '#10b981',
|
||||
'未修': dark ? '#9ca3af' : '#6b7280',
|
||||
'不及格': dark ? '#f87171' : '#ef4444',
|
||||
'退课': dark ? '#fbbf24' : '#f59e0b',
|
||||
};
|
||||
|
||||
courseStatusChart.setOption({
|
||||
tooltip: { trigger: 'item', formatter: '{b}: {c} 门 ({d}%)' },
|
||||
series: [{
|
||||
type: 'pie', radius: ['40%', '70%'], center: ['50%', '50%'],
|
||||
itemStyle: { borderRadius: 4, borderColor: dark ? '#1f2937' : '#fff', borderWidth: 2 },
|
||||
label: { fontSize: 11, color: dark ? '#d1d5db' : '#374151' },
|
||||
data: entries.map(([name, value]) => ({ name, value, itemStyle: { color: colorMap[name] || '#999' } }))
|
||||
}]
|
||||
}, true);
|
||||
}
|
||||
|
||||
// ── 深色模式观察者 ──
|
||||
let _darkObserver = null;
|
||||
let _lastItems = null;
|
||||
function setupDarkObserver(items) {
|
||||
_lastItems = items;
|
||||
if (_darkObserver) return;
|
||||
_darkObserver = new MutationObserver(() => {
|
||||
if (_lastItems && _lastItems.length > 0) {
|
||||
renderCreditBarChart(_lastItems);
|
||||
renderCourseStatusChart(_lastItems);
|
||||
}
|
||||
});
|
||||
_darkObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
|
||||
}
|
||||
|
||||
window.addEventListener('resize', () => {
|
||||
creditBarChart?.resize();
|
||||
courseStatusChart?.resize();
|
||||
});
|
||||
|
||||
// ── Start ──
|
||||
initSession().then(sessionOk => {
|
||||
if (!sessionOk) {
|
||||
showError('教务系统 Session 已失效,请尝试<a href="/dashboard">重新配置教务账号</a>');
|
||||
return;
|
||||
}
|
||||
loadParams();
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,623 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
|
||||
{% block title %}IP管理 - {{ brand_name }}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="space-y-6">
|
||||
|
||||
<!-- 页面标题 -->
|
||||
<div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4 list-item-enter" style="animation-delay: 0ms;">
|
||||
<div>
|
||||
<h1 class="text-2xl md:text-3xl font-bold text-neutral-900 dark:text-white">IP 管理</h1>
|
||||
<p class="text-neutral-500 dark:text-neutral-400 mt-1">访问控制、封禁管理与访问统计</p>
|
||||
</div>
|
||||
<div class="flex gap-3 flex-wrap">
|
||||
<button onclick="openBanModal()" class="btn-primary px-5 py-2.5 rounded-full text-sm font-bold">
|
||||
<svg class="w-4 h-4 inline-block mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"/>
|
||||
</svg>
|
||||
添加封禁
|
||||
</button>
|
||||
<button onclick="openConfigModal()" class="px-5 py-2.5 rounded-full text-sm font-bold border border-neutral-200 dark:border-neutral-700 text-neutral-700 dark:text-neutral-300 hover:bg-neutral-100 dark:hover:bg-neutral-800 transition-colors">
|
||||
频率设置
|
||||
</button>
|
||||
<a href="{{ url_for('main.admin_users') }}" class="px-5 py-2.5 rounded-full text-sm font-bold border border-neutral-200 dark:border-neutral-700 text-neutral-700 dark:text-neutral-300 hover:bg-neutral-100 dark:hover:bg-neutral-800 transition-colors flex items-center gap-1.5">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 17l-5-5m0 0l5-5m-5 5h12"/>
|
||||
</svg>
|
||||
返回管理后台
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 统计概览 -->
|
||||
<div class="grid grid-cols-2 md:grid-cols-4 gap-4">
|
||||
<div class="glass rounded-2xl p-5 layer-2 list-item-enter" style="animation-delay: 50ms;">
|
||||
<p class="text-sm text-neutral-500 dark:text-neutral-400">今日访问</p>
|
||||
<p class="text-2xl font-bold text-neutral-900 dark:text-white mt-1" id="statTotal">-</p>
|
||||
</div>
|
||||
<div class="glass rounded-2xl p-5 layer-2 list-item-enter" style="animation-delay: 100ms;">
|
||||
<p class="text-sm text-neutral-500 dark:text-neutral-400">独立IP</p>
|
||||
<p class="text-2xl font-bold text-neutral-900 dark:text-white mt-1" id="statUnique">-</p>
|
||||
</div>
|
||||
<div class="glass rounded-2xl p-5 layer-2 list-item-enter" style="animation-delay: 150ms;">
|
||||
<p class="text-sm text-neutral-500 dark:text-neutral-400">被拦截</p>
|
||||
<p class="text-2xl font-bold text-red-500 mt-1" id="statBlocked">-</p>
|
||||
</div>
|
||||
<div class="glass rounded-2xl p-5 layer-2 list-item-enter" style="animation-delay: 200ms;">
|
||||
<p class="text-sm text-neutral-500 dark:text-neutral-400">封禁规则</p>
|
||||
<p class="text-2xl font-bold text-neutral-900 dark:text-white mt-1" id="statBans">-</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 标签页切换 -->
|
||||
<div class="border-b border-neutral-200 dark:border-neutral-800 list-item-enter" style="animation-delay: 250ms;">
|
||||
<nav class="flex gap-6">
|
||||
<button onclick="switchTab('stats')" id="tab-stats" class="pb-3 text-sm font-medium border-b-2 border-neutral-900 dark:border-white text-neutral-900 dark:text-white transition-colors">
|
||||
统计图表
|
||||
</button>
|
||||
<button onclick="switchTab('logs')" id="tab-logs" class="pb-3 text-sm font-medium border-b-2 border-transparent text-neutral-500 dark:text-neutral-400 hover:text-neutral-700 dark:hover:text-neutral-200 transition-colors">
|
||||
访问日志
|
||||
</button>
|
||||
<button onclick="switchTab('bans')" id="tab-bans" class="pb-3 text-sm font-medium border-b-2 border-transparent text-neutral-500 dark:text-neutral-400 hover:text-neutral-700 dark:hover:text-neutral-200 transition-colors">
|
||||
封禁管理
|
||||
</button>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<!-- 统计图表 -->
|
||||
<div id="panel-stats" class="space-y-4">
|
||||
<div class="glass rounded-2xl p-5 layer-2 list-item-enter" style="animation-delay: 300ms;">
|
||||
<div class="flex items-center justify-between mb-3">
|
||||
<h3 class="text-sm font-semibold text-neutral-700 dark:text-neutral-300">访问时段分布</h3>
|
||||
<select id="statsHours" onchange="loadStats()" class="text-xs rounded-lg border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-900 px-2 py-1 text-neutral-700 dark:text-neutral-300">
|
||||
<option value="1">最近1小时</option>
|
||||
<option value="6">最近6小时</option>
|
||||
<option value="24" selected>最近24小时</option>
|
||||
<option value="72">最近3天</option>
|
||||
<option value="168">最近7天</option>
|
||||
</select>
|
||||
</div>
|
||||
<div id="chartHour" class="w-full h-64"></div>
|
||||
</div>
|
||||
<div class="grid md:grid-cols-2 gap-4">
|
||||
<div class="glass rounded-2xl p-5 layer-2 list-item-enter" style="animation-delay: 350ms;">
|
||||
<h3 class="text-sm font-semibold text-neutral-700 dark:text-neutral-300 mb-3">来源国家/地区 Top10</h3>
|
||||
<div id="chartCountry" class="w-full h-64"></div>
|
||||
</div>
|
||||
<div class="glass rounded-2xl p-5 layer-2 list-item-enter" style="animation-delay: 400ms;">
|
||||
<h3 class="text-sm font-semibold text-neutral-700 dark:text-neutral-300 mb-3">中国省份分布 Top15</h3>
|
||||
<div id="chartRegion" class="w-full h-64"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="glass rounded-2xl p-5 layer-2 list-item-enter" style="animation-delay: 450ms;">
|
||||
<div class="flex items-center justify-between mb-3">
|
||||
<h3 class="text-sm font-semibold text-neutral-700 dark:text-neutral-300">访问最多 IP Top10</h3>
|
||||
</div>
|
||||
<div id="topIpTable" class="space-y-2 max-h-64 overflow-y-auto"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 访问日志 -->
|
||||
<div id="panel-logs" class="hidden space-y-4">
|
||||
<div class="glass rounded-2xl p-5 layer-2 list-item-enter" style="animation-delay: 300ms;">
|
||||
<!-- 过滤栏 -->
|
||||
<div class="flex flex-wrap gap-3 mb-4">
|
||||
<input id="filterIp" type="text" placeholder="IP过滤..."
|
||||
class="rounded-xl border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-900 text-sm px-3 py-2 text-neutral-700 dark:text-neutral-300 w-40">
|
||||
<select id="filterBlocked" class="rounded-xl border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-900 text-sm px-3 py-2 text-neutral-700 dark:text-neutral-300">
|
||||
<option value="">全部</option>
|
||||
<option value="true">仅拦截</option>
|
||||
</select>
|
||||
<button onclick="loadLogs(1)" class="px-4 py-2 rounded-xl bg-blue-500 text-white text-sm font-medium hover:bg-blue-600 transition-colors">搜索</button>
|
||||
<button onclick="openCleanModal()" class="px-4 py-2 rounded-xl bg-neutral-100 dark:bg-neutral-800 text-neutral-700 dark:text-neutral-300 text-sm font-medium hover:bg-neutral-200 dark:hover:bg-neutral-700 transition-colors">🗑 清理日志</button>
|
||||
</div>
|
||||
<!-- 日志表格 -->
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead>
|
||||
<tr class="text-left text-neutral-500 dark:text-neutral-400 border-b border-neutral-200 dark:border-neutral-700">
|
||||
<th class="pb-3 pr-4 font-medium">时间</th>
|
||||
<th class="pb-3 pr-4 font-medium">IP</th>
|
||||
<th class="pb-3 pr-4 font-medium">地区</th>
|
||||
<th class="pb-3 pr-4 font-medium">路径</th>
|
||||
<th class="pb-3 pr-4 font-medium">状态</th>
|
||||
<th class="pb-3 font-medium">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="logsTableBody" class="divide-y divide-neutral-100 dark:divide-neutral-800">
|
||||
<tr><td colspan="6" class="py-8 text-center text-neutral-400">加载中...</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<!-- 分页 -->
|
||||
<div id="logsPagination" class="flex items-center justify-between mt-4">
|
||||
<span id="logsInfo" class="text-sm text-neutral-500"></span>
|
||||
<div class="flex gap-2" id="paginationBtns"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 封禁管理 -->
|
||||
<div id="panel-bans" class="hidden space-y-4">
|
||||
<div class="glass rounded-2xl p-5 layer-2 list-item-enter" style="animation-delay: 300ms;">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead>
|
||||
<tr class="text-left text-neutral-500 dark:text-neutral-400 border-b border-neutral-200 dark:border-neutral-700">
|
||||
<th class="pb-3 pr-4 font-medium">类型</th>
|
||||
<th class="pb-3 pr-4 font-medium">值</th>
|
||||
<th class="pb-3 pr-4 font-medium">原因</th>
|
||||
<th class="pb-3 pr-4 font-medium">到期时间</th>
|
||||
<th class="pb-3 pr-4 font-medium">创建时间</th>
|
||||
<th class="pb-3 pr-4 font-medium">操作者</th>
|
||||
<th class="pb-3 font-medium">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="bansTableBody" class="divide-y divide-neutral-100 dark:divide-neutral-800">
|
||||
<tr><td colspan="7" class="py-8 text-center text-neutral-400">加载中...</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<!-- 添加封禁 Modal -->
|
||||
<div id="banModal" class="fixed inset-0 z-50 hidden">
|
||||
<div class="absolute inset-0 bg-black/60 backdrop-blur-sm" onclick="closeBanModal()"></div>
|
||||
<div class="absolute inset-0 flex items-center justify-center p-4 pointer-events-none">
|
||||
<div class="bg-white dark:bg-neutral-900 rounded-2xl shadow-xl w-full max-w-md pointer-events-auto">
|
||||
<div class="p-6">
|
||||
<h3 class="text-lg font-bold text-neutral-900 dark:text-white mb-5">添加封禁规则</h3>
|
||||
<div class="space-y-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-neutral-700 dark:text-neutral-300 mb-1">封禁类型</label>
|
||||
<select id="banType" class="w-full rounded-xl border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-800 text-sm px-3 py-2.5 text-neutral-700 dark:text-neutral-300">
|
||||
<option value="ip">单个IP</option>
|
||||
<option value="cidr">IP段 (CIDR,如 1.2.3.0/24)</option>
|
||||
<option value="country">国家/地区代码 (如 US)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-neutral-700 dark:text-neutral-300 mb-1">封禁值</label>
|
||||
<input id="banValue" type="text" placeholder="IP / CIDR / 国家代码"
|
||||
class="w-full rounded-xl border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-800 text-sm px-3 py-2.5 text-neutral-700 dark:text-neutral-300">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-neutral-700 dark:text-neutral-300 mb-1">封禁时长</label>
|
||||
<select id="banDuration" class="w-full rounded-xl border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-800 text-sm px-3 py-2.5 text-neutral-700 dark:text-neutral-300">
|
||||
<option value="">永久封禁</option>
|
||||
<option value="1h">1小时</option>
|
||||
<option value="6h">6小时</option>
|
||||
<option value="1d">1天</option>
|
||||
<option value="3d">3天</option>
|
||||
<option value="1w">1周</option>
|
||||
<option value="1m">1个月</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-neutral-700 dark:text-neutral-300 mb-1">封禁原因</label>
|
||||
<input id="banReason" type="text" placeholder="可选"
|
||||
class="w-full rounded-xl border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-800 text-sm px-3 py-2.5 text-neutral-700 dark:text-neutral-300">
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex gap-3 mt-6">
|
||||
<button onclick="submitBan()" class="flex-1 btn-primary py-2.5 rounded-xl text-sm font-bold">确认封禁</button>
|
||||
<button onclick="closeBanModal()" class="flex-1 px-4 py-2.5 rounded-xl text-sm font-bold border border-neutral-200 dark:border-neutral-700 text-neutral-700 dark:text-neutral-300 hover:bg-neutral-100 dark:hover:bg-neutral-800 transition-colors">取消</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 快速封禁 Modal -->
|
||||
<div id="quickBanModal" class="fixed inset-0 z-50 hidden">
|
||||
<div class="absolute inset-0 bg-black/60 backdrop-blur-sm" onclick="document.getElementById('quickBanModal').classList.add('hidden')"></div>
|
||||
<div class="absolute inset-0 flex items-center justify-center p-4 pointer-events-none">
|
||||
<div class="bg-white dark:bg-neutral-900 rounded-2xl shadow-xl w-full max-w-md pointer-events-auto">
|
||||
<div class="p-6">
|
||||
<h3 class="text-lg font-bold text-neutral-900 dark:text-white mb-2">快速封禁 IP</h3>
|
||||
<p class="text-sm text-neutral-500 mb-5">IP:<strong id="quickBanIpDisplay" class="text-neutral-800 dark:text-neutral-200 font-mono"></strong></p>
|
||||
<input type="hidden" id="quickBanIp">
|
||||
<div class="space-y-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-neutral-700 dark:text-neutral-300 mb-1">封禁时长</label>
|
||||
<select id="quickBanDuration" class="w-full rounded-xl border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-800 text-sm px-3 py-2.5 text-neutral-700 dark:text-neutral-300">
|
||||
<option value="">永久封禁</option>
|
||||
<option value="1h">1小时</option>
|
||||
<option value="6h">6小时</option>
|
||||
<option value="1d">1天</option>
|
||||
<option value="3d">3天</option>
|
||||
<option value="1w">1周</option>
|
||||
<option value="1m">1个月</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-neutral-700 dark:text-neutral-300 mb-1">原因</label>
|
||||
<input id="quickBanReason" type="text" value="管理员从日志封禁"
|
||||
class="w-full rounded-xl border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-800 text-sm px-3 py-2.5 text-neutral-700 dark:text-neutral-300">
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex gap-3 mt-6">
|
||||
<button onclick="submitQuickBan()" class="flex-1 bg-red-500 text-white py-2.5 rounded-xl text-sm font-bold hover:bg-red-600 transition-colors">确认封禁</button>
|
||||
<button onclick="document.getElementById('quickBanModal').classList.add('hidden')" class="flex-1 px-4 py-2.5 rounded-xl text-sm font-bold border border-neutral-200 dark:border-neutral-700 text-neutral-700 dark:text-neutral-300 hover:bg-neutral-100 dark:hover:bg-neutral-800 transition-colors">取消</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 频率设置 Modal -->
|
||||
<div id="configModal" class="fixed inset-0 z-50 hidden">
|
||||
<div class="absolute inset-0 bg-black/60 backdrop-blur-sm" onclick="document.getElementById('configModal').classList.add('hidden')"></div>
|
||||
<div class="absolute inset-0 flex items-center justify-center p-4 pointer-events-none">
|
||||
<div class="bg-white dark:bg-neutral-900 rounded-2xl shadow-xl w-full max-w-md pointer-events-auto">
|
||||
<div class="p-6">
|
||||
<h3 class="text-lg font-bold text-neutral-900 dark:text-white mb-5">登录频率限制设置</h3>
|
||||
<div class="space-y-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-neutral-700 dark:text-neutral-300 mb-1">统计时间窗口(分钟)</label>
|
||||
<input id="cfgWindow" type="number" min="1" max="60"
|
||||
class="w-full rounded-xl border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-800 text-sm px-3 py-2.5 text-neutral-700 dark:text-neutral-300">
|
||||
<p class="text-xs text-neutral-400 mt-1">在此时间窗口内统计失败次数</p>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-neutral-700 dark:text-neutral-300 mb-1">最大失败次数</label>
|
||||
<input id="cfgMax" type="number" min="1" max="100"
|
||||
class="w-full rounded-xl border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-800 text-sm px-3 py-2.5 text-neutral-700 dark:text-neutral-300">
|
||||
<p class="text-xs text-neutral-400 mt-1">超过此次数自动封禁1小时</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-3">
|
||||
<input id="cfgChinaOnly" type="checkbox" class="w-4 h-4 rounded">
|
||||
<label class="text-sm font-medium text-neutral-700 dark:text-neutral-300">启用中国IP限制(关闭后允许境外访问)</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex gap-3 mt-6">
|
||||
<button onclick="submitConfig()" class="flex-1 btn-primary py-2.5 rounded-xl text-sm font-bold">保存配置</button>
|
||||
<button onclick="document.getElementById('configModal').classList.add('hidden')" class="flex-1 px-4 py-2.5 rounded-xl text-sm font-bold border border-neutral-200 dark:border-neutral-700 text-neutral-700 dark:text-neutral-300 hover:bg-neutral-100 dark:hover:bg-neutral-800 transition-colors">取消</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 清理日志 Modal -->
|
||||
<div id="cleanModal" class="fixed inset-0 z-50 hidden">
|
||||
<div class="absolute inset-0 bg-black/60 backdrop-blur-sm" onclick="document.getElementById('cleanModal').classList.add('hidden')"></div>
|
||||
<div class="absolute inset-0 flex items-center justify-center p-4 pointer-events-none">
|
||||
<div class="bg-white dark:bg-neutral-900 rounded-2xl shadow-xl w-full max-w-sm pointer-events-auto">
|
||||
<div class="p-6">
|
||||
<h3 class="text-lg font-bold text-neutral-900 dark:text-white mb-4">清理访问日志</h3>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-neutral-700 dark:text-neutral-300 mb-1">清理多少天前的日志</label>
|
||||
<select id="cleanDays" class="w-full rounded-xl border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-800 text-sm px-3 py-2.5 text-neutral-700 dark:text-neutral-300">
|
||||
<option value="1">1天前</option>
|
||||
<option value="3">3天前</option>
|
||||
<option value="7" selected>7天前</option>
|
||||
<option value="30">30天前</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="flex gap-3 mt-6">
|
||||
<button onclick="submitClean()" class="flex-1 bg-red-500 text-white py-2.5 rounded-xl text-sm font-bold hover:bg-red-600 transition-colors">确认清理</button>
|
||||
<button onclick="document.getElementById('cleanModal').classList.add('hidden')" class="flex-1 px-4 py-2.5 rounded-xl text-sm font-bold border border-neutral-200 dark:border-neutral-700 text-neutral-700 dark:text-neutral-300 hover:bg-neutral-100 dark:hover:bg-neutral-800 transition-colors">取消</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script src="{{ url_for('static', filename='echarts.min.js') }}"></script>
|
||||
<script>
|
||||
// ==================== 工具函数 ====================
|
||||
function showToast(msg, type='success') {
|
||||
const t = document.getElementById('toast');
|
||||
if (!t) return;
|
||||
const inner = document.getElementById('toastInner');
|
||||
inner.textContent = msg;
|
||||
inner.className = `rounded-2xl px-5 py-3 text-sm font-medium shadow-xl text-white ${type === 'success' ? 'bg-green-500' : 'bg-red-500'}`;
|
||||
t.classList.remove('hidden');
|
||||
setTimeout(() => t.classList.add('hidden'), 3000);
|
||||
}
|
||||
|
||||
async function apiFetch(url, options={}) {
|
||||
const resp = await fetch(url, {
|
||||
headers: {'Content-Type': 'application/json', ...(options.headers || {})},
|
||||
...options
|
||||
});
|
||||
return resp.json();
|
||||
}
|
||||
|
||||
// ==================== Tab 切换 ====================
|
||||
let currentTab = 'stats';
|
||||
function switchTab(tab) {
|
||||
['stats','logs','bans'].forEach(t => {
|
||||
document.getElementById(`panel-${t}`).classList.add('hidden');
|
||||
document.getElementById(`tab-${t}`).className = t === tab
|
||||
? 'pb-3 text-sm font-medium border-b-2 border-neutral-900 dark:border-white text-neutral-900 dark:text-white transition-colors'
|
||||
: 'pb-3 text-sm font-medium border-b-2 border-transparent text-neutral-500 dark:text-neutral-400 hover:text-neutral-700 dark:hover:text-neutral-200 transition-colors';
|
||||
});
|
||||
document.getElementById(`panel-${tab}`).classList.remove('hidden');
|
||||
currentTab = tab;
|
||||
if (tab === 'logs' && !logsLoaded) loadLogs(1);
|
||||
if (tab === 'bans' && !bansLoaded) loadBans();
|
||||
}
|
||||
|
||||
// ==================== 统计图表 ====================
|
||||
let chartHour = null, chartCountry = null, chartRegion = null;
|
||||
let logsLoaded = false, bansLoaded = false;
|
||||
|
||||
async function loadStats() {
|
||||
const hours = document.getElementById('statsHours').value;
|
||||
const data = await apiFetch(`/api/admin/ip/stats?hours=${hours}`);
|
||||
if (!data.success) { showToast('加载统计失败: ' + data.message, 'error'); return; }
|
||||
const s = data.stats;
|
||||
|
||||
document.getElementById('statTotal').textContent = s.total.toLocaleString();
|
||||
document.getElementById('statUnique').textContent = s.unique_ips.toLocaleString();
|
||||
document.getElementById('statBlocked').textContent = s.blocked.toLocaleString();
|
||||
document.getElementById('statBans').textContent = s.active_bans;
|
||||
|
||||
// 时段分布
|
||||
const now = new Date();
|
||||
const allHours = [];
|
||||
for (let i = parseInt(hours) - 1; i >= 0; i--) {
|
||||
const d = new Date(now.getTime() - i * 3600000);
|
||||
if (parseInt(hours) <= 24) {
|
||||
allHours.push(d.toISOString().slice(11, 16));
|
||||
} else {
|
||||
allHours.push(d.toISOString().slice(5, 10));
|
||||
}
|
||||
}
|
||||
const hourMap = {};
|
||||
s.by_hour.forEach(h => hourMap[String(h.hour).padStart(2,'0')] = h.count);
|
||||
const hourData = allHours.map((_, idx) => {
|
||||
if (parseInt(hours) <= 24) return hourMap[String(idx).padStart(2,'0')] || 0;
|
||||
const d = new Date(now.getTime() - (parseInt(hours) - 1 - idx) * 3600000);
|
||||
return hourMap[String(d.getUTCHours()).padStart(2,'0')] || 0;
|
||||
});
|
||||
renderHourBar('chartHour', allHours, hourData);
|
||||
|
||||
// 国家分布
|
||||
const topCountries = s.by_country.slice(0, 10);
|
||||
renderCountryBar('chartCountry', topCountries.map(c => c.country || '-'), topCountries.map(c => c.count));
|
||||
|
||||
// 省份分布
|
||||
const topRegions = s.by_region.slice(0, 15);
|
||||
renderRegionBar('chartRegion', topRegions.map(r => r.region || '-'), topRegions.map(r => r.count));
|
||||
|
||||
// Top IP
|
||||
document.getElementById('topIpTable').innerHTML = s.top_ips.slice(0, 10).map((ip, i) => `
|
||||
<div class="flex items-center justify-between py-2 border-b border-neutral-100 dark:border-neutral-800">
|
||||
<div class="flex items-center gap-3">
|
||||
<span class="w-5 text-xs text-neutral-400 font-mono">${i+1}</span>
|
||||
<div>
|
||||
<p class="text-sm font-mono text-neutral-800 dark:text-neutral-200">${ip.ip}</p>
|
||||
<p class="text-xs text-neutral-400">${ip.country||''} ${ip.region||''} ${ip.city||''}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-3">
|
||||
<span class="text-sm font-bold text-neutral-700 dark:text-neutral-300">${ip.count}</span>
|
||||
<button onclick="openQuickBan('${ip.ip}')" class="text-xs px-2 py-1 rounded-lg bg-red-100 text-red-600 hover:bg-red-200 transition-colors">封禁</button>
|
||||
</div>
|
||||
</div>`).join('');
|
||||
}
|
||||
|
||||
function renderHourBar(domId, labels, data) {
|
||||
const dom = document.getElementById(domId);
|
||||
if (!dom) return;
|
||||
if (chartHour) { chartHour.dispose(); chartHour = null; }
|
||||
const isDark = document.documentElement.classList.contains('dark');
|
||||
chartHour = echarts.init(dom);
|
||||
chartHour.setOption({
|
||||
tooltip: { trigger: 'axis', backgroundColor: isDark ? '#262626' : '#fff', textStyle: { color: isDark ? '#fff' : '#333' } },
|
||||
grid: { left: '3%', right: '4%', bottom: '3%', top: '10%', containLabel: true },
|
||||
xAxis: { type: 'category', data: labels, axisLabel: { color: isDark ? '#888' : '#666', rotate: labels.length > 12 ? 45 : 0 }, axisLine: { lineStyle: { color: isDark ? '#444' : '#ddd' } } },
|
||||
yAxis: { type: 'value', axisLabel: { color: isDark ? '#888' : '#666' }, splitLine: { lineStyle: { color: isDark ? '#333' : '#eee' } } },
|
||||
series: [{ type: 'bar', data: data, itemStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{ offset: 0, color: '#3b82f6' }, { offset: 1, color: '#60a5fa' }]), borderRadius: [4, 4, 0, 0] }, emphasis: { itemStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{ offset: 0, color: '#2563eb' }, { offset: 1, color: '#3b82f6' }]) } } }]
|
||||
});
|
||||
window.addEventListener('resize', () => chartHour && chartHour.resize());
|
||||
}
|
||||
|
||||
function renderCountryBar(domId, labels, data) {
|
||||
const dom = document.getElementById(domId);
|
||||
if (!dom) return;
|
||||
if (chartCountry) { chartCountry.dispose(); chartCountry = null; }
|
||||
const isDark = document.documentElement.classList.contains('dark');
|
||||
chartCountry = echarts.init(dom);
|
||||
chartCountry.setOption({
|
||||
tooltip: { trigger: 'axis', backgroundColor: isDark ? '#262626' : '#fff', textStyle: { color: isDark ? '#fff' : '#333' } },
|
||||
grid: { left: '3%', right: '4%', bottom: '15%', top: '10%', containLabel: true },
|
||||
xAxis: { type: 'category', data: labels, axisLabel: { color: isDark ? '#888' : '#666', rotate: 30 }, axisLine: { lineStyle: { color: isDark ? '#444' : '#ddd' } } },
|
||||
yAxis: { type: 'value', axisLabel: { color: isDark ? '#888' : '#666' }, splitLine: { lineStyle: { color: isDark ? '#333' : '#eee' } } },
|
||||
series: [{ type: 'bar', data: data, itemStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{ offset: 0, color: '#10b981' }, { offset: 1, color: '#34d399' }]), borderRadius: [4, 4, 0, 0] }, emphasis: { itemStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{ offset: 0, color: '#059669' }, { offset: 1, color: '#10b981' }]) } } }]
|
||||
});
|
||||
window.addEventListener('resize', () => chartCountry && chartCountry.resize());
|
||||
}
|
||||
|
||||
function renderRegionBar(domId, labels, data) {
|
||||
const dom = document.getElementById(domId);
|
||||
if (!dom) return;
|
||||
if (chartRegion) { chartRegion.dispose(); chartRegion = null; }
|
||||
const isDark = document.documentElement.classList.contains('dark');
|
||||
chartRegion = echarts.init(dom);
|
||||
chartRegion.setOption({
|
||||
tooltip: { trigger: 'axis', backgroundColor: isDark ? '#262626' : '#fff', textStyle: { color: isDark ? '#fff' : '#333' } },
|
||||
grid: { left: '3%', right: '4%', bottom: '15%', top: '10%', containLabel: true },
|
||||
xAxis: { type: 'category', data: labels, axisLabel: { color: isDark ? '#888' : '#666', rotate: 30 }, axisLine: { lineStyle: { color: isDark ? '#444' : '#ddd' } } },
|
||||
yAxis: { type: 'value', axisLabel: { color: isDark ? '#888' : '#666' }, splitLine: { lineStyle: { color: isDark ? '#333' : '#eee' } } },
|
||||
series: [{ type: 'bar', data: data, itemStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{ offset: 0, color: '#f59e0b' }, { offset: 1, color: '#fbbf24' }]), borderRadius: [4, 4, 0, 0] }, emphasis: { itemStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{ offset: 0, color: '#d97706' }, { offset: 1, color: '#f59e0b' }]) } } }]
|
||||
});
|
||||
window.addEventListener('resize', () => chartRegion && chartRegion.resize());
|
||||
}
|
||||
|
||||
// ==================== 访问日志 ====================
|
||||
let currentPage = 1;
|
||||
|
||||
async function loadLogs(page=1) {
|
||||
currentPage = page;
|
||||
logsLoaded = true;
|
||||
const ip = document.getElementById('filterIp').value.trim();
|
||||
const blocked = document.getElementById('filterBlocked').value;
|
||||
let url = `/api/admin/ip/logs?page=${page}&per_page=50`;
|
||||
if (ip) url += `&ip=${encodeURIComponent(ip)}`;
|
||||
if (blocked) url += `&blocked=${blocked}`;
|
||||
|
||||
const data = await apiFetch(url);
|
||||
if (!data.success) { showToast('加载日志失败', 'error'); return; }
|
||||
|
||||
const tbody = document.getElementById('logsTableBody');
|
||||
tbody.innerHTML = data.logs.length === 0 ? '<tr><td colspan="6" class="py-8 text-center text-neutral-400">暂无日志</td></tr>' :
|
||||
data.logs.map(l => `
|
||||
<tr class="hover:bg-neutral-50 dark:hover:bg-neutral-800/50">
|
||||
<td class="py-2.5 pr-4 text-xs text-neutral-500 whitespace-nowrap">${formatTime(l.created_at)}</td>
|
||||
<td class="py-2.5 pr-4"><span class="font-mono text-xs text-neutral-800 dark:text-neutral-200">${l.ip}</span></td>
|
||||
<td class="py-2.5 pr-4 text-xs text-neutral-500">${l.country||''} ${l.region||''}</td>
|
||||
<td class="py-2.5 pr-4 text-xs text-neutral-600 dark:text-neutral-400 max-w-[200px] truncate" title="${l.path||''}">${l.method||''} ${l.path||''}</td>
|
||||
<td class="py-2.5 pr-4">${l.blocked ? `<span class="text-xs px-2 py-0.5 rounded-full bg-red-100 text-red-600">拦截 ${l.block_reason||''}</span>` : `<span class="text-xs px-2 py-0.5 rounded-full bg-green-100 text-green-600">放行</span>`}</td>
|
||||
<td class="py-2.5"><button onclick="openQuickBan('${l.ip}')" class="text-xs px-2 py-1 rounded-lg bg-red-50 text-red-500 hover:bg-red-100 transition-colors">封禁</button></td>
|
||||
</tr>`).join('');
|
||||
|
||||
document.getElementById('logsInfo').textContent = `共 ${data.total} 条,第 ${page}/${data.pages} 页`;
|
||||
const paginationDiv = document.getElementById('paginationBtns');
|
||||
paginationDiv.innerHTML = '';
|
||||
const totalPages = data.pages;
|
||||
const start = Math.max(1, page-2), end = Math.min(totalPages, page+2);
|
||||
if (page > 1) addPageBtn(paginationDiv, page-1, '‹');
|
||||
for (let p=start; p<=end; p++) addPageBtn(paginationDiv, p, p, p===page);
|
||||
if (page < totalPages) addPageBtn(paginationDiv, page+1, '›');
|
||||
}
|
||||
|
||||
function addPageBtn(container, page, label, active=false) {
|
||||
const btn = document.createElement('button');
|
||||
btn.textContent = label;
|
||||
btn.className = `px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${active ? 'bg-blue-500 text-white' : 'bg-neutral-100 dark:bg-neutral-800 text-neutral-700 dark:text-neutral-300 hover:bg-neutral-200 dark:hover:bg-neutral-700'}`;
|
||||
btn.onclick = () => loadLogs(page);
|
||||
container.appendChild(btn);
|
||||
}
|
||||
|
||||
// ==================== 封禁管理 ====================
|
||||
async function loadBans() {
|
||||
bansLoaded = true;
|
||||
const data = await apiFetch('/api/admin/ip/bans');
|
||||
if (!data.success) { showToast('加载封禁列表失败', 'error'); return; }
|
||||
const tbody = document.getElementById('bansTableBody');
|
||||
tbody.innerHTML = data.bans.length === 0 ? '<tr><td colspan="7" class="py-8 text-center text-neutral-400">暂无封禁规则</td></tr>' :
|
||||
data.bans.map(b => `
|
||||
<tr class="${b.is_active ? '' : 'opacity-40'} hover:bg-neutral-50 dark:hover:bg-neutral-800/50">
|
||||
<td class="py-2.5 pr-4"><span class="text-xs px-2 py-0.5 rounded-full font-medium ${b.ban_type==='ip'?'bg-red-100 text-red-600':b.ban_type==='cidr'?'bg-orange-100 text-orange-600':'bg-purple-100 text-purple-600'}">${b.ban_type.toUpperCase()}</span></td>
|
||||
<td class="py-2.5 pr-4 font-mono text-sm text-neutral-800 dark:text-neutral-200">${b.value}</td>
|
||||
<td class="py-2.5 pr-4 text-xs text-neutral-500 max-w-[160px] truncate" title="${b.reason||''}">${b.reason||'-'}</td>
|
||||
<td class="py-2.5 pr-4 text-xs text-neutral-500">${b.is_permanent ? '<span class="text-red-500 font-semibold">永久</span>' : formatTime(b.expires_at)}</td>
|
||||
<td class="py-2.5 pr-4 text-xs text-neutral-500">${formatTime(b.created_at)}</td>
|
||||
<td class="py-2.5 pr-4 text-xs text-neutral-500">${b.created_by||'-'}</td>
|
||||
<td class="py-2.5"><button onclick="unbanById(${b.id},'${b.value}')" class="text-xs px-2 py-1 rounded-lg bg-green-50 text-green-600 hover:bg-green-100 transition-colors">解封</button></td>
|
||||
</tr>`).join('');
|
||||
}
|
||||
|
||||
async function unbanById(id, value) {
|
||||
if (!confirm(`确认解封 ${value}?`)) return;
|
||||
const data = await apiFetch('/api/admin/ip/unban', { method: 'POST', body: JSON.stringify({id}) });
|
||||
showToast(data.message, data.success ? 'success' : 'error');
|
||||
if (data.success) { bansLoaded = false; loadBans(); loadStats(); }
|
||||
}
|
||||
|
||||
// ==================== 添加封禁 Modal ====================
|
||||
function openBanModal() { document.getElementById('banModal').classList.remove('hidden'); }
|
||||
function closeBanModal() { document.getElementById('banModal').classList.add('hidden'); }
|
||||
|
||||
async function submitBan() {
|
||||
const value = document.getElementById('banValue').value.trim();
|
||||
if (!value) { showToast('请填写封禁值', 'error'); return; }
|
||||
const data = await apiFetch('/api/admin/ip/ban', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
value,
|
||||
ban_type: document.getElementById('banType').value,
|
||||
duration: document.getElementById('banDuration').value || null,
|
||||
reason: document.getElementById('banReason').value
|
||||
})
|
||||
});
|
||||
showToast(data.message, data.success ? 'success' : 'error');
|
||||
if (data.success) { closeBanModal(); bansLoaded = false; if (currentTab === 'bans') loadBans(); loadStats(); }
|
||||
}
|
||||
|
||||
// ==================== 快速封禁 ====================
|
||||
function openQuickBan(ip) {
|
||||
document.getElementById('quickBanIp').value = ip;
|
||||
document.getElementById('quickBanIpDisplay').textContent = ip;
|
||||
document.getElementById('quickBanModal').classList.remove('hidden');
|
||||
}
|
||||
|
||||
async function submitQuickBan() {
|
||||
const ip = document.getElementById('quickBanIp').value;
|
||||
const data = await apiFetch('/api/admin/ip/ban_from_log', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
ip,
|
||||
duration: document.getElementById('quickBanDuration').value || null,
|
||||
reason: document.getElementById('quickBanReason').value
|
||||
})
|
||||
});
|
||||
showToast(data.message, data.success ? 'success' : 'error');
|
||||
if (data.success) {
|
||||
document.getElementById('quickBanModal').classList.add('hidden');
|
||||
if (currentTab === 'logs') loadLogs(currentPage);
|
||||
if (currentTab === 'bans') loadBans();
|
||||
loadStats();
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 频率限制配置 Modal ====================
|
||||
async function openConfigModal() {
|
||||
const data = await apiFetch('/api/admin/ip/config');
|
||||
if (data.success) {
|
||||
document.getElementById('cfgWindow').value = data.config.login_window_minutes;
|
||||
document.getElementById('cfgMax').value = data.config.login_max_attempts;
|
||||
document.getElementById('cfgChinaOnly').checked = data.config.enable_china_only === 'true';
|
||||
}
|
||||
document.getElementById('configModal').classList.remove('hidden');
|
||||
}
|
||||
|
||||
async function submitConfig() {
|
||||
const data = await apiFetch('/api/admin/ip/config', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
login_window_minutes: parseInt(document.getElementById('cfgWindow').value),
|
||||
login_max_attempts: parseInt(document.getElementById('cfgMax').value),
|
||||
enable_china_only: document.getElementById('cfgChinaOnly').checked
|
||||
})
|
||||
});
|
||||
showToast(data.message, data.success ? 'success' : 'error');
|
||||
if (data.success) document.getElementById('configModal').classList.add('hidden');
|
||||
}
|
||||
|
||||
// ==================== 清理日志 Modal ====================
|
||||
function openCleanModal() { document.getElementById('cleanModal').classList.remove('hidden'); }
|
||||
|
||||
async function submitClean() {
|
||||
const days = parseInt(document.getElementById('cleanDays').value);
|
||||
const data = await apiFetch('/api/admin/ip/clean_logs', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({days})
|
||||
});
|
||||
showToast(data.message, data.success ? 'success' : 'error');
|
||||
if (data.success) {
|
||||
document.getElementById('cleanModal').classList.add('hidden');
|
||||
loadLogs(1);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 初始化 ====================
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
loadStats();
|
||||
apiFetch('/api/admin/ip/bans').then(d => {
|
||||
if (d.success) document.getElementById('statBans').textContent = d.bans.filter(b=>b.is_active).length;
|
||||
});
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,191 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
|
||||
{% block title %}用户管理 - {{ brand_name }}{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
|
||||
<style>
|
||||
.modal-overlay { position: fixed; inset: 0; z-index: 50; display: flex; align-items: center; justify-content: center; padding: 1rem; opacity: 0; pointer-events: none; transition: opacity 0.24s ease; }
|
||||
.modal-overlay.open { opacity: 1; pointer-events: auto; }
|
||||
.modal-backdrop { position: absolute; inset: 0; background: rgba(0,0,0,0.6); backdrop-filter: blur(4px); }
|
||||
.modal-panel { position: relative; width: 100%; max-width: 28rem; opacity: 0; transform: scale(0.95) translateY(8px); transition: opacity 0.24s ease, transform 0.26s cubic-bezier(0.22,1,0.36,1); }
|
||||
.modal-overlay.open .modal-panel { opacity: 1; transform: scale(1) translateY(0); }
|
||||
.modal-panel-lg { max-width: 48rem; }
|
||||
.pagination { display: flex; gap: 0.25rem; justify-content: center; align-items: center; padding: 0; margin: 0; list-style: none; }
|
||||
.page-item { list-style: none; }
|
||||
.page-link { display: inline-flex; align-items: center; justify-content: center; min-width: 2.25rem; height: 2.25rem; padding: 0 0.75rem; border-radius: 0.5rem; font-size: 0.875rem; font-weight: 500; background: rgba(255,255,255,0.6); border: 1px solid rgba(0,0,0,0.08); color: #333; cursor: pointer; transition: all 0.2s; text-decoration: none; }
|
||||
.page-link:hover { background: rgba(0,0,0,0.05); }
|
||||
.dark .page-link { background: rgba(23,23,23,0.8); border-color: rgba(255,255,255,0.08); color: #e5e5e5; }
|
||||
.dark .page-link:hover { background: rgba(255,255,255,0.05); }
|
||||
.page-item.active .page-link { background: #111; color: #fff; border-color: #111; }
|
||||
.dark .page-item.active .page-link { background: #fff; color: #000; border-color: #fff; }
|
||||
.page-item.disabled .page-link { opacity: 0.4; cursor: not-allowed; pointer-events: none; }
|
||||
.loading-spinner { width: 40px; height: 40px; border: 3px solid rgba(0,0,0,0.1); border-top-color: currentColor; border-radius: 50%; animation: spin 0.8s linear infinite; }
|
||||
.dark .loading-spinner { border-color: rgba(255,255,255,0.15); border-top-color: currentColor; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
@media (prefers-reduced-motion: reduce) { .loading-spinner { animation: none !important; border: 3px solid currentColor; opacity: 0.3; } }
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="space-y-6">
|
||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 list-item-enter" style="animation-delay:0ms">
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2"><i class="bi bi-people"></i> 用户管理</h2>
|
||||
<button class="btn-primary px-5 py-2.5 rounded-full text-sm font-bold inline-flex items-center gap-2" onclick="showModal('createUserModal')"><i class="bi bi-person-plus"></i> 添加用户</button>
|
||||
</div>
|
||||
|
||||
<div class="glass rounded-2xl p-6 layer-2 list-item-enter" style="animation-delay:50ms">
|
||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
|
||||
<div>
|
||||
<h5 class="font-bold mb-2 flex items-center gap-2"><i class="bi bi-shield-check"></i> Session 状态</h5>
|
||||
<div class="flex gap-4 flex-wrap">
|
||||
<span class="text-green-600 dark:text-green-400 flex items-center gap-1"><i class="bi bi-check-circle-fill"></i> 有效: <strong id="sessionValid">-</strong></span>
|
||||
<span class="text-red-500 dark:text-red-400 flex items-center gap-1"><i class="bi bi-x-circle-fill"></i> 过期: <strong id="sessionInvalid">-</strong></span>
|
||||
<span class="text-neutral-500 dark:text-neutral-400 flex items-center gap-1"><i class="bi bi-question-circle-fill"></i> 未知: <strong id="sessionUnknown">-</strong></span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<button class="btn-outline text-sm px-4 py-2" onclick="batchCheckSession()"><i class="bi bi-search"></i> 批量检查</button>
|
||||
<button class="btn-outline text-sm px-4 py-2" onclick="showModal('batchRefreshModal')"><i class="bi bi-arrow-clockwise"></i> 批量刷新</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-4 list-item-enter" style="animation-delay:100ms">
|
||||
<div class="glass rounded-2xl p-5 layer-2 flex items-center justify-between">
|
||||
<div><p class="text-sm text-neutral-500 dark:text-neutral-400">总用户数</p><p class="text-2xl font-bold text-neutral-900 dark:text-white mt-1" id="totalUsers">-</p></div>
|
||||
<div class="w-10 h-10 rounded-xl bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center text-blue-600 dark:text-blue-400"><i class="bi bi-people text-lg"></i></div>
|
||||
</div>
|
||||
<div class="glass rounded-2xl p-5 layer-2 flex items-center justify-between">
|
||||
<div><p class="text-sm text-neutral-500 dark:text-neutral-400">总任务数</p><p class="text-2xl font-bold text-neutral-900 dark:text-white mt-1" id="totalTasks">-</p></div>
|
||||
<div class="w-10 h-10 rounded-xl bg-amber-100 dark:bg-amber-900/30 flex items-center justify-center text-amber-600 dark:text-amber-400"><i class="bi bi-list-task text-lg"></i></div>
|
||||
</div>
|
||||
<div class="glass rounded-2xl p-5 layer-2 flex items-center justify-between">
|
||||
<div><p class="text-sm text-neutral-500 dark:text-neutral-400">运行中</p><p class="text-2xl font-bold text-neutral-900 dark:text-white mt-1" id="runningTasks">-</p></div>
|
||||
<div class="w-10 h-10 rounded-xl bg-green-100 dark:bg-green-900/30 flex items-center justify-center text-green-600 dark:text-green-400"><i class="bi bi-play-circle text-lg"></i></div>
|
||||
</div>
|
||||
<div class="glass rounded-2xl p-5 layer-2 flex items-center justify-between">
|
||||
<div><p class="text-sm text-neutral-500 dark:text-neutral-400">成功任务</p><p class="text-2xl font-bold text-neutral-900 dark:text-white mt-1" id="successTasks">-</p></div>
|
||||
<div class="w-10 h-10 rounded-xl bg-purple-100 dark:bg-purple-900/30 flex items-center justify-center text-purple-600 dark:text-purple-400"><i class="bi bi-check-circle text-lg"></i></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="glass rounded-2xl p-6 layer-2 list-item-enter" style="animation-delay:150ms">
|
||||
<div class="flex justify-between items-center mb-4">
|
||||
<h5 class="font-bold flex items-center gap-2"><i class="bi bi-list"></i> 用户列表</h5>
|
||||
<button class="btn-outline text-sm px-4 py-2" onclick="loadUsers()"><i class="bi bi-arrow-clockwise"></i> 刷新</button>
|
||||
</div>
|
||||
<div id="loadingIndicator" class="text-center py-12">
|
||||
<div class="loading-spinner mx-auto mb-3 text-neutral-900 dark:text-white"></div>
|
||||
<p class="text-neutral-500 dark:text-neutral-400">加载中...</p>
|
||||
</div>
|
||||
<div id="emptyState" class="text-center py-12" style="display:none">
|
||||
<div class="w-16 h-16 mx-auto mb-4 rounded-2xl bg-neutral-100 dark:bg-neutral-800 flex items-center justify-center text-neutral-400"><i class="bi bi-inbox text-2xl"></i></div>
|
||||
<p class="text-neutral-500 dark:text-neutral-400">暂无用户</p>
|
||||
</div>
|
||||
<div id="usersTableContainer" class="overflow-x-auto" style="display:none">
|
||||
<table class="data-table">
|
||||
<thead><tr><th>ID</th><th>用户名</th><th>学号</th><th>Session</th><th>角色</th><th>状态</th><th>创建时间</th><th>操作</th></tr></thead>
|
||||
<tbody id="usersTableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<nav id="pagination" class="mt-4" style="display:none"><ul class="pagination" id="paginationList"></ul></nav>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="createUserModal" class="modal-overlay" onclick="if(event.target===this)hideModal('createUserModal')">
|
||||
<div class="modal-backdrop" onclick="hideModal('createUserModal')"></div>
|
||||
<div class="modal-panel">
|
||||
<div class="glass rounded-2xl p-6 layer-4">
|
||||
<div class="flex justify-between items-center mb-6">
|
||||
<h3 class="text-xl font-bold text-neutral-900 dark:text-white flex items-center gap-2"><i class="bi bi-person-plus"></i> 添加用户</h3>
|
||||
<button onclick="hideModal('createUserModal')" class="p-2 hover:bg-neutral-100 dark:hover:bg-neutral-800 rounded-full transition"><i class="bi bi-x-lg"></i></button>
|
||||
</div>
|
||||
<form id="createUserForm" class="space-y-4">
|
||||
<div><label class="input-label">用户名(学号)</label><input type="text" class="input-field" id="newUsername" required></div>
|
||||
<div><label class="input-label">密码</label><input type="password" class="input-field" id="newPassword" required></div>
|
||||
<div class="flex items-center gap-2"><input type="checkbox" id="newIsAdmin" class="w-4 h-4 rounded border-neutral-300 dark:border-neutral-600 accent-neutral-900 dark:accent-white"><label for="newIsAdmin" class="text-sm text-neutral-700 dark:text-neutral-300">设为管理员</label></div>
|
||||
</form>
|
||||
<div class="flex gap-3 mt-6">
|
||||
<button type="button" onclick="hideModal('createUserModal')" class="flex-1 py-3 rounded-xl bg-neutral-100 dark:bg-neutral-800 text-neutral-700 dark:text-neutral-300 font-medium hover:bg-neutral-200 dark:hover:bg-neutral-700 transition">取消</button>
|
||||
<button type="button" onclick="submitCreateUser()" class="flex-1 py-3 rounded-xl bg-neutral-900 dark:bg-white text-white dark:text-black font-bold hover:shadow-lg transition"><i class="bi bi-check-circle"></i> 创建</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="batchRefreshModal" class="modal-overlay" onclick="if(event.target===this)hideModal('batchRefreshModal')">
|
||||
<div class="modal-backdrop" onclick="hideModal('batchRefreshModal')"></div>
|
||||
<div class="modal-panel modal-panel-lg">
|
||||
<div class="glass rounded-2xl p-6 layer-4 max-h-[90vh] overflow-y-auto">
|
||||
<div class="flex justify-between items-center mb-6">
|
||||
<h3 class="text-xl font-bold text-neutral-900 dark:text-white flex items-center gap-2"><i class="bi bi-arrow-clockwise"></i> 批量刷新 Session</h3>
|
||||
<button onclick="hideModal('batchRefreshModal')" class="p-2 hover:bg-neutral-100 dark:hover:bg-neutral-800 rounded-full transition"><i class="bi bi-x-lg"></i></button>
|
||||
</div>
|
||||
<div class="glass rounded-xl p-4 mb-4 bg-blue-50 dark:bg-blue-900/20 text-blue-800 dark:text-blue-200 text-sm"><i class="bi bi-info-circle"></i> 请选择刷新选项。强制刷新会忽略当前有效的 session,重新登录所有账号。</div>
|
||||
<div class="flex items-center gap-2 mb-4"><input type="checkbox" id="batchForceRefresh" class="w-4 h-4 rounded border-neutral-300 dark:border-neutral-600 accent-neutral-900 dark:accent-white"><label for="batchForceRefresh" class="text-sm text-neutral-700 dark:text-neutral-300"><strong>强制刷新</strong>(即使 session 有效也重新登录)</label></div>
|
||||
<div class="mb-4"><label class="input-label">密码映射(JSON 格式,可选)</label><textarea class="input-field" id="batchPasswordMap" rows="5" placeholder="{"学号1": "密码1", "学号2": "密码2"}"></textarea><p class="text-xs text-neutral-500 mt-1">如果不提供密码映射,将只检查状态,无法刷新过期的 session</p></div>
|
||||
<div id="batchRefreshResult" style="display:none">
|
||||
<div class="border-t border-neutral-200 dark:border-neutral-700 pt-4 mb-4">
|
||||
<h6 class="font-bold mb-2">刷新结果</h6>
|
||||
<div class="flex gap-3 mb-3 flex-wrap">
|
||||
<span class="text-green-600 dark:text-green-400">未过期: <strong id="resultValid">0</strong></span>
|
||||
<span class="text-blue-600 dark:text-blue-400">刷新成功: <strong id="resultRefreshed">0</strong></span>
|
||||
<span class="text-red-500 dark:text-red-400">登录失败: <strong id="resultFailed">0</strong></span>
|
||||
</div>
|
||||
<div class="overflow-y-auto" style="max-height:300px">
|
||||
<table class="data-table"><thead><tr><th>用户</th><th>状态</th><th>消息</th></tr></thead><tbody id="batchRefreshDetails"></tbody></table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex gap-3">
|
||||
<button type="button" onclick="hideModal('batchRefreshModal')" class="flex-1 py-3 rounded-xl bg-neutral-100 dark:bg-neutral-800 text-neutral-700 dark:text-neutral-300 font-medium hover:bg-neutral-200 dark:hover:bg-neutral-700 transition">关闭</button>
|
||||
<button type="button" id="btnCheckOnly" onclick="batchCheckOnly()" class="flex-1 py-3 rounded-xl bg-neutral-900 dark:bg-white text-white dark:text-black font-bold hover:shadow-lg transition"><i class="bi bi-search"></i> 仅检查</button>
|
||||
<button type="button" id="btnDoBatchRefresh" onclick="doBatchRefresh()" class="flex-1 py-3 rounded-xl bg-neutral-900 dark:bg-white text-white dark:text-black font-bold hover:shadow-lg transition"><i class="bi bi-arrow-clockwise"></i> 开始刷新</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="singleRefreshModal" class="modal-overlay" onclick="if(event.target===this)hideModal('singleRefreshModal')">
|
||||
<div class="modal-backdrop" onclick="hideModal('singleRefreshModal')"></div>
|
||||
<div class="modal-panel">
|
||||
<div class="glass rounded-2xl p-6 layer-4">
|
||||
<div class="flex justify-between items-center mb-6">
|
||||
<h3 class="text-xl font-bold text-neutral-900 dark:text-white flex items-center gap-2"><i class="bi bi-arrow-clockwise"></i> 刷新用户 Session</h3>
|
||||
<button onclick="hideModal('singleRefreshModal')" class="p-2 hover:bg-neutral-100 dark:hover:bg-neutral-800 rounded-full transition"><i class="bi bi-x-lg"></i></button>
|
||||
</div>
|
||||
<div class="space-y-4">
|
||||
<div><label class="input-label">用户</label><input type="text" class="input-field" id="singleRefreshUsername" readonly><input type="hidden" id="singleRefreshUserId"></div>
|
||||
<div><label class="input-label">教务系统密码</label><input type="password" class="input-field" id="singleRefreshPassword" placeholder="请输入密码"></div>
|
||||
<div class="flex items-center gap-2"><input type="checkbox" id="singleForceRefresh" class="w-4 h-4 rounded border-neutral-300 dark:border-neutral-600 accent-neutral-900 dark:accent-white"><label for="singleForceRefresh" class="text-sm text-neutral-700 dark:text-neutral-300">强制刷新(即使 session 有效)</label></div>
|
||||
<div id="singleRefreshResult"></div>
|
||||
</div>
|
||||
<div class="flex gap-3 mt-6">
|
||||
<button type="button" onclick="hideModal('singleRefreshModal')" class="flex-1 py-3 rounded-xl bg-neutral-100 dark:bg-neutral-800 text-neutral-700 dark:text-neutral-300 font-medium hover:bg-neutral-200 dark:hover:bg-neutral-700 transition">取消</button>
|
||||
<button type="button" id="btnDoSingleRefresh" onclick="doSingleRefresh()" class="flex-1 py-3 rounded-xl bg-neutral-900 dark:bg-white text-white dark:text-black font-bold hover:shadow-lg transition"><i class="bi bi-arrow-clockwise"></i> 刷新</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script>
|
||||
let currentPage=1,allUsers=[];
|
||||
function showModal(id){const m=document.getElementById(id);m.classList.add('open');document.body.style.overflow='hidden';}
|
||||
function hideModal(id){const m=document.getElementById(id);m.classList.remove('open');document.body.style.overflow='';}
|
||||
async function loadStats(){try{const d=await apiRequest('/api/admin/stats');if(d.success){document.getElementById('totalUsers').textContent=d.stats.total_users;document.getElementById('totalTasks').textContent=d.stats.total_tasks;document.getElementById('runningTasks').textContent=d.stats.running_tasks;document.getElementById('successTasks').textContent=d.stats.success_tasks;if(d.stats.session_stats){document.getElementById('sessionValid').textContent=d.stats.session_stats.valid||0;document.getElementById('sessionInvalid').textContent=d.stats.session_stats.invalid||0;document.getElementById('sessionUnknown').textContent=d.stats.session_stats.unknown||0;}}}catch(e){console.error(e);}}
|
||||
async function loadUsers(page=1){currentPage=page;document.getElementById('loadingIndicator').style.display='block';document.getElementById('emptyState').style.display='none';document.getElementById('usersTableContainer').style.display='none';document.getElementById('pagination').style.display='none';try{const d=await apiRequest(`/api/admin/users/list?page=${page}&per_page=20`);document.getElementById('loadingIndicator').style.display='none';if(!d.success||!d.users||d.users.length===0){document.getElementById('emptyState').style.display='block';return;}allUsers=d.users;renderUsersTable(d.users);renderPagination(d.total,d.pages,page);document.getElementById('usersTableContainer').style.display='block';document.getElementById('pagination').style.display='block';}catch(e){document.getElementById('loadingIndicator').style.display='none';showToast('加载失败','error');}}
|
||||
function renderUsersTable(users){const tbody=document.getElementById('usersTableBody');tbody.innerHTML=users.map(u=>`<tr><td>${u.id}</td><td><strong>${escapeHtml(u.username)}</strong></td><td>${u.jwxt_username?escapeHtml(u.jwxt_username):'<span class="text-neutral-400">-</span>'}</td><td>${u.session_status==='valid'?'<span class="status-badge status-success" title="更新时间: '+(u.session_updated_at?formatTime(u.session_updated_at):'未知')+'">有效</span>':u.session_status==='invalid'?'<span class="status-badge status-danger">过期</span>':'<span class="status-badge status-pending">未知</span>'}</td><td>${u.is_admin?'<span class="status-badge status-danger">管理员</span>':'<span class="status-badge status-pending">普通用户</span>'}</td><td>${u.is_active?'<span class="status-badge status-success">激活</span>':'<span class="status-badge status-pending">禁用</span>'}</td><td class="text-sm text-neutral-500">${formatTime(u.created_at)}</td><td><button class="btn-outline text-xs px-2 py-1" onclick="viewUserTasks(${u.id})" title="查看任务"><i class="bi bi-list-task"></i></button><button class="btn-outline text-xs px-2 py-1 ml-1" onclick="refreshUserSession(${u.id},'${u.jwxt_username||u.username}')" title="刷新Session"><i class="bi bi-arrow-clockwise"></i></button></td></tr>`).join('');}
|
||||
function renderPagination(total,pages,current){const ul=document.getElementById('paginationList');let h='';h+=`<li class="page-item ${current===1?'disabled':''}"><a class="page-link" href="#" onclick="loadUsers(${current-1});return false;">上一页</a></li>`;for(let i=1;i<=pages;i++){if(i===1||i===pages||(i>=current-2&&i<=current+2)){h+=`<li class="page-item ${i===current?'active':''}"><a class="page-link" href="#" onclick="loadUsers(${i});return false;">${i}</a></li>`;}else if(i===current-3||i===current+3){h+=`<li class="page-item disabled"><span class="page-link">...</span></li>`;}}h+=`<li class="page-item ${current===pages?'disabled':''}"><a class="page-link" href="#" onclick="loadUsers(${current+1});return false;">下一页</a></li>`;ul.innerHTML=h;}
|
||||
async function submitCreateUser(){const u=document.getElementById('newUsername').value.trim(),p=document.getElementById('newPassword').value,a=document.getElementById('newIsAdmin').checked;if(!u||!p){showToast('请填写完整信息','warning');return;}try{const d=await apiRequest('/api/admin/users/create',{method:'POST',body:JSON.stringify({username:u,password:p,is_admin:a})});if(d.success){showToast('用户创建成功','success');hideModal('createUserModal');document.getElementById('createUserForm').reset();loadUsers();loadStats();}else{showToast(d.message||'创建失败','error');}}catch(e){showToast('网络错误','error');}}
|
||||
function viewUserTasks(id){window.location.href=`/tasks?user_id=${id}`;}
|
||||
document.addEventListener('DOMContentLoaded',()=>{loadStats();loadUsers();});
|
||||
async function batchCheckSession(){if(!confirm('开始批量检查所有用户的 Session 状态?'))return;showToast('正在检查 Session 状态...','info');try{const d=await apiRequest('/api/admin/session/batch_check',{method:'POST',body:JSON.stringify({})});if(d.success){const r=d.results;showToast(`检查完成:有效${r.valid}个,过期${r.invalid}个,未配置${r.no_account}个`,'success');loadStats();loadUsers();}else{showToast(d.message||'检查失败','error');}}catch(e){showToast('网络错误','error');}}
|
||||
async function batchCheckOnly(){const btn=document.getElementById('btnCheckOnly');btn.disabled=true;btn.innerHTML='<i class="bi bi-search"></i> 检查中...';try{const d=await apiRequest('/api/admin/session/batch_check',{method:'POST',body:JSON.stringify({})});if(d.success){const results=d.results;document.getElementById('resultValid').textContent=results.valid;document.getElementById('resultRefreshed').textContent=0;document.getElementById('resultFailed').textContent=results.invalid+results.no_jwxt;const tbody=document.getElementById('batchRefreshDetails');tbody.innerHTML=results.details.map(d=>`<tr><td>${escapeHtml(d.username)}</td><td>${d.status==='valid'?'<span class="status-badge status-success">有效</span>':d.status==='no_jwxt'?'<span class="status-badge status-pending">未配置</span>':'<span class="status-badge status-danger">过期</span>'}</td><td class="text-sm text-neutral-500">${escapeHtml(d.message)||'-'}</td></tr>`).join('');document.getElementById('batchRefreshResult').style.display='block';loadStats();}}catch(e){showToast('检查失败','error');}finally{btn.disabled=false;btn.innerHTML='<i class="bi bi-search"></i> 仅检查';}}
|
||||
async function doBatchRefresh(){const force=document.getElementById('batchForceRefresh').checked;const passwordMapText=document.getElementById('batchPasswordMap').value.trim();let passwordMap={};if(passwordMapText){try{passwordMap=JSON.parse(passwordMapText);}catch(e){showToast('密码映射 JSON 格式错误','warning');return;}}const btn=document.getElementById('btnDoBatchRefresh');btn.disabled=true;btn.innerHTML='<i class="bi bi-arrow-clockwise"></i> 刷新中...';try{const d=await apiRequest('/api/admin/session/batch_refresh',{method:'POST',body:JSON.stringify({force:force,password_map:passwordMap})});if(d.success){const results=d.results;document.getElementById('resultValid').textContent=results.valid;document.getElementById('resultRefreshed').textContent=results.refreshed;document.getElementById('resultFailed').textContent=results.failed+results.no_password;const tbody=document.getElementById('batchRefreshDetails');tbody.innerHTML=results.details.map(d=>`<tr><td>${escapeHtml(d.username)}</td><td>${d.status==='valid'?'<span class="status-badge status-success">有效</span>':d.status==='refreshed'?'<span class="status-badge status-info">已刷新</span>':d.status==='no_password'?'<span class="status-badge status-warning">无密码</span>':'<span class="status-badge status-danger">失败</span>'}</td><td class="text-sm text-neutral-500">${escapeHtml(d.message)||'-'}</td></tr>`).join('');document.getElementById('batchRefreshResult').style.display='block';showToast(`刷新完成:有效${results.valid}个,刷新${results.refreshed}个,失败${results.failed}个`,'success');loadStats();loadUsers();}else{showToast(d.message||'刷新失败','error');}}catch(e){showToast('网络错误','error');}finally{btn.disabled=false;btn.innerHTML='<i class="bi bi-arrow-clockwise"></i> 开始刷新';}}
|
||||
function refreshUserSession(userId,username){document.getElementById('singleRefreshUserId').value=userId;document.getElementById('singleRefreshUsername').value=username;document.getElementById('singleRefreshPassword').value='';document.getElementById('singleForceRefresh').checked=false;document.getElementById('singleRefreshResult').innerHTML='';showModal('singleRefreshModal');}
|
||||
async function doSingleRefresh(){const userId=document.getElementById('singleRefreshUserId').value;const password=document.getElementById('singleRefreshPassword').value.trim();const force=document.getElementById('singleForceRefresh').checked;if(!password){document.getElementById('singleRefreshResult').innerHTML='<div class="glass rounded-xl p-3 bg-amber-50 dark:bg-amber-900/20 text-amber-800 dark:text-amber-200 text-sm">请输入密码</div>';return;}const btn=document.getElementById('btnDoSingleRefresh');btn.disabled=true;btn.innerHTML='<i class="bi bi-arrow-clockwise"></i> 刷新中...';try{const d=await apiRequest(`/api/admin/users/${userId}/session/refresh`,{method:'POST',body:JSON.stringify({jwxt_password:password,force:force})});if(d.success){document.getElementById('singleRefreshResult').innerHTML=`<div class="glass rounded-xl p-3 bg-green-50 dark:bg-green-900/20 text-green-800 dark:text-green-200 text-sm">${d.message}</div>`;setTimeout(()=>{hideModal('singleRefreshModal');loadStats();loadUsers();},1500);}else{document.getElementById('singleRefreshResult').innerHTML=`<div class="glass rounded-xl p-3 bg-red-50 dark:bg-red-900/20 text-red-800 dark:text-red-200 text-sm">${d.message}</div>`;}}catch(e){document.getElementById('singleRefreshResult').innerHTML='<div class="glass rounded-xl p-3 bg-red-50 dark:bg-red-900/20 text-red-800 dark:text-red-200 text-sm">刷新失败</div>';}finally{btn.disabled=false;btn.innerHTML='<i class="bi bi-arrow-clockwise"></i> 刷新';}}
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,76 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
|
||||
{% block title %}API 调用示例 - {{ brand_name }}{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
.prose h1 { font-size: 1.5rem; font-weight: 800; margin-bottom: 0.5rem; }
|
||||
.prose h2 { font-size: 1.1rem; font-weight: 700; margin-top: 2rem; margin-bottom: 0.75rem; padding-bottom: 0.4rem; border-bottom: 1px solid rgba(0,0,0,0.08); }
|
||||
.dark .prose h2 { border-bottom-color: rgba(255,255,255,0.08); }
|
||||
.prose h3 { font-size: 0.95rem; font-weight: 600; margin-top: 1.25rem; margin-bottom: 0.5rem; }
|
||||
.prose p { margin-bottom: 0.75rem; line-height: 1.75; color: #4b5563; }
|
||||
.dark .prose p { color: #9ca3af; }
|
||||
.prose ul, .prose ol { padding-left: 1.5rem; margin-bottom: 0.75rem; }
|
||||
.prose li { margin-bottom: 0.35rem; line-height: 1.7; color: #4b5563; }
|
||||
.dark .prose li { color: #9ca3af; }
|
||||
.prose ul li { list-style-type: disc; }
|
||||
.prose ol li { list-style-type: decimal; }
|
||||
.prose strong { font-weight: 600; color: #111827; }
|
||||
.dark .prose strong { color: #f3f4f6; }
|
||||
.prose table { width: 100%; border-collapse: collapse; margin: 1rem 0; font-size: 0.875rem; }
|
||||
.prose th { background: #f3f4f6; font-weight: 600; padding: 0.6rem 0.8rem; text-align: left; border: 1px solid #e5e7eb; }
|
||||
.dark .prose th { background: #1f2937; border-color: #374151; }
|
||||
.prose td { padding: 0.6rem 0.8rem; border: 1px solid #e5e7eb; }
|
||||
.dark .prose td { border-color: #374151; }
|
||||
.prose hr { border: none; border-top: 1px solid #e5e7eb; margin: 1.5rem 0; }
|
||||
.dark .prose hr { border-top-color: #374151; }
|
||||
.prose code { background: #f3f4f6; padding: 0.1em 0.4em; border-radius: 4px; font-size: 0.85em; }
|
||||
.dark .prose code { background: #1f2937; }
|
||||
.prose blockquote { border-left: 3px solid #e5e7eb; padding-left: 1rem; color: #6b7280; margin: 1rem 0; }
|
||||
.dark .prose blockquote { border-color: #374151; color: #9ca3af; }
|
||||
/* 代码块样式 */
|
||||
.prose pre { background: #1e293b; color: #e2e8f0; border-radius: 0.75rem; padding: 1rem 1.25rem; overflow-x: auto; margin: 1rem 0; font-size: 0.8rem; line-height: 1.6; }
|
||||
.prose pre code { background: transparent; padding: 0; color: inherit; font-size: inherit; }
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="max-w-3xl mx-auto py-4">
|
||||
<!-- 返回 -->
|
||||
<div class="mb-6 list-item-enter" style="animation-delay:0ms">
|
||||
<a href="javascript:history.back()" class="inline-flex items-center gap-1.5 text-sm text-neutral-500 hover:text-neutral-800 dark:hover:text-neutral-200 transition-colors">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"/>
|
||||
</svg>
|
||||
返回
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div class="glass rounded-3xl p-6 md:p-10 layer-3 list-item-enter" style="animation-delay:50ms">
|
||||
<!-- 头部 -->
|
||||
<div class="flex items-start gap-4 mb-8 pb-6 border-b border-neutral-200 dark:border-neutral-800">
|
||||
<div class="w-12 h-12 rounded-2xl bg-black dark:bg-white flex items-center justify-center text-white dark:text-black flex-shrink-0">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<polyline points="16 3 21 3 21 8"/><line x1="4" y1="20" x2="21" y2="3"/>
|
||||
<polyline points="21 16 21 21 16 21"/><line x1="15" y1="15" x2="21" y2="21"/>
|
||||
<line x1="4" y1="4" x2="9" y2="9"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<h1 class="text-xl md:text-2xl font-bold text-neutral-900 dark:text-white">API 调用示例</h1>
|
||||
<p class="text-sm text-neutral-500 dark:text-neutral-400 mt-1">常见场景的 Python 示例代码</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 正文:由后端读取 docs/api_examples.md 渲染 -->
|
||||
<div class="prose text-sm md:text-base text-neutral-800 dark:text-neutral-200">
|
||||
{{ content | safe }}
|
||||
</div>
|
||||
|
||||
<!-- 底部链接 -->
|
||||
<div class="mt-8 pt-6 border-t border-neutral-200 dark:border-neutral-800 flex gap-4 text-sm text-neutral-500">
|
||||
<a href="{{ url_for('main.page_api_playground') }}" class="hover:text-black dark:hover:text-white transition-colors underline underline-offset-2">API 接口测试</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,156 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
|
||||
{% block title %}{% if block_type == 'foreign' %}访问受限 - {{ brand_name }}{% else %}IP 已被封禁 - {{ brand_name }}{% endif %}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="min-h-[80vh] flex items-center justify-center px-4 py-8">
|
||||
<div class="max-w-md w-full space-y-6">
|
||||
<!-- 主卡片 -->
|
||||
<div class="glass rounded-2xl p-8 layer-2 list-item-enter">
|
||||
<!-- 图标 -->
|
||||
<div class="w-20 h-20 mx-auto mb-6 rounded-full flex items-center justify-center
|
||||
{% if block_type == 'foreign' %}bg-amber-100 dark:bg-amber-900/30{% else %}bg-red-100 dark:bg-red-900/30{% endif %}">
|
||||
{% if block_type == 'foreign' %}
|
||||
<svg class="w-10 h-10 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
||||
d="M3.055 11H5a2 2 0 012 2v1a2 2 0 002 2 2 2 0 012 2v2.945M8 3.935V5.5A2.5 2.5 0 0010.5 8h.5a2 2 0 012 2 2 2 0 104 0 2 2 0 012-2h1.064M15 20.488V18a2 2 0 012-2h3.064M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
|
||||
</svg>
|
||||
{% else %}
|
||||
<svg class="w-10 h-10 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
||||
d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"></path>
|
||||
</svg>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<!-- 标题 -->
|
||||
<h1 class="text-2xl font-bold text-neutral-900 dark:text-white text-center mb-2">
|
||||
{% if block_type == 'foreign' %}访问受限{% else %}IP 已被封禁{% endif %}
|
||||
</h1>
|
||||
|
||||
<!-- 副标题 -->
|
||||
<p class="text-neutral-500 dark:text-neutral-400 text-sm text-center mb-6">
|
||||
{% if block_type == 'foreign' %}
|
||||
本服务仅对中国大陆用户开放
|
||||
{% else %}
|
||||
您的 IP 地址已被系统封禁
|
||||
{% endif %}
|
||||
</p>
|
||||
|
||||
<!-- 提示框 -->
|
||||
<div class="{% if block_type == 'foreign' %}bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800{% else %}bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800{% endif %}
|
||||
rounded-2xl p-4 mb-6">
|
||||
{% if block_type == 'foreign' %}
|
||||
<p class="text-amber-800 dark:text-amber-300 text-sm font-medium mb-3 flex items-center gap-2">
|
||||
<svg class="w-4 h-4 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"></path>
|
||||
</svg>
|
||||
检测到您正在使用 VPN 或境外网络
|
||||
</p>
|
||||
<ul class="text-amber-700 dark:text-amber-400 text-sm space-y-2">
|
||||
<li class="flex items-start gap-2">
|
||||
<span class="mt-0.5 w-1.5 h-1.5 rounded-full bg-amber-500 flex-shrink-0"></span>
|
||||
请关闭 VPN、代理等翻墙工具后重试
|
||||
</li>
|
||||
<li class="flex items-start gap-2">
|
||||
<span class="mt-0.5 w-1.5 h-1.5 rounded-full bg-amber-500 flex-shrink-0"></span>
|
||||
请关闭浏览器的代理设置
|
||||
</li>
|
||||
<li class="flex items-start gap-2">
|
||||
<span class="mt-0.5 w-1.5 h-1.5 rounded-full bg-amber-500 flex-shrink-0"></span>
|
||||
如使用手机,请检查是否开启了加速器
|
||||
</li>
|
||||
<li class="flex items-start gap-2">
|
||||
<span class="mt-0.5 w-1.5 h-1.5 rounded-full bg-amber-500 flex-shrink-0"></span>
|
||||
关闭后请刷新本页面重试
|
||||
</li>
|
||||
</ul>
|
||||
{% else %}
|
||||
<p class="text-red-800 dark:text-red-300 text-sm font-medium mb-2 flex items-center gap-2">
|
||||
<svg class="w-4 h-4 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"></path>
|
||||
</svg>
|
||||
封禁原因
|
||||
</p>
|
||||
<p class="text-red-700 dark:text-red-400 text-sm">{{ reason }}</p>
|
||||
|
||||
{% if expires_at %}
|
||||
<!-- 解封倒计时 -->
|
||||
<div class="mt-4 pt-4 border-t border-red-200 dark:border-red-800">
|
||||
<div class="flex items-center justify-between text-sm">
|
||||
<span class="text-red-600 dark:text-red-400 font-medium">预计解封时间</span>
|
||||
<span id="countdown" class="font-mono font-bold text-red-700 dark:text-red-300"></span>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<!-- IP信息 -->
|
||||
<div class="bg-neutral-50 dark:bg-neutral-800/50 rounded-xl p-3 mb-6">
|
||||
<p class="text-neutral-400 dark:text-neutral-500 text-xs mb-1">您的 IP 地址</p>
|
||||
<p class="text-neutral-700 dark:text-neutral-200 font-mono text-sm font-bold">{{ ip }}</p>
|
||||
</div>
|
||||
|
||||
<!-- 操作按钮 -->
|
||||
<button onclick="location.reload()"
|
||||
class="w-full py-3 px-6 bg-neutral-900 dark:bg-white text-white dark:text-neutral-900 rounded-2xl font-medium
|
||||
hover:shadow-lg transition-colors duration-200 mb-3">
|
||||
{% if block_type == 'foreign' %}关闭 VPN 后点此重试{% else %}刷新页面{% endif %}
|
||||
</button>
|
||||
|
||||
<p class="text-neutral-400 dark:text-neutral-500 text-xs text-center">
|
||||
如有疑问,请联系管理员
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- 底部说明 -->
|
||||
<p class="text-center text-neutral-400 dark:text-neutral-500 text-xs">
|
||||
{{ brand_name }} · 仅限中国大陆用户访问
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if block_type != 'foreign' and expires_at %}
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
var countdownEl = document.getElementById('countdown');
|
||||
if (!countdownEl) return;
|
||||
|
||||
// expires_at 是 Unix 时间戳(服务器UTC),Date.now() 也是 UTC 毫秒
|
||||
// 直接相减,无需任何时区转换
|
||||
var expiresAtMs = {{ expires_at }} * 1000;
|
||||
|
||||
function updateCountdown() {
|
||||
var nowMs = Date.now();
|
||||
var diff = expiresAtMs - nowMs;
|
||||
|
||||
if (diff <= 0) {
|
||||
countdownEl.textContent = '已解封,刷新页面';
|
||||
location.reload();
|
||||
return;
|
||||
}
|
||||
|
||||
var totalSeconds = Math.floor(diff / 1000);
|
||||
var hours = Math.floor(totalSeconds / 3600);
|
||||
var minutes = Math.floor((totalSeconds % 3600) / 60);
|
||||
var seconds = totalSeconds % 60;
|
||||
|
||||
if (hours > 24) {
|
||||
var days = Math.floor(hours / 24);
|
||||
countdownEl.textContent = days + '天 ' + (hours % 24) + '小时';
|
||||
} else if (hours > 0) {
|
||||
countdownEl.textContent = hours + '小时 ' + minutes + '分 ' + seconds + '秒';
|
||||
} else if (minutes > 0) {
|
||||
countdownEl.textContent = minutes + '分 ' + seconds + '秒';
|
||||
} else {
|
||||
countdownEl.textContent = seconds + '秒';
|
||||
}
|
||||
}
|
||||
|
||||
updateCountdown();
|
||||
setInterval(updateCountdown, 1000);
|
||||
});
|
||||
</script>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,217 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
|
||||
{% block title %}场地课表 - {{ brand_name }}{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
@keyframes fadeSlideIn {
|
||||
from { opacity: 0; transform: translateY(8px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.row-animate { animation: fadeSlideIn 0.3s ease both; }
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 list-item-enter" style="animation-delay: 0ms;">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<rect x="3" y="3" width="18" height="18" rx="2" ry="2"/>
|
||||
<line x1="3" y1="9" x2="21" y2="9"/>
|
||||
<line x1="9" y1="21" x2="9" y2="9"/>
|
||||
</svg>
|
||||
场地课表
|
||||
</h2>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">查询教室/场地使用安排</p>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-3 items-center">
|
||||
<input id="buildingInput" type="text" placeholder="楼号(可选)" class="px-4 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm w-28">
|
||||
<input id="roomInput" type="text" placeholder="教室编号(可选)" class="px-4 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm w-32">
|
||||
<button onclick="refresh()"
|
||||
class="px-4 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm font-medium hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors">
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="loadingIndicator" class="text-center py-12 list-item-enter" style="animation-delay: 100ms;">
|
||||
<div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
|
||||
<p class="text-gray-500 dark:text-gray-400">正在查询场地课表...</p>
|
||||
</div>
|
||||
|
||||
<div id="errorMessage" class="glass rounded-2xl p-6 mb-4 text-center hidden">
|
||||
<p id="errorText" class="text-red-500"></p>
|
||||
</div>
|
||||
|
||||
<!-- 图表区域 -->
|
||||
<div id="chartsRow" class="hidden grid grid-cols-1 gap-4 mb-4 list-item-enter" style="animation-delay: 120ms;">
|
||||
<div class="glass rounded-2xl p-4">
|
||||
<h4 class="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">教学楼课程分布</h4>
|
||||
<div id="buildingChart" style="height: 280px;"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="dataContainer" class="hidden list-item-enter" style="animation-delay: 150ms;">
|
||||
<div class="glass rounded-2xl overflow-hidden">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead>
|
||||
<tr class="border-b border-gray-200 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-800/50">
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">序号</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">校区</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">教学楼</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">教室</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">课程名称</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">教师</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">上课时间</th>
|
||||
<th class="text-center py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">周次</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="tableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<div id="emptyState" class="glass rounded-2xl p-12 text-center hidden">
|
||||
<p class="text-gray-500 dark:text-gray-400 text-lg">暂无场地课表</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script src="{{ url_for('static', filename='echarts.min.js') }}"></script>
|
||||
<script>
|
||||
// ─── Session 自动刷新 ────────────────────────────────────────────
|
||||
async function initSession() {
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/ping');
|
||||
const data = await res.json();
|
||||
if (data.refreshed) console.log('[Session] 已刷新');
|
||||
return true;
|
||||
} catch (e) { console.warn('[Session] ping 失败:', e); return false; }
|
||||
}
|
||||
function isDarkMode() { return document.documentElement.classList.contains('dark'); }
|
||||
|
||||
// ─── ECharts 图表 ─────────────────────────────────────────────────
|
||||
let buildingChart = null;
|
||||
|
||||
function renderBuildingChart(items) {
|
||||
const container = document.getElementById('chartsRow');
|
||||
if (!container || !items.length) return;
|
||||
container.classList.remove('hidden');
|
||||
|
||||
const dom = document.getElementById('buildingChart');
|
||||
if (!dom) return;
|
||||
|
||||
// 按教学楼统计
|
||||
const buildingMap = {};
|
||||
items.forEach(item => {
|
||||
const b = item.jxlmc || item.JXLMC || item['教学楼'] || '未知';
|
||||
buildingMap[b] = (buildingMap[b] || 0) + 1;
|
||||
});
|
||||
const sorted = Object.entries(buildingMap).sort((a, b) => b[1] - a[1]);
|
||||
|
||||
const dark = isDarkMode();
|
||||
if (!buildingChart) buildingChart = echarts.init(dom);
|
||||
buildingChart.setOption({
|
||||
tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
|
||||
grid: { left: '3%', right: '10%', top: 10, bottom: 30, containLabel: true },
|
||||
xAxis: {
|
||||
type: 'category', data: sorted.map(s => s[0]),
|
||||
axisLabel: { color: dark ? '#9ca3af' : '#6b7280', fontSize: 11, rotate: sorted.length > 6 ? 30 : 0 }
|
||||
},
|
||||
yAxis: {
|
||||
type: 'value', name: '课程数',
|
||||
nameTextStyle: { color: dark ? '#9ca3af' : '#6b7280' },
|
||||
axisLabel: { color: dark ? '#9ca3af' : '#6b7280' }
|
||||
},
|
||||
series: [{
|
||||
type: 'bar', data: sorted.map(s => s[1]),
|
||||
itemStyle: { color: dark ? '#818cf8' : '#4f46e5', borderRadius: [6, 6, 0, 0] },
|
||||
emphasis: { itemStyle: { color: dark ? '#a5b4fc' : '#6366f1' } }
|
||||
}]
|
||||
}, { notMerge: true });
|
||||
buildingChart.resize();
|
||||
}
|
||||
|
||||
function setupDarkObserver() {
|
||||
const observer = new MutationObserver(() => {
|
||||
if (buildingChart) { buildingChart.dispose(); buildingChart = null; }
|
||||
const items = window._lastItems;
|
||||
if (items && items.length) renderBuildingChart(items);
|
||||
});
|
||||
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
|
||||
}
|
||||
|
||||
window.addEventListener('resize', () => {
|
||||
if (buildingChart) buildingChart.resize();
|
||||
});
|
||||
|
||||
// ─── 数据加载 ─────────────────────────────────────────────────────
|
||||
async function refresh() {
|
||||
document.getElementById('loadingIndicator').classList.remove('hidden');
|
||||
document.getElementById('errorMessage').classList.add('hidden');
|
||||
document.getElementById('dataContainer').classList.add('hidden');
|
||||
const chartsRow = document.getElementById('chartsRow');
|
||||
if (chartsRow) chartsRow.classList.add('hidden');
|
||||
|
||||
const lh = document.getElementById('buildingInput').value;
|
||||
const cdbh = document.getElementById('roomInput').value;
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams({ page_size: 200 });
|
||||
if (lh) params.set('lh', lh);
|
||||
if (cdbh) params.set('cdbh', cdbh);
|
||||
const res = await fetch('/api/jwxt/classroom-schedule?' + params);
|
||||
const data = await res.json();
|
||||
document.getElementById('loadingIndicator').classList.add('hidden');
|
||||
|
||||
if (!data.success) {
|
||||
document.getElementById('errorText').textContent = data.message || '查询失败';
|
||||
document.getElementById('errorMessage').classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
|
||||
const items = data.items || [];
|
||||
window._lastItems = items;
|
||||
if (!items.length) {
|
||||
document.getElementById('dataContainer').classList.remove('hidden');
|
||||
document.getElementById('emptyState').classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
renderTable(items);
|
||||
document.getElementById('dataContainer').classList.remove('hidden');
|
||||
renderBuildingChart(items);
|
||||
} catch (e) {
|
||||
document.getElementById('loadingIndicator').classList.add('hidden');
|
||||
document.getElementById('errorText').textContent = '网络错误: ' + e.message;
|
||||
document.getElementById('errorMessage').classList.remove('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
function renderTable(items) {
|
||||
const tbody = document.getElementById('tableBody');
|
||||
tbody.innerHTML = items.map((item, idx) => `
|
||||
<tr class="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50/50 dark:hover:bg-gray-800/30 transition-colors row-animate" style="animation-delay:${idx * 40}ms;">
|
||||
<td class="py-3 px-4 text-gray-400 dark:text-gray-500">${idx + 1}</td>
|
||||
<td class="py-3 px-4">${item.xqhmc || item.XQHMC || item['校区'] || '--'}</td>
|
||||
<td class="py-3 px-4">${item.jxlmc || item.JXLMC || item['教学楼'] || '--'}</td>
|
||||
<td class="py-3 px-4 font-medium">${item.cdmc || item.CDMC || item['教室'] || '--'}</td>
|
||||
<td class="py-3 px-4">${item.kcmc || item.KCMC || item['课程名称'] || '--'}</td>
|
||||
<td class="py-3 px-4">${item.jsmc || item.JSMC || item.jsxm || item['教师'] || '--'}</td>
|
||||
<td class="py-3 px-4 text-gray-500 dark:text-gray-400">${item.sksj || item.SKSJ || item['上课时间'] || '--'}</td>
|
||||
<td class="py-3 px-4 text-center text-gray-500 dark:text-gray-400">${item.zcsm || item.ZCSM || item['周次'] || '--'}</td>
|
||||
</tr>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
// ─── 初始化 ───────────────────────────────────────────────────────
|
||||
initSession().then(() => {
|
||||
setupDarkObserver();
|
||||
refresh();
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,638 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
|
||||
{% block title %}空闲教室查询 - {{ brand_name }}{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
@keyframes fadeSlideIn {
|
||||
from { opacity: 0; transform: translateY(8px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.row-animate { animation: fadeSlideIn 0.3s ease both; }
|
||||
select.filter-select {
|
||||
appearance: none;
|
||||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' fill='none' stroke='%23666' stroke-width='2' stroke-linecap='round'%3E%3Cpath d='M2 4l4 4 4-4'/%3E%3C/svg%3E");
|
||||
background-repeat: no-repeat;
|
||||
background-position: right 10px center;
|
||||
padding-right: 28px;
|
||||
}
|
||||
.dark select.filter-select {
|
||||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' fill='none' stroke='%23999' stroke-width='2' stroke-linecap='round'%3E%3Cpath d='M2 4l4 4 4-4'/%3E%3C/svg%3E");
|
||||
}
|
||||
.jyfs-radio { transition: all 0.2s; user-select: none; }
|
||||
.jyfs-radio:not(.active) { background: transparent; color: inherit; }
|
||||
.jyfs-radio.active { background: #000; color: #fff; }
|
||||
.dark .jyfs-radio.active { background: #fff; color: #000; }
|
||||
.time-chip {
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
min-width: 34px; height: 30px; padding: 0 8px;
|
||||
border-radius: 6px; border: 1px solid #d1d5db;
|
||||
font-size: 12px; cursor: pointer; user-select: none;
|
||||
transition: all 0.15s; background: transparent;
|
||||
}
|
||||
.dark .time-chip { border-color: #374151; }
|
||||
.time-chip:hover { border-color: #6b7280; }
|
||||
.time-chip.selected { background: #000; color: #fff; border-color: #000; }
|
||||
.dark .time-chip.selected { background: #fff; color: #000; border-color: #fff; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.row-animate { animation: none !important; opacity: 1 !important; }
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
<!-- Header -->
|
||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 list-item-enter" style="animation-delay: 0ms;">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<rect x="3" y="3" width="18" height="18" rx="2" ry="2"/>
|
||||
<line x1="3" y1="9" x2="21" y2="9"/>
|
||||
<line x1="9" y1="21" x2="9" y2="9"/>
|
||||
</svg>
|
||||
空闲教室查询
|
||||
</h2>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">查询当前可用的空闲教室</p>
|
||||
</div>
|
||||
<button onclick="doSearch()"
|
||||
class="px-4 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm font-medium hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<polyline points="23 4 23 10 17 10"/>
|
||||
<path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>
|
||||
</svg>
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Filter Bar -->
|
||||
<div class="glass rounded-2xl p-4 mb-4 list-item-enter max-w-5xl mx-auto" style="animation-delay: 50ms;">
|
||||
<div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3 items-end">
|
||||
<div class="w-full">
|
||||
<label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">校区</label>
|
||||
<select id="filter_xqh_id" class="filter-select w-full rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 px-3 py-2 text-sm">
|
||||
<option value="">加载中...</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="w-full">
|
||||
<label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">楼号</label>
|
||||
<select id="filter_lh" class="filter-select w-full rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 px-3 py-2 text-sm">
|
||||
<option value="">加载中...</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="w-full">
|
||||
<label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">场地类别</label>
|
||||
<select id="filter_cdlb_id" class="filter-select w-full rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 px-3 py-2 text-sm">
|
||||
<option value="">加载中...</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="w-full">
|
||||
<label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">二级类别</label>
|
||||
<select id="filter_cdejlb_id" class="filter-select w-full rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 px-3 py-2 text-sm">
|
||||
<option value="">加载中...</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="w-full">
|
||||
<label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">座位 ≥</label>
|
||||
<input id="filter_qszws" type="number" min="0" placeholder="不限"
|
||||
class="w-full rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 px-3 py-2 text-sm">
|
||||
</div>
|
||||
<div class="w-full">
|
||||
<label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">座位 ≤</label>
|
||||
<input id="filter_jszws" type="number" min="0" placeholder="不限"
|
||||
class="w-full rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 px-3 py-2 text-sm">
|
||||
</div>
|
||||
<div class="w-full">
|
||||
<label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">教室名称</label>
|
||||
<input id="filter_cdmc" type="text" placeholder="模糊搜索"
|
||||
class="w-full rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 px-3 py-2 text-sm">
|
||||
</div>
|
||||
<button id="searchBtn" onclick="doSearch()"
|
||||
class="px-5 py-2 rounded-lg bg-black dark:bg-white text-white dark:text-black text-sm font-medium hover:opacity-85 transition-opacity whitespace-nowrap flex-shrink-0"
|
||||
disabled>
|
||||
查询
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- jyfs 模式选择 -->
|
||||
<div class="glass rounded-2xl p-4 mb-4 list-item-enter" style="animation-delay: 80ms;">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-xs font-medium text-gray-500 dark:text-gray-400 mr-2">查询模式</span>
|
||||
<div class="flex rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
|
||||
<label class="jyfs-radio px-4 py-1.5 text-sm cursor-pointer border-r border-gray-200 dark:border-gray-700 bg-black dark:bg-white text-white dark:text-black" data-jyfs="0">
|
||||
<input type="radio" name="jyfs" value="0" class="hidden"> 按周次
|
||||
</label>
|
||||
<label class="jyfs-radio px-4 py-1.5 text-sm cursor-pointer border-r border-gray-200 dark:border-gray-700" data-jyfs="1">
|
||||
<input type="radio" name="jyfs" value="1" class="hidden" checked> 连续
|
||||
</label>
|
||||
<label class="jyfs-radio px-4 py-1.5 text-sm cursor-pointer" data-jyfs="2">
|
||||
<input type="radio" name="jyfs" value="2" class="hidden"> 按节次
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 时间选择器区域 -->
|
||||
<div id="timeSelectors" class="hidden">
|
||||
<!-- jyfs=0: 周次 + 星期 + 节次 -->
|
||||
<div id="timeSection_0" class="hidden">
|
||||
<div class="glass rounded-2xl p-4 mb-4">
|
||||
<div class="text-xs font-medium text-gray-500 dark:text-gray-400 mb-2">周次</div>
|
||||
<div class="flex gap-1 flex-wrap mb-1">
|
||||
<button class="week-select-all text-xs text-blue-500 hover:text-blue-600 px-2 py-0.5" data-select="all">全选</button>
|
||||
<button class="week-select-all text-xs text-gray-400 hover:text-gray-500 px-2 py-0.5" data-select="none">清空</button>
|
||||
</div>
|
||||
<div id="weekCheckboxes" class="flex flex-wrap gap-1.5"></div>
|
||||
</div>
|
||||
<div class="glass rounded-2xl p-4 mb-4">
|
||||
<div class="text-xs font-medium text-gray-500 dark:text-gray-400 mb-2">星期</div>
|
||||
<div class="flex gap-1 flex-wrap mb-1">
|
||||
<button class="day-select-all text-xs text-blue-500 hover:text-blue-600 px-2 py-0.5" data-select="all">全选</button>
|
||||
<button class="day-select-all text-xs text-gray-400 hover:text-gray-500 px-2 py-0.5" data-select="none">清空</button>
|
||||
</div>
|
||||
<div id="dayCheckboxes" class="flex flex-wrap gap-1.5"></div>
|
||||
</div>
|
||||
<div class="glass rounded-2xl p-4 mb-4">
|
||||
<div class="text-xs font-medium text-gray-500 dark:text-gray-400 mb-2">节次</div>
|
||||
<div class="flex gap-1 flex-wrap mb-1">
|
||||
<button class="period-select-all text-xs text-blue-500 hover:text-blue-600 px-2 py-0.5" data-select="all">全选</button>
|
||||
<button class="period-select-all text-xs text-gray-400 hover:text-gray-500 px-2 py-0.5" data-select="none">清空</button>
|
||||
</div>
|
||||
<div id="periodCheckboxes_0" class="flex flex-wrap gap-1.5"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- jyfs=2: 仅节次 -->
|
||||
<div id="timeSection_2" class="hidden">
|
||||
<div class="glass rounded-2xl p-4 mb-4">
|
||||
<div class="text-xs font-medium text-gray-500 dark:text-gray-400 mb-2">节次</div>
|
||||
<div class="flex gap-1 flex-wrap mb-1">
|
||||
<button class="period-select-all2 text-xs text-blue-500 hover:text-blue-600 px-2 py-0.5" data-select="all">全选</button>
|
||||
<button class="period-select-all2 text-xs text-gray-400 hover:text-gray-500 px-2 py-0.5" data-select="none">清空</button>
|
||||
</div>
|
||||
<div id="periodCheckboxes_2" class="flex flex-wrap gap-1.5"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Loading -->
|
||||
<div id="loadingIndicator" class="text-center py-12 hidden">
|
||||
<div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
|
||||
<p class="text-gray-500 dark:text-gray-400">正在查询空闲教室...</p>
|
||||
</div>
|
||||
|
||||
<!-- 图表区 -->
|
||||
<div id="chartsRow" class="mb-6 hidden">
|
||||
<div class="glass rounded-2xl p-4">
|
||||
<h3 class="text-sm font-semibold text-gray-600 dark:text-gray-400 mb-3">各楼栋空闲教室数量</h3>
|
||||
<div id="buildingChart" class="h-72"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Error -->
|
||||
<div id="errorMessage" class="glass rounded-2xl p-6 mb-4 text-center hidden">
|
||||
<p id="errorText" class="text-red-500"></p>
|
||||
</div>
|
||||
|
||||
<!-- Data Container -->
|
||||
<div id="dataContainer" class="hidden list-item-enter" style="animation-delay: 150ms;">
|
||||
<div class="glass rounded-2xl overflow-hidden">
|
||||
<div id="resultSummary" class="px-5 py-3 text-sm text-gray-500 dark:text-gray-400 border-b border-gray-200 dark:border-gray-700 hidden"></div>
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead>
|
||||
<tr class="border-b border-gray-200 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-800/50">
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">序号</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">校区</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">教学楼</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">教室名称</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">编号</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">类型</th>
|
||||
<th class="text-center py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">座位</th>
|
||||
<th class="text-center py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">楼层</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">学院</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="tableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Empty State -->
|
||||
<div id="emptyState" class="glass rounded-2xl p-12 text-center hidden">
|
||||
<p class="text-gray-500 dark:text-gray-400 text-lg">暂无空闲教室</p>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script src="{{ url_for('static', filename='echarts.min.js') }}"></script>
|
||||
<script>
|
||||
let paramsReady = false;
|
||||
let defaultXnm = '', defaultXqm = '', defaultXqhId = '1';
|
||||
let buildingChart = null;
|
||||
|
||||
// ── 深色模式 ──
|
||||
function isDarkMode() { return document.documentElement.classList.contains('dark'); }
|
||||
|
||||
// ── Session 健康检查 ──
|
||||
async function initSession() {
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/ping');
|
||||
const data = await res.json();
|
||||
if (!data.success) { console.warn('Session ping 失败:', data.message); return false; }
|
||||
if (data.refreshed) console.log('🔄 Session 已自动刷新');
|
||||
return true;
|
||||
} catch (e) { console.error('Session ping 异常:', e); return false; }
|
||||
}
|
||||
|
||||
// ── jyfs mode management ──
|
||||
let currentJyfs = '1'; // 默认连续
|
||||
let periodData = null; // 节次数据缓存
|
||||
|
||||
function setJyfs(mode) {
|
||||
currentJyfs = mode;
|
||||
// 更新 radio 样式
|
||||
document.querySelectorAll('.jyfs-radio').forEach(el => {
|
||||
el.classList.toggle('active', el.dataset.jyfs === mode);
|
||||
const inp = el.querySelector('input');
|
||||
if (inp) inp.checked = (el.dataset.jyfs === mode);
|
||||
});
|
||||
// 显示/隐藏时间选择器
|
||||
const ts = document.getElementById('timeSelectors');
|
||||
document.querySelectorAll('[id^="timeSection_"]').forEach(s => s.classList.add('hidden'));
|
||||
if (mode === '0') {
|
||||
ts.classList.remove('hidden');
|
||||
document.getElementById('timeSection_0').classList.remove('hidden');
|
||||
} else if (mode === '2') {
|
||||
ts.classList.remove('hidden');
|
||||
document.getElementById('timeSection_2').classList.remove('hidden');
|
||||
} else {
|
||||
ts.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
// ── 节次/周次 chip 渲染 ──
|
||||
function renderPeriodChips(periods, containerId, defaultSelected) {
|
||||
const container = document.getElementById(containerId);
|
||||
if (!container) return;
|
||||
// 按时段分组
|
||||
let html = '';
|
||||
let lastRsd = '';
|
||||
periods.forEach(p => {
|
||||
const jcmc = p.JCMC; // 1-11
|
||||
const sjd = p.SJD;
|
||||
const rsd = p.RSDMC; // 上午/下午/晚上
|
||||
if (rsd !== lastRsd) {
|
||||
if (lastRsd) html += '<div class="w-full h-0"></div>'; // break line
|
||||
html += `<span class="text-[10px] text-gray-400 dark:text-gray-500 mr-1 self-center">${rsd}</span>`;
|
||||
lastRsd = rsd;
|
||||
}
|
||||
const sel = defaultSelected ? ' selected' : '';
|
||||
html += `<span class="time-chip${sel}" data-value="${jcmc}" data-label="${jcmc}节 ${sjd}" title="${jcmc}节 ${sjd}">${jcmc}</span>`;
|
||||
});
|
||||
container.innerHTML = html;
|
||||
// 绑定点击
|
||||
container.querySelectorAll('.time-chip').forEach(chip => {
|
||||
chip.addEventListener('click', () => chip.classList.toggle('selected'));
|
||||
});
|
||||
}
|
||||
|
||||
function renderWeekChips(weeks, containerId, defaultSelected) {
|
||||
const container = document.getElementById(containerId);
|
||||
if (!container) return;
|
||||
container.innerHTML = weeks.map(w => {
|
||||
const n = w.dxqzc;
|
||||
const sel = defaultSelected ? ' selected' : '';
|
||||
return `<span class="time-chip${sel}" data-value="${n}" title="第${n}周">${n}</span>`;
|
||||
}).join('');
|
||||
container.querySelectorAll('.time-chip').forEach(chip => {
|
||||
chip.addEventListener('click', () => chip.classList.toggle('selected'));
|
||||
});
|
||||
}
|
||||
|
||||
function renderDayChips(containerId, defaultSelected) {
|
||||
const container = document.getElementById(containerId);
|
||||
if (!container) return;
|
||||
const days = [
|
||||
{v: 1, l: '一'}, {v: 2, l: '二'}, {v: 3, l: '三'},
|
||||
{v: 4, l: '四'}, {v: 5, l: '五'}, {v: 6, l: '六'}, {v: 7, l: '日'}
|
||||
];
|
||||
const defSet = defaultSelected ? new Set([1,2,3,4,5]) : new Set();
|
||||
container.innerHTML = days.map(d => {
|
||||
const sel = defSet.has(d.v) ? ' selected' : '';
|
||||
return `<span class="time-chip${sel}" data-value="${d.v}" title="星期${d.l}">${d.l}</span>`;
|
||||
}).join('');
|
||||
container.querySelectorAll('.time-chip').forEach(chip => {
|
||||
chip.addEventListener('click', () => chip.classList.toggle('selected'));
|
||||
});
|
||||
}
|
||||
|
||||
// ── 位掩码计算 ──
|
||||
function calcBitmask(containerId) {
|
||||
const container = document.getElementById(containerId);
|
||||
if (!container) return '';
|
||||
let mask = 0;
|
||||
container.querySelectorAll('.time-chip.selected').forEach(chip => {
|
||||
mask += Math.pow(2, parseInt(chip.dataset.value) - 1);
|
||||
});
|
||||
return mask > 0 ? String(mask) : '';
|
||||
}
|
||||
|
||||
function calcCommaList(containerId) {
|
||||
const container = document.getElementById(containerId);
|
||||
if (!container) return '';
|
||||
const vals = [];
|
||||
container.querySelectorAll('.time-chip.selected').forEach(chip => {
|
||||
vals.push(chip.dataset.value);
|
||||
});
|
||||
return vals.join(',');
|
||||
}
|
||||
|
||||
// ── Init: load dropdowns from教务 page ──
|
||||
async function loadParams() {
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/classroom/params');
|
||||
const data = await res.json();
|
||||
if (!data.success || !data.selects) {
|
||||
throw new Error(data.message || '获取下拉框参数失败');
|
||||
}
|
||||
fillSelect('filter_xqh_id', data.selects.xqh_id, true);
|
||||
fillSelect('filter_lh', data.selects.lh, true);
|
||||
fillSelect('filter_cdlb_id', data.selects.cdlb_id, true);
|
||||
fillSelect('filter_cdejlb_id', data.selects.cdejlb_id, true);
|
||||
defaultXnm = data.default_xnm || '';
|
||||
defaultXqm = data.default_xqm || '';
|
||||
// 获取默认校区ID用于节次查询
|
||||
const xqhSel = data.selects.xqh_id;
|
||||
if (xqhSel && xqhSel.default) defaultXqhId = xqhSel.default;
|
||||
|
||||
// 并行加载周次和节次数据
|
||||
await Promise.all([loadWeekData(), loadPeriodData()]);
|
||||
paramsReady = true;
|
||||
document.getElementById('searchBtn').disabled = false;
|
||||
doSearch();
|
||||
} catch (e) {
|
||||
document.getElementById('errorText').textContent = '加载参数失败: ' + e.message;
|
||||
document.getElementById('errorMessage').classList.remove('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
async function loadWeekData() {
|
||||
try {
|
||||
const res = await fetch(`/api/jwxt/classroom-filter-options?xnm=${defaultXnm}&xqm=${defaultXqm}`);
|
||||
const data = await res.json();
|
||||
if (data.success && data.items && data.items.nxqzcList) {
|
||||
const weeks = data.items.nxqzcList;
|
||||
const dqzcxq = data.items.dqzcxq || {};
|
||||
const dqzc = parseInt(dqzcxq.DQZC) || 1;
|
||||
// 默认选中当前周
|
||||
const isDefault = true;
|
||||
renderWeekChips(weeks, 'weekCheckboxes', isDefault);
|
||||
// 全选/清空按钮
|
||||
bindSelectAll('weekCheckboxes', '.week-select-all');
|
||||
}
|
||||
} catch (e) { console.warn('加载周次数据失败:', e); }
|
||||
}
|
||||
|
||||
async function loadPeriodData() {
|
||||
try {
|
||||
const res = await fetch(`/api/jwxt/classroom-periods?xnm=${defaultXnm}&xqm=${defaultXqm}&xqh_id=${defaultXqhId}`);
|
||||
const data = await res.json();
|
||||
if (data.success && data.jcList) {
|
||||
periodData = data.jcList;
|
||||
renderPeriodChips(periodData, 'periodCheckboxes_0', true);
|
||||
renderPeriodChips(periodData, 'periodCheckboxes_2', true);
|
||||
bindSelectAll('periodCheckboxes_0', '.period-select-all');
|
||||
bindSelectAll('periodCheckboxes_2', '.period-select-all2');
|
||||
renderDayChips('dayCheckboxes', true);
|
||||
bindSelectAll('dayCheckboxes', '.day-select-all');
|
||||
}
|
||||
} catch (e) { console.warn('加载节次数据失败:', e); }
|
||||
}
|
||||
|
||||
function bindSelectAll(containerId, btnSelector) {
|
||||
document.querySelectorAll(btnSelector).forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
const action = btn.dataset.select;
|
||||
const container = document.getElementById(containerId);
|
||||
if (!container) return;
|
||||
container.querySelectorAll('.time-chip').forEach(chip => {
|
||||
if (action === 'all') chip.classList.add('selected');
|
||||
else chip.classList.remove('selected');
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function fillSelect(id, selectData, addAll) {
|
||||
const el = document.getElementById(id);
|
||||
if (!selectData || !selectData.options || !selectData.options.length) {
|
||||
el.innerHTML = '<option value="">--</option>';
|
||||
return;
|
||||
}
|
||||
const defaultVal = selectData.default || '';
|
||||
let html = '';
|
||||
if (addAll) html += '<option value="">全部</option>';
|
||||
html += selectData.options.map(o =>
|
||||
`<option value="${escAttr(o.value)}" ${o.value === defaultVal ? 'selected' : ''}>${escHtml(o.label)}</option>`
|
||||
).join('');
|
||||
el.innerHTML = html;
|
||||
}
|
||||
|
||||
// ── jyfs radio event binding ──
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
document.querySelectorAll('.jyfs-radio').forEach(el => {
|
||||
el.addEventListener('click', () => setJyfs(el.dataset.jyfs));
|
||||
});
|
||||
// init with default mode
|
||||
setJyfs('1');
|
||||
});
|
||||
|
||||
// ── Search ──
|
||||
async function doSearch() {
|
||||
if (!paramsReady) return;
|
||||
showLoading();
|
||||
|
||||
const params = new URLSearchParams();
|
||||
if (defaultXnm) params.append('xnm', defaultXnm);
|
||||
if (defaultXqm) params.append('xqm', defaultXqm);
|
||||
params.append('page_size', '200');
|
||||
params.append('jyfs', currentJyfs);
|
||||
|
||||
// Append filter values (only non-empty)
|
||||
['xqh_id','lh','cdlb_id','cdejlb_id','qszws','jszws','cdmc'].forEach(name => {
|
||||
const val = document.getElementById('filter_' + name).value.trim();
|
||||
if (val) params.append(name, val);
|
||||
});
|
||||
|
||||
// Time selectors based on jyfs mode
|
||||
if (currentJyfs === '0') {
|
||||
// 按周次: zcd(bitmask) + xqj(comma) + jcd(bitmask)
|
||||
const zcd = calcBitmask('weekCheckboxes');
|
||||
const xqj = calcCommaList('dayCheckboxes');
|
||||
const jcd = calcBitmask('periodCheckboxes_0');
|
||||
if (zcd) params.append('zcd', zcd);
|
||||
if (xqj) params.append('xqj', xqj);
|
||||
if (jcd) params.append('jcd', jcd);
|
||||
} else if (currentJyfs === '2') {
|
||||
// 按节次: jcd(bitmask)
|
||||
const jcd = calcBitmask('periodCheckboxes_2');
|
||||
if (jcd) params.append('jcd', jcd);
|
||||
}
|
||||
// jyfs=1 (连续): 不需要额外时间参数
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/classrooms?' + params.toString());
|
||||
const data = await res.json();
|
||||
hideLoading();
|
||||
|
||||
if (!data.success) {
|
||||
showError(data.message || '查询失败');
|
||||
return;
|
||||
}
|
||||
|
||||
const items = data.items || [];
|
||||
if (!items.length) {
|
||||
showEmpty('暂无符合条件的空闲教室');
|
||||
return;
|
||||
}
|
||||
|
||||
renderTable(items);
|
||||
} catch (e) {
|
||||
hideLoading();
|
||||
showError('网络错误: ' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Render ──
|
||||
function renderTable(items) {
|
||||
const summary = document.getElementById('resultSummary');
|
||||
summary.textContent = `共 ${items.length} 间教室`;
|
||||
summary.classList.remove('hidden');
|
||||
|
||||
const tbody = document.getElementById('tableBody');
|
||||
tbody.innerHTML = items.map((item, idx) => {
|
||||
const xqmc = item.xqmc || item.xqhmc || item.XQHMC || '--';
|
||||
const jxlmc = item.jxlmc || item.JXLMC || '--';
|
||||
const cdmc = item.cdmc || item.CDMC || '--';
|
||||
const cdbh = item.cdbh || '--';
|
||||
const cdlbmc = item.cdlbmc || item.CDLBMC || '--';
|
||||
const zws = item.zws || item.kszws1 || item.ZWS || '--';
|
||||
const lch = item.lch || '--';
|
||||
const jgmc = item.jgmc || item.JGMC || '--';
|
||||
|
||||
return `
|
||||
<tr class="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50/50 dark:hover:bg-gray-800/30 transition-colors row-animate" style="animation-delay:${idx * 30}ms;">
|
||||
<td class="py-3 px-4 text-gray-400 dark:text-gray-500">${idx + 1}</td>
|
||||
<td class="py-3 px-4">${escHtml(xqmc)}</td>
|
||||
<td class="py-3 px-4">${escHtml(jxlmc)}</td>
|
||||
<td class="py-3 px-4 font-medium">${escHtml(cdmc)}</td>
|
||||
<td class="py-3 px-4 text-gray-500 text-xs">${escHtml(cdbh)}</td>
|
||||
<td class="py-3 px-4 text-gray-500">${escHtml(cdlbmc)}</td>
|
||||
<td class="py-3 px-4 text-center">${escHtml(zws)}</td>
|
||||
<td class="py-3 px-4 text-gray-400 dark:text-gray-500 text-xs">${escHtml(lch)}</td>
|
||||
<td class="py-3 px-4 text-gray-500 text-xs">${escHtml(jgmc)}</td>
|
||||
</tr>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
document.getElementById('dataContainer').classList.remove('hidden');
|
||||
document.getElementById('emptyState').classList.add('hidden');
|
||||
|
||||
// 渲染图表
|
||||
const chartsRow = document.getElementById('chartsRow');
|
||||
chartsRow.classList.remove('hidden');
|
||||
renderBuildingChart(items);
|
||||
setupDarkObserver(items);
|
||||
}
|
||||
|
||||
// ── Helpers ──
|
||||
function showLoading() {
|
||||
document.getElementById('loadingIndicator').classList.remove('hidden');
|
||||
document.getElementById('errorMessage').classList.add('hidden');
|
||||
document.getElementById('dataContainer').classList.add('hidden');
|
||||
document.getElementById('emptyState').classList.add('hidden');
|
||||
}
|
||||
function hideLoading() { document.getElementById('loadingIndicator').classList.add('hidden'); }
|
||||
function showError(msg) {
|
||||
document.getElementById('errorText').textContent = msg;
|
||||
document.getElementById('errorMessage').classList.remove('hidden');
|
||||
}
|
||||
function showEmpty(msg) {
|
||||
document.getElementById('dataContainer').classList.add('hidden');
|
||||
document.getElementById('emptyState').classList.remove('hidden');
|
||||
document.getElementById('emptyState').querySelector('p').textContent = msg;
|
||||
}
|
||||
// ── 各楼栋空闲教室数量柱状图 ──
|
||||
function renderBuildingChart(items) {
|
||||
const container = document.getElementById('buildingChart');
|
||||
if (!container) return;
|
||||
if (!buildingChart) buildingChart = echarts.init(container);
|
||||
|
||||
const buildingCount = {};
|
||||
items.forEach(item => {
|
||||
const building = item.jxlmc || item.JXLMC || '未知';
|
||||
buildingCount[building] = (buildingCount[building] || 0) + 1;
|
||||
});
|
||||
const entries = Object.entries(buildingCount).sort((a, b) => b[1] - a[1]);
|
||||
const dark = isDarkMode();
|
||||
|
||||
buildingChart.setOption({
|
||||
tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
|
||||
grid: { left: '3%', right: '4%', bottom: '3%', top: '5%', containLabel: true },
|
||||
xAxis: { type: 'value', name: '间数', minInterval: 1, nameTextStyle: { fontSize: 11 } },
|
||||
yAxis: { type: 'category', data: entries.map(e => e[0]), axisLabel: { fontSize: 11 }, inverse: true },
|
||||
series: [{
|
||||
type: 'bar', data: entries.map(e => e[1]),
|
||||
itemStyle: {
|
||||
color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
|
||||
{ offset: 0, color: dark ? '#a78bfa' : '#8b5cf6' },
|
||||
{ offset: 1, color: dark ? '#60a5fa' : '#3b82f6' }
|
||||
])
|
||||
},
|
||||
barMaxWidth: 28,
|
||||
label: { show: true, position: 'right', fontSize: 11, color: dark ? '#9ca3af' : '#6b7280' }
|
||||
}]
|
||||
}, true);
|
||||
}
|
||||
|
||||
// ── 深色模式观察者 ──
|
||||
let _darkObserver = null;
|
||||
let _lastClassroomItems = null;
|
||||
function setupDarkObserver(items) {
|
||||
_lastClassroomItems = items;
|
||||
if (_darkObserver) return;
|
||||
_darkObserver = new MutationObserver(() => {
|
||||
if (_lastClassroomItems && _lastClassroomItems.length > 0) {
|
||||
renderBuildingChart(_lastClassroomItems);
|
||||
}
|
||||
});
|
||||
_darkObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
|
||||
}
|
||||
|
||||
window.addEventListener('resize', () => { buildingChart?.resize(); });
|
||||
|
||||
function escHtml(s) {
|
||||
if (s == null) return '';
|
||||
return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
||||
}
|
||||
function escAttr(s) {
|
||||
if (s == null) return '';
|
||||
return String(s).replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
|
||||
}
|
||||
|
||||
// ── Start ──
|
||||
initSession().then(sessionOk => {
|
||||
if (!sessionOk) {
|
||||
showError('教务系统 Session 已失效,请尝试<a href="/dashboard">重新配置教务账号</a>');
|
||||
return;
|
||||
}
|
||||
loadParams();
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,603 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
|
||||
{% block title %}课程搜索 - {{ brand_name }}{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
@keyframes fadeSlideIn {
|
||||
from { opacity: 0; transform: translateY(8px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.row-animate { animation: fadeSlideIn 0.3s ease both; }
|
||||
|
||||
/* 课程卡片入场动画 */
|
||||
@keyframes cardFadeIn {
|
||||
from { opacity: 0; transform: translateY(12px) scale(0.97); }
|
||||
to { opacity: 1; transform: translateY(0) scale(1); }
|
||||
}
|
||||
.course-card-enter {
|
||||
animation: cardFadeIn 0.4s cubic-bezier(0.22, 1, 0.36, 1) both;
|
||||
}
|
||||
|
||||
/* 展开区域动画 */
|
||||
.session-list {
|
||||
max-height: 0;
|
||||
overflow: hidden;
|
||||
transition: max-height 0.35s cubic-bezier(0.22, 1, 0.36, 1);
|
||||
}
|
||||
.session-list.expanded {
|
||||
max-height: 9999px;
|
||||
}
|
||||
|
||||
/* 进度条动画 */
|
||||
@keyframes progressShine {
|
||||
0% { background-position: -200% 0; }
|
||||
100% { background-position: 200% 0; }
|
||||
}
|
||||
.progress-bar-fill {
|
||||
background: linear-gradient(90deg, #3b82f6, #60a5fa, #3b82f6);
|
||||
background-size: 200% 100%;
|
||||
animation: progressShine 2s linear infinite;
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
<!-- 标题 -->
|
||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 list-item-enter" style="animation-delay: 0ms;">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="11" cy="11" r="8"/>
|
||||
<path d="m21 21-4.3-4.3"/>
|
||||
</svg>
|
||||
课程搜索
|
||||
</h2>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">搜索全校授课信息(课程、教师、班级、地点等所有字段)</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 学年学期选择 + 搜索框 -->
|
||||
<div class="glass rounded-2xl p-4 mb-4 list-item-enter max-w-5xl mx-auto" style="animation-delay: 50ms;">
|
||||
<div class="flex flex-col md:flex-row gap-3 items-stretch md:items-end">
|
||||
<div class="flex gap-3">
|
||||
<div>
|
||||
<label class="block text-xs text-gray-500 dark:text-gray-400 mb-1">学年</label>
|
||||
<select id="fXnm" onchange="onFilterChange()" class="w-full md:w-32 px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm">
|
||||
<option value="2026" selected>2026-2027</option>
|
||||
<option value="2025">2025-2026</option>
|
||||
<option value="2024">2024-2025</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs text-gray-500 dark:text-gray-400 mb-1">学期</label>
|
||||
<select id="fXqm" onchange="onFilterChange()" class="w-full md:w-28 px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm">
|
||||
<option value="3" selected>第1学期</option>
|
||||
<option value="12">第2学期</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex-1">
|
||||
<label class="block text-xs text-gray-500 dark:text-gray-400 mb-1">搜索关键词</label>
|
||||
<div class="flex flex-col sm:flex-row gap-2">
|
||||
<input id="searchInput" type="text" placeholder="输入关键词:课程名、教师、班级、地点等"
|
||||
onkeydown="if(event.key==='Enter') doSearch()"
|
||||
class="flex-1 px-4 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm">
|
||||
<div class="flex gap-2">
|
||||
<select id="searchField" class="flex-1 sm:flex-none px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm">
|
||||
<option value="auto">全字段</option>
|
||||
<option value="kch">课程号</option>
|
||||
<option value="name">课程名</option>
|
||||
<option value="teacher">教师</option>
|
||||
<option value="class">班级</option>
|
||||
<option value="room">地点</option>
|
||||
</select>
|
||||
<button onclick="doSearch()" class="btn-primary px-5 py-2 rounded-lg text-sm font-medium shrink-0">
|
||||
搜索
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 索引状态卡片 -->
|
||||
<div id="indexStatusCard" class="glass rounded-2xl p-4 mb-4 list-item-enter max-w-5xl mx-auto" style="animation-delay: 100ms;">
|
||||
<!-- 由 JS 填充 -->
|
||||
</div>
|
||||
|
||||
<!-- 搜索结果 -->
|
||||
<div id="resultsContainer" class="max-w-5xl mx-auto"></div>
|
||||
|
||||
<!-- 浏览面板(无关键词时显示) -->
|
||||
<div id="browseContainer" class="max-w-5xl mx-auto hidden"></div>
|
||||
|
||||
<!-- 无结果提示 -->
|
||||
<div id="noResults" class="hidden text-center py-16 list-item-enter">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"
|
||||
class="mx-auto mb-4 text-gray-300 dark:text-gray-600">
|
||||
<circle cx="11" cy="11" r="8"/>
|
||||
<path d="m21 21-4.3-4.3"/>
|
||||
<path d="M8 11h6"/>
|
||||
</svg>
|
||||
<p class="text-gray-400 dark:text-gray-500">未找到匹配的课程</p>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script>
|
||||
const WEEKDAYS = ['', '周一', '周二', '周三', '周四', '周五', '周六', '周日'];
|
||||
let pollTimer = null;
|
||||
let lastSearchKeyword = '';
|
||||
let lastSearchField = 'auto';
|
||||
const canManageIndex = {{ 'true' if current_user.is_authenticated and current_user.username == '战忠沅' else 'false' }};
|
||||
|
||||
// ── 初始化 ──
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
checkIndexStatus();
|
||||
// 自动聚焦搜索框
|
||||
document.getElementById('searchInput').focus();
|
||||
});
|
||||
|
||||
function getXnm() { return document.getElementById('fXnm').value; }
|
||||
function getXqm() { return document.getElementById('fXqm').value; }
|
||||
|
||||
function onFilterChange() {
|
||||
checkIndexStatus();
|
||||
document.getElementById('searchInput').value = '';
|
||||
document.getElementById('resultsContainer').innerHTML = '';
|
||||
document.getElementById('noResults').classList.add('hidden');
|
||||
browseData = null;
|
||||
}
|
||||
|
||||
// ── 索引状态 ──
|
||||
async function checkIndexStatus() {
|
||||
const card = document.getElementById('indexStatusCard');
|
||||
try {
|
||||
const resp = await apiRequest(`/api/jwxt/course-index/status?xnm=${getXnm()}&xqm=${getXqm()}`);
|
||||
renderIndexStatus(resp);
|
||||
if (resp.building) {
|
||||
startPolling();
|
||||
} else {
|
||||
stopPolling();
|
||||
}
|
||||
} catch (e) {
|
||||
card.innerHTML = `<p class="text-sm text-red-500">状态获取失败: ${escapeHtml(e.message)}</p>`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderIndexStatus(s) {
|
||||
const card = document.getElementById('indexStatusCard');
|
||||
|
||||
if (s.building) {
|
||||
// 构建中
|
||||
const pct = s.total_teachers > 0 ? Math.round(s.current / s.total_teachers * 100) : 0;
|
||||
card.innerHTML = `
|
||||
<div class="flex items-center justify-between mb-2">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="status-badge status-running">构建中</span>
|
||||
<span class="text-sm text-gray-500 dark:text-gray-400">
|
||||
正在拉取教师课表... ${s.current}/${s.total_teachers}
|
||||
</span>
|
||||
</div>
|
||||
<span class="text-sm font-mono text-blue-500">${pct}%</span>
|
||||
</div>
|
||||
<div class="w-full h-2 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
|
||||
<div class="progress-bar-fill h-full rounded-full transition-all duration-500" style="width: ${pct}%"></div>
|
||||
</div>
|
||||
<div class="flex gap-4 mt-2 text-xs text-gray-400">
|
||||
<span>已索引 ${s.total_courses || 0} 门课程</span>
|
||||
<span>${s.total_sessions || 0} 条排课记录</span>
|
||||
${s.current_teacher ? `<span>当前: ${escapeHtml(s.current_teacher)}</span>` : ''}
|
||||
</div>
|
||||
`;
|
||||
} else if (s.exists && !s.needs_build) {
|
||||
// 索引可用
|
||||
card.innerHTML = `
|
||||
<div class="flex items-center justify-between flex-wrap gap-2">
|
||||
<div class="flex items-center gap-3 flex-wrap">
|
||||
<span class="status-badge status-success">索引就绪</span>
|
||||
<span class="text-sm text-gray-500 dark:text-gray-400">
|
||||
${s.total_courses} 门课程 · ${s.total_sessions} 条排课 · ${s.total_teachers} 位教师
|
||||
</span>
|
||||
<span class="text-xs text-gray-400">更新于 ${s.age_hours}h 前</span>
|
||||
</div>
|
||||
${canManageIndex ? `<button onclick=\"rebuildIndex()\" class=\"btn-outline text-xs shrink-0\">\n <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"12\" height=\"12\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><polyline points=\"23 4 23 10 17 10\"/><path d=\"M20.49 15a9 9 0 1 1-2.12-9.36L23 10\"/></svg>\n 重建索引\n </button>` : ''}
|
||||
</div>
|
||||
`;
|
||||
showBrowsePanel();
|
||||
} else {
|
||||
// 无索引
|
||||
card.innerHTML = `
|
||||
<div class="flex items-center justify-between flex-wrap gap-2">
|
||||
<div class="flex items-center gap-3 flex-wrap">
|
||||
<span class="status-badge status-pending">未构建</span>
|
||||
<span class="text-sm text-gray-500 dark:text-gray-400">
|
||||
需要全量拉取教师课表来建立课程索引,预计需要 3-5 分钟
|
||||
</span>
|
||||
</div>
|
||||
${canManageIndex ? `<button onclick=\"buildIndex()\" class=\"btn-primary px-4 py-2 rounded-lg text-sm font-medium shrink-0\">\n 构建索引\n </button>` : ''}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
// ── 构建索引 ──
|
||||
async function buildIndex() {
|
||||
try {
|
||||
const resp = await apiRequest(`/api/jwxt/course-index/build?xnm=${getXnm()}&xqm=${getXqm()}`, { method: 'POST' });
|
||||
if (resp.success) {
|
||||
showToast('索引构建已启动,请等待完成', 'info');
|
||||
checkIndexStatus();
|
||||
} else {
|
||||
showToast(resp.message || '构建失败', 'error');
|
||||
}
|
||||
} catch (e) {
|
||||
showToast('构建请求失败: ' + e.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function rebuildIndex() {
|
||||
// 先删除旧索引(通过传一个 force 参数让后端重建)
|
||||
// 后端 build 会先检查缓存,如果有效则直接返回。需要先删除缓存。
|
||||
try {
|
||||
// 直接调用 build,后端会先检查缓存。如果缓存有效,需要先标记过期。
|
||||
// 简单方案:直接修改 xnm/xqm 不现实。改为直接 POST 请求,后端 build_course_index 会检查缓存。
|
||||
// 如果缓存有效,build_course_index 直接返回缓存结果。需要先删除缓存文件。
|
||||
// 但我们不想暴露删除文件接口,所以改为:在 build 路由中加 force 参数。
|
||||
const resp = await apiRequest(`/api/jwxt/course-index/build?xnm=${getXnm()}&xqm=${getXqm()}&force=1`, { method: 'POST' });
|
||||
if (resp.success) {
|
||||
showToast('正在重建索引...', 'info');
|
||||
checkIndexStatus();
|
||||
} else {
|
||||
showToast(resp.message || '重建失败', 'error');
|
||||
}
|
||||
} catch (e) {
|
||||
showToast('重建请求失败: ' + e.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
// ── 轮询构建进度 ──
|
||||
function startPolling() {
|
||||
stopPolling();
|
||||
pollTimer = setInterval(async () => {
|
||||
try {
|
||||
const resp = await apiRequest(`/api/jwxt/course-index/status?xnm=${getXnm()}&xqm=${getXqm()}`);
|
||||
renderIndexStatus(resp);
|
||||
if (!resp.building) {
|
||||
stopPolling();
|
||||
if (resp.exists) {
|
||||
showToast('索引构建完成!', 'success');
|
||||
// 如果之前有搜索关键词,重新搜索
|
||||
if (lastSearchKeyword) {
|
||||
doSearch();
|
||||
}
|
||||
} else if (resp.needs_build) {
|
||||
showToast('索引构建可能失败,请重试', 'error');
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// 忽略轮询中的错误
|
||||
}
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
if (pollTimer) {
|
||||
clearInterval(pollTimer);
|
||||
pollTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
// ── 搜索 ──
|
||||
async function doSearch() {
|
||||
const keyword = document.getElementById('searchInput').value.trim();
|
||||
const field = document.getElementById('searchField').value;
|
||||
lastSearchKeyword = keyword;
|
||||
lastSearchField = field;
|
||||
|
||||
if (!keyword) {
|
||||
showBrowsePanel();
|
||||
return;
|
||||
}
|
||||
|
||||
document.getElementById('browseContainer').classList.add('hidden');
|
||||
|
||||
const resultsContainer = document.getElementById('resultsContainer');
|
||||
const noResults = document.getElementById('noResults');
|
||||
|
||||
// 显示加载状态
|
||||
resultsContainer.innerHTML = `
|
||||
<div class="text-center py-12 list-item-enter">
|
||||
<div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
|
||||
<p class="text-gray-500 dark:text-gray-400">正在搜索...</p>
|
||||
</div>
|
||||
`;
|
||||
noResults.classList.add('hidden');
|
||||
|
||||
try {
|
||||
const resp = await apiRequest(`/api/jwxt/course-search?keyword=${encodeURIComponent(keyword)}&xnm=${getXnm()}&xqm=${getXqm()}&field=${field}`);
|
||||
|
||||
if (!resp.success) {
|
||||
resultsContainer.innerHTML = `
|
||||
<div class="glass rounded-2xl p-6 text-center list-item-enter">
|
||||
<p class="text-red-500">${escapeHtml(resp.message || '搜索失败')}</p>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
const courses = resp.courses || [];
|
||||
if (courses.length === 0) {
|
||||
resultsContainer.innerHTML = '';
|
||||
noResults.classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
|
||||
renderResults(courses, resp);
|
||||
} catch (e) {
|
||||
resultsContainer.innerHTML = `
|
||||
<div class="glass rounded-2xl p-6 text-center list-item-enter">
|
||||
<p class="text-red-500">搜索失败: ${escapeHtml(e.message)}</p>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
// ── 渲染搜索结果 ──
|
||||
function renderResults(courses, meta) {
|
||||
const container = document.getElementById('resultsContainer');
|
||||
|
||||
let html = `
|
||||
<div class="flex items-center justify-between mb-3 px-1 list-item-enter">
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400">
|
||||
找到 <span class="font-bold text-black dark:text-white">${courses.length}</span> 门课程
|
||||
</p>
|
||||
</div>
|
||||
`;
|
||||
|
||||
courses.forEach((course, idx) => {
|
||||
const sessions = course.sessions || [];
|
||||
const delay = Math.min(idx * 50, 400);
|
||||
html += renderCourseCard(course, sessions, delay);
|
||||
});
|
||||
|
||||
container.innerHTML = html;
|
||||
}
|
||||
|
||||
function renderCourseCard(course, sessions, delay) {
|
||||
const id = `course_${course.kch.replace(/[^a-zA-Z0-9]/g, '')}`;
|
||||
const tags = [];
|
||||
if (course.xf) tags.push(`${course.xf}学分`);
|
||||
if (course.kcxzjc) tags.push(course.kcxzjc);
|
||||
if (course.khfsmc) tags.push(course.khfsmc);
|
||||
if (course.xslxbj === '☆' || course.xslxbj === '★') tags.push('选修');
|
||||
|
||||
// 统计不同教师数
|
||||
const teacherSet = new Set();
|
||||
sessions.forEach(s => { if (s.jsxm) teacherSet.add(s.jsxm); });
|
||||
|
||||
// 统计班级数
|
||||
const classSet = new Set();
|
||||
sessions.forEach(s => { if (s.jxbzcbjjc) classSet.add(s.jxbzcbjjc); });
|
||||
|
||||
return `
|
||||
<div class="glass rounded-2xl mb-3 overflow-hidden course-card-enter" style="animation-delay: ${delay}ms;" id="${id}">
|
||||
<!-- 课程头部 -->
|
||||
<div class="p-4 cursor-pointer hover:bg-black/[0.02] dark:hover:bg-white/[0.02] transition-colors" onclick="toggleSessions('${id}')">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex items-center gap-2 flex-wrap mb-1">
|
||||
<h3 class="font-bold text-base">${escapeHtml(course.kcmc || '未知课程')}</h3>
|
||||
${tags.map(t => `<span class="tag">${escapeHtml(t)}</span>`).join('')}
|
||||
</div>
|
||||
<p class="text-xs font-mono text-gray-400 dark:text-gray-500">${escapeHtml(course.kch || '')}</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-2 shrink-0">
|
||||
<div class="text-right hidden sm:block">
|
||||
<p class="text-xs text-gray-400">${teacherSet.size} 位教师</p>
|
||||
<p class="text-xs text-gray-400">${sessions.length} 个教学班</p>
|
||||
</div>
|
||||
<svg class="w-5 h-5 text-gray-400 transition-transform expand-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 手机端统计信息 -->
|
||||
<div class="flex gap-3 mt-2 sm:hidden">
|
||||
<span class="text-xs text-gray-400">${teacherSet.size} 位教师</span>
|
||||
<span class="text-xs text-gray-400">${sessions.length} 个教学班</span>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 教学班列表(可展开) -->
|
||||
<div class="session-list" id="${id}_sessions">
|
||||
<div class="border-t border-gray-100 dark:border-gray-800">
|
||||
${sessions.map((s, si) => renderSessionRow(s, si)).join('')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function renderSessionRow(s, idx) {
|
||||
const xqj = WEEKDAYS[parseInt(s.xqj)] || (s.xqj || '-');
|
||||
const skjc = s.skcd || s.skjc || '-';
|
||||
const zcd = s.zcd || '-';
|
||||
const teachers = s.jsxm || '-';
|
||||
const cls = s.jxbzcbjjc || '-';
|
||||
const room = s.cdmc || '-';
|
||||
const count = s.jxbrs || '-';
|
||||
const campus = s.zfjmc || '';
|
||||
|
||||
return `
|
||||
<div class="px-4 py-3 hover:bg-black/[0.02] dark:hover:bg-white/[0.02] transition-colors ${idx > 0 ? 'border-t border-gray-50 dark:border-gray-900' : ''}">
|
||||
<div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-2 text-sm">
|
||||
<div>
|
||||
<span class="text-xs text-gray-400 block">教师</span>
|
||||
<span class="font-medium">${escapeHtml(teachers)}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-xs text-gray-400 block">上课班级</span>
|
||||
<span class="text-xs">${escapeHtml(cls)}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-xs text-gray-400 block">时间</span>
|
||||
<span class="text-xs">${escapeHtml(xqj)} ${escapeHtml(String(skjc))}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-xs text-gray-400 block">周次</span>
|
||||
<span class="text-xs">${escapeHtml(String(zcd))}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-xs text-gray-400 block">地点</span>
|
||||
<span class="text-xs">${escapeHtml(room)}${campus ? ' <span class="text-gray-400">' + escapeHtml(campus) + '</span>' : ''}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-xs text-gray-400 block">人数</span>
|
||||
<span class="text-xs">${escapeHtml(String(count))}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function toggleSessions(id) {
|
||||
const el = document.getElementById(id + '_sessions');
|
||||
const icon = document.querySelector(`#${id} .expand-icon`);
|
||||
if (el.classList.contains('expanded')) {
|
||||
el.classList.remove('expanded');
|
||||
icon.style.transform = '';
|
||||
} else {
|
||||
el.classList.add('expanded');
|
||||
icon.style.transform = 'rotate(180deg)';
|
||||
}
|
||||
}
|
||||
|
||||
// ── 浏览面板 ──
|
||||
let browseData = null;
|
||||
let browseTab = 'courses';
|
||||
|
||||
async function showBrowsePanel() {
|
||||
const container = document.getElementById('browseContainer');
|
||||
const resultsContainer = document.getElementById('resultsContainer');
|
||||
|
||||
// 隐藏搜索结果
|
||||
resultsContainer.innerHTML = '';
|
||||
document.getElementById('noResults').classList.add('hidden');
|
||||
container.classList.remove('hidden');
|
||||
|
||||
if (!browseData || browseData._xnm !== getXnm() || browseData._xqm !== getXqm()) {
|
||||
container.innerHTML = `
|
||||
<div class="text-center py-12 list-item-enter">
|
||||
<div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
|
||||
<p class="text-gray-500 dark:text-gray-400">正在加载...</p>
|
||||
</div>
|
||||
`;
|
||||
try {
|
||||
const resp = await apiRequest(`/api/jwxt/course-browse?xnm=${getXnm()}&xqm=${getXqm()}`);
|
||||
if (!resp.success) {
|
||||
container.innerHTML = `<p class="text-sm text-gray-400 text-center py-8">${escapeHtml(resp.message || '加载失败')}</p>`;
|
||||
return;
|
||||
}
|
||||
resp._xnm = getXnm();
|
||||
resp._xqm = getXqm();
|
||||
browseData = resp;
|
||||
} catch (e) {
|
||||
container.innerHTML = `<p class="text-sm text-red-500 text-center py-8">加载失败: ${escapeHtml(e.message)}</p>`;
|
||||
return;
|
||||
}
|
||||
}
|
||||
renderBrowsePanel();
|
||||
}
|
||||
|
||||
function renderBrowsePanel() {
|
||||
const container = document.getElementById('browseContainer');
|
||||
const tabs = [
|
||||
{ key: 'courses', label: `课程 (${browseData.total_courses})` },
|
||||
{ key: 'teachers', label: `教师 (${browseData.total_teachers})` },
|
||||
{ key: 'rooms', label: `地点 (${browseData.total_rooms})` },
|
||||
{ key: 'classes', label: `班级 (${browseData.total_classes})` },
|
||||
];
|
||||
|
||||
let html = `
|
||||
<div class="glass rounded-2xl p-1 mb-4 flex gap-1 overflow-x-auto">
|
||||
${tabs.map(t => `
|
||||
<button data-key="${t.key}" onclick="switchBrowseTab('${t.key}')" class="browse-tab-btn px-4 py-2 rounded-lg text-sm font-medium transition-colors whitespace-nowrap ${browseTab === t.key ? 'bg-black dark:bg-white text-white dark:text-black' : 'text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800'}">${t.label}</button>
|
||||
`).join('')}
|
||||
</div>
|
||||
<div id="browseContent"></div>
|
||||
`;
|
||||
container.innerHTML = html;
|
||||
renderBrowseTab();
|
||||
}
|
||||
|
||||
function switchBrowseTab(tab) {
|
||||
browseTab = tab;
|
||||
// 更新按钮样式
|
||||
document.querySelectorAll('.browse-tab-btn').forEach(btn => {
|
||||
const isActive = btn.dataset.key === tab;
|
||||
btn.className = `browse-tab-btn px-4 py-2 rounded-lg text-sm font-medium transition-colors whitespace-nowrap ${isActive ? 'bg-black dark:bg-white text-white dark:text-black' : 'text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800'}`;
|
||||
});
|
||||
renderBrowseTab();
|
||||
}
|
||||
|
||||
function renderBrowseTab() {
|
||||
const el = document.getElementById('browseContent');
|
||||
|
||||
if (browseTab === 'courses') {
|
||||
el.innerHTML = renderCourseBrowseList(browseData.courses);
|
||||
} else if (browseTab === 'teachers') {
|
||||
el.innerHTML = renderSimpleBrowseList(browseData.teachers, '教师', 'course_count', '门课');
|
||||
} else if (browseTab === 'rooms') {
|
||||
el.innerHTML = renderSimpleBrowseList(browseData.rooms, '地点', 'session_count', '条排课');
|
||||
} else if (browseTab === 'classes') {
|
||||
el.innerHTML = renderSimpleBrowseList(browseData.classes, '班级', 'session_count', '条排课');
|
||||
}
|
||||
}
|
||||
|
||||
function renderCourseBrowseList(courses) {
|
||||
if (!courses.length) return '<p class="text-center text-gray-400 py-8">暂无数据</p>';
|
||||
return courses.map((c, idx) => `
|
||||
<div class="glass rounded-xl mb-2 p-3 flex items-center justify-between gap-3 cursor-pointer hover:bg-black/[0.02] dark:hover:bg-white/[0.02] transition-colors list-item-enter"
|
||||
style="animation-delay: ${Math.min(idx * 20, 300)}ms;"
|
||||
onclick="quickSearch('${escapeHtml(c.kcmc)}')">
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<span class="font-medium text-sm">${escapeHtml(c.kcmc)}</span>
|
||||
${c.xf ? `<span class="tag text-xs">${escapeHtml(c.xf)}学分</span>` : ''}
|
||||
${c.kcxzjc ? `<span class="tag text-xs">${escapeHtml(c.kcxzjc)}</span>` : ''}
|
||||
${c.khfsmc ? `<span class="tag text-xs">${escapeHtml(c.khfsmc)}</span>` : ''}
|
||||
</div>
|
||||
<p class="text-xs font-mono text-gray-400 mt-0.5">${escapeHtml(c.kch)}</p>
|
||||
</div>
|
||||
<div class="flex gap-3 shrink-0 text-xs text-gray-400">
|
||||
<span>${c.teacher_count} 教师</span>
|
||||
<span>${c.session_count} 教学班</span>
|
||||
</div>
|
||||
</div>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
function renderSimpleBrowseList(items, label, countKey, countLabel) {
|
||||
if (!items.length) return '<p class="text-center text-gray-400 py-8">暂无数据</p>';
|
||||
return items.map((item, idx) => `
|
||||
<div class="glass rounded-xl mb-2 p-3 flex items-center justify-between gap-3 cursor-pointer hover:bg-black/[0.02] dark:hover:bg-white/[0.02] transition-colors list-item-enter"
|
||||
style="animation-delay: ${Math.min(idx * 15, 300)}ms;"
|
||||
onclick="quickSearch('${escapeHtml(item.name)}')">
|
||||
<span class="font-medium text-sm">${escapeHtml(item.name)}</span>
|
||||
<span class="text-xs text-gray-400 shrink-0">${item[countKey]} ${countLabel}</span>
|
||||
</div>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
function quickSearch(keyword) {
|
||||
document.getElementById('searchInput').value = keyword;
|
||||
document.getElementById('searchField').value = 'auto';
|
||||
doSearch();
|
||||
}
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,74 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
{% block title %}校内课程替代申请 - {{ brand_name }}{% endblock %}
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
@keyframes fadeSlideIn {
|
||||
from { opacity: 0; transform: translateY(8px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.row-animate { animation: fadeSlideIn 0.3s ease both; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.row-animate { animation: none !important; opacity: 1 !important; }
|
||||
.list-item-enter { animation: none !important; opacity: 1 !important; }
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 list-item-enter">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 3h5v5"/><path d="M8 3H3v5"/><path d="M3 16v5h5"/><path d="M16 21h5v-5"/><line x1="12" y1="3" x2="12" y2="21"/><line x1="3" y1="12" x2="21" y2="12"/></svg>
|
||||
校内课程替代申请
|
||||
</h2>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">申请用已修课程替代未修课程</p>
|
||||
</div>
|
||||
<button onclick="loadData()" class="px-4 py-2 rounded-lg border"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>刷新</button>
|
||||
</div>
|
||||
<div id="loadingIndicator" class="text-center py-12 hidden"><div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div><p class="text-gray-500 dark:text-gray-400">加载中...</p></div>
|
||||
<div id="errorMessage" class="glass rounded-2xl p-6 mb-4 text-center hidden"><p id="errorText" class="text-red-500"></p></div>
|
||||
<div id="dataContainer" class="hidden">
|
||||
<div class="glass rounded-2xl overflow-hidden">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead><tr class="border-b border-gray-200 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-800/50"><th class="text-left py-3 px-4 font-semibold">原课程</th><th class="text-left py-3 px-4 font-semibold">替代课程</th><th class="text-left py-3 px-4 font-semibold">申请时间</th><th class="text-left py-3 px-4 font-semibold">审核状态</th></tr></thead>
|
||||
<tbody id="tableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="emptyState" class="glass rounded-2xl p-12 text-center hidden"><p class="text-gray-500 dark:text-gray-400 text-lg">暂无替代申请记录</p></div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block extra_js %}
|
||||
<script>
|
||||
async function loadData() {
|
||||
document.getElementById('loadingIndicator').classList.remove('hidden');
|
||||
document.getElementById('errorMessage').classList.add('hidden');
|
||||
document.getElementById('dataContainer').classList.add('hidden');
|
||||
document.getElementById('emptyState').classList.add('hidden');
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/course-substitution');
|
||||
const data = await res.json();
|
||||
document.getElementById('loadingIndicator').classList.add('hidden');
|
||||
if (!data.success) { showError(data.message); return; }
|
||||
const items = data.items || [];
|
||||
if (!items.length) { document.getElementById('emptyState').classList.remove('hidden'); return; }
|
||||
const tbody = document.getElementById('tableBody');
|
||||
tbody.innerHTML = items.map((item, i) => {
|
||||
return `<tr class="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50/50 dark:hover:bg-gray-800/30 transition-colors">
|
||||
<td class="py-3 px-4">${escHtml(item.ykcmc||item.原课程||'--')}</td>
|
||||
<td class="py-3 px-4">${escHtml(item.tdkcmc||item.替代课程||'--')}</td>
|
||||
<td class="py-3 px-4 text-gray-500">${escHtml(item.sqsj||item.申请时间||'--')}</td>
|
||||
<td class="py-3 px-4"><span class="px-2 py-0.5 rounded text-xs ${(item.shztmc||item.审核状态||'').includes('通过')?'bg-green-100 text-green-700':(item.shztmc||'').includes('待审')?'bg-yellow-100 text-yellow-700':'bg-gray-100 text-gray-600'}">${escHtml(item.shztmc||item.审核状态||'--')}</span></td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
document.getElementById('dataContainer').classList.remove('hidden');
|
||||
} catch(e) { document.getElementById('loadingIndicator').classList.add('hidden'); showError('网络错误: '+e.message); }
|
||||
}
|
||||
function showError(msg) { document.getElementById('errorText').textContent = msg; document.getElementById('errorMessage').classList.remove('hidden'); }
|
||||
function escHtml(s) { if(s==null) return ''; return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"'); }
|
||||
document.addEventListener('DOMContentLoaded', () => loadData());
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,74 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
{% block title %}成绩学分认定申请 - {{ brand_name }}{% endblock %}
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
@keyframes fadeSlideIn {
|
||||
from { opacity: 0; transform: translateY(8px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.row-animate { animation: fadeSlideIn 0.3s ease both; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.row-animate { animation: none !important; opacity: 1 !important; }
|
||||
.list-item-enter { animation: none !important; opacity: 1 !important; }
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 list-item-enter">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 10v6M2 10l10-5 10 5-10 5z"/><path d="M6 12v5c0 1.66 2.69 3 6 3"/></svg>
|
||||
成绩学分认定申请
|
||||
</h2>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">申请成绩和学分的认定</p>
|
||||
</div>
|
||||
<button onclick="loadData()" class="px-4 py-2 rounded-lg border"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>刷新</button>
|
||||
</div>
|
||||
<div id="loadingIndicator" class="text-center py-12 hidden"><div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div><p class="text-gray-500 dark:text-gray-400">加载中...</p></div>
|
||||
<div id="errorMessage" class="glass rounded-2xl p-6 mb-4 text-center hidden"><p id="errorText" class="text-red-500"></p></div>
|
||||
<div id="dataContainer" class="hidden">
|
||||
<div class="glass rounded-2xl overflow-hidden">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead><tr class="border-b border-gray-200 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-800/50"><th class="text-left py-3 px-4 font-semibold">课程名称</th><th class="text-left py-3 px-4 font-semibold">申请类型</th><th class="text-left py-3 px-4 font-semibold">申请时间</th><th class="text-left py-3 px-4 font-semibold">审核状态</th></tr></thead>
|
||||
<tbody id="tableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="emptyState" class="glass rounded-2xl p-12 text-center hidden"><p class="text-gray-500 dark:text-gray-400 text-lg">暂无认定申请记录</p></div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block extra_js %}
|
||||
<script>
|
||||
async function loadData() {
|
||||
document.getElementById('loadingIndicator').classList.remove('hidden');
|
||||
document.getElementById('errorMessage').classList.add('hidden');
|
||||
document.getElementById('dataContainer').classList.add('hidden');
|
||||
document.getElementById('emptyState').classList.add('hidden');
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/credit-recognition');
|
||||
const data = await res.json();
|
||||
document.getElementById('loadingIndicator').classList.add('hidden');
|
||||
if (!data.success) { showError(data.message); return; }
|
||||
const items = data.items || [];
|
||||
if (!items.length) { document.getElementById('emptyState').classList.remove('hidden'); return; }
|
||||
const tbody = document.getElementById('tableBody');
|
||||
tbody.innerHTML = items.map((item, i) => {
|
||||
return `<tr class="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50/50 dark:hover:bg-gray-800/30 transition-colors">
|
||||
<td class="py-3 px-4">${escHtml(item.kcmc||item.课程名称||'--')}</td>
|
||||
<td class="py-3 px-4 text-gray-500">${escHtml(item.sqlx||item.申请类型||'--')}</td>
|
||||
<td class="py-3 px-4 text-gray-500">${escHtml(item.sqsj||item.申请时间||'--')}</td>
|
||||
<td class="py-3 px-4"><span class="px-2 py-0.5 rounded text-xs ${(item.shztmc||item.审核状态||'').includes('通过')?'bg-green-100 text-green-700':(item.shztmc||item.审核状态||'').includes('待审')?'bg-yellow-100 text-yellow-700':'bg-gray-100 text-gray-600'}">${escHtml(item.shztmc||item.审核状态||'--')}</span></td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
document.getElementById('dataContainer').classList.remove('hidden');
|
||||
} catch(e) { document.getElementById('loadingIndicator').classList.add('hidden'); showError('网络错误: '+e.message); }
|
||||
}
|
||||
function showError(msg) { document.getElementById('errorText').textContent = msg; document.getElementById('errorMessage').classList.remove('hidden'); }
|
||||
function escHtml(s) { if(s==null) return ''; return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"'); }
|
||||
document.addEventListener('DOMContentLoaded', () => loadData());
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,446 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
|
||||
{% block title %}仪表盘 - {{ brand_name }}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="space-y-6">
|
||||
<!-- 欢迎区域 -->
|
||||
<div class="glass rounded-2xl p-6 layer-2 list-item-enter" style="animation-delay: 0ms;">
|
||||
<div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
|
||||
<div>
|
||||
<h1 class="text-2xl md:text-3xl font-bold text-neutral-900 dark:text-white">欢迎回来,{{ current_user.username }}</h1>
|
||||
<p class="text-neutral-500 dark:text-neutral-400 mt-1">这里是您的抢课任务概览</p>
|
||||
</div>
|
||||
<div class="flex gap-3 flex-wrap">
|
||||
<a href="{{ url_for('main.courses') }}" class="btn-primary px-5 py-2.5 rounded-full text-sm font-bold inline-flex items-center">
|
||||
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
|
||||
</svg>
|
||||
查询课程
|
||||
</a>
|
||||
<a href="{{ url_for('main.timetable') }}" class="px-5 py-2.5 rounded-full text-sm font-bold bg-blue-600 text-white hover:bg-blue-700 transition inline-flex items-center">
|
||||
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
|
||||
</svg>
|
||||
课表查询
|
||||
</a>
|
||||
<a href="{{ url_for('main.tasks') }}" class="px-5 py-2.5 rounded-full text-sm font-bold bg-green-600 text-white hover:bg-green-700 transition inline-flex items-center">
|
||||
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
|
||||
</svg>
|
||||
创建任务
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 统计卡片 -->
|
||||
<div class="grid grid-cols-2 md:grid-cols-4 gap-4">
|
||||
<div class="glass rounded-2xl p-5 layer-2 list-item-enter" style="animation-delay: 50ms;">
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<p class="text-sm text-neutral-500 dark:text-neutral-400">总任务数</p>
|
||||
<p class="text-2xl font-bold text-neutral-900 dark:text-white mt-1">{{ task_count }}</p>
|
||||
</div>
|
||||
<div class="w-10 h-10 rounded-xl bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center">
|
||||
<svg class="w-5 h-5 text-blue-600 dark:text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01"></path>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="glass rounded-2xl p-5 layer-2 list-item-enter" style="animation-delay: 100ms;">
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<p class="text-sm text-neutral-500 dark:text-neutral-400">待执行</p>
|
||||
<p class="text-2xl font-bold text-neutral-900 dark:text-white mt-1">{{ pending_count }}</p>
|
||||
</div>
|
||||
<div class="w-10 h-10 rounded-xl bg-amber-100 dark:bg-amber-900/30 flex items-center justify-center">
|
||||
<svg class="w-5 h-5 text-amber-600 dark:text-amber-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="glass rounded-2xl p-5 layer-2 list-item-enter" style="animation-delay: 150ms;">
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<p class="text-sm text-neutral-500 dark:text-neutral-400">抢课成功</p>
|
||||
<p class="text-2xl font-bold text-neutral-900 dark:text-white mt-1">{{ success_count }}</p>
|
||||
</div>
|
||||
<div class="w-10 h-10 rounded-xl bg-green-100 dark:bg-green-900/30 flex items-center justify-center">
|
||||
<svg class="w-5 h-5 text-green-600 dark:text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="glass rounded-2xl p-5 layer-2 list-item-enter" style="animation-delay: 200ms;">
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<p class="text-sm text-neutral-500 dark:text-neutral-400">选课系统</p>
|
||||
<p class="text-lg font-bold mt-1" id="systemStatus">
|
||||
<span class="inline-block w-4 h-4 border-2 border-neutral-300 dark:border-neutral-700 border-t-neutral-900 dark:border-t-white rounded-full animate-spin"></span>
|
||||
</p>
|
||||
</div>
|
||||
<div class="w-10 h-10 rounded-xl bg-purple-100 dark:bg-purple-900/30 flex items-center justify-center">
|
||||
<svg class="w-5 h-5 text-purple-600 dark:text-purple-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3.055 11H5a2 2 0 012 2v1a2 2 0 002 2 2 2 0 012 2v2.945M8 3.935V5.5A2.5 2.5 0 0010.5 8h.5a2 2 0 012 2 2 2 0 104 0 2 2 0 012-2h1.064M15 20.488V18a2 2 0 012-2h3.064M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Session 状态 -->
|
||||
<div class="glass rounded-2xl p-6 layer-2 list-item-enter" style="animation-delay: 250ms;">
|
||||
<div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
|
||||
<div>
|
||||
<h3 class="text-lg font-bold text-neutral-900 dark:text-white flex items-center gap-2">
|
||||
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"></path>
|
||||
</svg>
|
||||
登录状态
|
||||
</h3>
|
||||
<p class="text-sm text-neutral-500 mt-1" id="sessionStatusInfo">
|
||||
<span class="inline-block w-3 h-3 border-2 border-neutral-300 dark:border-neutral-700 border-t-neutral-900 dark:border-t-white rounded-full animate-spin mr-1"></span>
|
||||
检查中...
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex gap-3">
|
||||
<button onclick="refreshSession()" class="px-4 py-2 bg-neutral-100 dark:bg-neutral-800 text-neutral-700 dark:text-neutral-300 rounded-full text-sm font-medium hover:bg-neutral-200 dark:hover:bg-neutral-700 transition">
|
||||
<svg class="w-4 h-4 inline-block mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
|
||||
</svg>
|
||||
刷新登录
|
||||
</button>
|
||||
<button onclick="showJwxtConfigModal()" class="px-4 py-2 bg-neutral-900 dark:bg-white text-white dark:text-black rounded-full text-sm font-medium hover:shadow-lg transition">
|
||||
<svg class="w-4 h-4 inline-block mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
|
||||
</svg>
|
||||
配置账号
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 最近任务 -->
|
||||
<div class="glass rounded-2xl p-6 layer-2 list-item-enter" style="animation-delay: 300ms;">
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h3 class="text-lg font-bold text-neutral-900 dark:text-white">最近任务</h3>
|
||||
<a href="{{ url_for('main.tasks') }}" class="text-sm text-neutral-500 hover:text-neutral-700 dark:hover:text-neutral-300 transition flex items-center gap-1">
|
||||
查看全部
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
|
||||
</svg>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{% if recent_tasks %}
|
||||
<div class="overflow-x-auto max-w-5xl mx-auto">
|
||||
<table class="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>课程名称</th>
|
||||
<th>类型</th>
|
||||
<th>状态</th>
|
||||
<th>创建时间</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for task in recent_tasks %}
|
||||
<tr class="list-item-enter" style="animation-delay: {{ (loop.index0 * 30) }}ms;">
|
||||
<td class="font-medium">{{ task.course_name }}</td>
|
||||
<td>
|
||||
{% if task.task_type == 'immediate' %}
|
||||
<span class="status-badge status-info">立即</span>
|
||||
{% else %}
|
||||
<span class="status-badge status-warning">定时</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>
|
||||
{% if task.status == 'success' %}
|
||||
<span class="status-badge status-success">成功</span>
|
||||
{% elif task.status == 'pending' %}
|
||||
<span class="status-badge status-warning">待执行</span>
|
||||
{% elif task.status == 'running' %}
|
||||
<span class="status-badge status-info">运行中</span>
|
||||
{% else %}
|
||||
<span class="status-badge status-danger">失败</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td class="text-sm text-neutral-500">{{ task.created_at.strftime('%Y-%m-%d %H:%M') }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="text-center py-8">
|
||||
<svg class="w-12 h-12 text-neutral-300 dark:text-neutral-700 mx-auto mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4"></path>
|
||||
</svg>
|
||||
<p class="text-neutral-500">暂无任务,快去创建抢课任务吧!</p>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 刷新 Session 模态框 -->
|
||||
<div id="refreshSessionModal" class="fixed inset-0 z-50 flex items-center justify-center p-4 opacity-0 pointer-events-none transition-opacity duration-240">
|
||||
<div class="absolute inset-0 bg-black/60 backdrop-blur-sm" onclick="closeRefreshSessionModal()"></div>
|
||||
<div class="relative w-full max-w-md p-4">
|
||||
<div class="glass rounded-2xl p-6 layer-4 modal-animate">
|
||||
<div class="flex justify-between items-center mb-6">
|
||||
<h3 class="text-xl font-bold text-neutral-900 dark:text-white">刷新登录状态</h3>
|
||||
<button onclick="closeRefreshSessionModal()" class="p-2 hover:bg-neutral-100 dark:hover:bg-neutral-800 rounded-full transition">
|
||||
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<div class="bg-blue-50 dark:bg-blue-900/20 border border-blue-100 dark:border-blue-800 rounded-xl p-4 mb-4">
|
||||
<p class="text-sm text-blue-800 dark:text-blue-200">系统将自动使用已保存的教务系统密码刷新登录状态</p>
|
||||
</div>
|
||||
<div id="refreshResult"></div>
|
||||
<div class="flex gap-3 mt-6">
|
||||
<button type="button" onclick="closeRefreshSessionModal()" class="flex-1 py-3 rounded-xl bg-neutral-100 dark:bg-neutral-800 text-neutral-700 dark:text-neutral-300 font-medium hover:bg-neutral-200 dark:hover:bg-neutral-700 transition">
|
||||
取消
|
||||
</button>
|
||||
<button type="button" onclick="doRefreshSession()" class="flex-1 py-3 rounded-xl bg-neutral-900 dark:bg-white text-white dark:text-black font-bold hover:shadow-lg transition">
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 配置教务系统账号模态框 -->
|
||||
<div id="jwxtConfigModal" class="fixed inset-0 z-50 flex items-center justify-center p-4 opacity-0 pointer-events-none transition-opacity duration-240">
|
||||
<div class="absolute inset-0 bg-black/60 backdrop-blur-sm" onclick="closeJwxtConfigModal()"></div>
|
||||
<div class="relative w-full max-w-md p-4">
|
||||
<div class="glass rounded-2xl p-6 layer-4 modal-animate">
|
||||
<div class="flex justify-between items-center mb-6">
|
||||
<h3 class="text-xl font-bold text-neutral-900 dark:text-white">配置教务系统账号</h3>
|
||||
<button onclick="closeJwxtConfigModal()" class="p-2 hover:bg-neutral-100 dark:hover:bg-neutral-800 rounded-full transition">
|
||||
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<div class="bg-amber-50 dark:bg-amber-900/20 border border-amber-100 dark:border-amber-800 rounded-xl p-4 mb-4">
|
||||
<p class="text-sm text-amber-800 dark:text-amber-200">修改账号信息需要重新验证</p>
|
||||
</div>
|
||||
<div class="space-y-4">
|
||||
<div>
|
||||
<label class="input-label">学号</label>
|
||||
<input type="text" id="configJwxtUsername" class="input-field" placeholder="请输入学号">
|
||||
</div>
|
||||
<div>
|
||||
<label class="input-label">密码</label>
|
||||
<input type="password" id="configJwxtPassword" class="input-field" placeholder="请输入密码">
|
||||
</div>
|
||||
<div>
|
||||
<label class="input-label">姓名(选填)</label>
|
||||
<input type="text" id="configJwxtName" class="input-field" placeholder="请输入姓名">
|
||||
</div>
|
||||
<div id="configResult"></div>
|
||||
</div>
|
||||
<div class="flex gap-3 mt-6">
|
||||
<button type="button" onclick="closeJwxtConfigModal()" class="flex-1 py-3 rounded-xl bg-neutral-100 dark:bg-neutral-800 text-neutral-700 dark:text-neutral-300 font-medium hover:bg-neutral-200 dark:hover:bg-neutral-700 transition">
|
||||
取消
|
||||
</button>
|
||||
<button type="button" onclick="saveJwxtConfig()" class="flex-1 py-3 rounded-xl bg-neutral-900 dark:bg-white text-white dark:text-black font-bold hover:shadow-lg transition">
|
||||
保存并验证
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script>
|
||||
// 页面加载完成后执行
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
// 将弹窗移到 body 直接子级,确保 fixed 定位基于视口
|
||||
['refreshSessionModal', 'jwxtConfigModal'].forEach(id => {
|
||||
const el = document.getElementById(id);
|
||||
if (el) document.body.appendChild(el);
|
||||
});
|
||||
|
||||
checkSystemStatus();
|
||||
checkSessionStatus();
|
||||
|
||||
// 每30秒刷新一次状态
|
||||
setInterval(checkSystemStatus, 30000);
|
||||
setInterval(checkSessionStatus, 60000);
|
||||
});
|
||||
|
||||
// 检查选课系统状态
|
||||
async function checkSystemStatus() {
|
||||
try {
|
||||
const data = await apiRequest('/api/courses/status');
|
||||
const statusEl = document.getElementById('systemStatus');
|
||||
|
||||
if (data.success && data.is_open) {
|
||||
statusEl.innerHTML = '<span class="text-green-600 dark:text-green-400 flex items-center gap-1"><span class="w-2 h-2 bg-green-500 rounded-full"></span>开放中</span>';
|
||||
} else {
|
||||
statusEl.innerHTML = '<span class="text-amber-600 dark:text-amber-400 flex items-center gap-1"><span class="w-2 h-2 bg-amber-500 rounded-full"></span>未开放</span>';
|
||||
}
|
||||
} catch (error) {
|
||||
document.getElementById('systemStatus').innerHTML = '<span class="text-red-600">获取失败</span>';
|
||||
}
|
||||
}
|
||||
|
||||
// 检查 Session 状态
|
||||
async function checkSessionStatus() {
|
||||
try {
|
||||
const data = await apiRequest('/api/user/session/status');
|
||||
const infoEl = document.getElementById('sessionStatusInfo');
|
||||
|
||||
if (data.is_valid) {
|
||||
infoEl.innerHTML = `
|
||||
<span class="text-green-600 dark:text-green-400 flex items-center gap-2">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
|
||||
</svg>
|
||||
登录有效
|
||||
<span class="text-neutral-400 text-xs">更新时间: ${data.updated_at ? formatTime(data.updated_at) : '未知'}</span>
|
||||
</span>
|
||||
`;
|
||||
} else {
|
||||
infoEl.innerHTML = `
|
||||
<span class="text-red-600 dark:text-red-400 flex items-center gap-2">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
|
||||
</svg>
|
||||
登录已过期
|
||||
${data.error_msg ? `<span class="text-neutral-400 text-xs">${data.error_msg}</span>` : ''}
|
||||
</span>
|
||||
`;
|
||||
}
|
||||
} catch (error) {
|
||||
document.getElementById('sessionStatusInfo').innerHTML = '<span class="text-red-600">检查失败</span>';
|
||||
}
|
||||
}
|
||||
|
||||
// 显示刷新 Session 模态框
|
||||
function refreshSession() {
|
||||
document.getElementById('refreshResult').innerHTML = '';
|
||||
const modal = document.getElementById('refreshSessionModal');
|
||||
modal.classList.remove('opacity-0', 'pointer-events-none');
|
||||
modal.classList.add('opacity-100', 'pointer-events-auto');
|
||||
document.documentElement.style.overflow = 'hidden';
|
||||
document.body.style.overflow = 'hidden';
|
||||
}
|
||||
|
||||
function closeRefreshSessionModal() {
|
||||
const modal = document.getElementById('refreshSessionModal');
|
||||
modal.classList.add('opacity-0', 'pointer-events-none');
|
||||
modal.classList.remove('opacity-100', 'pointer-events-auto');
|
||||
document.documentElement.style.overflow = '';
|
||||
document.body.style.overflow = '';
|
||||
}
|
||||
|
||||
// 执行刷新 Session
|
||||
async function doRefreshSession() {
|
||||
const btn = document.querySelector('#refreshSessionModal button[onclick="doRefreshSession()"]');
|
||||
if (btn) { btn.disabled = true; btn.textContent = '刷新中…'; }
|
||||
const loadingToast = showToast('正在刷新登录状态…', 'info', 30000);
|
||||
try {
|
||||
const data = await apiRequest('/api/user/session/refresh', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({})
|
||||
});
|
||||
loadingToast.remove();
|
||||
|
||||
if (data.success) {
|
||||
showToast(data.message || '刷新成功', 'success');
|
||||
document.getElementById('refreshResult').innerHTML = `<div class="p-3 bg-green-50 dark:bg-green-900/20 text-green-800 dark:text-green-200 rounded-lg text-sm">${data.message}</div>`;
|
||||
setTimeout(() => {
|
||||
closeRefreshSessionModal();
|
||||
checkSessionStatus();
|
||||
}, 1500);
|
||||
} else {
|
||||
showToast(data.message || '刷新失败', 'error');
|
||||
document.getElementById('refreshResult').innerHTML = `<div class="p-3 bg-red-50 dark:bg-red-900/20 text-red-800 dark:text-red-200 rounded-lg text-sm">${data.message}</div>`;
|
||||
}
|
||||
} catch (error) {
|
||||
loadingToast.remove();
|
||||
showToast('刷新失败,请稍后重试', 'error');
|
||||
document.getElementById('refreshResult').innerHTML = '<div class="p-3 bg-red-50 dark:bg-red-900/20 text-red-800 dark:text-red-200 rounded-lg text-sm">刷新失败</div>';
|
||||
} finally {
|
||||
if (btn) { btn.disabled = false; btn.textContent = '刷新'; }
|
||||
}
|
||||
}
|
||||
|
||||
// 显示配置模态框
|
||||
function showJwxtConfigModal() {
|
||||
document.getElementById('configJwxtUsername').value = '';
|
||||
document.getElementById('configJwxtPassword').value = '';
|
||||
document.getElementById('configJwxtName').value = '';
|
||||
document.getElementById('configResult').innerHTML = '';
|
||||
const modal = document.getElementById('jwxtConfigModal');
|
||||
modal.classList.remove('opacity-0', 'pointer-events-none');
|
||||
modal.classList.add('opacity-100', 'pointer-events-auto');
|
||||
document.documentElement.style.overflow = 'hidden';
|
||||
document.body.style.overflow = 'hidden';
|
||||
}
|
||||
|
||||
function closeJwxtConfigModal() {
|
||||
const modal = document.getElementById('jwxtConfigModal');
|
||||
modal.classList.add('opacity-0', 'pointer-events-none');
|
||||
modal.classList.remove('opacity-100', 'pointer-events-auto');
|
||||
document.documentElement.style.overflow = '';
|
||||
document.body.style.overflow = '';
|
||||
}
|
||||
|
||||
// 保存教务系统配置
|
||||
async function saveJwxtConfig() {
|
||||
const username = document.getElementById('configJwxtUsername').value.trim();
|
||||
const password = document.getElementById('configJwxtPassword').value.trim();
|
||||
const name = document.getElementById('configJwxtName').value.trim();
|
||||
|
||||
if (!username || !password) {
|
||||
document.getElementById('configResult').innerHTML = '<div class="p-3 bg-amber-50 dark:bg-amber-900/20 text-amber-800 dark:text-amber-200 rounded-lg text-sm">请填写学号和密码</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
const btn = document.querySelector('#jwxtConfigModal button[onclick="saveJwxtConfig()"]');
|
||||
if (btn) { btn.disabled = true; btn.textContent = '登录中…'; }
|
||||
const loadingToast = showToast('正在登录教务系统…', 'info', 30000);
|
||||
|
||||
try {
|
||||
const data = await apiRequest('/api/user/jwxt/config', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
jwxt_username: username,
|
||||
jwxt_password: password,
|
||||
jwxt_name: name
|
||||
})
|
||||
});
|
||||
loadingToast.remove();
|
||||
|
||||
if (data.success) {
|
||||
showToast(data.message || '登录成功', 'success');
|
||||
document.getElementById('configResult').innerHTML = `<div class="p-3 bg-green-50 dark:bg-green-900/20 text-green-800 dark:text-green-200 rounded-lg text-sm">${data.message}</div>`;
|
||||
setTimeout(() => {
|
||||
closeJwxtConfigModal();
|
||||
checkSessionStatus();
|
||||
}, 1500);
|
||||
} else {
|
||||
showToast(data.message || '登录失败', 'error');
|
||||
document.getElementById('configResult').innerHTML = `<div class="p-3 bg-red-50 dark:bg-red-900/20 text-red-800 dark:text-red-200 rounded-lg text-sm">${data.message}</div>`;
|
||||
}
|
||||
} catch (error) {
|
||||
loadingToast.remove();
|
||||
showToast('配置失败,请稍后重试', 'error');
|
||||
document.getElementById('configResult').innerHTML = '<div class="p-3 bg-red-50 dark:bg-red-900/20 text-red-800 dark:text-red-200 rounded-lg text-sm">配置失败</div>';
|
||||
} finally {
|
||||
if (btn) { btn.disabled = false; btn.textContent = '保存并验证'; }
|
||||
}
|
||||
}
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,116 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
{% block title %}学籍异动申请 - {{ brand_name }}{% endblock %}
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
@keyframes fadeSlideIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
|
||||
.row-animate { animation: fadeSlideIn 0.3s ease both; }
|
||||
@media (prefers-reduced-motion: reduce) { .row-animate, .list-item-enter { animation: none !important; opacity: 1 !important; } }
|
||||
.badge { display: inline-flex; align-items: center; padding: 2px 8px; border-radius: 9999px; font-size: 11px; font-weight: 500; }
|
||||
.badge-green { background: #dcfce7; color: #166534; }
|
||||
.badge-yellow { background: #fef9c3; color: #854d0e; }
|
||||
.badge-gray { background: #f3f4f6; color: #4b5563; }
|
||||
.dark .badge-green { background: #14532d; color: #bbf7d0; }
|
||||
.dark .badge-yellow { background: #713f12; color: #fef08a; }
|
||||
.dark .badge-gray { background: #374151; color: #d1d5db; }
|
||||
.change-type-btn { display: inline-flex; align-items: center; padding: 6px 14px; border: 1px solid #d1d5db; border-radius: 8px; font-size: 13px; cursor: pointer; transition: all .15s; background: transparent; }
|
||||
.change-type-btn:hover { border-color: #000; background: #f5f5f5; }
|
||||
.dark .change-type-btn { border-color: #404040; color: #ccc; }
|
||||
.dark .change-type-btn:hover { border-color: #fff; background: #262626; color: #fff; }
|
||||
</style>
|
||||
{% endblock %}
|
||||
{% block content %}
|
||||
<div>
|
||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 list-item-enter" style="animation-delay:0ms;">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>
|
||||
学籍异动申请
|
||||
</h2>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">2025-2026学年2学期的学籍异动申请</p>
|
||||
</div>
|
||||
<button onclick="loadData()" class="px-4 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm font-medium hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors flex items-center gap-2"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>刷新</button>
|
||||
</div>
|
||||
|
||||
<!-- 可申请的异动类别 -->
|
||||
<div class="glass rounded-2xl p-4 mb-4 list-item-enter" style="animation-delay:50ms;">
|
||||
<p class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">可申请的异动类别:</p>
|
||||
<div id="changeTypesContainer" class="flex flex-wrap gap-2">
|
||||
<span class="text-gray-400 text-sm">加载中...</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="loadingIndicator" class="text-center py-12 hidden"><div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div><p class="text-gray-500 dark:text-gray-400">加载中...</p></div>
|
||||
<div id="errorMessage" class="glass rounded-2xl p-6 mb-4 text-center hidden"><p id="errorText" class="text-red-500"></p></div>
|
||||
<div id="dataContainer" class="hidden list-item-enter" style="animation-delay:100ms;">
|
||||
<div class="glass rounded-2xl overflow-hidden">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead>
|
||||
<tr class="border-b border-gray-200 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-800/50">
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap">申请状态</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap">审核状态</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap">异动学年</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap">异动学期</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap">异动类别</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap">异动原因</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap">申请理由</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap">联系电话</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="tableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="emptyState" class="glass rounded-2xl p-12 text-center hidden"><p class="text-gray-500 dark:text-gray-400 text-lg">暂无学籍异动申请记录</p></div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block extra_js %}
|
||||
<script>
|
||||
async function loadData() {
|
||||
document.getElementById('loadingIndicator').classList.remove('hidden');
|
||||
document.getElementById('errorMessage').classList.add('hidden');
|
||||
document.getElementById('dataContainer').classList.add('hidden');
|
||||
document.getElementById('emptyState').classList.add('hidden');
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/enrollment-change');
|
||||
const data = await res.json();
|
||||
document.getElementById('loadingIndicator').classList.add('hidden');
|
||||
if (!data.success) { showError(data.message); return; }
|
||||
|
||||
// 显示可申请的异动类型
|
||||
const ctContainer = document.getElementById('changeTypesContainer');
|
||||
if (data.change_types && data.change_types.length > 0) {
|
||||
ctContainer.innerHTML = data.change_types.map(t =>
|
||||
`<span class="change-type-btn">${escHtml(t.label||t.value)}</span>`
|
||||
).join('');
|
||||
} else {
|
||||
ctContainer.innerHTML = '<span class="text-gray-400 text-sm">无非当前可申请的异动类型</span>';
|
||||
}
|
||||
|
||||
const items = data.items || [];
|
||||
if (!items.length) { document.getElementById('emptyState').classList.remove('hidden'); return; }
|
||||
const tbody = document.getElementById('tableBody');
|
||||
tbody.innerHTML = items.map((item, i) => {
|
||||
const sqzt = item.sqztmc || item.申请状态 || '--';
|
||||
const shzt = item.shztmc || item.审核状态 || '--';
|
||||
const shBadge = shzt.includes('通过') ? 'badge-green' : shzt.includes('待审') ? 'badge-yellow' : 'badge-gray';
|
||||
return `<tr class="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50/50 dark:hover:bg-gray-800/30 transition-colors row-animate" style="animation-delay:${i*30}ms;">
|
||||
<td class="py-3 px-4 text-xs">${escHtml(sqzt)}</td>
|
||||
<td class="py-3 px-4"><span class="badge ${shBadge}">${escHtml(shzt)}</span></td>
|
||||
<td class="py-3 px-4 text-xs text-gray-500">${escHtml(item.ydxn||item.异动学年||'--')}</td>
|
||||
<td class="py-3 px-4 text-xs text-gray-500">${escHtml(item.ydxq||item.异动学期||'--')}</td>
|
||||
<td class="py-3 px-4 text-xs">${escHtml(item.ydlbmc||item.异动类别||'--')}</td>
|
||||
<td class="py-3 px-4 text-xs text-gray-500">${escHtml(item.ydyy||item.异动原因||'--')}</td>
|
||||
<td class="py-3 px-4 text-xs text-gray-500 max-w-[200px] truncate">${escHtml(item.sqly||item.申请理由||'--')}</td>
|
||||
<td class="py-3 px-4 text-xs">${escHtml(item.lxdh||item.联系电话||'--')}</td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
document.getElementById('dataContainer').classList.remove('hidden');
|
||||
} catch(e) { document.getElementById('loadingIndicator').classList.add('hidden'); showError('网络错误: '+e.message); }
|
||||
}
|
||||
function showError(msg) { document.getElementById('errorText').textContent = msg; document.getElementById('errorMessage').classList.remove('hidden'); }
|
||||
function escHtml(s) { if(s==null) return ''; return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"'); }
|
||||
document.addEventListener('DOMContentLoaded', () => loadData());
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,218 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
{% block title %}考级项目报名 - {{ brand_name }}{% endblock %}
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
@keyframes fadeSlideIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
|
||||
.row-animate { animation: fadeSlideIn 0.3s ease both; }
|
||||
@media (prefers-reduced-motion: reduce) { .row-animate, .list-item-enter { animation: none !important; opacity: 1 !important; } }
|
||||
.table-wrap { overflow-x: auto; -webkit-overflow-scrolling: touch; }
|
||||
.table-wrap table { min-width: 1800px; }
|
||||
.badge { display: inline-flex; align-items: center; padding: 2px 8px; border-radius: 9999px; font-size: 11px; font-weight: 500; }
|
||||
.badge-green { background: #dcfce7; color: #166534; }
|
||||
.badge-yellow { background: #fef9c3; color: #854d0e; }
|
||||
.badge-gray { background: #f3f4f6; color: #4b5563; }
|
||||
.badge-blue { background: #dbeafe; color: #1e40af; }
|
||||
.dark .badge-green { background: #14532d; color: #bbf7d0; }
|
||||
.dark .badge-yellow { background: #713f12; color: #fef08a; }
|
||||
.dark .badge-gray { background: #374151; color: #d1d5db; }
|
||||
.dark .badge-blue { background: #1e3a5f; color: #93c5fd; }
|
||||
.modal-overlay { position: fixed; inset: 0; z-index: 100; background: rgba(0,0,0,.5); display: flex; align-items: center; justify-content: center; }
|
||||
.modal-box { background: #fff; border-radius: 16px; max-width: 95vw; max-height: 85vh; overflow: hidden; display: flex; flex-direction: column; box-shadow: 0 25px 60px rgba(0,0,0,.3); }
|
||||
.dark .modal-box { background: #1a1a1a; }
|
||||
.modal-header { display: flex; justify-content: space-between; align-items: center; padding: 16px 20px; border-bottom: 1px solid #e5e5e5; }
|
||||
.dark .modal-header { border-color: #333; }
|
||||
.modal-body { padding: 16px 20px; overflow-y: auto; flex: 1; }
|
||||
</style>
|
||||
{% endblock %}
|
||||
{% block content %}
|
||||
<div>
|
||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 list-item-enter" style="animation-delay:0ms;">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>
|
||||
考级项目报名
|
||||
</h2>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">等级考试报名信息查询</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<span id="semesterLabel" class="text-sm font-medium text-gray-600 dark:text-gray-400"></span>
|
||||
<button onclick="loadExpired()" class="px-3 py-1.5 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-xs font-medium hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors">✉ 本学期过期项目报名信息</button>
|
||||
<button onclick="loadData()" class="px-3 py-1.5 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-xs font-medium hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors flex items-center gap-1"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>刷新</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="loadingIndicator" class="text-center py-12 hidden"><div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div><p class="text-gray-500 dark:text-gray-400">加载中...</p></div>
|
||||
<div id="errorMessage" class="glass rounded-2xl p-6 mb-4 text-center hidden"><p id="errorText" class="text-red-500"></p></div>
|
||||
<div id="dataContainer" class="hidden list-item-enter" style="animation-delay:100ms;">
|
||||
<div class="glass rounded-2xl overflow-hidden">
|
||||
<div class="table-wrap">
|
||||
<table class="w-full text-sm">
|
||||
<thead>
|
||||
<tr class="border-b border-gray-200 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-800/50">
|
||||
<th class="text-left py-3 px-3 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap text-xs">流程跟踪</th>
|
||||
<th class="text-left py-3 px-3 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap text-xs">审核状态</th>
|
||||
<th class="text-left py-3 px-3 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap text-xs">缴费状态</th>
|
||||
<th class="text-left py-3 px-3 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap text-xs">报名学年</th>
|
||||
<th class="text-left py-3 px-3 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap text-xs">报名学期</th>
|
||||
<th class="text-left py-3 px-3 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap text-xs">报名批次</th>
|
||||
<th class="text-left py-3 px-3 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap text-xs">项目类别</th>
|
||||
<th class="text-left py-3 px-3 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap text-xs">项目名称</th>
|
||||
<th class="text-left py-3 px-3 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap text-xs">项目成绩</th>
|
||||
<th class="text-left py-3 px-3 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap text-xs">成绩明细</th>
|
||||
<th class="text-right py-3 px-3 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap text-xs">报名费用</th>
|
||||
<th class="text-left py-3 px-3 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap text-xs">证件类型</th>
|
||||
<th class="text-left py-3 px-3 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap text-xs">证件号码</th>
|
||||
<th class="text-left py-3 px-3 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap text-xs">准考证号</th>
|
||||
<th class="text-left py-3 px-3 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap text-xs">考试时间</th>
|
||||
<th class="text-left py-3 px-3 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap text-xs">考试地点</th>
|
||||
<th class="text-left py-3 px-3 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap text-xs">考场号</th>
|
||||
<th class="text-left py-3 px-3 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap text-xs">座位号</th>
|
||||
<th class="text-left py-3 px-3 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap text-xs">手机号码</th>
|
||||
<th class="text-left py-3 px-3 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap text-xs">校区</th>
|
||||
<th class="text-left py-3 px-3 font-semibold text-gray-700 dark:text-gray-300 whitespace-nowrap text-xs">备注</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="tableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="emptyState" class="glass rounded-2xl p-12 text-center hidden"><p class="text-gray-500 dark:text-gray-400 text-lg">暂无考级报名信息</p></div>
|
||||
</div>
|
||||
|
||||
<!-- 过期项目弹窗 -->
|
||||
<div id="expiredModal" class="modal-overlay hidden" onclick="if(event.target===this)closeExpiredModal()">
|
||||
<div class="modal-box w-full max-w-4xl">
|
||||
<div class="modal-header">
|
||||
<h3 class="text-lg font-bold">查询过期项目</h3>
|
||||
<button onclick="closeExpiredModal()" class="p-1 hover:bg-gray-100 dark:hover:bg-gray-800 rounded transition-colors text-xl leading-none">×</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div id="expiredLoading" class="text-center py-8"><div class="w-8 h-8 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-3"></div><p class="text-gray-500 text-sm">加载中...</p></div>
|
||||
<div id="expiredError" class="text-center py-8 text-red-500 hidden"></div>
|
||||
<div id="expiredContent" class="hidden">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead>
|
||||
<tr class="border-b border-gray-200 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-800/50">
|
||||
<th class="text-left py-2 px-3 font-semibold text-xs text-gray-700 dark:text-gray-300">报名学年</th>
|
||||
<th class="text-left py-2 px-3 font-semibold text-xs text-gray-700 dark:text-gray-300">报名学期</th>
|
||||
<th class="text-left py-2 px-3 font-semibold text-xs text-gray-700 dark:text-gray-300">项目类别</th>
|
||||
<th class="text-left py-2 px-3 font-semibold text-xs text-gray-700 dark:text-gray-300">项目名称</th>
|
||||
<th class="text-left py-2 px-3 font-semibold text-xs text-gray-700 dark:text-gray-300">报名批次</th>
|
||||
<th class="text-right py-2 px-3 font-semibold text-xs text-gray-700 dark:text-gray-300">人数限制</th>
|
||||
<th class="text-left py-2 px-3 font-semibold text-xs text-gray-700 dark:text-gray-300">开始时间</th>
|
||||
<th class="text-left py-2 px-3 font-semibold text-xs text-gray-700 dark:text-gray-300">结束时间</th>
|
||||
<th class="text-right py-2 px-3 font-semibold text-xs text-gray-700 dark:text-gray-300">费用</th>
|
||||
<th class="text-center py-2 px-3 font-semibold text-xs text-gray-700 dark:text-gray-300">可退</th>
|
||||
<th class="text-center py-2 px-3 font-semibold text-xs text-gray-700 dark:text-gray-300">可补考</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="expiredTableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div id="expiredSummary" class="text-xs text-gray-500 text-right mt-3"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-end px-5 py-3 border-t border-gray-100 dark:border-gray-800">
|
||||
<button onclick="closeExpiredModal()" class="px-6 py-2 rounded-lg bg-black dark:bg-white text-white dark:text-black text-sm font-medium hover:opacity-85 transition-opacity">关 闭</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block extra_js %}
|
||||
<script>
|
||||
function v(item, keys) {
|
||||
for (const k of keys) { const val = item[k]; if (val != null && val !== '') return val; }
|
||||
return '--';
|
||||
}
|
||||
|
||||
async function loadData() {
|
||||
showLoading();
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/exam-registration');
|
||||
const data = await res.json();
|
||||
hideLoading();
|
||||
if (!data.success) { showError(data.message); return; }
|
||||
const items = data.items || [];
|
||||
if (!items.length) { showEmpty('暂无考级报名信息'); return; }
|
||||
renderTable(items);
|
||||
} catch(e) { hideLoading(); showError('网络错误: '+e.message); }
|
||||
}
|
||||
|
||||
function renderTable(items) {
|
||||
const tbody = document.getElementById('tableBody');
|
||||
tbody.innerHTML = items.map((item, i) => {
|
||||
const shzt = v(item, ['shztmc', 'shzt', '审核状态']);
|
||||
const jfzt = v(item, ['jfzt', 'jfztmc', '缴费状态']);
|
||||
const shBadge = shzt.includes('通过') ? 'badge-green' : shzt.includes('待审') ? 'badge-yellow' : shzt.includes('缴费') ? 'badge-blue' : 'badge-gray';
|
||||
const jfBadge = jfzt.includes('已缴') ? 'badge-green' : jfzt.includes('未缴') ? 'badge-yellow' : 'badge-gray';
|
||||
return `<tr class="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50/50 dark:hover:bg-gray-800/30 transition-colors row-animate" style="animation-delay:${i*30}ms;">
|
||||
<td class="py-2.5 px-3 text-xs">${escHtml(v(item,['lczz','流程跟踪']))}</td>
|
||||
<td class="py-2.5 px-3"><span class="badge ${shBadge}">${escHtml(shzt)}</span></td>
|
||||
<td class="py-2.5 px-3"><span class="badge ${jfBadge}">${escHtml(jfzt)}</span></td>
|
||||
<td class="py-2.5 px-3 text-xs text-gray-500">${escHtml(v(item,['bmdxnm','xnm','报名学年']))}</td>
|
||||
<td class="py-2.5 px-3 text-xs text-gray-500">${escHtml(v(item,['bmdxqm','xqm','报名学期']))}</td>
|
||||
<td class="py-2.5 px-3 text-xs text-gray-500">${escHtml(v(item,['bmpc','bmpcmc','报名批次']))}</td>
|
||||
<td class="py-2.5 px-3 text-xs">${escHtml(v(item,['xmlbmc','xmlb','项目类别']))}</td>
|
||||
<td class="py-2.5 px-3 font-medium">${escHtml(v(item,['xmmc','项目名称']))}</td>
|
||||
<td class="py-2.5 px-3 text-xs">${escHtml(v(item,['xmcj','项目成绩']))}</td>
|
||||
<td class="py-2.5 px-3 text-xs text-blue-500">${escHtml(v(item,['cjmx','成绩明细']))}</td>
|
||||
<td class="py-2.5 px-3 text-right text-xs font-medium">${escHtml(v(item,['bmfy','报名费用(元)','fy','费用']))}</td>
|
||||
<td class="py-2.5 px-3 text-xs text-gray-500">${escHtml(v(item,['zjlxmc','zjlx','证件类型']))}</td>
|
||||
<td class="py-2.5 px-3 text-xs">${escHtml(v(item,['zjhm','证件号码']))}</td>
|
||||
<td class="py-2.5 px-3 text-xs">${escHtml(v(item,['zkzh','准考证号']))}</td>
|
||||
<td class="py-2.5 px-3 text-xs text-gray-500">${escHtml(v(item,['kssj','考试时间']))}</td>
|
||||
<td class="py-2.5 px-3 text-xs">${escHtml(v(item,['ksdd','kscd','考试地点']))}</td>
|
||||
<td class="py-2.5 px-3 text-xs text-gray-500">${escHtml(v(item,['kch','考场号']))}</td>
|
||||
<td class="py-2.5 px-3 text-xs text-gray-500">${escHtml(v(item,['zwh','座位号']))}</td>
|
||||
<td class="py-2.5 px-3 text-xs">${escHtml(v(item,['sjhm','手机号码']))}</td>
|
||||
<td class="py-2.5 px-3 text-xs text-gray-500">${escHtml(v(item,['xqmc','校区']))}</td>
|
||||
<td class="py-2.5 px-3 text-xs text-gray-400 max-w-[120px] truncate">${escHtml(v(item,['bz','备注']))}</td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
document.getElementById('dataContainer').classList.remove('hidden');
|
||||
document.getElementById('emptyState').classList.add('hidden');
|
||||
}
|
||||
|
||||
async function loadExpired() {
|
||||
document.getElementById('expiredModal').classList.remove('hidden');
|
||||
document.getElementById('expiredLoading').classList.remove('hidden');
|
||||
document.getElementById('expiredError').classList.add('hidden');
|
||||
document.getElementById('expiredContent').classList.add('hidden');
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/exam-registration/expired');
|
||||
const data = await res.json();
|
||||
document.getElementById('expiredLoading').classList.add('hidden');
|
||||
if (!data.success) { document.getElementById('expiredError').textContent = data.message; document.getElementById('expiredError').classList.remove('hidden'); return; }
|
||||
const items = data.items || [];
|
||||
if (!items.length) { document.getElementById('expiredError').textContent = '暂无过期报名信息'; document.getElementById('expiredError').classList.remove('hidden'); return; }
|
||||
const tbody = document.getElementById('expiredTableBody');
|
||||
tbody.innerHTML = items.map((item, i) => `
|
||||
<tr class="border-b border-gray-100 dark:border-gray-800 row-animate" style="animation-delay:${i*30}ms;">
|
||||
<td class="py-2 px-3 text-xs">${escHtml(item.xnmc||'--')}</td>
|
||||
<td class="py-2 px-3 text-xs">${escHtml(item.xqmmc||'--')}</td>
|
||||
<td class="py-2 px-3 text-xs">${escHtml(item.xmlbmc||'--')}</td>
|
||||
<td class="py-2 px-3 text-xs font-medium">${escHtml(item.xmmc||'--')}</td>
|
||||
<td class="py-2 px-3 text-xs">${escHtml(item.bmpc||'--')}</td>
|
||||
<td class="py-2 px-3 text-xs text-right">${escHtml(item.rszgxz||'--')}</td>
|
||||
<td class="py-2 px-3 text-xs text-gray-500">${escHtml(item.kssj||'--')}</td>
|
||||
<td class="py-2 px-3 text-xs text-gray-500">${escHtml(item.jssj||'--')}</td>
|
||||
<td class="py-2 px-3 text-xs text-right font-medium">${escHtml(item.bmfy||'--')}</td>
|
||||
<td class="py-2 px-3 text-xs text-center">${item.sfkt==='1'?'✅':'❌'}</td>
|
||||
<td class="py-2 px-3 text-xs text-center">${item.sfkbk==='1'?'✅':'❌'}</td>
|
||||
</tr>
|
||||
`).join('');
|
||||
document.getElementById('expiredSummary').textContent = `共 ${items.length} 条记录`;
|
||||
document.getElementById('expiredContent').classList.remove('hidden');
|
||||
} catch(e) { document.getElementById('expiredLoading').classList.add('hidden'); document.getElementById('expiredError').textContent = '加载失败: '+e.message; document.getElementById('expiredError').classList.remove('hidden'); }
|
||||
}
|
||||
|
||||
function closeExpiredModal() { document.getElementById('expiredModal').classList.add('hidden'); }
|
||||
function showLoading() { document.getElementById('loadingIndicator').classList.remove('hidden'); document.getElementById('errorMessage').classList.add('hidden'); document.getElementById('dataContainer').classList.add('hidden'); document.getElementById('emptyState').classList.add('hidden'); }
|
||||
function hideLoading() { document.getElementById('loadingIndicator').classList.add('hidden'); }
|
||||
function showError(msg) { document.getElementById('errorText').textContent = msg; document.getElementById('errorMessage').classList.remove('hidden'); }
|
||||
function showEmpty(msg) { document.getElementById('emptyState').classList.remove('hidden'); document.getElementById('emptyState').querySelector('p').textContent = msg; }
|
||||
function escHtml(s) { if(s==null) return ''; return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"'); }
|
||||
document.addEventListener('DOMContentLoaded', () => loadData());
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,452 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
|
||||
{% block title %}考试安排 - {{ brand_name }}{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
@keyframes fadeSlideIn {
|
||||
from { opacity: 0; transform: translateY(8px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.row-animate {
|
||||
animation: fadeSlideIn 0.3s ease both;
|
||||
}
|
||||
|
||||
.exam-card {
|
||||
transition: all 0.25s ease;
|
||||
}
|
||||
.exam-card:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 8px 25px rgba(0,0,0,0.08);
|
||||
}
|
||||
.dark .exam-card:hover {
|
||||
box-shadow: 0 8px 25px rgba(0,0,0,0.4);
|
||||
}
|
||||
|
||||
.status-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
padding: 0.125rem 0.75rem;
|
||||
border-radius: 9999px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
.status-upcoming {
|
||||
background: #dbeafe;
|
||||
color: #1d4ed8;
|
||||
}
|
||||
.status-ongoing {
|
||||
background: #dcfce7;
|
||||
color: #16a34a;
|
||||
}
|
||||
.status-past {
|
||||
background: #f3f4f6;
|
||||
color: #6b7280;
|
||||
}
|
||||
.dark .status-upcoming {
|
||||
background: #1e3a5f;
|
||||
color: #93c5fd;
|
||||
}
|
||||
.dark .status-ongoing {
|
||||
background: #14532d;
|
||||
color: #86efac;
|
||||
}
|
||||
.dark .status-past {
|
||||
background: #374151;
|
||||
color: #9ca3af;
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.fade-slide-in { animation: none !important; opacity: 1 !important; }
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
<!-- 页面标题 -->
|
||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 list-item-enter" style="animation-delay: 0ms;">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<rect x="3" y="4" width="18" height="18" rx="2" ry="2"/>
|
||||
<line x1="16" y1="2" x2="16" y2="6"/>
|
||||
<line x1="8" y1="2" x2="8" y2="6"/>
|
||||
<line x1="3" y1="10" x2="21" y2="10"/>
|
||||
<line x1="8" y1="14" x2="8" y2="14.01"/>
|
||||
<line x1="12" y1="14" x2="12" y2="14.01"/>
|
||||
<line x1="16" y1="14" x2="16" y2="14.01"/>
|
||||
<line x1="8" y1="18" x2="8" y2="18.01"/>
|
||||
<line x1="12" y1="18" x2="12" y2="18.01"/>
|
||||
<line x1="16" y1="18" x2="16" y2="18.01"/>
|
||||
</svg>
|
||||
考试安排
|
||||
</h2>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">查看本学期考试时间与地点</p>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-3 items-center">
|
||||
<select id="semesterSelect"
|
||||
class="px-4 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-black dark:focus:ring-white">
|
||||
<option value="">当前学期</option>
|
||||
</select>
|
||||
<button onclick="refreshExams()"
|
||||
class="px-4 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm font-medium hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<polyline points="23 4 23 10 17 10"/>
|
||||
<path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>
|
||||
</svg>
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 加载提示 -->
|
||||
<div id="loadingIndicator" class="text-center py-12 list-item-enter" style="animation-delay: 100ms;">
|
||||
<div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
|
||||
<p class="text-gray-500 dark:text-gray-400">正在加载考试安排...</p>
|
||||
</div>
|
||||
|
||||
<!-- 图表区 -->
|
||||
<div id="chartsRow" class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6 hidden">
|
||||
<div class="glass rounded-2xl p-4">
|
||||
<h3 class="text-sm font-semibold text-gray-600 dark:text-gray-400 mb-3">考试日期分布</h3>
|
||||
<div id="examDateChart" class="h-64"></div>
|
||||
</div>
|
||||
<div class="glass rounded-2xl p-4">
|
||||
<h3 class="text-sm font-semibold text-gray-600 dark:text-gray-400 mb-3">考试形式分布</h3>
|
||||
<div id="examTypeChart" class="h-64"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 错误提示 -->
|
||||
<div id="errorMessage" class="glass rounded-2xl p-6 mb-4 text-center hidden list-item-enter" style="animation-delay: 100ms;">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"
|
||||
class="mx-auto mb-4 text-red-500">
|
||||
<circle cx="12" cy="12" r="10"/>
|
||||
<line x1="15" y1="9" x2="9" y2="15"/>
|
||||
<line x1="9" y1="9" x2="15" y2="15"/>
|
||||
</svg>
|
||||
<p id="errorText" class="text-gray-600 dark:text-gray-400"></p>
|
||||
</div>
|
||||
|
||||
<!-- 考试卡片列表 -->
|
||||
<div id="examsContainer" class="hidden list-item-enter grid grid-cols-1 lg:grid-cols-2 gap-4" style="animation-delay: 150ms;">
|
||||
</div>
|
||||
|
||||
<!-- 空状态 -->
|
||||
<div id="emptyState" class="glass rounded-2xl p-12 text-center hidden list-item-enter" style="animation-delay: 150ms;">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round"
|
||||
class="mx-auto mb-4 text-gray-300 dark:text-gray-600">
|
||||
<rect x="3" y="4" width="18" height="18" rx="2" ry="2"/>
|
||||
<line x1="16" y1="2" x2="16" y2="6"/>
|
||||
<line x1="8" y1="2" x2="8" y2="6"/>
|
||||
<line x1="3" y1="10" x2="21" y2="10"/>
|
||||
</svg>
|
||||
<p class="text-gray-500 dark:text-gray-400 text-lg">暂无考试安排</p>
|
||||
<p class="text-gray-400 dark:text-gray-500 text-sm mt-1">可能尚未发布或已全部结束</p>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script src="{{ url_for('static', filename='echarts.min.js') }}"></script>
|
||||
<script>
|
||||
let examDateChart = null;
|
||||
let examTypeChart = null;
|
||||
|
||||
// ── 深色模式 ──
|
||||
function isDarkMode() { return document.documentElement.classList.contains('dark'); }
|
||||
|
||||
// ── Session 健康检查 ──
|
||||
async function initSession() {
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/ping');
|
||||
const data = await res.json();
|
||||
if (!data.success) { console.warn('Session ping 失败:', data.message); return false; }
|
||||
if (data.refreshed) console.log('🔄 Session 已自动刷新');
|
||||
return true;
|
||||
} catch (e) { console.error('Session ping 异常:', e); return false; }
|
||||
}
|
||||
|
||||
async function loadSemesters() {
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/semesters');
|
||||
const data = await res.json();
|
||||
if (data.success && data.semesters) {
|
||||
const sel = document.getElementById('semesterSelect');
|
||||
data.semesters.forEach(s => {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = s.id;
|
||||
opt.textContent = s.name || s.id;
|
||||
sel.appendChild(opt);
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('加载学期列表失败:', e);
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshExams() {
|
||||
const loading = document.getElementById('loadingIndicator');
|
||||
const error = document.getElementById('errorMessage');
|
||||
const container = document.getElementById('examsContainer');
|
||||
const empty = document.getElementById('emptyState');
|
||||
|
||||
loading.classList.remove('hidden');
|
||||
error.classList.add('hidden');
|
||||
container.classList.add('hidden');
|
||||
empty.classList.add('hidden');
|
||||
|
||||
const semester = document.getElementById('semesterSelect').value;
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/exams?' + new URLSearchParams({ semester }));
|
||||
const data = await res.json();
|
||||
|
||||
loading.classList.add('hidden');
|
||||
|
||||
if (!data.success) {
|
||||
showError(data.message || '查询失败');
|
||||
return;
|
||||
}
|
||||
|
||||
const exams = data.items || [];
|
||||
|
||||
if (exams.length === 0) {
|
||||
empty.classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
|
||||
renderExams(exams);
|
||||
container.classList.remove('hidden');
|
||||
|
||||
// 渲染图表
|
||||
const chartsRow = document.getElementById('chartsRow');
|
||||
chartsRow.classList.remove('hidden');
|
||||
renderExamDateChart(exams);
|
||||
renderExamTypeChart(exams);
|
||||
setupDarkObserver(exams);
|
||||
} catch (e) {
|
||||
loading.classList.add('hidden');
|
||||
showError('网络错误: ' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
// 正方系统 kssj 格式: "2026-07-09(10:30-12:10)" 或 "2026-07-09"
|
||||
function parseKssj(kssj) {
|
||||
const m = (kssj || '').match(/^(\d{4}-\d{2}-\d{2})(?:\((\d{2}:\d{2})-(\d{2}:\d{2})\))?$/);
|
||||
if (m) return { date: m[1], startTime: m[2] || '', endTime: m[3] || '' };
|
||||
const fallback = (kssj || '').match(/^(\d{4})[年-](\d{1,2})[月-](\d{1,2})/);
|
||||
if (fallback) {
|
||||
const y = fallback[1], mo = fallback[2].padStart(2,'0'), d = fallback[3].padStart(2,'0');
|
||||
return { date: y + '-' + mo + '-' + d };
|
||||
}
|
||||
return { date: kssj || '--' };
|
||||
}
|
||||
|
||||
function getExamStatus(kssj) {
|
||||
const parsed = parseKssj(kssj);
|
||||
const dateStr = parsed.date;
|
||||
if (dateStr === '--') return { status: 'unknown', label: '未知', class: 'status-past' };
|
||||
|
||||
const d = new Date(dateStr + (parsed.startTime ? 'T' + parsed.startTime : ''));
|
||||
const now = new Date();
|
||||
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
const examDay = new Date(d.getFullYear(), d.getMonth(), d.getDate());
|
||||
|
||||
if (examDay < today) return { status: 'past', label: '已结束', class: 'status-past' };
|
||||
if (examDay > today) return { status: 'upcoming', label: '即将考试', class: 'status-upcoming' };
|
||||
|
||||
if (!parsed.startTime || !parsed.endTime) return { status: 'ongoing', label: '今日考试', class: 'status-ongoing' };
|
||||
|
||||
const toMin = s => { const p = s.split(':'); return parseInt(p[0])*60 + parseInt(p[1]); };
|
||||
const nowMin = now.getHours() * 60 + now.getMinutes();
|
||||
const startMin = toMin(parsed.startTime);
|
||||
const endMin = toMin(parsed.endTime);
|
||||
|
||||
if (nowMin < startMin) return { status: 'upcoming', label: '即将考试', class: 'status-upcoming' };
|
||||
if (nowMin > endMin) return { status: 'past', label: '已结束', class: 'status-past' };
|
||||
return { status: 'ongoing', label: '正在考试', class: 'status-ongoing' };
|
||||
}
|
||||
|
||||
function renderExams(exams) {
|
||||
const container = document.getElementById('examsContainer');
|
||||
container.innerHTML = '';
|
||||
|
||||
// 按考试时间排序
|
||||
exams.sort((a, b) => {
|
||||
const da = a.kssj || '';
|
||||
const db = b.kssj || '';
|
||||
return da.localeCompare(db);
|
||||
});
|
||||
|
||||
exams.forEach((item, idx) => {
|
||||
const courseName = item.kcmc || item.KCMC || item['课程名称'] || '未知课程';
|
||||
const parsed = parseKssj(item.kssj);
|
||||
const examDate = parsed.date;
|
||||
const examTime = parsed.startTime && parsed.endTime ? `${parsed.startTime} ~ ${parsed.endTime}` : (item.kssj || '--');
|
||||
const location = item.cdmc || item.KSDD || item['考试地点'] || '--';
|
||||
const examType = item.khfs || item.ksxs || item.KSXS || item['考试形式'] || '--';
|
||||
const campus = item.cdxqmc || item.xqmc || item.XQMC || '--';
|
||||
const teacher = item.jsxx || '--';
|
||||
|
||||
const status = getExamStatus(item.kssj);
|
||||
const delay = idx * 60;
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'exam-card glass rounded-2xl p-5 row-animate';
|
||||
card.style.animationDelay = delay + 'ms';
|
||||
card.innerHTML = `
|
||||
<div class="flex flex-col sm:flex-row sm:items-start justify-between gap-3">
|
||||
<!-- 左侧信息 -->
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex items-start gap-3 mb-3">
|
||||
<div class="w-10 h-10 rounded-xl bg-gray-100 dark:bg-gray-800 flex items-center justify-center flex-shrink-0">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"
|
||||
class="text-gray-600 dark:text-gray-400">
|
||||
<path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/>
|
||||
<path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<h3 class="text-base font-semibold truncate">${courseName}</h3>
|
||||
<div class="flex flex-wrap gap-x-4 gap-y-1 mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
<span>${examType}</span>
|
||||
<span>${campus}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 sm:grid-cols-4 gap-3">
|
||||
<div>
|
||||
<div class="text-xs text-gray-400 dark:text-gray-500 mb-0.5">考试日期</div>
|
||||
<div class="text-sm font-medium">${examDate}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-xs text-gray-400 dark:text-gray-500 mb-0.5">考试时间</div>
|
||||
<div class="text-sm font-medium">${examTime}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-xs text-gray-400 dark:text-gray-500 mb-0.5">考试地点</div>
|
||||
<div class="text-sm font-medium">${location}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-xs text-gray-400 dark:text-gray-500 mb-0.5">任课教师</div>
|
||||
<div class="text-sm font-medium">${teacher}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 右侧状态 -->
|
||||
<div class="flex-shrink-0">
|
||||
<span class="status-badge ${status.class}">${status.label}</span>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
container.appendChild(card);
|
||||
});
|
||||
}
|
||||
|
||||
function showError(msg) {
|
||||
const error = document.getElementById('errorMessage');
|
||||
document.getElementById('errorText').textContent = msg;
|
||||
error.classList.remove('hidden');
|
||||
}
|
||||
|
||||
// ── 考试日期分布柱状图 ──
|
||||
function renderExamDateChart(exams) {
|
||||
const container = document.getElementById('examDateChart');
|
||||
if (!container) return;
|
||||
if (!examDateChart) examDateChart = echarts.init(container);
|
||||
|
||||
const dateCount = {};
|
||||
exams.forEach(item => {
|
||||
const parsed = parseKssj(item.kssj);
|
||||
const date = parsed.date || '';
|
||||
if (date) dateCount[date] = (dateCount[date] || 0) + 1;
|
||||
});
|
||||
const dates = Object.keys(dateCount).sort();
|
||||
|
||||
const dark = isDarkMode();
|
||||
examDateChart.setOption({
|
||||
tooltip: { trigger: 'axis' },
|
||||
xAxis: { type: 'category', data: dates, axisLabel: { fontSize: 10, rotate: 30 } },
|
||||
yAxis: { type: 'value', name: '场次', minInterval: 1, nameTextStyle: { fontSize: 11 } },
|
||||
series: [{
|
||||
type: 'bar', data: dates.map(d => dateCount[d]),
|
||||
itemStyle: {
|
||||
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
|
||||
{ offset: 0, color: dark ? '#fbbf24' : '#f59e0b' },
|
||||
{ offset: 1, color: dark ? '#d97706' : '#b45309' }
|
||||
])
|
||||
},
|
||||
barMaxWidth: 36,
|
||||
label: { show: true, position: 'top', fontSize: 11, color: dark ? '#9ca3af' : '#6b7280' }
|
||||
}]
|
||||
}, true);
|
||||
}
|
||||
|
||||
// ── 考试形式饼图 ──
|
||||
function renderExamTypeChart(exams) {
|
||||
const container = document.getElementById('examTypeChart');
|
||||
if (!container) return;
|
||||
if (!examTypeChart) examTypeChart = echarts.init(container);
|
||||
|
||||
const typeCount = {};
|
||||
exams.forEach(item => {
|
||||
const type = item.khfs || item.ksxs || item.KSXS || item['考试形式'] || '其他';
|
||||
typeCount[type] = (typeCount[type] || 0) + 1;
|
||||
});
|
||||
const entries = Object.entries(typeCount).sort((a, b) => b[1] - a[1]);
|
||||
const dark = isDarkMode();
|
||||
const colors = dark
|
||||
? ['#60a5fa', '#34d399', '#fbbf24', '#f87171', '#a78bfa', '#f472b6']
|
||||
: ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899'];
|
||||
|
||||
examTypeChart.setOption({
|
||||
tooltip: { trigger: 'item', formatter: '{b}: {c} 场 ({d}%)' },
|
||||
series: [{
|
||||
type: 'pie', radius: ['40%', '70%'], center: ['50%', '50%'],
|
||||
itemStyle: { borderRadius: 4, borderColor: dark ? '#1f2937' : '#fff', borderWidth: 2 },
|
||||
label: { fontSize: 11, color: dark ? '#d1d5db' : '#374151' },
|
||||
data: entries.map(([name, value], i) => ({ name, value, itemStyle: { color: colors[i % colors.length] } }))
|
||||
}]
|
||||
}, true);
|
||||
}
|
||||
|
||||
// ── 深色模式观察者 ──
|
||||
let _darkObserver = null;
|
||||
function setupDarkObserver(exams) {
|
||||
if (_darkObserver) return;
|
||||
_darkObserver = new MutationObserver(() => {
|
||||
if (exams.length > 0) {
|
||||
renderExamDateChart(exams);
|
||||
renderExamTypeChart(exams);
|
||||
}
|
||||
});
|
||||
_darkObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
|
||||
}
|
||||
|
||||
window.addEventListener('resize', () => {
|
||||
examDateChart?.resize();
|
||||
examTypeChart?.resize();
|
||||
});
|
||||
|
||||
// 学期切换自动刷新
|
||||
document.getElementById('semesterSelect').addEventListener('change', refreshExams);
|
||||
|
||||
// 初始化:先检查 session,再加载数据
|
||||
initSession().then(sessionOk => {
|
||||
if (!sessionOk) {
|
||||
showError('教务系统 Session 已失效,请尝试<a href="/dashboard" class="underline">重新配置教务账号</a>');
|
||||
return;
|
||||
}
|
||||
loadSemesters().then(() => refreshExams());
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,16 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>正在跳转...</title>
|
||||
<script>
|
||||
// 自动跳转到新的购买页面
|
||||
window.location.href = '/buy';
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<p>正在跳转到购买页面...</p>
|
||||
<p>如果未自动跳转,请<a href="/buy">点击这里</a></p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,74 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
{% block title %}成绩复查申请 - {{ brand_name }}{% endblock %}
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
@keyframes fadeSlideIn {
|
||||
from { opacity: 0; transform: translateY(8px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.row-animate { animation: fadeSlideIn 0.3s ease both; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.row-animate { animation: none !important; opacity: 1 !important; }
|
||||
.list-item-enter { animation: none !important; opacity: 1 !important; }
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 list-item-enter">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M16 2v6h6"/><path d="M12 18v-4"/><path d="M12 10v-1"/></svg>
|
||||
成绩复查申请
|
||||
</h2>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">对课程成绩有疑问时申请复查</p>
|
||||
</div>
|
||||
<button onclick="loadData()" class="px-4 py-2 rounded-lg border"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>刷新</button>
|
||||
</div>
|
||||
<div id="loadingIndicator" class="text-center py-12 hidden"><div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div><p class="text-gray-500 dark:text-gray-400">加载中...</p></div>
|
||||
<div id="errorMessage" class="glass rounded-2xl p-6 mb-4 text-center hidden"><p id="errorText" class="text-red-500"></p></div>
|
||||
<div id="dataContainer" class="hidden">
|
||||
<div class="glass rounded-2xl overflow-hidden">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead><tr class="border-b border-gray-200 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-800/50"><th class="text-left py-3 px-4 font-semibold">课程名称</th><th class="text-left py-3 px-4 font-semibold">原成绩</th><th class="text-left py-3 px-4 font-semibold">申请原因</th><th class="text-left py-3 px-4 font-semibold">审核状态</th></tr></thead>
|
||||
<tbody id="tableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="emptyState" class="glass rounded-2xl p-12 text-center hidden"><p class="text-gray-500 dark:text-gray-400 text-lg">暂无复查申请记录</p></div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block extra_js %}
|
||||
<script>
|
||||
async function loadData() {
|
||||
document.getElementById('loadingIndicator').classList.remove('hidden');
|
||||
document.getElementById('errorMessage').classList.add('hidden');
|
||||
document.getElementById('dataContainer').classList.add('hidden');
|
||||
document.getElementById('emptyState').classList.add('hidden');
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/grade-review');
|
||||
const data = await res.json();
|
||||
document.getElementById('loadingIndicator').classList.add('hidden');
|
||||
if (!data.success) { showError(data.message); return; }
|
||||
const items = data.items || [];
|
||||
if (!items.length) { document.getElementById('emptyState').classList.remove('hidden'); return; }
|
||||
const tbody = document.getElementById('tableBody');
|
||||
tbody.innerHTML = items.map((item, i) => {
|
||||
return `<tr class="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50/50 dark:hover:bg-gray-800/30 transition-colors">
|
||||
<td class="py-3 px-4">${escHtml(item.kcmc||item.课程名称||'--')}</td>
|
||||
<td class="py-3 px-4">${escHtml(item.ycj||item.原成绩||'--')}</td>
|
||||
<td class="py-3 px-4 text-gray-500 text-xs">${escHtml(item.sqyy||item.申请原因||'--')}</td>
|
||||
<td class="py-3 px-4"><span class="px-2 py-0.5 rounded text-xs ${(item.shztmc||item.审核状态||'').includes('通过')?'bg-green-100 text-green-700':(item.shztmc||'').includes('待审')?'bg-yellow-100 text-yellow-700':'bg-gray-100 text-gray-600'}">${escHtml(item.shztmc||item.审核状态||'--')}</span></td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
document.getElementById('dataContainer').classList.remove('hidden');
|
||||
} catch(e) { document.getElementById('loadingIndicator').classList.add('hidden'); showError('网络错误: '+e.message); }
|
||||
}
|
||||
function showError(msg) { document.getElementById('errorText').textContent = msg; document.getElementById('errorMessage').classList.remove('hidden'); }
|
||||
function escHtml(s) { if(s==null) return ''; return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"'); }
|
||||
document.addEventListener('DOMContentLoaded', () => loadData());
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,622 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
|
||||
{% block title %}成绩查询 - {{ brand_name }}{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
.grade-a-plus { color: #22c55e; }
|
||||
.grade-a { color: #16a34a; }
|
||||
.grade-b { color: #2563eb; }
|
||||
.grade-c { color: #d97706; }
|
||||
.grade-d { color: #dc2626; }
|
||||
.grade-fail { color: #991b1b; }
|
||||
.grade-retake { color: #2563eb; } /* 补考/重修通过 */
|
||||
.dark .grade-a-plus { color: #4ade80; }
|
||||
.dark .grade-a { color: #22c55e; }
|
||||
.dark .grade-b { color: #60a5fa; }
|
||||
.dark .grade-c { color: #fbbf24; }
|
||||
.dark .grade-d { color: #f87171; }
|
||||
.dark .grade-fail { color: #ef4444; }
|
||||
.dark .grade-retake { color: #60a5fa; }
|
||||
|
||||
@keyframes fadeSlideIn {
|
||||
from { opacity: 0; transform: translateY(8px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.row-animate {
|
||||
animation: fadeSlideIn 0.3s ease both;
|
||||
}
|
||||
|
||||
@keyframes shimmer {
|
||||
0% { background-position: -200% 0; }
|
||||
100% { background-position: 200% 0; }
|
||||
}
|
||||
.skeleton {
|
||||
background: linear-gradient(90deg, #e5e7eb 25%, #f3f4f6 50%, #e5e7eb 75%);
|
||||
background-size: 200% 100%;
|
||||
animation: shimmer 1.5s infinite;
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
.dark .skeleton {
|
||||
background: linear-gradient(90deg, #374151 25%, #4b5563 50%, #374151 75%);
|
||||
background-size: 200% 100%;
|
||||
}
|
||||
|
||||
.stat-card {
|
||||
transition: transform 0.2s ease, box-shadow 0.2s ease;
|
||||
}
|
||||
.stat-card:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 8px 25px rgba(0,0,0,0.08);
|
||||
}
|
||||
.dark .stat-card:hover {
|
||||
box-shadow: 0 8px 25px rgba(0,0,0,0.4);
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.stat-card { transition: none !important; }
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
<!-- 页面标题 -->
|
||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 list-item-enter" style="animation-delay: 0ms;">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
||||
<polyline points="14 2 14 8 20 8"/>
|
||||
<line x1="16" y1="13" x2="8" y2="13"/>
|
||||
<line x1="16" y1="17" x2="8" y2="17"/>
|
||||
<polyline points="10 9 9 9 8 9"/>
|
||||
</svg>
|
||||
成绩查询
|
||||
</h2>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">查看各学期课程成绩与绩点</p>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-3 items-center">
|
||||
<select id="yearSelect"
|
||||
class="px-4 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-black dark:focus:ring-white">
|
||||
<option value="">全部学年</option>
|
||||
</select>
|
||||
<select id="termSelect"
|
||||
class="px-4 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-black dark:focus:ring-white">
|
||||
<option value="">全部学期</option>
|
||||
</select>
|
||||
<select id="courseMarkSelect"
|
||||
class="px-4 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-black dark:focus:ring-white">
|
||||
<option value="">全部课程标记</option>
|
||||
<option value="0">主修</option>
|
||||
<option value="1">辅修</option>
|
||||
<option value="2">二专业</option>
|
||||
<option value="3">二学位</option>
|
||||
<option value="4">非学位</option>
|
||||
<option value="8">二学位转一专</option>
|
||||
</select>
|
||||
<button onclick="refreshGrades()"
|
||||
class="px-4 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm font-medium hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<polyline points="23 4 23 10 17 10"/>
|
||||
<path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>
|
||||
</svg>
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 颜色图例 -->
|
||||
<div id="colorLegend" class="mb-4 list-item-enter hidden" style="animation-delay: 25ms;">
|
||||
<div class="glass rounded-2xl px-4 py-2.5 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs">
|
||||
<span class="text-gray-400 dark:text-gray-500">图例:</span>
|
||||
<span class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-full bg-red-500 inline-block"></span>不合格(红)</span>
|
||||
<span class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-full bg-blue-500 inline-block"></span>补考/重修通过(蓝)</span>
|
||||
<span class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-full bg-green-500 inline-block"></span>正常通过(绿)</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 统计卡片 -->
|
||||
<div id="statsRow" class="grid grid-cols-2 md:grid-cols-5 gap-3 mb-6 list-item-enter hidden" style="animation-delay: 50ms;">
|
||||
<div class="stat-card glass rounded-2xl p-4 text-center">
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400 mb-1">课程总数</div>
|
||||
<div id="statTotal" class="text-2xl font-bold">--</div>
|
||||
</div>
|
||||
<div class="stat-card glass rounded-2xl p-4 text-center">
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400 mb-1">总学分</div>
|
||||
<div id="statCredits" class="text-2xl font-bold">--</div>
|
||||
</div>
|
||||
<div class="stat-card glass rounded-2xl p-4 text-center">
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400 mb-1">平均绩点</div>
|
||||
<div id="statGPA" class="text-2xl font-bold">--</div>
|
||||
</div>
|
||||
<div class="stat-card glass rounded-2xl p-4 text-center">
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400 mb-1">加权平均分</div>
|
||||
<div id="statAvg" class="text-2xl font-bold">--</div>
|
||||
</div>
|
||||
<div class="stat-card glass rounded-2xl p-4 text-center">
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400 mb-1">总学分绩点</div>
|
||||
<div id="statXfjd" class="text-2xl font-bold">--</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 图表区 -->
|
||||
<div id="chartsRow" class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6 hidden">
|
||||
<div class="glass rounded-2xl p-4">
|
||||
<h3 class="text-sm font-semibold text-gray-600 dark:text-gray-400 mb-3">成绩分布</h3>
|
||||
<div id="scoreDistChart" class="h-64"></div>
|
||||
</div>
|
||||
<div class="glass rounded-2xl p-4">
|
||||
<h3 class="text-sm font-semibold text-gray-600 dark:text-gray-400 mb-3">课程类别学分分布</h3>
|
||||
<div id="courseTypeChart" class="h-64"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 加载提示 -->
|
||||
<div id="loadingIndicator" class="text-center py-12 list-item-enter" style="animation-delay: 100ms;">
|
||||
<div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
|
||||
<p class="text-gray-500 dark:text-gray-400">正在加载成绩数据...</p>
|
||||
</div>
|
||||
|
||||
<!-- 错误提示 -->
|
||||
<div id="errorMessage" class="glass rounded-2xl p-6 mb-4 text-center hidden list-item-enter" style="animation-delay: 100ms;">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"
|
||||
class="mx-auto mb-4 text-red-500">
|
||||
<circle cx="12" cy="12" r="10"/>
|
||||
<line x1="15" y1="9" x2="9" y2="15"/>
|
||||
<line x1="9" y1="9" x2="15" y2="15"/>
|
||||
</svg>
|
||||
<p id="errorText" class="text-gray-600 dark:text-gray-400"></p>
|
||||
</div>
|
||||
|
||||
<!-- 成绩表格 -->
|
||||
<div id="gradesContainer" class="hidden list-item-enter" style="animation-delay: 150ms;">
|
||||
<div id="gradesTableWrapper" class="glass rounded-2xl overflow-hidden hidden">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-xs whitespace-nowrap">
|
||||
<thead>
|
||||
<tr class="border-b border-gray-200 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-800/50">
|
||||
<th class="text-left py-2.5 px-2 font-semibold text-gray-700 dark:text-gray-300">序号</th>
|
||||
<th class="text-left py-2.5 px-2 font-semibold text-gray-700 dark:text-gray-300">学年学期</th>
|
||||
<th class="text-left py-2.5 px-2 font-semibold text-gray-700 dark:text-gray-300">课程代码</th>
|
||||
<th class="text-left py-2.5 px-2 font-semibold text-gray-700 dark:text-gray-300">课程名称</th>
|
||||
<th class="text-left py-2.5 px-2 font-semibold text-gray-700 dark:text-gray-300">课程性质</th>
|
||||
<th class="text-center py-2.5 px-2 font-semibold text-gray-700 dark:text-gray-300">学分</th>
|
||||
<th class="text-center py-2.5 px-2 font-semibold text-gray-700 dark:text-gray-300">成绩</th>
|
||||
<th class="text-center py-2.5 px-2 font-semibold text-gray-700 dark:text-gray-300">成绩备注</th>
|
||||
<th class="text-center py-2.5 px-2 font-semibold text-gray-700 dark:text-gray-300">绩点</th>
|
||||
<th class="text-center py-2.5 px-2 font-semibold text-gray-700 dark:text-gray-300">成绩性质</th>
|
||||
<th class="text-center py-2.5 px-2 font-semibold text-gray-700 dark:text-gray-300">学位课</th>
|
||||
<th class="text-left py-2.5 px-2 font-semibold text-gray-700 dark:text-gray-300">开课学院</th>
|
||||
<th class="text-center py-2.5 px-2 font-semibold text-gray-700 dark:text-gray-300">课程标记</th>
|
||||
<th class="text-left py-2.5 px-2 font-semibold text-gray-700 dark:text-gray-300">课程类别</th>
|
||||
<th class="text-left py-2.5 px-2 font-semibold text-gray-700 dark:text-gray-300">课程归属</th>
|
||||
<th class="text-left py-2.5 px-2 font-semibold text-gray-700 dark:text-gray-300">任课教师</th>
|
||||
<th class="text-center py-2.5 px-2 font-semibold text-gray-700 dark:text-gray-300">考核方式</th>
|
||||
<th class="text-center py-2.5 px-2 font-semibold text-gray-700 dark:text-gray-300">学分绩点</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="gradesTableBody">
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 空状态 -->
|
||||
<div id="emptyState" class="glass rounded-2xl p-12 text-center hidden">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round"
|
||||
class="mx-auto mb-4 text-gray-300 dark:text-gray-600">
|
||||
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
||||
<polyline points="14 2 14 8 20 8"/>
|
||||
</svg>
|
||||
<p class="text-gray-500 dark:text-gray-400 text-lg">暂无成绩数据</p>
|
||||
<p class="text-gray-400 dark:text-gray-500 text-sm mt-1">尝试切换学期或刷新页面</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script src="{{ url_for('static', filename='echarts.min.js') }}"></script>
|
||||
<script>
|
||||
let allGrades = [];
|
||||
let scoreDistChart = null;
|
||||
let courseTypeChart = null;
|
||||
let currentPage = 1;
|
||||
let pageSize = 100;
|
||||
let gradesTotal = 0;
|
||||
|
||||
// ── 深色模式判断 ──
|
||||
function isDarkMode() { return document.documentElement.classList.contains('dark'); }
|
||||
|
||||
// ── Session 健康检查 ──
|
||||
async function initSession() {
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/ping');
|
||||
const data = await res.json();
|
||||
if (!data.success) {
|
||||
console.warn('Session ping 失败:', data.message);
|
||||
return false;
|
||||
}
|
||||
if (data.refreshed) console.log('🔄 Session 已自动刷新');
|
||||
return true;
|
||||
} catch (e) {
|
||||
console.error('Session ping 异常:', e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 成绩等级 → 绩点映射
|
||||
function gradeToPoint(grade) {
|
||||
const g = String(grade || '').trim().toUpperCase();
|
||||
const map = {
|
||||
'A+': 4.0, 'A': 4.0, 'A-': 3.7,
|
||||
'B+': 3.3, 'B': 3.0, 'B-': 2.7,
|
||||
'C+': 2.3, 'C': 2.0, 'C-': 1.7,
|
||||
'D+': 1.3, 'D': 1.0, 'D-': 0.7,
|
||||
'F': 0.0,
|
||||
};
|
||||
if (map[g] !== undefined) return map[g];
|
||||
const num = parseFloat(grade);
|
||||
if (isNaN(num)) return 0;
|
||||
if (num >= 95) return 4.0;
|
||||
if (num >= 90) return 4.0;
|
||||
if (num >= 85) return 3.7;
|
||||
if (num >= 80) return 3.3;
|
||||
if (num >= 75) return 3.0;
|
||||
if (num >= 70) return 2.7;
|
||||
if (num >= 65) return 2.3;
|
||||
if (num >= 60) return 2.0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 判断是否为补考/重修/缓考成绩(用于蓝色标识)
|
||||
function isRetake(ksxz) {
|
||||
if (!ksxz) return false;
|
||||
return /补考|重修|缓考/.test(ksxz);
|
||||
}
|
||||
|
||||
function gradeColorClass(grade, ksxz) {
|
||||
// 补考/重修通过 → 蓝色标识(对齐教务系统)
|
||||
if (isRetake(ksxz)) {
|
||||
const num = parseFloat(grade);
|
||||
if (!isNaN(num) && num >= 60) return 'grade-retake';
|
||||
const g = String(grade || '').trim();
|
||||
if (['优秀','良好','中等','及格'].includes(g)) return 'grade-retake';
|
||||
}
|
||||
const g = String(grade || '').trim().toUpperCase();
|
||||
if (['A+', 'A', 'A-'].includes(g)) return 'grade-a-plus';
|
||||
if (['B+', 'B', 'B-'].includes(g)) return 'grade-b';
|
||||
if (['C+', 'C', 'C-'].includes(g)) return 'grade-c';
|
||||
if (['D+', 'D', 'D-'].includes(g)) return 'grade-d';
|
||||
if (g === 'F') return 'grade-fail';
|
||||
const num = parseFloat(grade);
|
||||
if (!isNaN(num)) {
|
||||
if (num >= 90) return 'grade-a-plus';
|
||||
if (num >= 80) return 'grade-a';
|
||||
if (num >= 70) return 'grade-b';
|
||||
if (num >= 60) return 'grade-c';
|
||||
return 'grade-fail';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
async function loadYears() {
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/semesters');
|
||||
const data = await res.json();
|
||||
if (data.success && data.years) {
|
||||
const yearSel = document.getElementById('yearSelect');
|
||||
const termSel = document.getElementById('termSelect');
|
||||
|
||||
// 学年下拉(从近到远)
|
||||
data.years.sort((a, b) => parseInt(b.value) - parseInt(a.value)).forEach(y => {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = y.value;
|
||||
opt.textContent = y.label;
|
||||
yearSel.appendChild(opt);
|
||||
});
|
||||
|
||||
// 学期下拉
|
||||
(data.terms || []).forEach(t => {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = t.value;
|
||||
opt.textContent = t.label;
|
||||
termSel.appendChild(opt);
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('加载筛选条件失败:', e);
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshGrades(page) {
|
||||
if (page !== undefined) currentPage = page; else currentPage = 1;
|
||||
const loading = document.getElementById('loadingIndicator');
|
||||
const error = document.getElementById('errorMessage');
|
||||
const container = document.getElementById('gradesContainer');
|
||||
const statsRow = document.getElementById('statsRow');
|
||||
const colorLegend = document.getElementById('colorLegend');
|
||||
const empty = document.getElementById('emptyState');
|
||||
const chartsRow = document.getElementById('chartsRow');
|
||||
const tableWrapper = document.getElementById('gradesTableWrapper');
|
||||
|
||||
loading.classList.remove('hidden');
|
||||
error.classList.add('hidden');
|
||||
container.classList.add('hidden');
|
||||
statsRow.classList.add('hidden');
|
||||
colorLegend.classList.add('hidden');
|
||||
empty.classList.add('hidden');
|
||||
chartsRow.classList.add('hidden');
|
||||
if (tableWrapper) tableWrapper.classList.add('hidden');
|
||||
|
||||
const year = document.getElementById('yearSelect').value;
|
||||
const term = document.getElementById('termSelect').value;
|
||||
const kcbj = document.getElementById('courseMarkSelect').value;
|
||||
|
||||
// 构建 API 参数: 学年 + 学期分开(对齐教务系统)
|
||||
const params = { kcbj, page: currentPage, page_size: pageSize };
|
||||
if (year) params.xnm = year;
|
||||
if (term) params.xqm = term;
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/grades?' + new URLSearchParams(params));
|
||||
const data = await res.json();
|
||||
|
||||
loading.classList.add('hidden');
|
||||
|
||||
if (!data.success) {
|
||||
showError(data.message || '查询失败');
|
||||
return;
|
||||
}
|
||||
|
||||
allGrades = data.items || [];
|
||||
gradesTotal = data.total || allGrades.length;
|
||||
|
||||
if (allGrades.length === 0) {
|
||||
container.classList.remove('hidden');
|
||||
empty.classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
|
||||
renderGrades(allGrades);
|
||||
container.classList.remove('hidden');
|
||||
statsRow.classList.remove('hidden');
|
||||
colorLegend.classList.remove('hidden');
|
||||
if (tableWrapper) tableWrapper.classList.remove('hidden');
|
||||
renderPagination();
|
||||
} catch (e) {
|
||||
loading.classList.add('hidden');
|
||||
showError('网络错误: ' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
function renderGrades(grades) {
|
||||
const tbody = document.getElementById('gradesTableBody');
|
||||
tbody.innerHTML = '';
|
||||
|
||||
let totalCredits = 0;
|
||||
let totalPoints = 0; // 绩点×学分 加权
|
||||
let totalXfjd = 0; // 官方学分绩点
|
||||
let totalScore = 0;
|
||||
let scoreCount = 0;
|
||||
|
||||
grades.forEach((item, idx) => {
|
||||
// 字段映射(兼容大小写和中文别名)
|
||||
const xnmmc = item.xnmmc || item['学年'] || '';
|
||||
const xqmmc = item.xqmmc || item['学期'] || '';
|
||||
const kch = item.kch || item['课程代码'] || '';
|
||||
const kcmc = item.kcmc || item['课程名称'] || '未知课程';
|
||||
const kcxzmc = item.kcxzmc || item['课程性质'] || '';
|
||||
const xf = parseFloat(item.xf || item['学分'] || 0) || 0;
|
||||
const cj = item.cj || item['成绩'] || item.bfzcj || '--';
|
||||
const cjbz = item.cjbz || item['成绩备注'] || '';
|
||||
const jd = parseFloat(item.jd); // 官方绩点
|
||||
const ksxz = item.ksxz || item['成绩性质'] || '';
|
||||
const sfxwkc = item.sfxwkc || item['是否学位课程'] || '';
|
||||
const kkbmmc = item.kkbmmc || item['开课学院'] || '';
|
||||
const kcbj = item.kcbj || item['课程标记'] || '';
|
||||
const kclbmc = item.kclbmc || item['课程类别'] || '';
|
||||
const kcgsmc = item.kcgsmc || item['课程归属'] || '';
|
||||
const jsxm = item.jsxm || item['任课教师'] || '';
|
||||
const khfsmc = item.khfsmc || item['考核方式'] || '';
|
||||
const xfjd = parseFloat(item.xfjd || 0) || 0; // 官方学分绩点
|
||||
|
||||
// 绩点取值:优先官方 jd,否则本地计算
|
||||
const point = isNaN(jd) ? gradeToPoint(cj) : jd;
|
||||
const pointDisplay = isNaN(jd) ? point.toFixed(1) : jd.toFixed(2);
|
||||
const numScore = parseFloat(cj);
|
||||
|
||||
if (!isNaN(numScore) && numScore > 0) {
|
||||
totalScore += numScore * xf;
|
||||
scoreCount += xf;
|
||||
}
|
||||
totalCredits += xf;
|
||||
totalPoints += point * xf;
|
||||
totalXfjd += xfjd;
|
||||
|
||||
// 颜色:根据成绩性质判断是否为补考蓝色
|
||||
const colorClass = gradeColorClass(cj, ksxz);
|
||||
const delay = Math.min(idx * 30, 600);
|
||||
|
||||
// 学年学期合并显示
|
||||
const xnxq = xnmmc ? (xnmmc + (xqmmc ? '-' + xqmmc : '')) : '--';
|
||||
|
||||
const tr = document.createElement('tr');
|
||||
tr.className = 'border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50/50 dark:hover:bg-gray-800/30 transition-colors row-animate';
|
||||
tr.style.animationDelay = delay + 'ms';
|
||||
tr.innerHTML = `
|
||||
<td class="py-2.5 px-2 text-gray-400 dark:text-gray-500">${idx + 1}</td>
|
||||
<td class="py-2.5 px-2">${xnxq}</td>
|
||||
<td class="py-2.5 px-2 text-gray-500 dark:text-gray-400 font-mono text-xs">${kch}</td>
|
||||
<td class="py-2.5 px-2 font-medium">${kcmc}</td>
|
||||
<td class="py-2.5 px-2 text-gray-500 dark:text-gray-400">${kcxzmc}</td>
|
||||
<td class="py-2.5 px-2 text-center">${xf.toFixed(1)}</td>
|
||||
<td class="py-2.5 px-2 text-center font-semibold ${colorClass}">${cj}</td>
|
||||
<td class="py-2.5 px-2 text-center text-gray-400 dark:text-gray-500 text-xs">${cjbz}</td>
|
||||
<td class="py-2.5 px-2 text-center font-semibold ${colorClass}">${pointDisplay}</td>
|
||||
<td class="py-2.5 px-2 text-center text-gray-500 dark:text-gray-400">${ksxz}</td>
|
||||
<td class="py-2.5 px-2 text-center">${sfxwkc}</td>
|
||||
<td class="py-2.5 px-2 text-gray-500 dark:text-gray-400">${kkbmmc}</td>
|
||||
<td class="py-2.5 px-2 text-center text-gray-500 dark:text-gray-400">${kcbj}</td>
|
||||
<td class="py-2.5 px-2 text-gray-500 dark:text-gray-400">${kclbmc}</td>
|
||||
<td class="py-2.5 px-2 text-gray-500 dark:text-gray-400">${kcgsmc}</td>
|
||||
<td class="py-2.5 px-2 text-gray-500 dark:text-gray-400">${jsxm}</td>
|
||||
<td class="py-2.5 px-2 text-center text-gray-500 dark:text-gray-400">${khfsmc}</td>
|
||||
<td class="py-2.5 px-2 text-center font-semibold">${xfjd > 0 ? xfjd.toFixed(2) : '--'}</td>
|
||||
`;
|
||||
tbody.appendChild(tr);
|
||||
});
|
||||
|
||||
// 更新统计
|
||||
const gpa = totalCredits > 0 ? (totalPoints / totalCredits).toFixed(2) : '--';
|
||||
const weightedAvg = scoreCount > 0 ? (totalScore / scoreCount).toFixed(1) : '--';
|
||||
|
||||
document.getElementById('statTotal').textContent = grades.length;
|
||||
document.getElementById('statCredits').textContent = totalCredits.toFixed(1);
|
||||
document.getElementById('statGPA').textContent = gpa;
|
||||
document.getElementById('statAvg').textContent = weightedAvg;
|
||||
document.getElementById('statXfjd').textContent = totalXfjd > 0 ? totalXfjd.toFixed(1) : '--';
|
||||
|
||||
// 渲染图表
|
||||
const chartsRow = document.getElementById('chartsRow');
|
||||
chartsRow.classList.remove('hidden');
|
||||
renderScoreDistChart(grades);
|
||||
renderCourseTypeChart(grades);
|
||||
setupDarkObserver();
|
||||
}
|
||||
|
||||
// ── 分页组件 ──
|
||||
function renderPagination() {
|
||||
let container = document.getElementById('paginationBar');
|
||||
if (!container) {
|
||||
container = document.createElement('div');
|
||||
container.id = 'paginationBar';
|
||||
container.className = 'flex justify-center items-center gap-2 mt-4';
|
||||
document.getElementById('gradesContainer').appendChild(container);
|
||||
}
|
||||
const totalPages = Math.ceil(gradesTotal / pageSize) || 1;
|
||||
if (totalPages <= 1) { container.innerHTML = ''; return; }
|
||||
|
||||
let html = '';
|
||||
html += `<button onclick="refreshGrades(${currentPage - 1})" ${currentPage <= 1 ? 'disabled' : ''}
|
||||
class="px-3 py-1.5 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-xs disabled:opacity-30 hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors">上一页</button>`;
|
||||
html += `<span class="text-xs text-gray-500 dark:text-gray-400">第 ${currentPage} / ${totalPages} 页(共 ${gradesTotal} 条)</span>`;
|
||||
html += `<button onclick="refreshGrades(${currentPage + 1})" ${currentPage >= totalPages ? 'disabled' : ''}
|
||||
class="px-3 py-1.5 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-xs disabled:opacity-30 hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors">下一页</button>`;
|
||||
container.innerHTML = html;
|
||||
}
|
||||
|
||||
function showError(msg) {
|
||||
const error = document.getElementById('errorMessage');
|
||||
document.getElementById('errorText').textContent = msg;
|
||||
error.classList.remove('hidden');
|
||||
}
|
||||
|
||||
// ── 成绩分布柱状图 ──
|
||||
function renderScoreDistChart(grades) {
|
||||
const container = document.getElementById('scoreDistChart');
|
||||
if (!container) return;
|
||||
if (!scoreDistChart) scoreDistChart = echarts.init(container);
|
||||
|
||||
const bins = { '优秀(90-100)': 0, '良好(80-89)': 0, '中等(70-79)': 0, '及格(60-69)': 0, '不及格(0-59)': 0 };
|
||||
grades.forEach(item => {
|
||||
const grade = item.cj || item.CJ || item['成绩'] || item.bfzcj || item.BFZCJ || '';
|
||||
const num = parseFloat(grade);
|
||||
if (isNaN(num) || num <= 0) return;
|
||||
if (num >= 90) bins['优秀(90-100)']++;
|
||||
else if (num >= 80) bins['良好(80-89)']++;
|
||||
else if (num >= 70) bins['中等(70-79)']++;
|
||||
else if (num >= 60) bins['及格(60-69)']++;
|
||||
else bins['不及格(0-59)']++;
|
||||
});
|
||||
|
||||
const dark = isDarkMode();
|
||||
scoreDistChart.setOption({
|
||||
tooltip: { trigger: 'axis' },
|
||||
xAxis: { type: 'category', data: Object.keys(bins), axisLabel: { fontSize: 11 } },
|
||||
yAxis: { type: 'value', name: '门数', nameTextStyle: { fontSize: 11 } },
|
||||
series: [{
|
||||
type: 'bar', data: Object.values(bins),
|
||||
itemStyle: {
|
||||
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
|
||||
{ offset: 0, color: dark ? '#60a5fa' : '#3b82f6' },
|
||||
{ offset: 1, color: dark ? '#1d4ed8' : '#1e40af' }
|
||||
])
|
||||
},
|
||||
barMaxWidth: 40,
|
||||
label: { show: true, position: 'top', fontSize: 11, color: dark ? '#9ca3af' : '#6b7280' }
|
||||
}]
|
||||
}, true);
|
||||
}
|
||||
|
||||
// ── 课程类别学分饼图 ──
|
||||
function renderCourseTypeChart(grades) {
|
||||
const container = document.getElementById('courseTypeChart');
|
||||
if (!container) return;
|
||||
if (!courseTypeChart) courseTypeChart = echarts.init(container);
|
||||
|
||||
const typeMap = {};
|
||||
grades.forEach(item => {
|
||||
const type = item.kclbmc || item.KCLBMC || item['课程类别'] || item.kclx || '其他';
|
||||
const credits = parseFloat(item.xf || item.XF || item['学分'] || 0) || 0;
|
||||
typeMap[type] = (typeMap[type] || 0) + credits;
|
||||
});
|
||||
|
||||
const entries = Object.entries(typeMap).sort((a, b) => b[1] - a[1]);
|
||||
const dark = isDarkMode();
|
||||
const colors = dark
|
||||
? ['#60a5fa', '#34d399', '#fbbf24', '#f87171', '#a78bfa', '#f472b6', '#38bdf8', '#fb923c']
|
||||
: ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899', '#06b6d4', '#f97316'];
|
||||
|
||||
courseTypeChart.setOption({
|
||||
tooltip: { trigger: 'item', formatter: '{b}: {c} 学分 ({d}%)' },
|
||||
series: [{
|
||||
type: 'pie',
|
||||
radius: ['40%', '70%'],
|
||||
center: ['50%', '50%'],
|
||||
itemStyle: { borderRadius: 4, borderColor: dark ? '#1f2937' : '#fff', borderWidth: 2 },
|
||||
label: { fontSize: 11, color: dark ? '#d1d5db' : '#374151' },
|
||||
data: entries.map(([name, value], i) => ({ name, value, itemStyle: { color: colors[i % colors.length] } }))
|
||||
}]
|
||||
}, true);
|
||||
}
|
||||
|
||||
// ── 深色模式观察者 ──
|
||||
let _darkObserver = null;
|
||||
function setupDarkObserver() {
|
||||
if (_darkObserver) return;
|
||||
_darkObserver = new MutationObserver(() => {
|
||||
const grades = allGrades;
|
||||
if (grades.length > 0) {
|
||||
if (scoreDistChart) renderScoreDistChart(grades);
|
||||
if (courseTypeChart) renderCourseTypeChart(grades);
|
||||
}
|
||||
});
|
||||
_darkObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
|
||||
}
|
||||
|
||||
// ── 图表响应式缩放 ──
|
||||
window.addEventListener('resize', () => {
|
||||
scoreDistChart?.resize();
|
||||
courseTypeChart?.resize();
|
||||
});
|
||||
|
||||
// 学年/学期/课程标记切换自动刷新
|
||||
document.getElementById('yearSelect').addEventListener('change', refreshGrades);
|
||||
document.getElementById('termSelect').addEventListener('change', refreshGrades);
|
||||
document.getElementById('courseMarkSelect').addEventListener('change', refreshGrades);
|
||||
|
||||
// 初始化:先检查 session,再加载数据
|
||||
initSession().then(sessionOk => {
|
||||
if (!sessionOk) {
|
||||
showError('教务系统 Session 已失效,请尝试<a href="/dashboard" class="underline">重新配置教务账号</a>');
|
||||
return;
|
||||
}
|
||||
loadYears().then(() => refreshGrades());
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,162 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
|
||||
{% block title %}登录 - {{ brand_name }}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="min-h-[70vh] flex items-center justify-center">
|
||||
<div class="w-full max-w-md">
|
||||
<!-- 登录卡片 -->
|
||||
<div class="glass rounded-3xl p-8 layer-4 list-item-enter" style="animation-delay: 0ms;">
|
||||
<!-- Logo -->
|
||||
<div class="text-center mb-8">
|
||||
<div class="w-16 h-16 bg-black dark:bg-white rounded-2xl flex items-center justify-center text-white dark:text-black font-bold text-2xl mx-auto mb-4">
|
||||
S
|
||||
</div>
|
||||
<h1 class="text-2xl font-bold text-neutral-900 dark:text-white">欢迎回来</h1>
|
||||
<p class="text-neutral-500 dark:text-neutral-400 mt-2">登录您的账号继续使用</p>
|
||||
</div>
|
||||
|
||||
<!-- 登录表单 -->
|
||||
<form id="loginForm" onsubmit="handleLogin(event)" class="space-y-5">
|
||||
<div>
|
||||
<label class="input-label">用户名</label>
|
||||
<input type="text" name="username" id="username" class="input-field" placeholder="请输入用户名" required autofocus>
|
||||
</div>
|
||||
<div>
|
||||
<label class="input-label">密码</label>
|
||||
<input type="password" name="password" id="password" class="input-field" placeholder="请输入密码" required>
|
||||
</div>
|
||||
|
||||
<div id="errorMessage" class="hidden p-3 bg-red-50 dark:bg-red-900/20 border border-red-100 dark:border-red-800 rounded-xl text-sm text-red-800 dark:text-red-200">
|
||||
</div>
|
||||
|
||||
<!-- 协议勾选 -->
|
||||
<label class="flex items-start gap-2.5 cursor-pointer select-none group" id="termsLabel">
|
||||
<div class="relative flex-shrink-0 mt-0.5">
|
||||
<input type="checkbox" id="agreeTerms" class="sr-only" onchange="updateCheckbox(this)">
|
||||
<div id="checkboxBox" class="w-[18px] h-[18px] rounded border-2 border-neutral-300 dark:border-neutral-600 transition-all flex items-center justify-center">
|
||||
<svg id="checkIcon" class="w-2.5 h-2.5 text-white dark:text-black hidden" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7"/>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<span class="text-xs text-neutral-500 dark:text-neutral-400 leading-relaxed">
|
||||
我已阅读并同意
|
||||
<a href="{{ url_for('main.terms') }}" target="_blank" onclick="event.stopPropagation()" class="text-neutral-800 dark:text-neutral-200 font-medium underline underline-offset-2 hover:text-black dark:hover:text-white">用户服务协议</a>
|
||||
和
|
||||
<a href="{{ url_for('main.privacy') }}" target="_blank" onclick="event.stopPropagation()" class="text-neutral-800 dark:text-neutral-200 font-medium underline underline-offset-2 hover:text-black dark:hover:text-white">隐私政策</a>
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<button type="submit" id="submitBtn" class="w-full btn-primary py-3.5 rounded-full text-sm font-bold">
|
||||
登录
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<!-- 分割线 -->
|
||||
<div class="relative my-6">
|
||||
<div class="absolute inset-0 flex items-center">
|
||||
<div class="w-full border-t border-neutral-200 dark:border-neutral-800"></div>
|
||||
</div>
|
||||
<div class="relative flex justify-center text-sm">
|
||||
<span class="px-4 bg-white dark:bg-dark-card text-neutral-500">还没有账号?</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 注册按钮 -->
|
||||
<a href="{{ url_for('main.register') }}" class="block w-full py-3.5 rounded-full text-sm font-bold text-center border-2 border-neutral-200 dark:border-neutral-800 text-neutral-700 dark:text-neutral-300 hover:border-neutral-400 dark:hover:border-neutral-600 transition">
|
||||
立即注册
|
||||
</a>
|
||||
|
||||
<!-- 购买按钮 -->
|
||||
<a href="{{ url_for('main.buy') }}" class="block w-full py-3.5 rounded-full text-sm font-bold text-center border-2 border-neutral-200 dark:border-neutral-800 text-neutral-700 dark:text-neutral-300 hover:border-neutral-400 dark:hover:border-neutral-600 transition mt-3">
|
||||
购买注册码
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<!-- 返回首页 -->
|
||||
<div class="text-center mt-6">
|
||||
<a href="{{ url_for('main.buy') }}" class="text-sm text-neutral-500 hover:text-neutral-700 dark:hover:text-neutral-300 transition flex items-center justify-center gap-1">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
|
||||
</svg>
|
||||
返回首页
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script>
|
||||
function updateCheckbox(input) {
|
||||
const box = document.getElementById('checkboxBox');
|
||||
const icon = document.getElementById('checkIcon');
|
||||
const isDark = document.documentElement.classList.contains('dark');
|
||||
if (input.checked) {
|
||||
box.classList.remove('border-neutral-300', 'dark:border-neutral-600');
|
||||
box.classList.add('bg-black', 'border-black', 'dark:bg-white', 'dark:border-white');
|
||||
icon.classList.remove('hidden');
|
||||
} else {
|
||||
box.classList.add('border-neutral-300', 'dark:border-neutral-600');
|
||||
box.classList.remove('bg-black', 'border-black', 'dark:bg-white', 'dark:border-white');
|
||||
icon.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleLogin(event) {
|
||||
event.preventDefault();
|
||||
|
||||
const username = document.getElementById('username').value.trim();
|
||||
const password = document.getElementById('password').value;
|
||||
const submitBtn = document.getElementById('submitBtn');
|
||||
const errorDiv = document.getElementById('errorMessage');
|
||||
|
||||
// 验证协议勾选
|
||||
if (!document.getElementById('agreeTerms').checked) {
|
||||
errorDiv.textContent = '请先阅读并同意用户服务协议和隐私政策';
|
||||
errorDiv.classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
|
||||
// 禁用按钮
|
||||
submitBtn.disabled = true;
|
||||
submitBtn.innerHTML = '<span class="inline-block w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin mr-2"></span>登录中...';
|
||||
errorDiv.classList.add('hidden');
|
||||
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('username', username);
|
||||
formData.append('password', password);
|
||||
|
||||
const response = await fetch('{{ url_for('main.login') }}', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
});
|
||||
|
||||
if (response.redirected) {
|
||||
window.location.href = response.url;
|
||||
return;
|
||||
}
|
||||
|
||||
const html = await response.text();
|
||||
|
||||
// 检查是否有错误消息
|
||||
if (html.includes('用户名或密码错误') || html.includes('alert-danger')) {
|
||||
errorDiv.textContent = '用户名或密码错误';
|
||||
errorDiv.classList.remove('hidden');
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.innerHTML = '登录';
|
||||
} else {
|
||||
// 登录成功,刷新页面
|
||||
window.location.href = '{{ url_for('main.dashboard') }}';
|
||||
}
|
||||
} catch (error) {
|
||||
errorDiv.textContent = '网络错误,请稍后重试';
|
||||
errorDiv.classList.remove('hidden');
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.innerHTML = '登录';
|
||||
}
|
||||
}
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,294 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
|
||||
{% block title %}抢课日志 - 教务抢课系统{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
<!-- 页面标题 -->
|
||||
<div class="flex justify-between items-center mb-6 list-item-enter" style="animation-delay: 0ms;">
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>
|
||||
抢课日志
|
||||
</h2>
|
||||
<div>
|
||||
<button onclick="clearLogs()"
|
||||
class="px-4 py-2 border border-red-300 dark:border-red-700 text-red-600 dark:text-red-400 rounded-full hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg>
|
||||
清空日志
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 筛选栏 -->
|
||||
<div class="glass rounded-2xl p-6 mb-6 list-item-enter" style="animation-delay: 50ms;">
|
||||
<div class="flex flex-col md:flex-row gap-4 items-center">
|
||||
<div class="flex-1 grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<select id="levelFilter" onchange="loadLogs()"
|
||||
class="w-full px-4 py-2 rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-black focus:outline-none focus:ring-2 focus:ring-black dark:focus:ring-white">
|
||||
<option value="">全部级别</option>
|
||||
<option value="info">信息</option>
|
||||
<option value="success">成功</option>
|
||||
<option value="warning">警告</option>
|
||||
<option value="error">错误</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<select id="taskFilter" onchange="loadLogs()"
|
||||
class="w-full px-4 py-2 rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-black focus:outline-none focus:ring-2 focus:ring-black dark:focus:ring-white">
|
||||
<option value="">全部任务</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-4">
|
||||
<button onclick="loadLogs()"
|
||||
class="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-full hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16"/><path d="M16 21h5v-5"/></svg>
|
||||
刷新
|
||||
</button>
|
||||
<label class="flex items-center gap-2 cursor-pointer">
|
||||
<input type="checkbox" id="autoRefresh" checked onchange="setupAutoRefresh()"
|
||||
class="w-4 h-4 accent-black dark:accent-white">
|
||||
<span class="text-sm">自动刷新</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 日志列表 -->
|
||||
<div class="glass rounded-2xl p-6 list-item-enter" style="animation-delay: 100ms;">
|
||||
<div id="loadingIndicator" class="text-center py-12">
|
||||
<div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
|
||||
<p class="text-gray-500 dark:text-gray-400">加载中...</p>
|
||||
</div>
|
||||
|
||||
<div id="emptyState" class="text-center py-12" style="display: none;">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="mx-auto mb-4 text-gray-400"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>
|
||||
<p class="text-gray-500 dark:text-gray-400">暂无日志</p>
|
||||
</div>
|
||||
|
||||
<div id="logsContainer" style="display: none;">
|
||||
<div id="logsList" class="space-y-2 max-h-[600px] overflow-y-auto font-mono text-sm max-w-4xl mx-auto">
|
||||
<!-- 日志内容 -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 分页 -->
|
||||
<nav id="pagination" class="mt-6" style="display: none;">
|
||||
<div class="flex justify-center items-center gap-2">
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script>
|
||||
let currentPage = 1;
|
||||
let autoRefreshInterval = null;
|
||||
let lastLogId = 0;
|
||||
|
||||
// 加载日志
|
||||
async function loadLogs(page = 1, incremental = false) {
|
||||
if (!incremental) {
|
||||
currentPage = page;
|
||||
document.getElementById('loadingIndicator').style.display = 'block';
|
||||
document.getElementById('emptyState').style.display = 'none';
|
||||
document.getElementById('logsContainer').style.display = 'none';
|
||||
document.getElementById('pagination').style.display = 'none';
|
||||
}
|
||||
|
||||
const level = document.getElementById('levelFilter').value;
|
||||
const taskId = document.getElementById('taskFilter').value;
|
||||
|
||||
try {
|
||||
let url;
|
||||
if (incremental && lastLogId > 0) {
|
||||
url = `/api/logs/recent?after_id=${lastLogId}`;
|
||||
if (taskId) url += `&task_id=${taskId}`;
|
||||
} else {
|
||||
url = `/api/logs/list?page=${page}&per_page=50`;
|
||||
if (level) url += `&level=${level}`;
|
||||
if (taskId) url += `&task_id=${taskId}`;
|
||||
}
|
||||
|
||||
const data = await apiRequest(url);
|
||||
|
||||
if (!incremental) {
|
||||
document.getElementById('loadingIndicator').style.display = 'none';
|
||||
}
|
||||
|
||||
if (!data.success) {
|
||||
if (!incremental) {
|
||||
document.getElementById('emptyState').style.display = 'block';
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const logs = data.logs || [];
|
||||
|
||||
if (logs.length === 0 && !incremental) {
|
||||
document.getElementById('emptyState').style.display = 'block';
|
||||
return;
|
||||
}
|
||||
|
||||
renderLogs(logs, incremental);
|
||||
|
||||
if (!incremental) {
|
||||
document.getElementById('logsContainer').style.display = 'block';
|
||||
if (data.pages > 1) {
|
||||
renderPagination(data.total, data.pages, page);
|
||||
document.getElementById('pagination').style.display = 'block';
|
||||
}
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
if (!incremental) {
|
||||
document.getElementById('loadingIndicator').style.display = 'none';
|
||||
showToast('加载失败', 'error');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 渲染日志
|
||||
function renderLogs(logs, append = false) {
|
||||
const container = document.getElementById('logsList');
|
||||
|
||||
if (!append) {
|
||||
container.innerHTML = '';
|
||||
lastLogId = 0;
|
||||
}
|
||||
|
||||
logs.forEach(log => {
|
||||
if (log.id > lastLogId) {
|
||||
lastLogId = log.id;
|
||||
}
|
||||
|
||||
const levelColors = {
|
||||
'info': 'text-blue-600 dark:text-blue-400',
|
||||
'success': 'text-green-600 dark:text-green-400',
|
||||
'warning': 'text-yellow-600 dark:text-yellow-400',
|
||||
'error': 'text-red-600 dark:text-red-400'
|
||||
};
|
||||
|
||||
const logClass = levelColors[log.level] || 'text-gray-600 dark:text-gray-400';
|
||||
const taskInfo = log.task_id ? `<span class="text-gray-400">[任务#${log.task_id}]</span> ` : '';
|
||||
|
||||
const logHtml = `
|
||||
<div class="p-3 rounded-lg bg-white/50 dark:bg-black/30 border border-gray-100 dark:border-gray-800 hover:bg-white dark:hover:bg-black transition-colors">
|
||||
<span class="text-gray-400 text-xs">${formatTime(log.created_at)}</span>
|
||||
<span class="${logClass} font-bold text-xs">[${log.level.toUpperCase()}]</span>
|
||||
${taskInfo}<span class="text-gray-700 dark:text-gray-300">${escapeHtml(log.message)}</span>
|
||||
</div>
|
||||
`;
|
||||
|
||||
container.insertAdjacentHTML('beforeend', logHtml);
|
||||
// 防 DOM 无限增长(长挂机内存泄漏)
|
||||
while (container.children.length > 500) container.firstChild.remove();
|
||||
});
|
||||
|
||||
// 滚动到底部(如果是追加模式)
|
||||
if (append) {
|
||||
container.scrollTop = container.scrollHeight;
|
||||
}
|
||||
}
|
||||
|
||||
// 渲染分页
|
||||
function renderPagination(total, pages, current) {
|
||||
const nav = document.getElementById('pagination').querySelector('div');
|
||||
let html = '';
|
||||
|
||||
html += `
|
||||
<button onclick="loadLogs(${current - 1})" ${current === 1 ? 'disabled' : ''}
|
||||
class="px-3 py-1 rounded-lg border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
|
||||
上一页
|
||||
</button>
|
||||
`;
|
||||
|
||||
for (let i = 1; i <= pages; i++) {
|
||||
if (i === 1 || i === pages || (i >= current - 2 && i <= current + 2)) {
|
||||
html += `
|
||||
<button onclick="loadLogs(${i})"
|
||||
class="px-3 py-1 rounded-lg transition-colors ${i === current ? 'bg-black dark:bg-white text-white dark:text-black' : 'border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-800'}">
|
||||
${i}
|
||||
</button>
|
||||
`;
|
||||
} else if (i === current - 3 || i === current + 3) {
|
||||
html += `<span class="px-2 text-gray-400">...</span>`;
|
||||
}
|
||||
}
|
||||
|
||||
html += `
|
||||
<button onclick="loadLogs(${current + 1})" ${current === pages ? 'disabled' : ''}
|
||||
class="px-3 py-1 rounded-lg border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
|
||||
下一页
|
||||
</button>
|
||||
`;
|
||||
|
||||
nav.innerHTML = html;
|
||||
}
|
||||
|
||||
// 加载任务列表(用于筛选)
|
||||
async function loadTasksForFilter() {
|
||||
try {
|
||||
const data = await apiRequest('/api/tasks/list?per_page=100');
|
||||
if (data.success && data.tasks) {
|
||||
const select = document.getElementById('taskFilter');
|
||||
// 保留第一个选项
|
||||
const firstOption = select.options[0];
|
||||
select.innerHTML = '';
|
||||
select.appendChild(firstOption);
|
||||
|
||||
data.tasks.forEach(task => {
|
||||
const option = document.createElement('option');
|
||||
option.value = task.id;
|
||||
option.textContent = `#${task.id} ${task.course_name}`;
|
||||
select.appendChild(option);
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载任务列表失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// 清空日志
|
||||
async function clearLogs() {
|
||||
if (!confirm('确定要清空所有日志吗?此操作不可恢复。')) return;
|
||||
|
||||
// 这里可以添加清空日志的API调用
|
||||
showToast('日志已清空', 'success');
|
||||
loadLogs();
|
||||
}
|
||||
|
||||
// HTML转义
|
||||
function escapeHtml(text) {
|
||||
if (!text) return '';
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
// 设置自动刷新
|
||||
function setupAutoRefresh() {
|
||||
const checkbox = document.getElementById('autoRefresh');
|
||||
|
||||
if (checkbox.checked) {
|
||||
autoRefreshInterval = setInterval(() => {
|
||||
loadLogs(currentPage, true);
|
||||
}, 3000);
|
||||
} else {
|
||||
if (autoRefreshInterval) {
|
||||
clearInterval(autoRefreshInterval);
|
||||
autoRefreshInterval = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 页面加载
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
loadLogs();
|
||||
loadTasksForFilter();
|
||||
setupAutoRefresh();
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,606 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN" class="scroll-smooth">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<title>订单状态 - {{ brand_name }}</title>
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<script>
|
||||
tailwind.config = {
|
||||
darkMode: 'class',
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
dark: {
|
||||
bg: '#0a0a0a',
|
||||
card: '#171717',
|
||||
border: '#262626'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;800;900&family=Noto+Sans+SC:wght@300;400;500;700;900&display=swap"
|
||||
rel="stylesheet">
|
||||
<style>
|
||||
body {
|
||||
font-family: 'Inter', 'Noto Sans SC', sans-serif;
|
||||
transition: background-color 0.3s ease, color 0.3s ease;
|
||||
}
|
||||
|
||||
.glass {
|
||||
background: rgba(255, 255, 255, 0.85);
|
||||
backdrop-filter: blur(20px);
|
||||
-webkit-backdrop-filter: blur(20px);
|
||||
border: 1px solid rgba(255, 255, 255, 0.9);
|
||||
}
|
||||
|
||||
.dark .glass {
|
||||
background: rgba(23, 23, 23, 0.85);
|
||||
border: 1px solid rgba(38, 38, 38, 0.9);
|
||||
}
|
||||
|
||||
.layer-4 {
|
||||
box-shadow: 0 24px 60px -10px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
.dark .layer-4 {
|
||||
box-shadow: 0 24px 60px -10px rgba(0, 0, 0, 0.7);
|
||||
}
|
||||
|
||||
.bg-grid {
|
||||
background-size: 40px 40px;
|
||||
background-image: linear-gradient(to right, rgba(0, 0, 0, 0.03) 1px, transparent 1px),
|
||||
linear-gradient(to bottom, rgba(0, 0, 0, 0.03) 1px, transparent 1px);
|
||||
}
|
||||
|
||||
.dark .bg-grid {
|
||||
background-image: linear-gradient(to right, rgba(255, 255, 255, 0.03) 1px, transparent 1px),
|
||||
linear-gradient(to bottom, rgba(255, 255, 255, 0.03) 1px, transparent 1px);
|
||||
}
|
||||
|
||||
@keyframes shake {
|
||||
0%, 100% { transform: translateX(0); }
|
||||
10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
|
||||
20%, 40%, 60%, 80% { transform: translateX(5px); }
|
||||
}
|
||||
|
||||
.shake {
|
||||
animation: shake 0.5s ease-in-out;
|
||||
}
|
||||
|
||||
@keyframes pulse-warning {
|
||||
0%, 100% { opacity: 1; }
|
||||
50% { opacity: 0.6; }
|
||||
}
|
||||
|
||||
.pulse-warning {
|
||||
animation: pulse-warning 1.5s ease-in-out infinite;
|
||||
}
|
||||
|
||||
/* Toast 通知 */
|
||||
@media (min-width: 769px) {
|
||||
.toast-container {
|
||||
position: fixed;
|
||||
top: 20px;
|
||||
right: 20px;
|
||||
z-index: 9999;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.toast {
|
||||
background: #2c3e50;
|
||||
color: white;
|
||||
padding: 14px 22px;
|
||||
border-radius: 8px;
|
||||
margin-bottom: 10px;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
|
||||
transform: translateX(100%);
|
||||
opacity: 0;
|
||||
transition: all 0.3s ease;
|
||||
pointer-events: all;
|
||||
min-width: 250px;
|
||||
max-width: 350px;
|
||||
font-size: 14px;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.toast.show {
|
||||
transform: translateX(0);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.toast-container {
|
||||
position: fixed;
|
||||
bottom: max(20px, env(safe-area-inset-bottom));
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 9999;
|
||||
pointer-events: none;
|
||||
width: 90%;
|
||||
max-width: 400px;
|
||||
}
|
||||
|
||||
.toast {
|
||||
background: #2c3e50;
|
||||
color: white;
|
||||
padding: 12px 20px;
|
||||
border-radius: 24px;
|
||||
margin-bottom: 8px;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.25);
|
||||
transform: translateY(100px);
|
||||
opacity: 0;
|
||||
transition: all 0.3s ease;
|
||||
pointer-events: all;
|
||||
width: 100%;
|
||||
font-size: 14px;
|
||||
text-align: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.toast.show {
|
||||
transform: translateY(0);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.toast.error {
|
||||
background: #e74c3c;
|
||||
}
|
||||
|
||||
.toast.success {
|
||||
background: #27ae60;
|
||||
}
|
||||
|
||||
.dark .toast.error {
|
||||
background: #ff6b6b;
|
||||
}
|
||||
|
||||
.dark .toast.success {
|
||||
background: #4caf50;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body class="bg-neutral-50 text-neutral-900 dark:bg-dark-bg dark:text-neutral-100 min-h-screen">
|
||||
<!-- Toast 通知容器 -->
|
||||
<div class="toast-container" id="toastContainer"></div>
|
||||
|
||||
<!-- 导航 -->
|
||||
<nav class="fixed w-full z-50 glass border-b border-black/5 dark:border-white/10 transition-colors duration-300">
|
||||
<div class="max-w-6xl mx-auto px-4 md:px-6 h-16 flex justify-between items-center">
|
||||
<a href="/buy" class="flex items-center gap-2 md:gap-3 group cursor-pointer">
|
||||
<div class="w-8 h-8 bg-black dark:bg-white rounded-lg flex items-center justify-center text-white dark:text-black font-bold text-sm group-hover:rotate-12 transition-transform shrink-0">
|
||||
S</div>
|
||||
<span class="font-bold tracking-tight text-sm md:text-base truncate">{{ brand_name }}</span>
|
||||
</a>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<!-- 主内容区 -->
|
||||
<main class="pt-24 md:pt-32 pb-16 md:pb-24 px-4 md:px-6 bg-grid min-h-screen flex items-center justify-center">
|
||||
<div class="max-w-md w-full">
|
||||
<div class="glass rounded-2xl md:rounded-3xl p-8 md:p-12 layer-4 text-center" id="mainCard">
|
||||
<!-- 加载状态 -->
|
||||
<div id="loadingState">
|
||||
<div class="w-20 h-20 md:w-24 md:h-24 bg-blue-100 dark:bg-blue-900/30 rounded-full flex items-center justify-center mx-auto mb-6">
|
||||
<svg class="w-10 h-10 md:w-12 md:h-12 text-blue-500 animate-spin" fill="none" viewBox="0 0 24 24">
|
||||
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
|
||||
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||
</svg>
|
||||
</div>
|
||||
<h1 class="text-2xl md:text-3xl font-bold mb-2 text-neutral-900 dark:text-white">正在查询订单...</h1>
|
||||
<p class="text-neutral-500 dark:text-neutral-400">请稍候</p>
|
||||
</div>
|
||||
|
||||
<!-- 订单过期状态 -->
|
||||
<div id="expiredState" class="hidden">
|
||||
<div class="w-20 h-20 md:w-24 md:h-24 bg-orange-100 dark:bg-orange-900/30 rounded-full flex items-center justify-center mx-auto mb-6">
|
||||
<svg class="w-10 h-10 md:w-12 md:h-12 text-orange-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
|
||||
</svg>
|
||||
</div>
|
||||
<h1 class="text-2xl md:text-3xl font-bold mb-2 text-neutral-900 dark:text-white">订单已过期</h1>
|
||||
<p class="text-neutral-500 dark:text-neutral-400 mb-6">
|
||||
该订单已超过5分钟有效期,请重新下单
|
||||
</p>
|
||||
<div class="bg-neutral-100 dark:bg-neutral-800 rounded-xl p-4 mb-6">
|
||||
<div class="text-xs text-neutral-500 dark:text-neutral-400 mb-1">原订单号</div>
|
||||
<div class="text-sm font-mono text-neutral-700 dark:text-neutral-300" id="expiredOrderId">-</div>
|
||||
</div>
|
||||
<a href="/buy" class="block w-full py-3 bg-black dark:bg-white text-white dark:text-black font-semibold rounded-xl hover:shadow-lg transition-all">
|
||||
重新购买
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<!-- 订单取消状态 -->
|
||||
<div id="cancelledState" class="hidden">
|
||||
<div class="w-20 h-20 md:w-24 md:h-24 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center mx-auto mb-6">
|
||||
<svg class="w-10 h-10 md:w-12 md:h-12 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"></path>
|
||||
</svg>
|
||||
</div>
|
||||
<h1 class="text-2xl md:text-3xl font-bold mb-2 text-neutral-900 dark:text-white">订单已取消</h1>
|
||||
<p class="text-neutral-500 dark:text-neutral-400 mb-2" id="cancelReason">您已取消该订单</p>
|
||||
<p class="text-neutral-500 dark:text-neutral-400 mb-6">
|
||||
如需继续购买,请重新下单
|
||||
</p>
|
||||
<a href="/buy" class="block w-full py-3 bg-black dark:bg-white text-white dark:text-black font-semibold rounded-xl hover:shadow-lg transition-all">
|
||||
重新购买
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<!-- 支付失败状态 -->
|
||||
<div id="failedState" class="hidden">
|
||||
<div class="w-20 h-20 md:w-24 md:h-24 bg-red-100 dark:bg-red-900/30 rounded-full flex items-center justify-center mx-auto mb-6 shake">
|
||||
<svg class="w-10 h-10 md:w-12 md:h-12 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
|
||||
</svg>
|
||||
</div>
|
||||
<h1 class="text-2xl md:text-3xl font-bold mb-2 text-neutral-900 dark:text-white">支付失败</h1>
|
||||
<p class="text-neutral-500 dark:text-neutral-400 mb-6" id="errorMsg">
|
||||
支付过程中出现问题,请重新尝试
|
||||
</p>
|
||||
<div class="bg-neutral-100 dark:bg-neutral-800 rounded-xl p-4 mb-6">
|
||||
<div class="text-xs text-neutral-500 dark:text-neutral-400 mb-1">订单号</div>
|
||||
<div class="text-sm font-mono text-neutral-700 dark:text-neutral-300" id="failedOrderId">-</div>
|
||||
</div>
|
||||
<div class="space-y-3">
|
||||
<a href="/buy" class="block w-full py-3 bg-black dark:bg-white text-white dark:text-black font-semibold rounded-xl hover:shadow-lg transition-all">
|
||||
重新购买
|
||||
</a>
|
||||
<a href="/" class="block w-full py-3 bg-neutral-200 dark:bg-neutral-800 text-neutral-700 dark:text-neutral-300 font-semibold rounded-xl hover:bg-neutral-300 dark:hover:bg-neutral-700 transition-colors">
|
||||
返回首页
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 订单待支付状态(5分钟内) -->
|
||||
<div id="pendingState" class="hidden">
|
||||
<!-- 倒计时警告 -->
|
||||
<div class="bg-orange-50 dark:bg-orange-900/20 border border-orange-200 dark:border-orange-800 rounded-xl p-4 mb-6 pulse-warning">
|
||||
<div class="flex items-center gap-3">
|
||||
<svg class="w-6 h-6 text-orange-500 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
|
||||
</svg>
|
||||
<div class="text-left">
|
||||
<div class="text-sm font-semibold text-orange-800 dark:text-orange-200">订单即将过期</div>
|
||||
<div class="text-xs text-orange-600 dark:text-orange-400 mt-0.5">
|
||||
剩余 <span id="countdown" class="font-bold">--:--</span> 自动失效
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="w-20 h-20 md:w-24 md:h-24 bg-yellow-100 dark:bg-yellow-900/30 rounded-full flex items-center justify-center mx-auto mb-6">
|
||||
<svg class="w-10 h-10 md:w-12 md:h-12 text-yellow-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
|
||||
</svg>
|
||||
</div>
|
||||
<h1 class="text-2xl md:text-3xl font-bold mb-2 text-neutral-900 dark:text-white">等待支付</h1>
|
||||
<p class="text-neutral-500 dark:text-neutral-400 mb-6">
|
||||
订单尚未支付,如需取消请点击下方按钮
|
||||
</p>
|
||||
|
||||
<div class="bg-neutral-100 dark:bg-neutral-800 rounded-xl p-4 mb-6">
|
||||
<div class="text-xs text-neutral-500 dark:text-neutral-400 mb-1">订单号</div>
|
||||
<div class="text-sm font-mono text-neutral-700 dark:text-neutral-300" id="pendingOrderId">-</div>
|
||||
<div class="text-xs text-neutral-500 dark:text-neutral-400 mt-2 mb-1">应付金额</div>
|
||||
<div class="text-lg font-bold text-neutral-900 dark:text-white">¥<span id="pendingAmount">-</span></div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-3">
|
||||
<button id="retryPayBtn" onclick="retryPay()" class="w-full py-3 bg-black dark:bg-white text-white dark:text-black font-semibold rounded-xl hover:shadow-lg transition-all">
|
||||
继续支付
|
||||
</button>
|
||||
<button id="cancelOrderBtn" onclick="cancelOrder()" class="w-full py-3 bg-neutral-200 dark:bg-neutral-800 text-neutral-700 dark:text-neutral-300 font-semibold rounded-xl hover:bg-neutral-300 dark:hover:bg-neutral-700 transition-colors">
|
||||
取消订单
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<script>
|
||||
// 全局变量
|
||||
let orderId = null;
|
||||
let countdownTimer = null;
|
||||
let currentOrderStatus = null;
|
||||
|
||||
// Toast 通知
|
||||
function showToast(message, type = 'info', duration = 3000) {
|
||||
const container = document.getElementById('toastContainer');
|
||||
const toast = document.createElement('div');
|
||||
toast.className = `toast ${type}`;
|
||||
toast.innerHTML = `<span>${message}</span>`;
|
||||
container.appendChild(toast);
|
||||
setTimeout(() => toast.classList.add('show'), 10);
|
||||
setTimeout(() => {
|
||||
toast.classList.remove('show');
|
||||
setTimeout(() => toast.remove(), 400);
|
||||
}, duration);
|
||||
}
|
||||
|
||||
// 主题初始化
|
||||
if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
|
||||
document.documentElement.classList.add('dark');
|
||||
}
|
||||
|
||||
// 从URL获取订单号
|
||||
function getOrderIdFromUrl() {
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
return urlParams.get('orderNo') || urlParams.get('order_id') || '{{ order_id }}';
|
||||
}
|
||||
|
||||
// 查询订单状态
|
||||
async function fetchOrderStatus(orderId) {
|
||||
try {
|
||||
const response = await fetch(`/api/orders/${orderId}/status`);
|
||||
const data = await response.json();
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error('查询订单状态失败:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 获取订单详情
|
||||
async function fetchOrder(orderId) {
|
||||
try {
|
||||
const response = await fetch(`/api/orders/${orderId}`);
|
||||
const data = await response.json();
|
||||
return data.order;
|
||||
} catch (error) {
|
||||
console.error('获取订单详情失败:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 获取支付参数并跳转
|
||||
async function retryPay() {
|
||||
if (!orderId) return;
|
||||
|
||||
const btn = document.getElementById('retryPayBtn');
|
||||
btn.disabled = true;
|
||||
btn.textContent = '正在获取支付信息...';
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/api/orders/${orderId}/payment_params`);
|
||||
const data = await response.json();
|
||||
|
||||
if (!data.success) {
|
||||
showToast(data.message || '获取支付信息失败', 'error');
|
||||
btn.disabled = false;
|
||||
btn.textContent = '继续支付';
|
||||
return;
|
||||
}
|
||||
|
||||
// 构建支付表单
|
||||
const form = document.createElement('form');
|
||||
form.method = 'POST';
|
||||
form.action = 'https://api-4ndv48ogy5fk.zhifu.fm.it88168.com/api/startOrder';
|
||||
form.target = '_self';
|
||||
form.style.display = 'none';
|
||||
|
||||
const fields = ['merchantNum', 'orderNo', 'amount', 'notifyUrl', 'returnUrl', 'payType', 'sign', 'returnType', 'subject'];
|
||||
fields.forEach(field => {
|
||||
if (data.params && data.params[field]) {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'hidden';
|
||||
input.name = field;
|
||||
input.value = data.params[field];
|
||||
form.appendChild(input);
|
||||
}
|
||||
});
|
||||
|
||||
document.body.appendChild(form);
|
||||
form.submit();
|
||||
|
||||
} catch (error) {
|
||||
console.error('支付跳转失败:', error);
|
||||
showToast('支付跳转失败,请重试', 'error');
|
||||
btn.disabled = false;
|
||||
btn.textContent = '继续支付';
|
||||
}
|
||||
}
|
||||
|
||||
// 取消订单
|
||||
async function cancelOrder() {
|
||||
if (!orderId) return;
|
||||
|
||||
if (!confirm('确定要取消这个订单吗?取消后无法恢复。')) {
|
||||
return;
|
||||
}
|
||||
|
||||
const btn = document.getElementById('cancelOrderBtn');
|
||||
btn.disabled = true;
|
||||
btn.textContent = '正在取消...';
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/orders/${orderId}/cancel`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ reason: '用户主动取消' })
|
||||
});
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
showToast('订单已取消', 'success');
|
||||
// 停止倒计时
|
||||
if (countdownTimer) {
|
||||
clearInterval(countdownTimer);
|
||||
}
|
||||
// 更新UI
|
||||
document.getElementById('pendingState').classList.add('hidden');
|
||||
document.getElementById('cancelledState').classList.remove('hidden');
|
||||
} else {
|
||||
showToast(data.message || '取消订单失败', 'error');
|
||||
btn.disabled = false;
|
||||
btn.textContent = '取消订单';
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('取消订单失败:', error);
|
||||
showToast('取消订单失败,请重试', 'error');
|
||||
btn.disabled = false;
|
||||
btn.textContent = '取消订单';
|
||||
}
|
||||
}
|
||||
|
||||
// 更新倒计时显示
|
||||
function updateCountdown(remainingSeconds) {
|
||||
const countdownEl = document.getElementById('countdown');
|
||||
if (remainingSeconds <= 0) {
|
||||
countdownEl.textContent = '00:00';
|
||||
// 停止倒计时
|
||||
if (countdownTimer) {
|
||||
clearInterval(countdownTimer);
|
||||
}
|
||||
// 刷新状态
|
||||
checkOrderStatus();
|
||||
return;
|
||||
}
|
||||
|
||||
const minutes = Math.floor(remainingSeconds / 60);
|
||||
const seconds = remainingSeconds % 60;
|
||||
countdownEl.textContent = `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
// 检查订单状态
|
||||
async function checkOrderStatus() {
|
||||
if (!orderId) return;
|
||||
|
||||
const data = await fetchOrderStatus(orderId);
|
||||
if (!data) {
|
||||
showFailedState('无法获取订单状态');
|
||||
return;
|
||||
}
|
||||
|
||||
currentOrderStatus = data;
|
||||
|
||||
// 根据状态显示不同UI
|
||||
if (data.status === 'pending') {
|
||||
if (data.is_expired || data.remaining_seconds <= 0) {
|
||||
showExpiredState();
|
||||
} else {
|
||||
showPendingState(data, await fetchOrder(orderId));
|
||||
}
|
||||
} else if (data.status === 'cancelled' || data.status === 'expired') {
|
||||
if (data.status === 'cancelled') {
|
||||
showCancelledState(data.cancel_reason);
|
||||
} else {
|
||||
showExpiredState();
|
||||
}
|
||||
} else if (data.status === 'paid' || data.status === 'processed') {
|
||||
// 订单已支付,跳转到成功页面
|
||||
window.location.href = `/success/${orderId}`;
|
||||
} else {
|
||||
// 其他状态(如 failed)
|
||||
showFailedState();
|
||||
}
|
||||
}
|
||||
|
||||
// 显示加载状态
|
||||
function showLoadingState() {
|
||||
document.getElementById('loadingState').classList.remove('hidden');
|
||||
document.getElementById('expiredState').classList.add('hidden');
|
||||
document.getElementById('cancelledState').classList.add('hidden');
|
||||
document.getElementById('failedState').classList.add('hidden');
|
||||
document.getElementById('pendingState').classList.add('hidden');
|
||||
}
|
||||
|
||||
// 显示订单过期状态
|
||||
function showExpiredState() {
|
||||
document.getElementById('loadingState').classList.add('hidden');
|
||||
document.getElementById('expiredState').classList.remove('hidden');
|
||||
document.getElementById('cancelledState').classList.add('hidden');
|
||||
document.getElementById('failedState').classList.add('hidden');
|
||||
document.getElementById('pendingState').classList.add('hidden');
|
||||
document.getElementById('expiredOrderId').textContent = orderId;
|
||||
}
|
||||
|
||||
// 显示订单取消状态
|
||||
function showCancelledState(reason) {
|
||||
document.getElementById('loadingState').classList.add('hidden');
|
||||
document.getElementById('expiredState').classList.add('hidden');
|
||||
document.getElementById('cancelledState').classList.remove('hidden');
|
||||
document.getElementById('failedState').classList.add('hidden');
|
||||
document.getElementById('pendingState').classList.add('hidden');
|
||||
document.getElementById('cancelReason').textContent = reason || '您已取消该订单';
|
||||
}
|
||||
|
||||
// 显示支付失败状态
|
||||
function showFailedState(errorMsg) {
|
||||
document.getElementById('loadingState').classList.add('hidden');
|
||||
document.getElementById('expiredState').classList.add('hidden');
|
||||
document.getElementById('cancelledState').classList.add('hidden');
|
||||
document.getElementById('failedState').classList.remove('hidden');
|
||||
document.getElementById('pendingState').classList.add('hidden');
|
||||
if (errorMsg) {
|
||||
document.getElementById('errorMsg').textContent = errorMsg;
|
||||
}
|
||||
document.getElementById('failedOrderId').textContent = orderId;
|
||||
}
|
||||
|
||||
// 显示待支付状态
|
||||
async function showPendingState(statusData, orderData) {
|
||||
document.getElementById('loadingState').classList.add('hidden');
|
||||
document.getElementById('expiredState').classList.add('hidden');
|
||||
document.getElementById('cancelledState').classList.add('hidden');
|
||||
document.getElementById('failedState').classList.add('hidden');
|
||||
document.getElementById('pendingState').classList.remove('hidden');
|
||||
|
||||
document.getElementById('pendingOrderId').textContent = orderId;
|
||||
if (orderData) {
|
||||
document.getElementById('pendingAmount').textContent = orderData.final_amount || orderData.amount || '-';
|
||||
}
|
||||
|
||||
// 启动倒计时
|
||||
if (countdownTimer) {
|
||||
clearInterval(countdownTimer);
|
||||
}
|
||||
|
||||
let remaining = statusData.remaining_seconds || 0;
|
||||
updateCountdown(remaining);
|
||||
|
||||
countdownTimer = setInterval(() => {
|
||||
remaining--;
|
||||
updateCountdown(remaining);
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
// 页面加载时查询订单状态
|
||||
window.addEventListener('load', async () => {
|
||||
orderId = getOrderIdFromUrl();
|
||||
|
||||
if (!orderId || orderId === '{{ order_id }}') {
|
||||
// 没有订单号,跳转到购买页面
|
||||
window.location.href = '/buy';
|
||||
return;
|
||||
}
|
||||
|
||||
showLoadingState();
|
||||
|
||||
// 延迟一点再查询,让用户看到加载状态
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
|
||||
checkOrderStatus();
|
||||
});
|
||||
|
||||
// 页面离开时清理定时器
|
||||
window.addEventListener('beforeunload', () => {
|
||||
if (countdownTimer) {
|
||||
clearInterval(countdownTimer);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,321 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN" class="scroll-smooth">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{% if pending %}支付确认中{% else %}支付成功 - 兑换码领取{% endif %}</title>
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<script>
|
||||
tailwind.config = {
|
||||
darkMode: 'class',
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
dark: {
|
||||
bg: '#0a0a0a',
|
||||
card: '#171717',
|
||||
border: '#262626'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;800;900&family=Noto+Sans+SC:wght@300;400;500;700;900&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
body {
|
||||
font-family: 'Inter', 'Noto Sans SC', sans-serif;
|
||||
transition: background-color 0.3s ease, color 0.3s ease;
|
||||
}
|
||||
|
||||
.glass {
|
||||
background: rgba(255, 255, 255, 0.85);
|
||||
backdrop-filter: blur(20px);
|
||||
-webkit-backdrop-filter: blur(20px);
|
||||
border: 1px solid rgba(255, 255, 255, 0.9);
|
||||
}
|
||||
|
||||
.dark .glass {
|
||||
background: rgba(23, 23, 23, 0.85);
|
||||
border: 1px solid rgba(38, 38, 38, 0.9);
|
||||
}
|
||||
|
||||
.layer-3 {
|
||||
box-shadow: 0 12px 40px -5px rgba(0, 0, 0, 0.12);
|
||||
}
|
||||
|
||||
.dark .layer-3 {
|
||||
box-shadow: 0 12px 40px -5px rgba(0, 0, 0, 0.6);
|
||||
}
|
||||
|
||||
.bg-grid {
|
||||
background-size: 40px 40px;
|
||||
background-image: linear-gradient(to right, rgba(0, 0, 0, 0.03) 1px, transparent 1px),
|
||||
linear-gradient(to bottom, rgba(0, 0, 0, 0.03) 1px, transparent 1px);
|
||||
}
|
||||
|
||||
.dark .bg-grid {
|
||||
background-image: linear-gradient(to right, rgba(255, 255, 255, 0.03) 1px, transparent 1px),
|
||||
linear-gradient(to bottom, rgba(255, 255, 255, 0.03) 1px, transparent 1px);
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: #111;
|
||||
color: #fff;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
.dark .btn-primary {
|
||||
background: #fff;
|
||||
color: #000;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 10px 30px -5px rgba(0, 0 0, 0.3);
|
||||
}
|
||||
|
||||
.dark .btn-primary:hover {
|
||||
box-shadow: 0 10px 30px -5px rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
|
||||
.code-card {
|
||||
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.code-card:hover {
|
||||
transform: translateY(-2px);
|
||||
border-color: #111;
|
||||
}
|
||||
|
||||
.dark .code-card:hover {
|
||||
border-color: #fff;
|
||||
}
|
||||
|
||||
.code-card:active {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
|
||||
.code-card.copied {
|
||||
border-color: #10b981 !important;
|
||||
background: rgba(16, 185, 129, 0.05) !important;
|
||||
}
|
||||
|
||||
.code-card.copied::after {
|
||||
content: "已复制";
|
||||
position: absolute;
|
||||
right: 12px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
background: #10b981;
|
||||
color: white;
|
||||
padding: 4px 12px;
|
||||
border-radius: 20px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
animation: fadeIn 0.3s ease;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from { opacity: 0; transform: translateY(-50%) translateX(10px); }
|
||||
to { opacity: 1; transform: translateY(-50%) translateX(0); }
|
||||
}
|
||||
|
||||
@keyframes slideUp {
|
||||
from { opacity: 0; transform: translateY(30px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
.animate-slide-up {
|
||||
animation: slideUp 0.6s cubic-bezier(0.4, 0, 0.2, 1) forwards;
|
||||
}
|
||||
|
||||
.success-check {
|
||||
animation: scaleIn 0.5s cubic-bezier(0.4, 0, 0.2, 1) forwards;
|
||||
}
|
||||
|
||||
@keyframes scaleIn {
|
||||
from { transform: scale(0); opacity: 0; }
|
||||
to { transform: scale(1); opacity: 1; }
|
||||
}
|
||||
|
||||
.spinner {
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
border: 4px solid #e5e5e5;
|
||||
border-top: 4px solid #111;
|
||||
border-radius: 50%;
|
||||
animation: spin 1s linear infinite;
|
||||
}
|
||||
|
||||
.dark .spinner {
|
||||
border-color: #262626;
|
||||
border-top-color: #fff;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
0% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(360deg); }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body class="bg-neutral-50 text-neutral-900 dark:bg-dark-bg dark:text-neutral-100 min-h-screen flex items-center justify-center p-4 bg-grid">
|
||||
|
||||
{% if status == 'pending' %}
|
||||
<!-- 等待支付确认状态 -->
|
||||
<div class="glass rounded-3xl p-10 layer-3 text-center max-w-md w-full animate-slide-up">
|
||||
<div class="spinner mx-auto mb-6"></div>
|
||||
<h2 class="text-2xl font-bold mb-2 text-neutral-900 dark:text-white">正在确认支付结果...</h2>
|
||||
<p class="text-neutral-500 dark:text-neutral-400 mb-6">请稍候,系统正在处理您的订单</p>
|
||||
<div class="inline-flex items-center gap-2 px-4 py-2 bg-neutral-100 dark:bg-neutral-800 rounded-full">
|
||||
<span class="w-2 h-2 bg-neutral-400 rounded-full animate-pulse"></span>
|
||||
<span class="text-xs text-neutral-500 dark:text-neutral-400 font-mono">{{ order_id }}</span>
|
||||
</div>
|
||||
<p class="mt-6 text-xs text-neutral-400 dark:text-neutral-500">页面将在 3 秒后自动刷新</p>
|
||||
</div>
|
||||
<script>
|
||||
setTimeout(() => location.reload(), 3000);
|
||||
</script>
|
||||
{% else %}
|
||||
<!-- 支付成功状态 -->
|
||||
|
||||
<!-- Toast 容器 -->
|
||||
<div class="toast-container" id="toastContainer"></div>
|
||||
|
||||
<div class="w-full max-w-lg animate-slide-up">
|
||||
|
||||
<!-- 成功状态卡片 -->
|
||||
<div class="glass rounded-3xl p-8 md:p-10 layer-3 mb-6 text-center">
|
||||
<!-- 成功图标 -->
|
||||
<div class="success-check w-20 h-20 bg-black dark:bg-white rounded-full flex items-center justify-center mx-auto mb-6 text-white dark:text-black shadow-lg">
|
||||
<svg class="w-10 h-10" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7"></path>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<h1 class="text-3xl md:text-4xl font-black tracking-tight mb-2 text-neutral-900 dark:text-white">支付成功</h1>
|
||||
<p class="text-neutral-500 dark:text-neutral-400 mb-8">您的授权兑换码已生成</p>
|
||||
|
||||
<!-- 订单信息 -->
|
||||
<div class="bg-neutral-100 dark:bg-neutral-800/50 rounded-2xl p-6 mb-8 text-left space-y-3">
|
||||
<div class="flex justify-between items-center text-sm">
|
||||
<span class="text-neutral-500 dark:text-neutral-400">订单编号</span>
|
||||
<span class="font-mono font-medium text-neutral-900 dark:text-white text-xs tracking-wider">{{ order.order_id }}</span>
|
||||
</div>
|
||||
<div class="flex justify-between items-center text-sm">
|
||||
<span class="text-neutral-500 dark:text-neutral-400">支付金额</span>
|
||||
<span class="font-bold text-lg text-neutral-900 dark:text-white">¥{{ order.amount }}</span>
|
||||
</div>
|
||||
<div class="flex justify-between items-center text-sm">
|
||||
<span class="text-neutral-500 dark:text-neutral-400">购买份数</span>
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="font-medium text-neutral-900 dark:text-white">{{ order.quantity }} 份</span>
|
||||
<span class="px-2 py-0.5 bg-neutral-200 dark:bg-neutral-700 text-neutral-600 dark:text-neutral-300 text-[10px] font-bold rounded-full">有效期至本学期结束</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 兑换码区域 -->
|
||||
<div class="text-left mb-6">
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h3 class="text-sm font-bold uppercase tracking-wider text-neutral-500 dark:text-neutral-400">兑换码列表</h3>
|
||||
<span class="text-xs text-neutral-400 dark:text-neutral-500">点击复制</span>
|
||||
</div>
|
||||
|
||||
<div class="space-y-3" id="codesContainer">
|
||||
{% for code in codes %}
|
||||
<div class="code-card bg-white dark:bg-neutral-800 border border-neutral-200 dark:border-neutral-700 rounded-xl p-4 font-mono text-sm md:text-base tracking-wider text-center text-neutral-900 dark:text-white cursor-pointer select-all" onclick="copyCode(this, '{{ code }}')">
|
||||
{{ code }}
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 下载按钮 -->
|
||||
<a href="{{ download_url }}" class="btn-primary w-full py-4 rounded-full font-bold text-sm tracking-wide inline-flex items-center justify-center gap-2 group">
|
||||
<svg class="w-5 h-5 transition-transform group-hover:-translate-y-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path>
|
||||
</svg>
|
||||
立即下载软件
|
||||
</a>
|
||||
<p class="mt-3 text-xs text-neutral-400 dark:text-neutral-500">
|
||||
Windows 10/11 64位 · 版本 {{ version }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- 提示信息 -->
|
||||
<div class="glass rounded-2xl p-6 layer-1 border-l-4 border-l-yellow-500 dark:border-l-yellow-600">
|
||||
<div class="flex items-start gap-3">
|
||||
<svg class="w-5 h-5 text-yellow-600 dark:text-yellow-500 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
|
||||
</svg>
|
||||
<div class="text-sm text-neutral-600 dark:text-neutral-300 leading-relaxed">
|
||||
<strong class="text-neutral-900 dark:text-white block mb-1">重要提示</strong>
|
||||
首个兑换码已自动复制到剪贴板。每个兑换码仅限激活一台设备,激活后当前选课周期内有效。请妥善保存订单编号以便日后查询。
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// 主题初始化(跟随系统)
|
||||
if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
|
||||
document.documentElement.classList.add('dark');
|
||||
}
|
||||
|
||||
// Toast 通知
|
||||
function showToast(message) {
|
||||
const container = document.getElementById('toastContainer');
|
||||
const toast = document.createElement('div');
|
||||
toast.className = 'toast';
|
||||
toast.innerHTML = `<span>${message}</span>`;
|
||||
container.appendChild(toast);
|
||||
setTimeout(() => toast.classList.add('show'), 10);
|
||||
setTimeout(() => {
|
||||
toast.classList.remove('show');
|
||||
setTimeout(() => toast.remove(), 400);
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
// 复制功能
|
||||
async function copyToClipboard(text) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
showToast(`已复制: ${text}`);
|
||||
} catch (err) {
|
||||
const input = document.createElement('input');
|
||||
input.value = text;
|
||||
document.body.appendChild(input);
|
||||
input.select();
|
||||
document.execCommand('copy');
|
||||
document.body.removeChild(input);
|
||||
showToast('已复制到剪贴板');
|
||||
}
|
||||
}
|
||||
|
||||
function copyCode(element, text) {
|
||||
copyToClipboard(text);
|
||||
element.classList.add('copied');
|
||||
setTimeout(() => element.classList.remove('copied'), 2000);
|
||||
}
|
||||
|
||||
// 页面加载后自动复制第一个兑换码
|
||||
window.addEventListener('load', () => {
|
||||
setTimeout(() => {
|
||||
const firstCode = document.querySelector('.code-card');
|
||||
if (firstCode) {
|
||||
const codeText = firstCode.textContent.trim();
|
||||
copyToClipboard(codeText);
|
||||
firstCode.classList.add('copied');
|
||||
setTimeout(() => firstCode.classList.remove('copied'), 2000);
|
||||
}
|
||||
}, 800);
|
||||
});
|
||||
</script>
|
||||
{% endif %}
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,139 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
|
||||
{% block title %}个人信息 - {{ brand_name }}{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
.info-label { color: #6b7280; }
|
||||
.dark .info-label { color: #9ca3af; }
|
||||
.info-value { font-weight: 500; }
|
||||
|
||||
@keyframes fadeSlideIn {
|
||||
from { opacity: 0; transform: translateY(8px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.row-animate { animation: fadeSlideIn 0.3s ease both; }
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 list-item-enter" style="animation-delay: 0ms;">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
|
||||
<circle cx="12" cy="7" r="4"/>
|
||||
</svg>
|
||||
个人信息
|
||||
</h2>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">查看学籍基本信息</p>
|
||||
</div>
|
||||
<button onclick="refreshInfo()"
|
||||
class="px-4 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm font-medium hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<polyline points="23 4 23 10 17 10"/>
|
||||
<path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>
|
||||
</svg>
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div id="loadingIndicator" class="text-center py-12 list-item-enter" style="animation-delay: 100ms;">
|
||||
<div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
|
||||
<p class="text-gray-500 dark:text-gray-400">正在加载个人信息...</p>
|
||||
</div>
|
||||
|
||||
<div id="errorMessage" class="glass rounded-2xl p-6 mb-4 text-center hidden list-item-enter">
|
||||
<p id="errorText" class="text-red-500"></p>
|
||||
</div>
|
||||
|
||||
<div id="infoContainer" class="hidden list-item-enter" style="animation-delay: 150ms;">
|
||||
<div class="glass rounded-2xl p-6">
|
||||
<div id="infoGrid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script>
|
||||
// ── Session 健康检查 ──
|
||||
async function initSession() {
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/ping');
|
||||
const data = await res.json();
|
||||
if (!data.success) { console.warn('Session ping 失败:', data.message); return false; }
|
||||
if (data.refreshed) console.log('🔄 Session 已自动刷新');
|
||||
return true;
|
||||
} catch (e) { console.error('Session ping 异常:', e); return false; }
|
||||
}
|
||||
|
||||
const LABEL_MAP = {
|
||||
'xh': '学号', 'xm': '姓名', 'xbm': '性别', 'csrq': '出生日期',
|
||||
'mzm': '民族', 'zym': '专业', 'jg': '籍贯', 'bjm': '班级',
|
||||
'yxm': '院系', 'nj': '年级', 'xz': '学制', 'rxrq': '入学日期',
|
||||
'sfzh': '身份证号', 'lxsj': '联系电话', 'email': '电子邮箱',
|
||||
'jtdz': '家庭地址', 'BJ': '班级', 'NJ': '年级', 'ZY': '专业',
|
||||
'YX': '院系', 'XM': '姓名', 'XH': '学号', 'XB': '性别',
|
||||
};
|
||||
|
||||
async function refreshInfo() {
|
||||
document.getElementById('loadingIndicator').classList.remove('hidden');
|
||||
document.getElementById('errorMessage').classList.add('hidden');
|
||||
document.getElementById('infoContainer').classList.add('hidden');
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/personal-info');
|
||||
const data = await res.json();
|
||||
|
||||
document.getElementById('loadingIndicator').classList.add('hidden');
|
||||
|
||||
if (!data.success) {
|
||||
document.getElementById('errorText').textContent = data.message || '查询失败';
|
||||
document.getElementById('errorMessage').classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
|
||||
renderInfo(data.info || {});
|
||||
document.getElementById('infoContainer').classList.remove('hidden');
|
||||
} catch (e) {
|
||||
document.getElementById('loadingIndicator').classList.add('hidden');
|
||||
document.getElementById('errorText').textContent = '网络错误: ' + e.message;
|
||||
document.getElementById('errorMessage').classList.remove('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
function renderInfo(info) {
|
||||
const grid = document.getElementById('infoGrid');
|
||||
if (!info || !Object.keys(info).length) {
|
||||
grid.innerHTML = '<p class="text-center text-gray-400 col-span-full">暂无数据</p>';
|
||||
return;
|
||||
}
|
||||
const entries = [];
|
||||
for (const [key, value] of Object.entries(info)) {
|
||||
const label = LABEL_MAP[key] || key;
|
||||
if (key.startsWith('_') || value === null || value === '' || typeof value === 'object') continue;
|
||||
if (key.toLowerCase().includes('password') || key.toLowerCase().includes('pwd')) continue;
|
||||
entries.push({ label, value });
|
||||
}
|
||||
if (!entries.length) {
|
||||
grid.innerHTML = '<p class="text-center text-gray-400 col-span-full">暂无有效字段</p>';
|
||||
return;
|
||||
}
|
||||
grid.innerHTML = entries.map((e, i) => `
|
||||
<div class="row-animate flex flex-col gap-1 p-3 rounded-xl bg-gray-50/50 dark:bg-gray-800/30" style="animation-delay:${i * 30}ms;">
|
||||
<span class="info-label text-xs">${e.label}</span>
|
||||
<span class="info-value text-sm">${e.value}</span>
|
||||
</div>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
initSession().then(sessionOk => {
|
||||
if (!sessionOk) console.warn('教务 Session 可能已失效');
|
||||
refreshInfo();
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,91 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
{% block title %}个人信息编辑 - {{ brand_name }}{% endblock %}
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
@keyframes fadeSlideIn {
|
||||
from { opacity: 0; transform: translateY(8px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.row-animate { animation: fadeSlideIn 0.3s ease both; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.row-animate { animation: none !important; opacity: 1 !important; }
|
||||
.list-item-enter { animation: none !important; opacity: 1 !important; }
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 list-item-enter">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
|
||||
个人信息编辑
|
||||
</h2>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">编辑个人基本信息</p>
|
||||
</div>
|
||||
</div>
|
||||
<div id="loadingIndicator" class="text-center py-12 hidden"><div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div><p class="text-gray-500 dark:text-gray-400">加载中...</p></div>
|
||||
<div id="errorMessage" class="glass rounded-2xl p-6 mb-4 text-center hidden"><p id="errorText" class="text-red-500"></p></div>
|
||||
<div id="formContainer" class="hidden">
|
||||
<div class="glass rounded-2xl p-6 max-w-2xl mx-auto">
|
||||
<form id="editForm">
|
||||
<div id="formFields"></div>
|
||||
<div class="mt-6 flex gap-3">
|
||||
<button type="submit" class="px-6 py-2.5 rounded-lg bg-black dark:bg-white text-white dark:text-black text-sm font-medium hover:opacity-85 transition-opacity">保存修改</button>
|
||||
<button type="button" onclick="loadData()" class="px-4 py-2.5 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm font-medium">刷新</button>
|
||||
</div>
|
||||
</form>
|
||||
<div id="resultMessage" class="mt-4 hidden"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="emptyState" class="glass rounded-2xl p-12 text-center hidden"><p class="text-gray-500 dark:text-gray-400 text-lg">无可编辑字段</p></div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block extra_js %}
|
||||
<script>
|
||||
async function loadData() {
|
||||
document.getElementById('loadingIndicator').classList.remove('hidden');
|
||||
document.getElementById('errorMessage').classList.add('hidden');
|
||||
document.getElementById('formContainer').classList.add('hidden');
|
||||
document.getElementById('emptyState').classList.add('hidden');
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/personal-info-editable');
|
||||
const data = await res.json();
|
||||
document.getElementById('loadingIndicator').classList.add('hidden');
|
||||
if (!data.success) { showError(data.message); return; }
|
||||
const fields = data.fields || [];
|
||||
if (!fields.length) { document.getElementById('emptyState').classList.remove('hidden'); return; }
|
||||
const container = document.getElementById('formFields');
|
||||
container.innerHTML = fields.map(f => {
|
||||
if (f.readonly) return '';
|
||||
let input;
|
||||
if (f.type === 'select') {
|
||||
input = `<select name="${escAttr(f.name)}" class="w-full rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 px-3 py-2 text-sm">${f.options.map(o => `<option value="${escAttr(o.value)}" ${o.selected?'selected':''}>${escHtml(o.label)}</option>`).join('')}</select>`;
|
||||
} else {
|
||||
input = `<input type="text" name="${escAttr(f.name)}" value="${escAttr(f.value)}" class="w-full rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 px-3 py-2 text-sm">`;
|
||||
}
|
||||
return `<div class="mb-4"><label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">${escHtml(f.label)}</label>${input}</div>`;
|
||||
}).join('');
|
||||
document.getElementById('formContainer').classList.remove('hidden');
|
||||
} catch(e) { document.getElementById('loadingIndicator').classList.add('hidden'); showError('网络错误: '+e.message); }
|
||||
}
|
||||
document.getElementById('editForm').addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const formData = new FormData(e.target);
|
||||
const data = Object.fromEntries(formData.entries());
|
||||
const resultEl = document.getElementById('resultMessage');
|
||||
resultEl.classList.remove('hidden');
|
||||
resultEl.innerHTML = '<p class="text-gray-500">提交中...</p>';
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/personal-info/update', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(data) });
|
||||
const result = await res.json();
|
||||
resultEl.innerHTML = result.success ? '<p class="text-green-600">✅ 更新成功</p>' : '<p class="text-red-500">❌ ' + escHtml(result.message) + '</p>';
|
||||
} catch(e) { resultEl.innerHTML = '<p class="text-red-500">❌ 网络错误</p>'; }
|
||||
});
|
||||
function showError(msg) { document.getElementById('errorText').textContent = msg; document.getElementById('errorMessage').classList.remove('hidden'); }
|
||||
function escHtml(s) { if(s==null) return ''; return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"'); }
|
||||
function escAttr(s) { if(s==null) return ''; return String(s).replace(/&/g,'&').replace(/"/g,'"').replace(/</g,'<').replace(/>/g,'>'); }
|
||||
document.addEventListener('DOMContentLoaded', () => loadData());
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,67 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
|
||||
{% block title %}隐私政策 - {{ brand_name }}{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
.prose h1 { font-size: 1.5rem; font-weight: 800; margin-bottom: 0.5rem; }
|
||||
.prose h2 { font-size: 1.1rem; font-weight: 700; margin-top: 2rem; margin-bottom: 0.75rem; padding-bottom: 0.4rem; border-bottom: 1px solid rgba(0,0,0,0.08); }
|
||||
.dark .prose h2 { border-bottom-color: rgba(255,255,255,0.08); }
|
||||
.prose h3 { font-size: 0.95rem; font-weight: 600; margin-top: 1.25rem; margin-bottom: 0.5rem; }
|
||||
.prose p { margin-bottom: 0.75rem; line-height: 1.75; color: #4b5563; }
|
||||
.dark .prose p { color: #9ca3af; }
|
||||
.prose ul, .prose ol { padding-left: 1.5rem; margin-bottom: 0.75rem; }
|
||||
.prose li { margin-bottom: 0.35rem; line-height: 1.7; color: #4b5563; }
|
||||
.dark .prose li { color: #9ca3af; }
|
||||
.prose ul li { list-style-type: disc; }
|
||||
.prose strong { font-weight: 600; color: #111827; }
|
||||
.dark .prose strong { color: #f3f4f6; }
|
||||
.prose table { width: 100%; border-collapse: collapse; margin: 1rem 0; font-size: 0.875rem; }
|
||||
.prose th { background: #f3f4f6; font-weight: 600; padding: 0.6rem 0.8rem; text-align: left; border: 1px solid #e5e7eb; }
|
||||
.dark .prose th { background: #1f2937; border-color: #374151; }
|
||||
.prose td { padding: 0.6rem 0.8rem; border: 1px solid #e5e7eb; }
|
||||
.dark .prose td { border-color: #374151; }
|
||||
.prose hr { border: none; border-top: 1px solid #e5e7eb; margin: 1.5rem 0; }
|
||||
.dark .prose hr { border-top-color: #374151; }
|
||||
.prose code { background: #f3f4f6; padding: 0.1em 0.4em; border-radius: 4px; font-size: 0.85em; }
|
||||
.dark .prose code { background: #1f2937; }
|
||||
.prose blockquote { border-left: 3px solid #e5e7eb; padding-left: 1rem; color: #6b7280; margin: 1rem 0; }
|
||||
.dark .prose blockquote { border-color: #374151; color: #9ca3af; }
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="max-w-3xl mx-auto py-4">
|
||||
<!-- 返回 -->
|
||||
<div class="mb-6 list-item-enter" style="animation-delay:0ms">
|
||||
<a href="javascript:history.back()" class="inline-flex items-center gap-1.5 text-sm text-neutral-500 hover:text-neutral-800 dark:hover:text-neutral-200 transition-colors">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"/>
|
||||
</svg>
|
||||
返回
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div class="glass rounded-3xl p-6 md:p-10 layer-3 list-item-enter" style="animation-delay:50ms">
|
||||
<!-- 头部 -->
|
||||
<div class="flex items-start gap-4 mb-8 pb-6 border-b border-neutral-200 dark:border-neutral-800">
|
||||
<div class="w-12 h-12 rounded-2xl bg-black dark:bg-white flex items-center justify-center text-white dark:text-black font-bold text-lg flex-shrink-0">S</div>
|
||||
<div>
|
||||
<h1 class="text-xl md:text-2xl font-bold text-neutral-900 dark:text-white">隐私政策</h1>
|
||||
<p class="text-sm text-neutral-500 dark:text-neutral-400 mt-1">{{ brand_name }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 正文:由后端读取 docs/privacy.md 渲染 -->
|
||||
<div class="prose text-sm md:text-base text-neutral-800 dark:text-neutral-200">
|
||||
{{ content | safe }}
|
||||
</div>
|
||||
|
||||
<!-- 底部链接 -->
|
||||
<div class="mt-8 pt-6 border-t border-neutral-200 dark:border-neutral-800 flex gap-4 text-sm text-neutral-500">
|
||||
<a href="{{ url_for('main.terms') }}" class="hover:text-black dark:hover:text-white transition-colors underline underline-offset-2">用户服务协议</a>
|
||||
<a href="{{ url_for('main.buy') }}" class="hover:text-black dark:hover:text-white transition-colors underline underline-offset-2">购买页面</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,275 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
|
||||
{% block title %}注册 - {{ brand_name }}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="min-h-[70vh] flex items-center justify-center py-8">
|
||||
<div class="w-full max-w-md">
|
||||
<!-- 注册卡片 -->
|
||||
<div class="glass rounded-3xl p-8 layer-4 list-item-enter" style="animation-delay: 0ms;">
|
||||
<!-- Logo -->
|
||||
<div class="text-center mb-8">
|
||||
<div class="w-16 h-16 bg-black dark:bg-white rounded-2xl flex items-center justify-center text-white dark:text-black font-bold text-2xl mx-auto mb-4">
|
||||
S
|
||||
</div>
|
||||
<h1 class="text-2xl font-bold text-neutral-900 dark:text-white">创建账号</h1>
|
||||
<p class="text-neutral-500 dark:text-neutral-400 mt-2">填写以下信息完成注册</p>
|
||||
</div>
|
||||
|
||||
<!-- 注册表单 -->
|
||||
<form id="registerForm" onsubmit="handleRegister(event)" class="space-y-4">
|
||||
<!-- 注册码 -->
|
||||
<div>
|
||||
<label class="input-label">
|
||||
注册码
|
||||
<span class="text-red-500">*</span>
|
||||
</label>
|
||||
<div class="relative">
|
||||
<input type="text" name="ticket_code" id="ticket_code" class="input-field font-mono uppercase" placeholder="XXXX-XXXX-XXXX-XXXX" required>
|
||||
<a href="{{ url_for('main.buy') }}" class="absolute right-3 top-1/2 -translate-y-1/2 text-xs text-neutral-500 hover:text-neutral-700 dark:hover:text-neutral-300 transition">
|
||||
购买注册码
|
||||
</a>
|
||||
</div>
|
||||
<p class="text-xs text-neutral-500 mt-1" id="ticketSchoolHint">输入注册码后将显示可选学校</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="input-label" for="school_id">学校 <span class="text-red-500">*</span></label>
|
||||
<select id="school_id" name="school_id" class="input-field" required>
|
||||
<option value="">请选择学校</option>
|
||||
{% for school in schools %}<option value="{{ school.id }}">{{ school.name }}</option>{% endfor %}
|
||||
</select>
|
||||
<p class="text-xs text-neutral-500 mt-1">注册后学校不可修改</p>
|
||||
</div>
|
||||
|
||||
<!-- 网站账号 -->
|
||||
<div class="border-t border-neutral-200 dark:border-neutral-800 pt-4">
|
||||
<h3 class="text-sm font-medium text-neutral-700 dark:text-neutral-300 mb-3">网站登录账号</h3>
|
||||
<div class="space-y-4">
|
||||
<div>
|
||||
<label class="input-label">用户名</label>
|
||||
<input type="text" name="username" id="username" class="input-field" placeholder="设置登录用户名" required>
|
||||
</div>
|
||||
<div>
|
||||
<label class="input-label">密码</label>
|
||||
<input type="password" name="password" id="password" class="input-field" placeholder="设置登录密码" required>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 教务系统账号 -->
|
||||
<div class="border-t border-neutral-200 dark:border-neutral-800 pt-4">
|
||||
<h3 class="text-sm font-medium text-neutral-700 dark:text-neutral-300 mb-3">教务系统账号(用于抢课)</h3>
|
||||
<div class="space-y-4">
|
||||
<div>
|
||||
<label class="input-label">学号</label>
|
||||
<input type="text" name="jwxt_username" id="jwxt_username" class="input-field" placeholder="请输入学号" required>
|
||||
</div>
|
||||
<div>
|
||||
<label class="input-label">密码</label>
|
||||
<input type="password" name="jwxt_password" id="jwxt_password" class="input-field" placeholder="请输入教务系统密码" required>
|
||||
</div>
|
||||
<div>
|
||||
<label class="input-label">姓名(选填)</label>
|
||||
<input type="text" name="jwxt_name" id="jwxt_name" class="input-field" placeholder="请输入姓名">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="errorMessage" class="hidden p-3 bg-red-50 dark:bg-red-900/20 border border-red-100 dark:border-red-800 rounded-xl text-sm text-red-800 dark:text-red-200">
|
||||
</div>
|
||||
|
||||
<div id="successMessage" class="hidden p-3 bg-green-50 dark:bg-green-900/20 border border-green-100 dark:border-green-800 rounded-xl text-sm text-green-800 dark:text-green-200">
|
||||
</div>
|
||||
|
||||
<!-- 协议勾选 -->
|
||||
<label class="flex items-start gap-2.5 cursor-pointer select-none" id="termsLabel">
|
||||
<div class="relative flex-shrink-0 mt-0.5">
|
||||
<input type="checkbox" id="agreeTerms" class="sr-only" onchange="updateCheckbox(this)">
|
||||
<div id="checkboxBox" class="w-[18px] h-[18px] rounded border-2 border-neutral-300 dark:border-neutral-600 transition-all flex items-center justify-center">
|
||||
<svg id="checkIcon" class="w-2.5 h-2.5 text-white dark:text-black hidden" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7"/>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<span class="text-xs text-neutral-500 dark:text-neutral-400 leading-relaxed">
|
||||
我已阅读并同意
|
||||
<a href="{{ url_for('main.terms') }}" target="_blank" onclick="event.stopPropagation()" class="text-neutral-800 dark:text-neutral-200 font-medium underline underline-offset-2 hover:text-black dark:hover:text-white">用户服务协议</a>
|
||||
和
|
||||
<a href="{{ url_for('main.privacy') }}" target="_blank" onclick="event.stopPropagation()" class="text-neutral-800 dark:text-neutral-200 font-medium underline underline-offset-2 hover:text-black dark:hover:text-white">隐私政策</a>,包括本服务收集并使用我的教务系统账号信息
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<button type="submit" id="submitBtn" class="w-full btn-primary py-3.5 rounded-full text-sm font-bold mt-6">
|
||||
注册
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<!-- 分割线 -->
|
||||
<div class="relative my-6">
|
||||
<div class="absolute inset-0 flex items-center">
|
||||
<div class="w-full border-t border-neutral-200 dark:border-neutral-800"></div>
|
||||
</div>
|
||||
<div class="relative flex justify-center text-sm">
|
||||
<span class="px-4 bg-white dark:bg-dark-card text-neutral-500">已有账号?</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 登录按钮 -->
|
||||
<a href="{{ url_for('main.login') }}" class="block w-full py-3.5 rounded-full text-sm font-bold text-center border-2 border-neutral-200 dark:border-neutral-800 text-neutral-700 dark:text-neutral-300 hover:border-neutral-400 dark:hover:border-neutral-600 transition">
|
||||
立即登录
|
||||
</a>
|
||||
|
||||
<!-- 购买按钮 -->
|
||||
<a href="{{ url_for('main.buy') }}" class="block w-full py-3.5 rounded-full text-sm font-bold text-center border-2 border-neutral-200 dark:border-neutral-800 text-neutral-700 dark:text-neutral-300 hover:border-neutral-400 dark:hover:border-neutral-600 transition mt-3">
|
||||
购买注册码
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<!-- 返回首页 -->
|
||||
<div class="text-center mt-6">
|
||||
<a href="{{ url_for('main.buy') }}" class="text-sm text-neutral-500 hover:text-neutral-700 dark:hover:text-neutral-300 transition flex items-center justify-center gap-1">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
|
||||
</svg>
|
||||
返回首页
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script>
|
||||
function updateCheckbox(input) {
|
||||
const box = document.getElementById('checkboxBox');
|
||||
const icon = document.getElementById('checkIcon');
|
||||
if (input.checked) {
|
||||
box.classList.remove('border-neutral-300', 'dark:border-neutral-600');
|
||||
box.classList.add('bg-black', 'border-black', 'dark:bg-white', 'dark:border-white');
|
||||
icon.classList.remove('hidden');
|
||||
} else {
|
||||
box.classList.add('border-neutral-300', 'dark:border-neutral-600');
|
||||
box.classList.remove('bg-black', 'border-black', 'dark:bg-white', 'dark:border-white');
|
||||
icon.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
// 格式化注册码输入
|
||||
document.getElementById('ticket_code').addEventListener('input', function(e) {
|
||||
let value = e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, '');
|
||||
let formatted = '';
|
||||
for (let i = 0; i < value.length && i < 16; i++) {
|
||||
if (i > 0 && i % 4 === 0) formatted += '-';
|
||||
formatted += value[i];
|
||||
}
|
||||
e.target.value = formatted;
|
||||
});
|
||||
|
||||
const allSchools = {{ schools | map(attribute='id') | list | tojson }};
|
||||
let ticketCheckTimer;
|
||||
document.getElementById('ticket_code').addEventListener('input', () => {
|
||||
clearTimeout(ticketCheckTimer);
|
||||
ticketCheckTimer = setTimeout(checkTicketSchools, 350);
|
||||
});
|
||||
|
||||
async function checkTicketSchools() {
|
||||
const code = document.getElementById('ticket_code').value.replace(/[^A-Z0-9]/gi, '').toUpperCase();
|
||||
const select = document.getElementById('school_id');
|
||||
const hint = document.getElementById('ticketSchoolHint');
|
||||
const choices = [...select.options].slice(1);
|
||||
if (code.length !== 16) {
|
||||
choices.forEach(option => option.hidden = false);
|
||||
select.disabled = false;
|
||||
hint.textContent = '输入注册码后将显示可选学校';
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response = await fetch('/api/tickets/schools/' + encodeURIComponent(code));
|
||||
const data = await response.json();
|
||||
if (code !== document.getElementById('ticket_code').value.replace(/[^A-Z0-9]/gi, '').toUpperCase()) return;
|
||||
if (!data.success) {
|
||||
choices.forEach(option => option.hidden = false);
|
||||
select.disabled = false;
|
||||
hint.textContent = data.message;
|
||||
return;
|
||||
}
|
||||
const allowed = data.school_ids === null ? allSchools : data.school_ids;
|
||||
choices.forEach(option => option.hidden = !allowed.includes(option.value));
|
||||
if (!allowed.includes(select.value)) select.value = allowed.length === 1 ? allowed[0] : '';
|
||||
select.disabled = allowed.length === 1;
|
||||
hint.textContent = allowed.length === 1 ? '该注册码仅限所选学校,学校已锁定' :
|
||||
(data.school_ids === null ? '该注册码适用于全部学校' : '请从注册码允许的学校中选择');
|
||||
} catch (error) { hint.textContent = '暂时无法检查注册码适用学校'; }
|
||||
}
|
||||
|
||||
async function handleRegister(event) {
|
||||
event.preventDefault();
|
||||
|
||||
// 验证协议勾选
|
||||
if (!document.getElementById('agreeTerms').checked) {
|
||||
const errorDiv = document.getElementById('errorMessage');
|
||||
errorDiv.textContent = '请先阅读并同意用户服务协议和隐私政策';
|
||||
errorDiv.classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
|
||||
// 去掉注册码中的横线,只保留字母和数字
|
||||
const ticketCode = document.getElementById('ticket_code').value.replace(/[^A-Z0-9]/gi, '').toUpperCase();
|
||||
const username = document.getElementById('username').value.trim();
|
||||
const password = document.getElementById('password').value;
|
||||
const jwxtUsername = document.getElementById('jwxt_username').value.trim();
|
||||
const jwxtPassword = document.getElementById('jwxt_password').value;
|
||||
const jwxtName = document.getElementById('jwxt_name').value.trim();
|
||||
const schoolId = document.getElementById('school_id').value;
|
||||
|
||||
const submitBtn = document.getElementById('submitBtn');
|
||||
const errorDiv = document.getElementById('errorMessage');
|
||||
const successDiv = document.getElementById('successMessage');
|
||||
|
||||
// 禁用按钮
|
||||
submitBtn.disabled = true;
|
||||
submitBtn.innerHTML = '<span class="inline-block w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin mr-2"></span>注册中...';
|
||||
errorDiv.classList.add('hidden');
|
||||
successDiv.classList.add('hidden');
|
||||
|
||||
try {
|
||||
const response = await fetch('{{ url_for('main.register') }}', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
ticket_code: ticketCode,
|
||||
username: username,
|
||||
password: password,
|
||||
jwxt_username: jwxtUsername,
|
||||
jwxt_password: jwxtPassword,
|
||||
jwxt_name: jwxtName,
|
||||
school_id: schoolId
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
successDiv.textContent = data.message || '注册成功,即将跳转到登录页面...';
|
||||
successDiv.classList.remove('hidden');
|
||||
setTimeout(() => {
|
||||
window.location.href = '{{ url_for('main.login') }}';
|
||||
}, 1500);
|
||||
} else {
|
||||
errorDiv.textContent = data.message || '注册失败';
|
||||
errorDiv.classList.remove('hidden');
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.innerHTML = '注册';
|
||||
}
|
||||
} catch (error) {
|
||||
errorDiv.textContent = '网络错误,请稍后重试';
|
||||
errorDiv.classList.remove('hidden');
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.innerHTML = '注册';
|
||||
}
|
||||
}
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,314 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
|
||||
{% block title %}重修课程查询 - {{ brand_name }}{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
@keyframes fadeSlideIn {
|
||||
from { opacity: 0; transform: translateY(8px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.row-animate { animation: fadeSlideIn 0.3s ease both; }
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 list-item-enter" style="animation-delay: 0ms;">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
|
||||
<circle cx="12" cy="12" r="3"/>
|
||||
</svg>
|
||||
重修课程查询
|
||||
</h2>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">查看可重修课程信息</p>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-3 items-center">
|
||||
<select id="xnmSelect" class="px-4 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm">
|
||||
<option value="">全部学年</option>
|
||||
</select>
|
||||
<select id="xqmSelect" class="px-4 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm">
|
||||
<option value="">全部学期</option>
|
||||
<option value="3">第一学期</option>
|
||||
<option value="12">第二学期</option>
|
||||
</select>
|
||||
<label class="flex items-center gap-2 text-sm cursor-pointer select-none">
|
||||
<input type="checkbox" id="myFailedOnly" checked onchange="refresh()"
|
||||
class="w-4 h-4 rounded border-gray-300 dark:border-gray-600 text-black dark:text-white focus:ring-black dark:focus:ring-white">
|
||||
<span class="text-gray-600 dark:text-gray-400">仅显示我的不及格课程</span>
|
||||
</label>
|
||||
<button onclick="refresh()"
|
||||
class="px-4 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm font-medium hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors flex items-center gap-2">
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="loadingIndicator" class="text-center py-12 list-item-enter" style="animation-delay: 100ms;">
|
||||
<div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
|
||||
<p class="text-gray-500 dark:text-gray-400">正在查询重修课程...</p>
|
||||
</div>
|
||||
|
||||
<div id="errorMessage" class="glass rounded-2xl p-6 mb-4 text-center hidden">
|
||||
<p id="errorText" class="text-red-500"></p>
|
||||
</div>
|
||||
|
||||
<div id="dataContainer" class="hidden list-item-enter" style="animation-delay: 150ms;">
|
||||
<!-- ECharts 图表 -->
|
||||
<div id="chartsRow" class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4 hidden">
|
||||
<div class="glass rounded-2xl p-4">
|
||||
<h3 class="text-sm font-semibold mb-2 text-gray-700 dark:text-gray-300">开课学院分布</h3>
|
||||
<div id="deptChart" style="height:300px;"></div>
|
||||
</div>
|
||||
<div class="glass rounded-2xl p-4">
|
||||
<h3 class="text-sm font-semibold mb-2 text-gray-700 dark:text-gray-300">重修状态分布</h3>
|
||||
<div id="statusChart" style="height:300px;"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="glass rounded-2xl overflow-hidden">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead>
|
||||
<tr class="border-b border-gray-200 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-800/50">
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">序号</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">重修学年</th>
|
||||
<th class="text-center py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">重修学期</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">课程代码</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">课程名称</th>
|
||||
<th class="text-center py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">学分</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">开课学院</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">课程类别</th>
|
||||
<th class="text-center py-3 px-4 font-semibold text-gray-700 dark:text-gray-300" id="thOriginalCj" style="display:none;">原成绩</th>
|
||||
<th class="text-center py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">重修状态</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="tableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<div id="emptyState" class="glass rounded-2xl p-12 text-center hidden">
|
||||
<p class="text-gray-500 dark:text-gray-400 text-lg">暂无可重修课程</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script src="{{ url_for('static', filename='echarts.min.js') }}"></script>
|
||||
<script>
|
||||
// ── 深色模式 ──
|
||||
function isDarkMode() { return document.documentElement.classList.contains('dark'); }
|
||||
|
||||
// ── Session 健康检查 ──
|
||||
async function initSession() {
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/ping');
|
||||
const data = await res.json();
|
||||
if (!data.success) { console.warn('Session ping 失败:', data.message); return false; }
|
||||
if (data.refreshed) console.log('🔄 Session 已自动刷新');
|
||||
return true;
|
||||
} catch (e) { console.error('Session ping 异常:', e); return false; }
|
||||
}
|
||||
|
||||
// 动态计算当前学年学期
|
||||
function getCurrentSemester() {
|
||||
const now = new Date();
|
||||
const year = now.getFullYear();
|
||||
const month = now.getMonth() + 1; // 1-12
|
||||
// 第一学期:9月-次年2月;第二学期:3月-8月
|
||||
if (month >= 9) {
|
||||
return { xnm: year, xqm: '3', label: year + '-' + (year + 1) + ' 第一学期' };
|
||||
} else if (month >= 3) {
|
||||
return { xnm: year - 1, xqm: '12', label: (year - 1) + '-' + year + ' 第二学期' };
|
||||
} else {
|
||||
return { xnm: year - 1, xqm: '3', label: (year - 1) + '-' + year + ' 第一学期' };
|
||||
}
|
||||
}
|
||||
|
||||
// 填充学年选项
|
||||
function initYearSelects() {
|
||||
const current = getCurrentSemester();
|
||||
const xnmSelect = document.getElementById('xnmSelect');
|
||||
const xqmSelect = document.getElementById('xqmSelect');
|
||||
|
||||
// 生成最近5个学年
|
||||
for (let y = current.xnm; y >= current.xnm - 4; y--) {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = y;
|
||||
opt.textContent = y + '-' + (y + 1);
|
||||
xnmSelect.appendChild(opt);
|
||||
}
|
||||
|
||||
// 设置默认值
|
||||
xnmSelect.value = current.xnm;
|
||||
xqmSelect.value = current.xqm;
|
||||
}
|
||||
initYearSelects();
|
||||
|
||||
async function refresh() {
|
||||
document.getElementById('loadingIndicator').classList.remove('hidden');
|
||||
document.getElementById('errorMessage').classList.add('hidden');
|
||||
document.getElementById('dataContainer').classList.add('hidden');
|
||||
|
||||
await initSession();
|
||||
|
||||
const xnm = document.getElementById('xnmSelect').value;
|
||||
const xqm = document.getElementById('xqmSelect').value;
|
||||
const showAll = document.getElementById('myFailedOnly').checked ? '0' : '1';
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams({ page_size: 500, show_all: showAll });
|
||||
if (xnm) params.set('xnm', xnm);
|
||||
if (xqm) params.set('xqm', xqm);
|
||||
const res = await fetch('/api/jwxt/retake-courses?' + params);
|
||||
const data = await res.json();
|
||||
document.getElementById('loadingIndicator').classList.add('hidden');
|
||||
|
||||
if (!data.success) {
|
||||
document.getElementById('errorText').textContent = data.message || '查询失败';
|
||||
document.getElementById('errorMessage').classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
|
||||
const items = data.items || [];
|
||||
const isMatched = data.matched && !showAll;
|
||||
|
||||
// 显示/隐藏原成绩列
|
||||
document.getElementById('thOriginalCj').style.display = isMatched ? '' : 'none';
|
||||
|
||||
if (!items.length) {
|
||||
document.getElementById('dataContainer').classList.remove('hidden');
|
||||
document.getElementById('emptyState').classList.remove('hidden');
|
||||
document.getElementById('tableBody').innerHTML = '';
|
||||
document.getElementById('chartsRow').classList.add('hidden');
|
||||
if (isMatched && (!data.failed_courses || !data.failed_courses.length)) {
|
||||
document.getElementById('emptyState').querySelector('p').textContent = '没有不及格课程';
|
||||
} else if (isMatched) {
|
||||
document.getElementById('emptyState').querySelector('p').textContent = '当前学期没有你不及格课程对应的重修班,试试切换学年或取消"仅显示不及格"';
|
||||
} else {
|
||||
document.getElementById('emptyState').querySelector('p').textContent = '暂无可重修课程';
|
||||
}
|
||||
return;
|
||||
}
|
||||
document.getElementById('emptyState').classList.add('hidden');
|
||||
renderTable(items, isMatched);
|
||||
renderCharts(items);
|
||||
document.getElementById('chartsRow').classList.remove('hidden');
|
||||
setupDarkObserver();
|
||||
document.getElementById('dataContainer').classList.remove('hidden');
|
||||
} catch (e) {
|
||||
document.getElementById('loadingIndicator').classList.add('hidden');
|
||||
document.getElementById('errorText').textContent = '网络错误: ' + e.message;
|
||||
document.getElementById('errorMessage').classList.remove('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
function renderTable(items, showOriginalCj) {
|
||||
const tbody = document.getElementById('tableBody');
|
||||
tbody.innerHTML = items.map((item, idx) => {
|
||||
const origCj = item._original_cj;
|
||||
const origCjDisplay = origCj !== undefined
|
||||
? '<span class="text-red-500 dark:text-red-400 font-semibold">' + origCj + '</span>'
|
||||
: '--';
|
||||
const origCjCell = showOriginalCj
|
||||
? '<td class="py-3 px-4 text-center">' + origCjDisplay + '</td>'
|
||||
: '';
|
||||
|
||||
return '<tr class="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50/50 dark:hover:bg-gray-800/30 transition-colors row-animate" style="animation-delay:' + (idx * 40) + 'ms;">' +
|
||||
'<td class="py-3 px-4 text-gray-400 dark:text-gray-500">' + (idx + 1) + '</td>' +
|
||||
'<td class="py-3 px-4 text-gray-500 dark:text-gray-400">' + (item.cxxnmc || '--') + '</td>' +
|
||||
'<td class="py-3 px-4 text-center text-gray-500 dark:text-gray-400">' + (item.cxxqmc || '--') + '</td>' +
|
||||
'<td class="py-3 px-4 text-gray-500 dark:text-gray-400 font-mono text-xs">' + (item.kch || '--') + '</td>' +
|
||||
'<td class="py-3 px-4 font-medium">' + (item.kcmc || '--') + '</td>' +
|
||||
'<td class="py-3 px-4 text-center">' + (item.xf || '--') + '</td>' +
|
||||
'<td class="py-3 px-4 text-gray-500 dark:text-gray-400">' + (item.kkbmmc || '--') + '</td>' +
|
||||
'<td class="py-3 px-4 text-gray-500 dark:text-gray-400">' + (item.kclbmc || '--') + '</td>' +
|
||||
origCjCell +
|
||||
'<td class="py-3 px-4 text-center text-gray-500 dark:text-gray-400">' + (item.cxzt || '--') + '</td>' +
|
||||
'</tr>';
|
||||
}).join('');
|
||||
}
|
||||
|
||||
// ── ECharts 图表渲染 ──
|
||||
let deptChartInst = null, statusChartInst = null;
|
||||
let _lastRetakeItems = [];
|
||||
|
||||
function renderCharts(items) {
|
||||
_lastRetakeItems = items;
|
||||
renderDeptChart(items);
|
||||
renderStatusChart(items);
|
||||
}
|
||||
|
||||
function renderDeptChart(items) {
|
||||
const dom = document.getElementById('deptChart');
|
||||
if (!dom) return;
|
||||
if (deptChartInst) deptChartInst.dispose();
|
||||
|
||||
const counts = {};
|
||||
items.forEach(it => {
|
||||
const k = it.kkbmmc || '未知';
|
||||
counts[k] = (counts[k] || 0) + 1;
|
||||
});
|
||||
const keys = Object.keys(counts).sort((a, b) => counts[b] - counts[a]);
|
||||
|
||||
deptChartInst = echarts.init(dom);
|
||||
deptChartInst.setOption({
|
||||
tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
|
||||
grid: { left: 100, right: 30, top: 10, bottom: 20 },
|
||||
xAxis: { type: 'value' },
|
||||
yAxis: { type: 'category', data: keys, axisLabel: { fontSize: 11 } },
|
||||
series: [{
|
||||
type: 'bar', data: keys.map(k => counts[k]),
|
||||
itemStyle: { color: isDarkMode() ? '#818cf8' : '#4f46e5' },
|
||||
barMaxWidth: 24
|
||||
}]
|
||||
});
|
||||
}
|
||||
|
||||
function renderStatusChart(items) {
|
||||
const dom = document.getElementById('statusChart');
|
||||
if (!dom) return;
|
||||
if (statusChartInst) statusChartInst.dispose();
|
||||
|
||||
const counts = {};
|
||||
items.forEach(it => {
|
||||
const k = it.cxzt || '未知';
|
||||
counts[k] = (counts[k] || 0) + 1;
|
||||
});
|
||||
const data = Object.entries(counts).map(([name, value]) => ({ name, value }));
|
||||
|
||||
statusChartInst = echarts.init(dom);
|
||||
statusChartInst.setOption({
|
||||
tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
|
||||
legend: { bottom: 0, textStyle: { fontSize: 11, color: isDarkMode() ? '#9ca3af' : '#6b7280' } },
|
||||
series: [{
|
||||
type: 'pie', radius: ['45%', '70%'], center: ['50%', '45%'],
|
||||
data: data,
|
||||
label: { formatter: '{b}\n{d}%', fontSize: 11 },
|
||||
itemStyle: { borderColor: isDarkMode() ? '#1f2937' : '#fff', borderWidth: 2 }
|
||||
}]
|
||||
});
|
||||
}
|
||||
|
||||
// ── 深色模式观察 ──
|
||||
let _darkObserverRetake = null;
|
||||
function setupDarkObserver() {
|
||||
if (_darkObserverRetake) _darkObserverRetake.disconnect();
|
||||
_darkObserverRetake = new MutationObserver(() => {
|
||||
if (deptChartInst) { deptChartInst.dispose(); deptChartInst = null; }
|
||||
if (statusChartInst) { statusChartInst.dispose(); statusChartInst = null; }
|
||||
if (_lastRetakeItems.length) renderCharts(_lastRetakeItems);
|
||||
});
|
||||
_darkObserverRetake.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
|
||||
}
|
||||
window.addEventListener('resize', () => {
|
||||
if (deptChartInst) deptChartInst.resize();
|
||||
if (statusChartInst) statusChartInst.resize();
|
||||
});
|
||||
|
||||
refresh();
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,73 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
{% block title %}重修报名 - {{ brand_name }}{% endblock %}
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
@keyframes fadeSlideIn {
|
||||
from { opacity: 0; transform: translateY(8px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.row-animate { animation: fadeSlideIn 0.3s ease both; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.row-animate { animation: none !important; opacity: 1 !important; }
|
||||
.list-item-enter { animation: none !important; opacity: 1 !important; }
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 list-item-enter">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 10v6M2 10l10-5 10 5-10 5z"/><path d="M6 12v5c0 1.66 2.69 3 6 3s6-1.34 6-3v-5"/></svg>
|
||||
重修报名
|
||||
</h2>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">重修课程报名</p>
|
||||
</div>
|
||||
<button onclick="loadData()" class="px-4 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm font-medium hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors flex items-center gap-2"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>刷新</button>
|
||||
</div>
|
||||
<div id="loadingIndicator" class="text-center py-12 hidden"><div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div><p class="text-gray-500 dark:text-gray-400">加载中...</p></div>
|
||||
<div id="errorMessage" class="glass rounded-2xl p-6 mb-4 text-center hidden"><p id="errorText" class="text-red-500"></p></div>
|
||||
<div id="dataContainer" class="hidden">
|
||||
<div class="glass rounded-2xl overflow-hidden">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead><tr class="border-b border-gray-200 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-800/50"><th class="text-left py-3 px-4 font-semibold">课程名称</th><th class="text-left py-3 px-4 font-semibold">课程代码</th><th class="text-left py-3 px-4 font-semibold">学分</th><th class="text-left py-3 px-4 font-semibold">报名状态</th><th class="text-left py-3 px-4 font-semibold">操作</th></tr></thead>
|
||||
<tbody id="tableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="emptyState" class="glass rounded-2xl p-12 text-center hidden"><p class="text-gray-500 dark:text-gray-400 text-lg">暂无重修报名信息</p></div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block extra_js %}
|
||||
<script>
|
||||
async function loadData() {
|
||||
document.getElementById('loadingIndicator').classList.remove('hidden');
|
||||
document.getElementById('errorMessage').classList.add('hidden');
|
||||
document.getElementById('dataContainer').classList.add('hidden');
|
||||
document.getElementById('emptyState').classList.add('hidden');
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/retake-registration');
|
||||
const data = await res.json();
|
||||
document.getElementById('loadingIndicator').classList.add('hidden');
|
||||
if (!data.success) { showError(data.message); return; }
|
||||
const items = data.items || data.registered || [];
|
||||
if (!items.length) { document.getElementById('emptyState').classList.remove('hidden'); return; }
|
||||
const tbody = document.getElementById('tableBody');
|
||||
tbody.innerHTML = items.map((item, i) => {
|
||||
const kcmc = item.kcmc || item.课程名称 || '--';
|
||||
const kch = item.kch_id || item.kch || item.课程代码 || '--';
|
||||
const xf = item.xf || item.学分 || '--';
|
||||
const status = item.bmztmc || item.报名状态 || item.state || '--';
|
||||
return `<tr class="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50/50 dark:hover:bg-gray-800/30 transition-colors"><td class="py-3 px-4">${escHtml(kcmc)}</td><td class="py-3 px-4 text-gray-500 text-xs">${escHtml(kch)}</td><td class="py-3 px-4">${escHtml(xf)}</td><td class="py-3 px-4">${escHtml(status)}</td><td class="py-3 px-4">${status.includes('已报')||status.includes('已选')?'<span class="text-xs text-gray-400">已报名</span>':'<button onclick="alert(\'报名功能需在教务系统操作\')" class="text-xs text-blue-500 hover:text-blue-600">报名</button>'}</td></tr>`;
|
||||
}).join('');
|
||||
document.getElementById('dataContainer').classList.remove('hidden');
|
||||
} catch(e) { document.getElementById('loadingIndicator').classList.add('hidden'); showError('网络错误: '+e.message); }
|
||||
}
|
||||
function showError(msg) { document.getElementById('errorText').textContent = msg; document.getElementById('errorMessage').classList.remove('hidden'); }
|
||||
function escHtml(s) { if(s==null) return ''; return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"'); }
|
||||
document.addEventListener('DOMContentLoaded', () => loadData());
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,577 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN" class="scroll-smooth">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<title>支付成功 - {{ brand_name }}</title>
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<script>
|
||||
tailwind.config = {
|
||||
darkMode: 'class',
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
dark: {
|
||||
bg: '#0a0a0a',
|
||||
card: '#171717',
|
||||
border: '#262626'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;800;900&family=Noto+Sans+SC:wght@300;400;500;700;900&display=swap"
|
||||
rel="stylesheet">
|
||||
<style>
|
||||
* {
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'Inter', 'Noto Sans SC', sans-serif;
|
||||
transition: background-color 0.3s ease, color 0.3s ease;
|
||||
}
|
||||
|
||||
.glass {
|
||||
background: rgba(255, 255, 255, 0.85);
|
||||
backdrop-filter: blur(20px);
|
||||
-webkit-backdrop-filter: blur(20px);
|
||||
border: 1px solid rgba(255, 255, 255, 0.9);
|
||||
}
|
||||
|
||||
.dark .glass {
|
||||
background: rgba(23, 23, 23, 0.85);
|
||||
border: 1px solid rgba(38, 38, 38, 0.9);
|
||||
}
|
||||
|
||||
.glass-dark {
|
||||
background: rgba(17, 17, 17, 0.85);
|
||||
backdrop-filter: blur(20px);
|
||||
-webkit-backdrop-filter: blur(20px);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.dark .glass-dark {
|
||||
background: rgba(10, 10, 10, 0.9);
|
||||
border: 1px solid rgba(38, 38, 38, 0.5);
|
||||
}
|
||||
|
||||
.layer-4 {
|
||||
box-shadow: 0 24px 60px -10px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
.dark .layer-4 {
|
||||
box-shadow: 0 24px 60px -10px rgba(0, 0, 0, 0.7);
|
||||
}
|
||||
|
||||
.bg-grid {
|
||||
background-size: 40px 40px;
|
||||
background-image: linear-gradient(to right, rgba(0, 0, 0, 0.03) 1px, transparent 1px),
|
||||
linear-gradient(to bottom, rgba(0, 0, 0, 0.03) 1px, transparent 1px);
|
||||
}
|
||||
|
||||
.dark .bg-grid {
|
||||
background-image: linear-gradient(to right, rgba(255, 255, 255, 0.03) 1px, transparent 1px),
|
||||
linear-gradient(to bottom, rgba(255, 255, 255, 0.03) 1px, transparent 1px);
|
||||
}
|
||||
|
||||
/* 成功动画 */
|
||||
@keyframes successPop {
|
||||
0% {
|
||||
transform: scale(0);
|
||||
opacity: 0;
|
||||
}
|
||||
50% {
|
||||
transform: scale(1.2);
|
||||
}
|
||||
100% {
|
||||
transform: scale(1);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.success-icon {
|
||||
animation: successPop 0.6s cubic-bezier(0.4, 0, 0.2, 1) forwards;
|
||||
}
|
||||
|
||||
/* 注册码卡片样式 */
|
||||
.ticket-card {
|
||||
background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
|
||||
border: 2px solid #86efac;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.dark .ticket-card {
|
||||
background: linear-gradient(135deg, #14532d 0%, #166534 100%);
|
||||
border-color: #22c55e;
|
||||
}
|
||||
|
||||
.ticket-card:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 10px 30px -5px rgba(34, 197, 94, 0.3);
|
||||
}
|
||||
|
||||
.ticket-code {
|
||||
font-family: 'SF Mono', 'Monaco', 'Inconsolata', 'Roboto Mono', monospace;
|
||||
letter-spacing: 2px;
|
||||
}
|
||||
|
||||
/* 复制按钮 */
|
||||
.copy-btn {
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.copy-btn:hover {
|
||||
transform: scale(1.05);
|
||||
}
|
||||
|
||||
.copy-btn:active {
|
||||
transform: scale(0.95);
|
||||
}
|
||||
|
||||
/* Toast 通知 */
|
||||
@media (min-width: 769px) {
|
||||
.toast-container {
|
||||
position: fixed;
|
||||
top: 20px;
|
||||
right: 20px;
|
||||
z-index: 9999;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.toast {
|
||||
background: #2c3e50;
|
||||
color: white;
|
||||
padding: 14px 22px;
|
||||
border-radius: 8px;
|
||||
margin-bottom: 10px;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
|
||||
transform: translateX(100%);
|
||||
opacity: 0;
|
||||
transition: all 0.3s ease;
|
||||
pointer-events: all;
|
||||
min-width: 250px;
|
||||
max-width: 350px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.toast.show {
|
||||
transform: translateX(0);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.toast-container {
|
||||
position: fixed;
|
||||
bottom: max(20px, env(safe-area-inset-bottom));
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 9999;
|
||||
pointer-events: none;
|
||||
width: 90%;
|
||||
max-width: 400px;
|
||||
}
|
||||
|
||||
.toast {
|
||||
background: #2c3e50;
|
||||
color: white;
|
||||
padding: 12px 20px;
|
||||
border-radius: 24px;
|
||||
margin-bottom: 8px;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.25);
|
||||
transform: translateY(100px);
|
||||
opacity: 0;
|
||||
transition: all 0.3s ease;
|
||||
pointer-events: all;
|
||||
width: 100%;
|
||||
font-size: 14px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.toast.show {
|
||||
transform: translateY(0);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.toast.success {
|
||||
background: #27ae60;
|
||||
}
|
||||
|
||||
.toast.error {
|
||||
background: #e74c3c;
|
||||
}
|
||||
|
||||
.dark .toast.success {
|
||||
background: #4caf50;
|
||||
}
|
||||
|
||||
.dark .toast.error {
|
||||
background: #ff6b6b;
|
||||
}
|
||||
|
||||
/* 步骤指示器 */
|
||||
.step-item {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.step-item::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
right: -50%;
|
||||
width: 100%;
|
||||
height: 2px;
|
||||
background: #e5e5e5;
|
||||
transform: translateY(-50%);
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.dark .step-item::after {
|
||||
background: #404040;
|
||||
}
|
||||
|
||||
.step-item:last-child::after {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.step-number {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 50%;
|
||||
background: #111;
|
||||
color: white;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.dark .step-number {
|
||||
background: #fff;
|
||||
color: #000;
|
||||
}
|
||||
|
||||
/* 脉冲动画 */
|
||||
@keyframes pulse-ring {
|
||||
0% {
|
||||
transform: scale(0.8);
|
||||
opacity: 1;
|
||||
}
|
||||
100% {
|
||||
transform: scale(1.5);
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.pulse-ring {
|
||||
position: absolute;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 50%;
|
||||
background: rgba(34, 197, 94, 0.4);
|
||||
animation: pulse-ring 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
|
||||
}
|
||||
|
||||
/* 安全区域适配 */
|
||||
.safe-area-inset-bottom {
|
||||
padding-bottom: env(safe-area-inset-bottom);
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body class="bg-neutral-50 text-neutral-900 dark:bg-dark-bg dark:text-neutral-100 min-h-screen">
|
||||
<!-- Toast 通知容器 -->
|
||||
<div class="toast-container" id="toastContainer"></div>
|
||||
|
||||
<!-- 导航 -->
|
||||
<nav class="fixed w-full z-50 glass border-b border-black/5 dark:border-white/10 transition-colors duration-300"
|
||||
id="navbar">
|
||||
<div class="max-w-6xl mx-auto px-4 md:px-6 h-16 flex justify-between items-center">
|
||||
<a href="/buy" class="flex items-center gap-2 md:gap-3 group cursor-pointer">
|
||||
<div
|
||||
class="w-8 h-8 bg-black dark:bg-white rounded-lg flex items-center justify-center text-white dark:text-black font-bold text-sm group-hover:rotate-12 transition-transform shrink-0">
|
||||
S</div>
|
||||
<div class="flex items-center gap-1.5 md:gap-2 min-w-0">
|
||||
<span class="font-bold tracking-tight text-sm md:text-base truncate">{{ brand_name }}</span>
|
||||
</div>
|
||||
</a>
|
||||
|
||||
<div class="flex items-center gap-2 md:gap-6">
|
||||
<button onclick="toggleTheme()"
|
||||
class="p-2 rounded-full hover:bg-neutral-200 dark:hover:bg-neutral-800 transition-colors shrink-0"
|
||||
aria-label="切换主题">
|
||||
<svg id="sun-icon" class="w-5 h-5 hidden dark:block text-neutral-300" fill="none"
|
||||
stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
||||
d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z">
|
||||
</path>
|
||||
</svg>
|
||||
<svg id="moon-icon" class="w-5 h-5 block dark:hidden text-neutral-600" fill="none"
|
||||
stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
||||
d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z">
|
||||
</path>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<!-- 主内容区 -->
|
||||
<main class="pt-24 md:pt-32 pb-16 md:pb-24 px-4 md:px-6 bg-grid min-h-screen">
|
||||
<div class="max-w-3xl mx-auto">
|
||||
<!-- 成功提示 -->
|
||||
<div class="text-center mb-8 md:mb-12">
|
||||
<div class="relative inline-flex items-center justify-center mb-6">
|
||||
<div class="pulse-ring"></div>
|
||||
<div class="success-icon w-20 h-20 md:w-24 md:h-24 bg-green-500 rounded-full flex items-center justify-center layer-4">
|
||||
<svg class="w-10 h-10 md:w-12 md:h-12 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7"></path>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<h1 class="text-2xl md:text-4xl font-bold mb-2 text-neutral-900 dark:text-white">支付成功!</h1>
|
||||
<p class="text-neutral-500 dark:text-neutral-400">您的注册码已生成,请妥善保管</p>
|
||||
</div>
|
||||
|
||||
<!-- 注册码卡片 -->
|
||||
<div class="glass rounded-2xl md:rounded-3xl p-6 md:p-8 layer-4 mb-8">
|
||||
<div class="flex items-center gap-3 mb-6">
|
||||
<div class="w-10 h-10 bg-green-100 dark:bg-green-900/30 rounded-xl flex items-center justify-center">
|
||||
<svg class="w-5 h-5 text-green-600 dark:text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z"></path>
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<h2 class="text-lg font-bold text-neutral-900 dark:text-white">您的注册码</h2>
|
||||
<p class="text-sm text-neutral-500 dark:text-neutral-400">已自动复制到剪贴板</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 注册码列表 -->
|
||||
<div id="ticketList" class="space-y-3 mb-6">
|
||||
{% for code in ticket_codes %}
|
||||
<div class="ticket-card rounded-xl p-4 md:p-5 flex items-center justify-between gap-4">
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="text-xs text-green-700 dark:text-green-300 mb-1 font-medium">注册码 {{ loop.index }}</div>
|
||||
<div class="ticket-code text-lg md:text-xl font-bold text-green-800 dark:text-green-200 truncate" id="ticket-{{ loop.index }}">{{ code }}</div>
|
||||
</div>
|
||||
<button onclick="copyTicket('{{ code }}', this)" class="copy-btn flex-shrink-0 p-2.5 bg-white dark:bg-neutral-800 rounded-lg shadow-sm hover:shadow-md transition-all" title="复制">
|
||||
<svg class="w-5 h-5 text-neutral-600 dark:text-neutral-400 copy-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"></path>
|
||||
</svg>
|
||||
<svg class="w-5 h-5 text-green-600 check-icon hidden" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
|
||||
<!-- 复制全部按钮 -->
|
||||
{% if ticket_codes|length > 1 %}
|
||||
<button onclick="copyAllTickets()" class="w-full py-3 bg-green-500 hover:bg-green-600 text-white font-semibold rounded-xl transition-colors flex items-center justify-center gap-2">
|
||||
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3"></path>
|
||||
</svg>
|
||||
复制全部注册码
|
||||
</button>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<!-- 使用步骤 -->
|
||||
<div class="glass rounded-2xl md:rounded-3xl p-6 md:p-8 layer-4 mb-8">
|
||||
<h2 class="text-lg font-bold text-neutral-900 dark:text-white mb-6 flex items-center gap-2">
|
||||
<svg class="w-5 h-5 text-neutral-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
|
||||
</svg>
|
||||
使用步骤
|
||||
</h2>
|
||||
|
||||
<div class="grid grid-cols-3 gap-4 mb-8">
|
||||
<div class="step-item text-center">
|
||||
<div class="step-number mx-auto mb-3">1</div>
|
||||
<div class="text-sm font-medium text-neutral-700 dark:text-neutral-300">访问登录页</div>
|
||||
<div class="text-xs text-neutral-400 mt-1">点击按钮前往</div>
|
||||
</div>
|
||||
<div class="step-item text-center">
|
||||
<div class="step-number mx-auto mb-3">2</div>
|
||||
<div class="text-sm font-medium text-neutral-700 dark:text-neutral-300">注册账号</div>
|
||||
<div class="text-xs text-neutral-400 mt-1">使用注册码</div>
|
||||
</div>
|
||||
<div class="step-item text-center">
|
||||
<div class="step-number mx-auto mb-3">3</div>
|
||||
<div class="text-sm font-medium text-neutral-700 dark:text-neutral-300">开始使用</div>
|
||||
<div class="text-xs text-neutral-400 mt-1">下载软件</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 登录地址 -->
|
||||
<div class="bg-neutral-50 dark:bg-neutral-800/50 rounded-xl p-4 mb-4">
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="text-xs text-neutral-500 dark:text-neutral-400 mb-1">登录地址</div>
|
||||
<div class="text-sm md:text-base font-medium text-neutral-900 dark:text-white truncate" id="loginUrl">{{ login_url or 'https://jwxt.bansonic.top' }}</div>
|
||||
</div>
|
||||
<a href="{{ login_url or 'https://jwxt.bansonic.top' }}" target="_blank" class="flex-shrink-0 px-4 py-2 bg-black dark:bg-white text-white dark:text-black text-sm font-semibold rounded-lg hover:shadow-lg transition-all flex items-center gap-2">
|
||||
前往登录
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"></path>
|
||||
</svg>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 重要提示 -->
|
||||
<div class="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-xl p-4">
|
||||
<div class="flex items-start gap-3">
|
||||
<svg class="w-5 h-5 text-amber-600 dark:text-amber-400 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
|
||||
</svg>
|
||||
<div class="text-sm text-amber-800 dark:text-amber-200">
|
||||
<p class="font-semibold mb-1">重要提示:</p>
|
||||
<ul class="space-y-1 text-amber-700 dark:text-amber-300">
|
||||
<li>• 每个注册码只能使用一次,请妥善保管</li>
|
||||
<li>• 注册码已发送至您的邮箱,请注意查收</li>
|
||||
<li>• 如遇问题,请联系客服获取帮助</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 返回按钮 -->
|
||||
<div class="text-center">
|
||||
<a href="/buy" class="inline-flex items-center gap-2 px-6 py-3 bg-neutral-200 dark:bg-neutral-800 text-neutral-700 dark:text-neutral-300 font-semibold rounded-xl hover:bg-neutral-300 dark:hover:bg-neutral-700 transition-colors">
|
||||
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
|
||||
</svg>
|
||||
返回购买页面
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<script>
|
||||
// 主题切换
|
||||
function initTheme() {
|
||||
if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
|
||||
document.documentElement.classList.add('dark');
|
||||
} else {
|
||||
document.documentElement.classList.remove('dark');
|
||||
}
|
||||
}
|
||||
|
||||
function toggleTheme() {
|
||||
if (document.documentElement.classList.contains('dark')) {
|
||||
document.documentElement.classList.remove('dark');
|
||||
localStorage.theme = 'light';
|
||||
} else {
|
||||
document.documentElement.classList.add('dark');
|
||||
localStorage.theme = 'dark';
|
||||
}
|
||||
}
|
||||
|
||||
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
|
||||
if (!localStorage.theme) {
|
||||
if (e.matches) document.documentElement.classList.add('dark');
|
||||
else document.documentElement.classList.remove('dark');
|
||||
}
|
||||
});
|
||||
|
||||
initTheme();
|
||||
|
||||
// Toast 通知
|
||||
function showToast(message, type = 'success', duration = 3000) {
|
||||
const container = document.getElementById('toastContainer');
|
||||
const toast = document.createElement('div');
|
||||
toast.className = `toast ${type}`;
|
||||
toast.innerHTML = `<span>${message}</span>`;
|
||||
|
||||
container.appendChild(toast);
|
||||
setTimeout(() => toast.classList.add('show'), 10);
|
||||
setTimeout(() => {
|
||||
toast.classList.remove('show');
|
||||
setTimeout(() => toast.remove(), 400);
|
||||
}, duration);
|
||||
}
|
||||
|
||||
// 复制单个注册码
|
||||
async function copyTicket(code, btn) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(code);
|
||||
|
||||
// 切换图标
|
||||
const copyIcon = btn.querySelector('.copy-icon');
|
||||
const checkIcon = btn.querySelector('.check-icon');
|
||||
|
||||
copyIcon.classList.add('hidden');
|
||||
checkIcon.classList.remove('hidden');
|
||||
|
||||
showToast('注册码已复制到剪贴板', 'success');
|
||||
|
||||
// 2秒后恢复图标
|
||||
setTimeout(() => {
|
||||
copyIcon.classList.remove('hidden');
|
||||
checkIcon.classList.add('hidden');
|
||||
}, 2000);
|
||||
|
||||
} catch (err) {
|
||||
// 降级方案
|
||||
const textArea = document.createElement('textarea');
|
||||
textArea.value = code;
|
||||
document.body.appendChild(textArea);
|
||||
textArea.select();
|
||||
document.execCommand('copy');
|
||||
document.body.removeChild(textArea);
|
||||
|
||||
showToast('注册码已复制到剪贴板', 'success');
|
||||
}
|
||||
}
|
||||
|
||||
// 复制全部注册码
|
||||
async function copyAllTickets() {
|
||||
const ticketElements = document.querySelectorAll('[id^="ticket-"]');
|
||||
const codes = Array.from(ticketElements).map(el => el.textContent.trim()).join('\n');
|
||||
|
||||
try {
|
||||
await navigator.clipboard.writeText(codes);
|
||||
showToast('全部注册码已复制到剪贴板', 'success');
|
||||
} catch (err) {
|
||||
const textArea = document.createElement('textarea');
|
||||
textArea.value = codes;
|
||||
document.body.appendChild(textArea);
|
||||
textArea.select();
|
||||
document.execCommand('copy');
|
||||
document.body.removeChild(textArea);
|
||||
|
||||
showToast('全部注册码已复制到剪贴板', 'success');
|
||||
}
|
||||
}
|
||||
|
||||
// 页面加载完成后自动复制第一个注册码
|
||||
window.addEventListener('load', () => {
|
||||
const firstTicket = document.querySelector('.ticket-code');
|
||||
if (firstTicket) {
|
||||
const code = firstTicket.textContent.trim();
|
||||
|
||||
// 尝试自动复制
|
||||
navigator.clipboard.writeText(code).then(() => {
|
||||
showToast('注册码已自动复制到剪贴板', 'success', 4000);
|
||||
}).catch(() => {
|
||||
// 静默失败,用户可手动复制
|
||||
});
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,75 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
{% block title %}更换指导教师申请 - {{ brand_name }}{% endblock %}
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
@keyframes fadeSlideIn {
|
||||
from { opacity: 0; transform: translateY(8px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.row-animate { animation: fadeSlideIn 0.3s ease both; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.row-animate { animation: none !important; opacity: 1 !important; }
|
||||
.list-item-enter { animation: none !important; opacity: 1 !important; }
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 list-item-enter">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
|
||||
更换指导教师申请
|
||||
</h2>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">申请更换毕业论文(设计)指导教师</p>
|
||||
</div>
|
||||
<button onclick="loadData()" class="px-4 py-2 rounded-lg border"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>刷新</button>
|
||||
</div>
|
||||
<div id="loadingIndicator" class="text-center py-12 hidden"><div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div><p class="text-gray-500 dark:text-gray-400">加载中...</p></div>
|
||||
<div id="errorMessage" class="glass rounded-2xl p-6 mb-4 text-center hidden"><p id="errorText" class="text-red-500"></p></div>
|
||||
<div id="dataContainer" class="hidden">
|
||||
<div class="glass rounded-2xl overflow-hidden">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead><tr class="border-b border-gray-200 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-800/50"><th class="text-left py-3 px-4 font-semibold">原指导教师</th><th class="text-left py-3 px-4 font-semibold">更换为</th><th class="text-left py-3 px-4 font-semibold">申请理由</th><th class="text-left py-3 px-4 font-semibold">审核状态</th></tr></thead>
|
||||
<tbody id="tableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="emptyState" class="glass rounded-2xl p-12 text-center hidden"><p class="text-gray-500 dark:text-gray-400 text-lg">暂无记录</p></div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block extra_js %}
|
||||
<script>
|
||||
async function loadData() {
|
||||
document.getElementById('loadingIndicator').classList.remove('hidden');
|
||||
document.getElementById('errorMessage').classList.add('hidden');
|
||||
document.getElementById('dataContainer').classList.add('hidden');
|
||||
document.getElementById('emptyState').classList.add('hidden');
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/supervisor-change');
|
||||
const data = await res.json();
|
||||
document.getElementById('loadingIndicator').classList.add('hidden');
|
||||
if (!data.success) { showError(data.message); return; }
|
||||
const items = data.items || [];
|
||||
if (!items.length) { document.getElementById('emptyState').classList.remove('hidden'); return; }
|
||||
const tbody = document.getElementById('tableBody');
|
||||
tbody.innerHTML = items.map((item, i) => {
|
||||
return `<tr class="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50/50 dark:hover:bg-gray-800/30 transition-colors">
|
||||
<td class="py-3 px-4">${escHtml(item.yjs||item.原指导教师||'--')}</td>
|
||||
<td class="py-3 px-4">${escHtml(item.xjs||item.更换为||'--')}</td>
|
||||
<td class="py-3 px-4 text-gray-500 text-xs">${escHtml(item.sqly||item.申请理由||'--')}</td>
|
||||
<td class="py-3 px-4"><span class="px-2 py-0.5 rounded text-xs ${(item.shztmc||item.审核状态||'').includes('通过')?'bg-green-100':(item.shztmc||'').includes('待审')?'bg-yellow-100':'bg-gray-100'}">${escHtml(item.shztmc||item.审核状态||'--')}</span></td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
document.getElementById('dataContainer').classList.remove('hidden');
|
||||
} catch(e) { document.getElementById('loadingIndicator').classList.add('hidden'); showError('网络错误: '+e.message); }
|
||||
}
|
||||
function showError(msg) { document.getElementById('errorText').textContent = msg; document.getElementById('errorMessage').classList.remove('hidden'); }
|
||||
function escHtml(s) { if(s==null) return ''; return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"'); }
|
||||
function escAttr(s) { if(s==null) return ''; return String(s).replace(/&/g,'&').replace(/"/g,'"').replace(/</g,'<').replace(/>/g,'>'); }
|
||||
document.addEventListener('DOMContentLoaded', () => loadData());
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,728 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
|
||||
{% block title %}抢课任务 - 教务抢课系统{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
/* 任务详情模态框动画 */
|
||||
#taskDetailModal {
|
||||
transition: opacity 0.24s ease;
|
||||
}
|
||||
/* 增量刷新闪烁高亮 */
|
||||
@keyframes cellFlash {
|
||||
0% { background-color: rgba(34, 197, 94, 0.25); }
|
||||
100% { background-color: transparent; }
|
||||
}
|
||||
.cell-flash {
|
||||
animation: cellFlash 0.8s ease-out;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.dark .cell-flash {
|
||||
animation-name: cellFlashDark;
|
||||
}
|
||||
@keyframes cellFlashDark {
|
||||
0% { background-color: rgba(34, 197, 94, 0.3); }
|
||||
100% { background-color: transparent; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.cell-flash, .dark .cell-flash { animation: none !important; }
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
<!-- 页面标题 -->
|
||||
<div class="flex justify-between items-center mb-6 list-item-enter" style="animation-delay: 0ms;">
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg>
|
||||
抢课任务管理
|
||||
</h2>
|
||||
<a href="{{ url_for('main.courses') }}"
|
||||
class="px-6 py-2 bg-black dark:bg-white text-white dark:text-black rounded-full font-medium hover:opacity-80 transition-opacity flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/></svg>
|
||||
新建任务
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<!-- 管理员查看其他用户任务的提示 -->
|
||||
<div id="viewingUserBanner" class="hidden mb-4">
|
||||
<div class="glass rounded-2xl px-4 py-3 flex items-center gap-3 text-sm">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-blue-500 flex-shrink-0"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
|
||||
<span>正在查看 <strong id="viewingUserName">用户</strong> 的任务列表</span>
|
||||
<a href="/tasks" class="ml-auto px-3 py-1 rounded-full bg-black dark:bg-white text-white dark:text-black text-xs font-medium hover:opacity-80 transition-opacity">返回我的任务</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 筛选栏 -->
|
||||
<div class="glass rounded-2xl p-4 sm:p-6 mb-4 sm:mb-6 list-item-enter" style="animation-delay: 50ms;">
|
||||
<div class="flex flex-col sm:flex-row gap-3 sm:gap-4 items-stretch sm:items-center">
|
||||
<div class="flex-1">
|
||||
<div class="relative">
|
||||
<select id="statusFilter" onchange="loadTasks()"
|
||||
class="w-full sm:w-64 px-4 py-2.5 rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-black focus:outline-none focus:ring-2 focus:ring-black dark:focus:ring-white appearance-none text-sm">
|
||||
<option value="">📋 全部状态</option>
|
||||
<option value="pending">⏳ 待执行</option>
|
||||
<option value="running">🔄 执行中</option>
|
||||
<option value="success">✅ 成功</option>
|
||||
<option value="failed">❌ 失败</option>
|
||||
<option value="cancelled">🚫 已取消</option>
|
||||
</select>
|
||||
<span class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex gap-2 items-center">
|
||||
<span id="autoRefreshBadge" class="hidden text-xs text-gray-400 flex items-center gap-1">
|
||||
<span class="w-1.5 h-1.5 rounded-full bg-green-500 inline-block"></span>
|
||||
自动刷新中
|
||||
</span>
|
||||
<button onclick="loadTasks(1)"
|
||||
class="btn-outline text-sm px-4 py-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16"/><path d="M16 21h5v-5"/></svg>
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 任务列表 -->
|
||||
<div class="glass rounded-2xl p-4 sm:p-6 list-item-enter" style="animation-delay: 100ms;">
|
||||
<div id="loadingIndicator" class="text-center py-12">
|
||||
<div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
|
||||
<p class="text-gray-500 dark:text-gray-400">加载中...</p>
|
||||
</div>
|
||||
|
||||
<div id="emptyState" class="text-center py-12" style="display: none;">
|
||||
<div class="w-16 h-16 mx-auto mb-4 rounded-2xl bg-gray-100 dark:bg-gray-800 flex items-center justify-center">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="text-gray-400"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg>
|
||||
</div>
|
||||
<p class="text-gray-500 dark:text-gray-400 mb-1 font-medium">暂无任务</p>
|
||||
<p class="text-sm text-gray-400 dark:text-gray-500 mb-5">去课程列表创建你的第一个抢课任务</p>
|
||||
<a href="{{ url_for('main.courses') }}"
|
||||
class="inline-flex items-center gap-2 px-6 py-2.5 bg-black dark:bg-white text-white dark:text-black rounded-full font-medium hover:opacity-80 transition-all hover:shadow-lg">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/></svg>
|
||||
创建任务
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div id="tasksTableContainer" class="max-w-5xl mx-auto" style="display: none;">
|
||||
<div class="-mx-2 sm:mx-0">
|
||||
<table class="card-on-mobile data-table w-full">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>课程名称</th>
|
||||
<th>教师</th>
|
||||
<th>类型</th>
|
||||
<th>状态</th>
|
||||
<th>重试</th>
|
||||
<th>创建时间</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="tasksTableBody">
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 分页 -->
|
||||
<nav id="pagination" class="mt-4 sm:mt-6" style="display: none;">
|
||||
<div class="flex justify-center items-center gap-1.5 sm:gap-2">
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 任务详情模态框 -->
|
||||
<div id="taskDetailModal" class="fixed inset-0 z-50 flex items-center justify-center p-4 opacity-0 pointer-events-none transition-opacity duration-300">
|
||||
<div class="absolute inset-0 bg-black/50 backdrop-blur-sm" onclick="closeTaskDetailModal()"></div>
|
||||
<div class="relative w-full max-w-3xl p-4">
|
||||
<div class="glass rounded-2xl p-6 max-h-[90vh] overflow-y-auto" onclick="event.stopPropagation()">
|
||||
<div class="flex justify-between items-center mb-6">
|
||||
<h3 class="text-xl font-bold flex items-center gap-2">
|
||||
<div class="w-8 h-8 rounded-lg bg-gray-100 dark:bg-gray-800 flex items-center justify-center">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
|
||||
</div>
|
||||
任务详情
|
||||
</h3>
|
||||
<button onclick="closeTaskDetailModal()" class="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div id="taskDetailLoading" class="text-center py-8">
|
||||
<div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
|
||||
</div>
|
||||
|
||||
<div id="taskDetailContent" style="display: none;">
|
||||
<div class="overflow-x-auto mb-6">
|
||||
<table class="w-full">
|
||||
<tbody class="divide-y divide-gray-200 dark:divide-gray-700">
|
||||
<tr><td class="py-3 text-gray-500 dark:text-gray-400 w-32">课程名称</td><td id="detailCourseName" class="py-3 font-medium"></td></tr>
|
||||
<tr><td class="py-3 text-gray-500 dark:text-gray-400">教学班</td><td id="detailClassInfo" class="py-3"></td></tr>
|
||||
<tr><td class="py-3 text-gray-500 dark:text-gray-400">教师</td><td id="detailTeacher" class="py-3"></td></tr>
|
||||
<tr><td class="py-3 text-gray-500 dark:text-gray-400">学分</td><td id="detailCredit" class="py-3"></td></tr>
|
||||
<tr><td class="py-3 text-gray-500 dark:text-gray-400">任务类型</td><td id="detailType" class="py-3"></td></tr>
|
||||
<tr><td class="py-3 text-gray-500 dark:text-gray-400">状态</td><td id="detailStatus" class="py-3"></td></tr>
|
||||
<tr><td class="py-3 text-gray-500 dark:text-gray-400">重试次数</td><td id="detailRetries" class="py-3"></td></tr>
|
||||
<tr><td class="py-3 text-gray-500 dark:text-gray-400">创建时间</td><td id="detailCreated" class="py-3"></td></tr>
|
||||
<tr><td class="py-3 text-gray-500 dark:text-gray-400">开始时间</td><td id="detailStarted" class="py-3"></td></tr>
|
||||
<tr><td class="py-3 text-gray-500 dark:text-gray-400">完成时间</td><td id="detailCompleted" class="py-3"></td></tr>
|
||||
<tr><td class="py-3 text-gray-500 dark:text-gray-400">结果消息</td><td id="detailMessage" class="py-3"></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<!-- 自定义规则展示 -->
|
||||
<div id="detailRulesContainer" class="mb-6 hidden">
|
||||
<h6 class="font-semibold mb-3 flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg>
|
||||
自定义规则
|
||||
</h6>
|
||||
<div id="detailRulesBody" class="space-y-2"></div>
|
||||
</div>
|
||||
|
||||
<h6 class="font-semibold mb-3 flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>
|
||||
实时日志
|
||||
</h6>
|
||||
<div id="taskLogs" class="scrollbar-thin space-y-1.5 max-h-[300px] overflow-y-auto font-mono text-sm p-3 sm:p-4 rounded-xl bg-white/50 dark:bg-black/30 border border-gray-200 dark:border-gray-700">
|
||||
<!-- 日志内容 -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-3 justify-end mt-6">
|
||||
<button onclick="closeTaskDetailModal()"
|
||||
class="px-6 py-2 border border-gray-300 dark:border-gray-600 rounded-full hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors">
|
||||
关闭
|
||||
</button>
|
||||
<button id="cancelTaskBtn" onclick="cancelCurrentTask()" style="display: none;"
|
||||
class="px-6 py-2 bg-red-600 text-white rounded-full font-medium hover:bg-red-700 transition-colors flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>
|
||||
取消任务
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script>
|
||||
let currentPage = 1;
|
||||
let currentTaskId = null;
|
||||
let logRefreshInterval = null;
|
||||
let lastLogId = 0;
|
||||
// 管理员查看指定用户的任务
|
||||
const viewingUserId = new URLSearchParams(window.location.search).get('user_id') || '';
|
||||
|
||||
function openTaskDetailModal() {
|
||||
const modal = document.getElementById('taskDetailModal');
|
||||
modal.classList.remove('opacity-0', 'pointer-events-none');
|
||||
modal.classList.add('opacity-100', 'pointer-events-auto');
|
||||
document.documentElement.style.overflow = 'hidden';
|
||||
document.body.style.overflow = 'hidden';
|
||||
}
|
||||
|
||||
function closeTaskDetailModal() {
|
||||
const modal = document.getElementById('taskDetailModal');
|
||||
modal.classList.add('opacity-0', 'pointer-events-none');
|
||||
modal.classList.remove('opacity-100', 'pointer-events-auto');
|
||||
document.documentElement.style.overflow = '';
|
||||
document.body.style.overflow = '';
|
||||
if (logRefreshInterval) {
|
||||
clearInterval(logRefreshInterval);
|
||||
logRefreshInterval = null;
|
||||
}
|
||||
}
|
||||
|
||||
// 加载任务列表
|
||||
async function loadTasks(page = 1) {
|
||||
currentPage = page;
|
||||
const status = document.getElementById('statusFilter').value;
|
||||
|
||||
document.getElementById('loadingIndicator').style.display = 'block';
|
||||
document.getElementById('emptyState').style.display = 'none';
|
||||
document.getElementById('tasksTableContainer').style.display = 'none';
|
||||
document.getElementById('pagination').style.display = 'none';
|
||||
|
||||
try {
|
||||
let url = `/api/tasks/list?page=${page}&per_page=20`;
|
||||
if (status) url += `&status=${status}`;
|
||||
|
||||
const data = await apiRequest(url);
|
||||
|
||||
document.getElementById('loadingIndicator').style.display = 'none';
|
||||
|
||||
if (!data.success || !data.tasks || data.tasks.length === 0) {
|
||||
document.getElementById('emptyState').style.display = 'block';
|
||||
if (viewingUserId) {
|
||||
// 管理员查看他人任务:即使空也显示表格区域,方便看横幅
|
||||
document.getElementById('tasksTableContainer').style.display = 'block';
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
renderTasksTable(data.tasks);
|
||||
renderPagination(data.total, data.pages, page);
|
||||
|
||||
document.getElementById('tasksTableContainer').style.display = 'block';
|
||||
document.getElementById('pagination').style.display = 'block';
|
||||
|
||||
// 显示自动刷新 badge
|
||||
const badge = document.getElementById('autoRefreshBadge');
|
||||
if (badge) badge.classList.remove('hidden');
|
||||
|
||||
// 管理员查看其他用户:显示横幅
|
||||
if (viewingUserId) {
|
||||
document.getElementById('viewingUserBanner')?.classList.remove('hidden');
|
||||
const nameEl = document.getElementById('viewingUserName');
|
||||
if (data.tasks && data.tasks.length > 0 && data.tasks[0].username) {
|
||||
nameEl.textContent = data.tasks[0].username;
|
||||
} else {
|
||||
nameEl.textContent = 'ID ' + viewingUserId;
|
||||
}
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
document.getElementById('loadingIndicator').style.display = 'none';
|
||||
if (!silent) showToast('加载失败,请稍后重试', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
// 渲染任务表格
|
||||
function renderTasksTable(tasks) {
|
||||
const tbody = document.getElementById('tasksTableBody');
|
||||
tbody.innerHTML = tasks.map((task, index) => {
|
||||
const typeBadge = task.task_type === 'immediate'
|
||||
? '<span class="status-badge status-info"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline-block -mt-0.5 mr-0.5"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg> 立即</span>'
|
||||
: '<span class="status-badge status-warning"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline-block -mt-0.5 mr-0.5"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg> 定时</span>';
|
||||
|
||||
const delay = Math.min(index * 30, 300);
|
||||
return `
|
||||
<tr data-task-id="${task.id}" class="list-item-enter" style="animation-delay: ${delay}ms;">
|
||||
<td data-label="ID"><span class="font-mono text-xs sm:text-sm text-gray-500 dark:text-gray-400">#${task.id}</span></td>
|
||||
<td data-label="课程名称"><strong class="text-sm">${escapeHtml(task.course_name)}</strong></td>
|
||||
<td data-label="教师"><span class="text-sm">${escapeHtml(task.teacher_name || '-')}</span></td>
|
||||
<td data-label="类型">${typeBadge}</td>
|
||||
<td data-label="状态" class="task-status-cell">${getStatusBadge(task.status)}</td>
|
||||
<td data-label="重试" class="task-retry-cell"><span class="text-xs sm:text-sm">${task.retry_count}/${task.max_retries === 0 ? '∞' : task.max_retries}</span></td>
|
||||
<td data-label="创建时间"><span class="text-xs sm:text-sm text-gray-500">${formatTime(task.created_at)}</span></td>
|
||||
<td data-label="操作" class="task-actions-cell">
|
||||
<div class="flex gap-1.5 sm:gap-2">
|
||||
<button onclick="viewTaskDetail(${task.id})"
|
||||
class="p-1.5 sm:p-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors" title="查看详情">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>
|
||||
</button>
|
||||
${(task.status === 'pending' || task.status === 'running') ? `
|
||||
<button onclick="cancelTask(${task.id})"
|
||||
class="p-1.5 sm:p-2 border border-red-300 dark:border-red-700 text-red-600 dark:text-red-400 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors" title="取消任务">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>
|
||||
</button>
|
||||
` : ''}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
// ── 增量刷新(只更新变化的单元格) ──
|
||||
let _refreshCount = 0;
|
||||
|
||||
async function incrementalRefresh() {
|
||||
// 仅当表格可见时才刷新
|
||||
const container = document.getElementById('tasksTableContainer');
|
||||
if (!container || container.style.display === 'none') return;
|
||||
|
||||
const status = document.getElementById('statusFilter').value;
|
||||
try {
|
||||
const data = await apiRequest(getTaskListUrl(currentPage) + (status ? '&status=' + status : ''));
|
||||
if (!data.success || !data.tasks) return;
|
||||
|
||||
const tbody = document.getElementById('tasksTableBody');
|
||||
const existingRows = tbody.querySelectorAll('tr[data-task-id]');
|
||||
const existingMap = {};
|
||||
existingRows.forEach(tr => { existingMap[tr.getAttribute('data-task-id')] = tr; });
|
||||
|
||||
let changed = false;
|
||||
|
||||
data.tasks.forEach((task, idx) => {
|
||||
const tid = String(task.id);
|
||||
const oldRow = existingMap[tid];
|
||||
if (oldRow) {
|
||||
// 行存在 → 增量更新单元格
|
||||
if (updateCellIfChanged(oldRow, '.task-status-cell', getStatusBadge(task.status))) changed = true;
|
||||
if (updateCellIfChanged(oldRow, '.task-retry-cell',
|
||||
'<span class="text-xs sm:text-sm">' + task.retry_count + '/' + (task.max_retries === 0 ? '∞' : task.max_retries) + '</span>')) changed = true;
|
||||
|
||||
// 操作列:如果状态从 pending/running 变了,需隐藏取消按钮
|
||||
const actionsCell = oldRow.querySelector('.task-actions-cell');
|
||||
const newActionsHtml = buildActionsHtml(task);
|
||||
if (actionsCell && actionsCell.innerHTML.trim() !== newActionsHtml.trim()) {
|
||||
actionsCell.innerHTML = newActionsHtml;
|
||||
changed = true;
|
||||
}
|
||||
} else {
|
||||
// 新任务出现在本页 → 插入
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
|
||||
if (changed) {
|
||||
_refreshCount++;
|
||||
const badge = document.getElementById('autoRefreshBadge');
|
||||
if (badge) {
|
||||
badge.classList.remove('hidden');
|
||||
badge.innerHTML = '<span class="w-1.5 h-1.5 rounded-full bg-green-500 inline-block"></span> 已更新';
|
||||
clearTimeout(badge._hideTimer);
|
||||
badge._hideTimer = setTimeout(() => {
|
||||
badge.innerHTML = '<span class="w-1.5 h-1.5 rounded-full bg-green-500 inline-block"></span> 自动刷新中';
|
||||
}, 2000);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// 静默失败
|
||||
}
|
||||
}
|
||||
|
||||
// ── 辅助:仅当值不同时才更新 DOM,并附带闪烁反馈 ──
|
||||
function updateCellIfChanged(row, selector, newHtml) {
|
||||
const cell = row.querySelector(selector);
|
||||
if (!cell) return false;
|
||||
const old = cell.innerHTML.trim();
|
||||
if (old === newHtml.trim()) return false;
|
||||
cell.innerHTML = newHtml;
|
||||
// 闪烁高亮
|
||||
cell.classList.remove('cell-flash');
|
||||
void cell.offsetWidth; // 强制 reflow
|
||||
cell.classList.add('cell-flash');
|
||||
setTimeout(() => cell.classList.remove('cell-flash'), 800);
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── 辅助:构建操作列 HTML ──
|
||||
function buildActionsHtml(task) {
|
||||
const viewBtn = '<button onclick="viewTaskDetail(' + task.id + ')" class="p-1.5 sm:p-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors" title="查看详情"><svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg></button>';
|
||||
const cancelBtn = (task.status === 'pending' || task.status === 'running')
|
||||
? '<button onclick="cancelTask(' + task.id + ')" class="p-1.5 sm:p-2 border border-red-300 dark:border-red-700 text-red-600 dark:text-red-400 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors" title="取消任务"><svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg></button>'
|
||||
: '';
|
||||
return '<div class="flex gap-1.5 sm:gap-2">' + viewBtn + cancelBtn + '</div>';
|
||||
}
|
||||
|
||||
function getTaskListUrl(page) {
|
||||
let url = `/api/tasks/list?page=${page}&per_page=20`;
|
||||
if (viewingUserId) url += `&user_id=${viewingUserId}`;
|
||||
return url;
|
||||
}
|
||||
|
||||
// 加载任务列表(全量,仅手动调用时触发 loading) ──
|
||||
async function loadTasks(page = 1, silent = false) {
|
||||
currentPage = page;
|
||||
const status = document.getElementById('statusFilter').value;
|
||||
|
||||
if (!silent) {
|
||||
document.getElementById('loadingIndicator').style.display = 'block';
|
||||
document.getElementById('emptyState').style.display = 'none';
|
||||
document.getElementById('tasksTableContainer').style.display = 'none';
|
||||
document.getElementById('pagination').style.display = 'none';
|
||||
}
|
||||
|
||||
try {
|
||||
let url = getTaskListUrl(page);
|
||||
if (status) url += `&status=${status}`;
|
||||
|
||||
const data = await apiRequest(url);
|
||||
|
||||
if (!silent) {
|
||||
document.getElementById('loadingIndicator').style.display = 'none';
|
||||
}
|
||||
|
||||
if (!data.success || !data.tasks || data.tasks.length === 0) {
|
||||
document.getElementById('emptyState').style.display = 'block';
|
||||
document.getElementById('tasksTableContainer').style.display = 'none';
|
||||
return;
|
||||
}
|
||||
|
||||
renderTasksTable(data.tasks);
|
||||
renderPagination(data.total, data.pages, page);
|
||||
|
||||
document.getElementById('tasksTableContainer').style.display = 'block';
|
||||
document.getElementById('pagination').style.display = 'block';
|
||||
|
||||
// 显示自动刷新 badge
|
||||
const badge = document.getElementById('autoRefreshBadge');
|
||||
if (badge) badge.classList.remove('hidden');
|
||||
|
||||
} catch (error) {
|
||||
if (!silent) {
|
||||
document.getElementById('loadingIndicator').style.display = 'none';
|
||||
showToast('加载失败,请稍后重试', 'error');
|
||||
}
|
||||
}
|
||||
}
|
||||
function renderPagination(total, pages, current) {
|
||||
const nav = document.getElementById('pagination').querySelector('div');
|
||||
let html = '';
|
||||
|
||||
html += `
|
||||
<button onclick="loadTasks(${current - 1})" ${current === 1 ? 'disabled' : ''}
|
||||
class="px-2.5 sm:px-3 py-1.5 text-xs sm:text-sm rounded-lg border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m15 18-6-6 6-6"/></svg>
|
||||
<span class="hidden sm:inline">上一页</span>
|
||||
</button>
|
||||
`;
|
||||
|
||||
for (let i = 1; i <= pages; i++) {
|
||||
if (i === 1 || i === pages || (i >= current - 2 && i <= current + 2)) {
|
||||
html += `
|
||||
<button onclick="loadTasks(${i})"
|
||||
class="min-w-[32px] sm:min-w-[36px] h-8 sm:h-9 rounded-lg text-xs sm:text-sm font-medium transition-all ${i === current ? 'bg-black dark:bg-white text-white dark:text-black shadow-sm' : 'border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-800'}">
|
||||
${i}
|
||||
</button>
|
||||
`;
|
||||
} else if (i === current - 3 || i === current + 3) {
|
||||
html += `<span class="px-1 sm:px-2 text-gray-400 text-xs sm:text-sm">…</span>`;
|
||||
}
|
||||
}
|
||||
|
||||
html += `
|
||||
<button onclick="loadTasks(${current + 1})" ${current === pages ? 'disabled' : ''}
|
||||
class="px-2.5 sm:px-3 py-1.5 text-xs sm:text-sm rounded-lg border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1">
|
||||
<span class="hidden sm:inline">下一页</span>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m9 18 6-6-6-6"/></svg>
|
||||
</button>
|
||||
`;
|
||||
|
||||
nav.innerHTML = html;
|
||||
}
|
||||
|
||||
// 查看任务详情
|
||||
async function viewTaskDetail(taskId) {
|
||||
currentTaskId = taskId;
|
||||
lastLogId = 0;
|
||||
|
||||
document.getElementById('taskDetailLoading').style.display = 'block';
|
||||
document.getElementById('taskDetailContent').style.display = 'none';
|
||||
document.getElementById('cancelTaskBtn').style.display = 'none';
|
||||
|
||||
openTaskDetailModal();
|
||||
|
||||
// 清除之前的定时器
|
||||
if (logRefreshInterval) {
|
||||
clearInterval(logRefreshInterval);
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await apiRequest(`/api/tasks/${taskId}`);
|
||||
|
||||
document.getElementById('taskDetailLoading').style.display = 'none';
|
||||
document.getElementById('taskDetailContent').style.display = 'block';
|
||||
|
||||
if (data.success) {
|
||||
const task = data.task;
|
||||
document.getElementById('detailCourseName').textContent = task.course_name;
|
||||
document.getElementById('detailClassInfo').textContent = task.class_info || '-';
|
||||
document.getElementById('detailTeacher').textContent = task.teacher_name || '-';
|
||||
document.getElementById('detailCredit').textContent = task.credit || '-';
|
||||
document.getElementById('detailType').innerHTML = task.task_type === 'immediate'
|
||||
? '<span class="status-badge status-info"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline-block -mt-0.5 mr-0.5"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg> 立即抢课</span>'
|
||||
: '<span class="status-badge status-warning"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline-block -mt-0.5 mr-0.5"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg> 定时抢课</span> <span class="text-xs text-gray-400">(' + formatTime(task.scheduled_time) + ')</span>';
|
||||
document.getElementById('detailStatus').innerHTML = getStatusBadge(task.status);
|
||||
document.getElementById('detailRetries').textContent = `${task.retry_count}/${task.max_retries}`;
|
||||
document.getElementById('detailCreated').textContent = formatTime(task.created_at);
|
||||
document.getElementById('detailStarted').textContent = formatTime(task.started_at);
|
||||
document.getElementById('detailCompleted').textContent = formatTime(task.completed_at);
|
||||
document.getElementById('detailMessage').textContent = task.result_message || '-';
|
||||
|
||||
// 显示自定义规则
|
||||
renderTaskRules(task.rules);
|
||||
|
||||
// 显示取消按钮
|
||||
if (task.status === 'pending' || task.status === 'running') {
|
||||
document.getElementById('cancelTaskBtn').style.display = 'inline-flex';
|
||||
}
|
||||
|
||||
// 加载日志
|
||||
loadTaskLogs(taskId);
|
||||
|
||||
// 如果任务正在运行,定时刷新日志
|
||||
if (task.status === 'running') {
|
||||
logRefreshInterval = setInterval(() => loadTaskLogs(taskId, true), 2000);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
document.getElementById('taskDetailLoading').style.display = 'none';
|
||||
showToast('加载详情失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
// 加载任务日志
|
||||
async function loadTaskLogs(taskId, incremental = false) {
|
||||
try {
|
||||
let url = `/api/logs/list?task_id=${taskId}&per_page=100`;
|
||||
if (incremental && lastLogId > 0) {
|
||||
url = `/api/logs/recent?task_id=${taskId}&after_id=${lastLogId}`;
|
||||
}
|
||||
|
||||
const data = await apiRequest(url);
|
||||
|
||||
if (data.success && data.logs) {
|
||||
const logContainer = document.getElementById('taskLogs');
|
||||
|
||||
if (!incremental) {
|
||||
logContainer.innerHTML = '';
|
||||
}
|
||||
|
||||
const levelColors = {
|
||||
'info': 'text-blue-600 dark:text-blue-400',
|
||||
'success': 'text-green-600 dark:text-green-400',
|
||||
'warning': 'text-yellow-600 dark:text-yellow-400',
|
||||
'error': 'text-red-600 dark:text-red-400'
|
||||
};
|
||||
|
||||
data.logs.forEach(log => {
|
||||
if (log.id > lastLogId) {
|
||||
lastLogId = log.id;
|
||||
}
|
||||
|
||||
const logClass = levelColors[log.level] || 'text-gray-600 dark:text-gray-400';
|
||||
const logHtml = `
|
||||
<div class="p-2 rounded-lg bg-white/50 dark:bg-black/30">
|
||||
<span class="text-gray-400 text-xs">${log.created_at ? formatTime(log.created_at).split(' ').slice(1).join(' ') : ''}</span>
|
||||
<span class="${logClass} font-bold text-xs">[${log.level.toUpperCase()}]</span>
|
||||
${escapeHtml(log.message)}
|
||||
</div>
|
||||
`;
|
||||
|
||||
logContainer.insertAdjacentHTML('beforeend', logHtml);
|
||||
});
|
||||
|
||||
// 滚动到底部
|
||||
logContainer.scrollTop = logContainer.scrollHeight;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载日志失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// 取消任务
|
||||
async function cancelTask(taskId) {
|
||||
if (!confirm('确定要取消这个任务吗?')) return;
|
||||
|
||||
try {
|
||||
const data = await apiRequest(`/api/tasks/${taskId}/cancel`, {
|
||||
method: 'POST'
|
||||
});
|
||||
|
||||
if (data.success) {
|
||||
showToast('任务已取消', 'success');
|
||||
loadTasks(currentPage);
|
||||
} else {
|
||||
showToast(data.message || '取消失败', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
showToast('网络错误', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
// 取消当前查看的任务
|
||||
async function cancelCurrentTask() {
|
||||
if (currentTaskId) {
|
||||
await cancelTask(currentTaskId);
|
||||
closeTaskDetailModal();
|
||||
}
|
||||
}
|
||||
|
||||
// HTML转义
|
||||
function escapeHtml(text) {
|
||||
if (!text) return '';
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
// ── SVG 图标(用于状态徽章) ──
|
||||
const ICONS = {
|
||||
pending: '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline-block -mt-0.5 mr-0.5"><path d="M12 2v6l4 4-4 4v6"/><path d="M4 2h16"/><path d="M4 22h16"/></svg>',
|
||||
running: '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline-block -mt-0.5 mr-0.5 animate-spin"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',
|
||||
success: '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline-block -mt-0.5 mr-0.5"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>',
|
||||
failed: '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline-block -mt-0.5 mr-0.5"><circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/></svg>',
|
||||
cancelled: '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline-block -mt-0.5 mr-0.5"><circle cx="12" cy="12" r="10"/><path d="m4.9 4.9 14.2 14.2"/></svg>',
|
||||
expired: '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline-block -mt-0.5 mr-0.5"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>',
|
||||
unknown: '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline-block -mt-0.5 mr-0.5"><circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><path d="M12 17h.01"/></svg>',
|
||||
};
|
||||
|
||||
// ── 渲染自定义规则 ──
|
||||
function renderTaskRules(rules) {
|
||||
const container = document.getElementById('detailRulesContainer');
|
||||
const body = document.getElementById('detailRulesBody');
|
||||
if (!container || !body) return;
|
||||
|
||||
if (!rules || !rules.on_has_vacancy || rules.on_has_vacancy.length === 0) {
|
||||
container.classList.add('hidden');
|
||||
return;
|
||||
}
|
||||
|
||||
container.classList.remove('hidden');
|
||||
body.innerHTML = rules.on_has_vacancy.map((rule, i) => {
|
||||
if (rule.action === 'drop_course') {
|
||||
return `
|
||||
<div class="flex items-center gap-2 p-2.5 rounded-xl bg-emerald-50/80 dark:bg-emerald-950/20 border border-emerald-200 dark:border-emerald-800">
|
||||
<span class="flex-shrink-0 w-6 h-6 rounded-md bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300 flex items-center justify-center text-xs font-bold">${i + 1}</span>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="flex-shrink-0 text-emerald-600 dark:text-emerald-400"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg>
|
||||
<span class="text-sm font-medium text-emerald-800 dark:text-emerald-200">退课</span>
|
||||
<span class="text-sm text-gray-600 dark:text-gray-400">${escapeHtml(rule.course_name || '未知课程')}</span>
|
||||
<span class="text-xs text-gray-400 dark:text-gray-500 ml-auto">抢课前执行</span>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
if (rule.action === 'wait') {
|
||||
return `
|
||||
<div class="flex items-center gap-2 p-2.5 rounded-xl bg-blue-50/80 dark:bg-blue-950/20 border border-blue-200 dark:border-blue-800">
|
||||
<span class="flex-shrink-0 w-6 h-6 rounded-md bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300 flex items-center justify-center text-xs font-bold">${i + 1}</span>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="flex-shrink-0 text-blue-600 dark:text-blue-400"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
|
||||
<span class="text-sm font-medium text-blue-800 dark:text-blue-200">等待</span>
|
||||
<span class="text-sm text-gray-600 dark:text-gray-400">${rule.seconds || 2} 秒</span>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
return '';
|
||||
}).join('') + `
|
||||
<div class="flex items-center gap-2 p-2.5 rounded-xl bg-gray-100/80 dark:bg-gray-800/60 border border-dashed border-gray-300 dark:border-gray-700">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="flex-shrink-0 text-gray-500"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>
|
||||
<span class="text-sm text-gray-500 dark:text-gray-400">→ 然后自动抢课</span>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// 状态徽章
|
||||
function getStatusBadge(status) {
|
||||
const statusMap = {
|
||||
'pending': { class: 'status-pending', icon: ICONS.pending, text: '待执行' },
|
||||
'running': { class: 'status-running', icon: ICONS.running, text: '执行中' },
|
||||
'success': { class: 'status-success', icon: ICONS.success, text: '成功' },
|
||||
'failed': { class: 'status-failed', icon: ICONS.failed, text: '失败' },
|
||||
'cancelled': { class: 'status-cancelled', icon: ICONS.cancelled, text: '已取消' },
|
||||
'expired': { class: 'status-cancelled', icon: ICONS.expired, text: '已过期' }
|
||||
};
|
||||
const s = statusMap[status] || { class: 'status-pending', icon: ICONS.unknown, text: status };
|
||||
return '<span class="status-badge ' + s.class + '">' + s.icon + s.text + '</span>';
|
||||
}
|
||||
|
||||
// 页面加载
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
// 将弹窗移到 body 直接子级,确保 fixed 定位基于视口
|
||||
const taskDetailModal = document.getElementById('taskDetailModal');
|
||||
if (taskDetailModal) document.body.appendChild(taskDetailModal);
|
||||
|
||||
loadTasks();
|
||||
|
||||
// 每5秒增量刷新(只更新变化的单元格,不重绘整表)
|
||||
setInterval(() => incrementalRefresh(), 5000);
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,816 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
|
||||
{% block title %}教师课表 - {{ brand_name }}{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
@keyframes fadeSlideIn {
|
||||
from { opacity: 0; transform: translateY(8px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.row-animate { animation: fadeSlideIn 0.3s ease both; }
|
||||
|
||||
/* 课程格子入场动画 */
|
||||
@keyframes cellFadeIn {
|
||||
from { opacity: 0; transform: translateY(6px) scale(0.96); }
|
||||
to { opacity: 1; transform: translateY(0) scale(1); }
|
||||
}
|
||||
.course-cell {
|
||||
animation: cellFadeIn 0.32s cubic-bezier(0.22, 1, 0.36, 1) both;
|
||||
}
|
||||
|
||||
/* 弹窗 */
|
||||
#teacherModal {
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: opacity 0.22s ease;
|
||||
}
|
||||
#teacherModal.modal-open {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
#teacherModal .modal-backdrop {
|
||||
opacity: 0;
|
||||
transition: opacity 0.22s ease;
|
||||
}
|
||||
#teacherModal.modal-open .modal-backdrop {
|
||||
opacity: 1;
|
||||
}
|
||||
#teacherModal .modal-panel {
|
||||
opacity: 0;
|
||||
transform: scale(0.94) translateY(12px);
|
||||
transition: opacity 0.22s ease, transform 0.26s cubic-bezier(0.22, 1, 0.36, 1);
|
||||
}
|
||||
#teacherModal.modal-open .modal-panel {
|
||||
opacity: 1;
|
||||
transform: scale(1) translateY(0);
|
||||
}
|
||||
|
||||
/* 行悬停提示 */
|
||||
.clickable-row { cursor: pointer; }
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 list-item-enter" style="animation-delay: 0ms;">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/>
|
||||
<circle cx="9" cy="7" r="4"/>
|
||||
<path d="M23 21v-2a4 4 0 0 0-3-3.87"/>
|
||||
<path d="M16 3.13a4 4 0 0 1 0 7.75"/>
|
||||
</svg>
|
||||
教师课表
|
||||
</h2>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">查询教师授课安排,点击教师行可预览课程表</p>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<button onclick="refresh()"
|
||||
class="px-4 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm font-medium hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<polyline points="23 4 23 10 17 10"/>
|
||||
<path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>
|
||||
</svg>
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 筛选条件 -->
|
||||
<div class="glass rounded-2xl p-4 mb-4 list-item-enter max-w-5xl mx-auto" style="animation-delay: 50ms;">
|
||||
<div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
|
||||
<div>
|
||||
<label class="block text-xs text-gray-500 dark:text-gray-400 mb-1">学年</label>
|
||||
<select id="fXnm" onchange="refresh()" class="w-full px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm">
|
||||
<option value="">全部</option>
|
||||
<option value="2026" selected>2026-2027</option>
|
||||
<option value="2025">2025-2026</option>
|
||||
<option value="2024">2024-2025</option>
|
||||
<option value="2023">2023-2024</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs text-gray-500 dark:text-gray-400 mb-1">学期</label>
|
||||
<select id="fXqm" onchange="refresh()" class="w-full px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm">
|
||||
<option value="">全部</option>
|
||||
<option value="3" selected>第1学期</option>
|
||||
<option value="12">第2学期</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs text-gray-500 dark:text-gray-400 mb-1">校区</label>
|
||||
<select id="fXqh" onchange="refresh()" class="w-full px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm">
|
||||
<option value="">全部</option>
|
||||
<option value="1">长清校区</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs text-gray-500 dark:text-gray-400 mb-1">职称</label>
|
||||
<select id="fZcm" onchange="refresh()" class="w-full px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm">
|
||||
<option value="">全部</option>
|
||||
<option value="01">教授</option>
|
||||
<option value="02">副教授</option>
|
||||
<option value="03">讲师</option>
|
||||
<option value="04">助教</option>
|
||||
<option value="05">未评级</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs text-gray-500 dark:text-gray-400 mb-1">部门/学院</label>
|
||||
<select id="fJg" onchange="refresh()" class="w-full px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm">
|
||||
<option value="">全部</option>
|
||||
<option value="301">劳动关系学院</option>
|
||||
<option value="302">工商学院</option>
|
||||
<option value="303">会计学院</option>
|
||||
<option value="304">艺术学院</option>
|
||||
<option value="305">信息工程学院</option>
|
||||
<option value="306">经贸学院</option>
|
||||
<option value="307">智能工程学院</option>
|
||||
<option value="308">人文学院</option>
|
||||
<option value="311">马克思主义学院</option>
|
||||
<option value="312">体育教学部</option>
|
||||
<option value="313">国际交流学院</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs text-gray-500 dark:text-gray-400 mb-1">开课学院</label>
|
||||
<select id="fKkbm" onchange="refresh()" class="w-full px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm">
|
||||
<option value="">全部</option>
|
||||
<option value="301">劳动关系学院</option>
|
||||
<option value="302">工商学院</option>
|
||||
<option value="303">会计学院</option>
|
||||
<option value="304">艺术学院</option>
|
||||
<option value="305">信息工程学院</option>
|
||||
<option value="306">经贸学院</option>
|
||||
<option value="307">智能工程学院</option>
|
||||
<option value="308">人文学院</option>
|
||||
<option value="311">马克思主义学院</option>
|
||||
<option value="312">体育教学部</option>
|
||||
<option value="313">国际交流学院</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs text-gray-500 dark:text-gray-400 mb-1">教师工号/姓名</label>
|
||||
<input id="fJgh" type="text" placeholder="可模糊搜索" onkeydown="if(event.key==='Enter')refresh()"
|
||||
class="w-full px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm">
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex gap-3 mt-3 items-center flex-wrap">
|
||||
<label class="flex items-center gap-1.5 text-sm text-gray-600 dark:text-gray-400 cursor-pointer">
|
||||
<input type="checkbox" id="fZxszjjs" onchange="refresh()" class="w-4 h-4 rounded accent-black dark:accent-white">
|
||||
只显示主讲教师
|
||||
</label>
|
||||
<label class="flex items-center gap-1.5 text-sm text-gray-600 dark:text-gray-400 cursor-pointer">
|
||||
<input type="checkbox" id="fSfwp" onchange="refresh()" class="w-4 h-4 rounded accent-black dark:accent-white">
|
||||
仅显示外聘教师
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 图表区域 -->
|
||||
<div id="chartsRow" class="hidden grid grid-cols-1 md:grid-cols-2 gap-4 mb-4 list-item-enter" style="animation-delay: 120ms;">
|
||||
<div class="glass rounded-2xl p-4">
|
||||
<h4 class="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">职称分布</h4>
|
||||
<div id="titleChart" style="height: 260px;"></div>
|
||||
</div>
|
||||
<div class="glass rounded-2xl p-4">
|
||||
<h4 class="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">学院分布</h4>
|
||||
<div id="deptChart" style="height: 260px;"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 加载中 -->
|
||||
<div id="loadingIndicator" class="text-center py-12 list-item-enter" style="animation-delay: 100ms;">
|
||||
<div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
|
||||
<p class="text-gray-500 dark:text-gray-400">正在查询教师列表...</p>
|
||||
</div>
|
||||
|
||||
<!-- 错误提示 -->
|
||||
<div id="errorMessage" class="glass rounded-2xl p-6 mb-4 text-center hidden">
|
||||
<p id="errorText" class="text-red-500"></p>
|
||||
</div>
|
||||
|
||||
<!-- 结果 -->
|
||||
<div id="dataContainer" class="hidden list-item-enter" style="animation-delay: 150ms;">
|
||||
<div class="flex justify-between items-center mb-3 px-1">
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400">共 <span id="totalCount" class="font-bold text-black dark:text-white">0</span> 条记录</p>
|
||||
<p class="text-xs text-gray-400 dark:text-gray-500">点击行可预览课程表</p>
|
||||
</div>
|
||||
<div class="glass rounded-2xl overflow-hidden">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead>
|
||||
<tr class="border-b border-gray-200 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-800/50">
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">#</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">工号</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">姓名</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">职称</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">所属学院</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">校区</th>
|
||||
<th class="text-center py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">电话</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="tableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<div id="emptyState" class="glass rounded-2xl p-12 text-center hidden">
|
||||
<p class="text-gray-500 dark:text-gray-400 text-lg">暂无符合条件的教师</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 教师课表明细弹窗 -->
|
||||
<div id="teacherModal" class="fixed inset-0 z-50 flex items-center justify-center p-4" aria-labelledby="modal-title" role="dialog" aria-modal="true">
|
||||
<!-- 背景遮罩 -->
|
||||
<div class="modal-backdrop fixed inset-0 bg-black/50 backdrop-blur-sm" onclick="closeTeacherModal()"></div>
|
||||
|
||||
<!-- 弹窗面板 -->
|
||||
<div class="modal-panel relative glass rounded-2xl shadow-xl w-full max-w-2xl max-h-[85vh] flex flex-col overflow-hidden">
|
||||
<!-- 顶部标题区 -->
|
||||
<div class="flex items-center gap-3 p-5 pb-4 flex-shrink-0 border-b border-gray-200 dark:border-gray-700">
|
||||
<div id="modalTeacherIcon" class="w-10 h-10 rounded-xl bg-blue-900/50 text-blue-100 flex items-center justify-center flex-shrink-0">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
|
||||
<circle cx="12" cy="7" r="4"></circle>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="min-w-0 flex-1">
|
||||
<h3 id="modalTeacherName" class="text-lg font-bold text-gray-900 dark:text-white leading-tight truncate">--</h3>
|
||||
<p id="modalTeacherInfo" class="text-sm text-gray-500 dark:text-gray-400 truncate">--</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-2 flex-shrink-0">
|
||||
<span id="modalCourseCount" class="px-2 py-1 rounded-full text-xs font-medium bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-300">0门课</span>
|
||||
<button onclick="closeTeacherModal()" class="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-full transition-colors">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<line x1="18" y1="6" x2="6" y2="18"></line>
|
||||
<line x1="6" y1="6" x2="18" y2="18"></line>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 加载指示器 -->
|
||||
<div id="modalLoading" class="flex-1 flex items-center justify-center py-12">
|
||||
<div class="w-8 h-8 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin"></div>
|
||||
</div>
|
||||
|
||||
<!-- 错误提示 -->
|
||||
<div id="modalError" class="flex-1 flex items-center justify-center py-12 hidden">
|
||||
<p id="modalErrorText" class="text-red-500 text-sm"></p>
|
||||
</div>
|
||||
|
||||
<!-- 课表内容区 -->
|
||||
<div id="modalContent" class="flex-1 overflow-y-auto p-4 hidden">
|
||||
<!-- 视图切换 + 周次选择 -->
|
||||
<div class="flex items-center justify-between gap-2 mb-3">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-xs text-gray-500 dark:text-gray-400">周次:</span>
|
||||
<select id="modalWeekSelect" onchange="renderTeacherScheduleInModal()" class="px-2 py-1 rounded border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-xs">
|
||||
</select>
|
||||
</div>
|
||||
<div class="flex items-center gap-1 p-0.5 rounded-lg bg-gray-100 dark:bg-gray-800">
|
||||
<button id="viewGridBtn" onclick="switchView('grid')" class="px-3 py-1 rounded-md text-xs font-medium bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm transition-all">网格</button>
|
||||
<button id="viewListBtn" onclick="switchView('list')" class="px-3 py-1 rounded-md text-xs font-medium text-gray-500 dark:text-gray-400 transition-all">列表</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 课表网格视图 -->
|
||||
<div id="gridView" class="overflow-x-auto">
|
||||
<div class="grid gap-1 min-w-[320px]" id="teacherScheduleGrid" style="grid-template-columns: 48px repeat(7, 1fr); grid-template-rows: 32px repeat(11, minmax(48px, auto));">
|
||||
<!-- 由 JS 动态生成 -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 列表视图 -->
|
||||
<div id="listView" class="hidden overflow-x-auto">
|
||||
<table class="w-full text-xs">
|
||||
<thead>
|
||||
<tr class="border-b border-gray-200 dark:border-gray-700 text-gray-500 dark:text-gray-400">
|
||||
<th class="py-2 px-2 text-left font-medium">星期</th>
|
||||
<th class="py-2 px-2 text-left font-medium">节次</th>
|
||||
<th class="py-2 px-2 text-left font-medium">课程</th>
|
||||
<th class="py-2 px-2 text-left font-medium">上课班级</th>
|
||||
<th class="py-2 px-2 text-left font-medium">人数</th>
|
||||
<th class="py-2 px-2 text-left font-medium">地点</th>
|
||||
<th class="py-2 px-2 text-left font-medium">周次</th>
|
||||
<th class="py-2 px-2 text-left font-medium">考核</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="listTableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<!-- 空状态 -->
|
||||
<div id="modalEmpty" class="text-center py-8 hidden">
|
||||
<p class="text-gray-400 dark:text-gray-500 text-sm">该周次暂无课程</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script src="{{ url_for('static', filename='echarts.min.js') }}"></script>
|
||||
<script>
|
||||
// ─── Session 自动刷新 ────────────────────────────────────────────
|
||||
async function initSession() {
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/ping');
|
||||
const data = await res.json();
|
||||
if (data.refreshed) console.log('[Session] 已刷新');
|
||||
return true;
|
||||
} catch (e) { console.warn('[Session] ping 失败:', e); return false; }
|
||||
}
|
||||
function isDarkMode() { return document.documentElement.classList.contains('dark'); }
|
||||
// ─── 工具函数(复用 timetable.html 逻辑)──────────────────────────────
|
||||
|
||||
// 解析周次描述
|
||||
function parseWeekRange(zcd) {
|
||||
if (!zcd) return { start: 1, end: 20, isOdd: false, isEven: false };
|
||||
const isOdd = zcd.includes('(单)');
|
||||
const isEven = zcd.includes('(双)');
|
||||
const clean = zcd.replace(/\([^)]*\)/g, '');
|
||||
const segments = clean.split(',');
|
||||
let minWeek = 20, maxWeek = 0;
|
||||
for (const seg of segments) {
|
||||
const match = seg.match(/(\d+)(?:-(\d+))?/);
|
||||
if (match) {
|
||||
const start = parseInt(match[1]);
|
||||
const end = match[2] ? parseInt(match[2]) : start;
|
||||
minWeek = Math.min(minWeek, start);
|
||||
maxWeek = Math.max(maxWeek, end);
|
||||
}
|
||||
}
|
||||
if (minWeek > maxWeek) return { start: 1, end: 20, isOdd, isEven };
|
||||
return { start: minWeek, end: maxWeek, isOdd, isEven };
|
||||
}
|
||||
|
||||
// 判断课程是否在指定周次
|
||||
function isCourseInWeek(course, week) {
|
||||
const zcd = course.zcd;
|
||||
if (!zcd) return true;
|
||||
const isOdd = zcd.includes('(单)');
|
||||
const isEven = zcd.includes('(双)');
|
||||
const clean = zcd.replace(/\([^)]*\)/g, '');
|
||||
const segments = clean.split(',');
|
||||
let inRange = false;
|
||||
for (const seg of segments) {
|
||||
const match = seg.match(/(\d+)(?:-(\d+))?/);
|
||||
if (match) {
|
||||
const start = parseInt(match[1]);
|
||||
const end = match[2] ? parseInt(match[2]) : start;
|
||||
if (start <= week && week <= end) { inRange = true; break; }
|
||||
}
|
||||
}
|
||||
if (!inRange) return false;
|
||||
if (isOdd && week % 2 === 0) return false;
|
||||
if (isEven && week % 2 === 1) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// 解析节数范围
|
||||
function parsePeriodRange(jcor) {
|
||||
if (!jcor || typeof jcor !== 'string') return { start: 1, end: 1 };
|
||||
const parts = jcor.split(/[-,\s]+/).filter(p => p.trim());
|
||||
if (parts.length >= 2) {
|
||||
const s = parseInt(parts[0]);
|
||||
const e = parseInt(parts[parts.length - 1]);
|
||||
if (!isNaN(s) && !isNaN(e) && s > 0 && e > 0) return { start: s, end: e };
|
||||
}
|
||||
const p = parseInt(jcor);
|
||||
if (!isNaN(p) && p > 0) return { start: p, end: p };
|
||||
return { start: 1, end: 1 };
|
||||
}
|
||||
|
||||
// 课程图标
|
||||
function getCourseIcon(name) {
|
||||
const n = name || '';
|
||||
function has(...keys) { return keys.some(k => n.includes(k)); }
|
||||
const icons = {
|
||||
math: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="9" y1="9" x2="15" y2="9"/><line x1="12" y1="6" x2="12" y2="12"/><line x1="9" y1="15" x2="15" y2="15"/></svg>`,
|
||||
code: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>`,
|
||||
default: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/><path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/></svg>`
|
||||
};
|
||||
if (has('数学', '微积分', '线性代数', '概率', '统计学')) return icons.math;
|
||||
if (has('C语言', 'C++', 'Java', 'Python', '编程', '程序设计', '算法', '数据结构', '计算机', 'Web', '软件')) return icons.code;
|
||||
return icons.default;
|
||||
}
|
||||
|
||||
// 课程颜色
|
||||
const COURSE_COLORS = [
|
||||
{ bg: 'bg-blue-900/50', border: 'border-blue-700/70', text: 'text-blue-100' },
|
||||
{ bg: 'bg-emerald-900/50', border: 'border-emerald-700/70', text: 'text-emerald-100' },
|
||||
{ bg: 'bg-violet-900/50', border: 'border-violet-700/70', text: 'text-violet-100' },
|
||||
{ bg: 'bg-amber-900/50', border: 'border-amber-700/70', text: 'text-amber-100' },
|
||||
{ bg: 'bg-rose-900/50', border: 'border-rose-700/70', text: 'text-rose-100' },
|
||||
{ bg: 'bg-cyan-900/50', border: 'border-cyan-700/70', text: 'text-cyan-100' },
|
||||
{ bg: 'bg-lime-900/50', border: 'border-lime-700/70', text: 'text-lime-100' },
|
||||
{ bg: 'bg-fuchsia-900/50', border: 'border-fuchsia-700/70', text: 'text-fuchsia-100' },
|
||||
];
|
||||
const courseColorMap = new Map();
|
||||
function getCourseColor(name) {
|
||||
if (!courseColorMap.has(name)) {
|
||||
let h = 0; for (let i = 0; i < name.length; i++) h = name.charCodeAt(i) + ((h << 5) - h);
|
||||
courseColorMap.set(name, Math.abs(h) % COURSE_COLORS.length);
|
||||
}
|
||||
return COURSE_COLORS[courseColorMap.get(name)];
|
||||
}
|
||||
|
||||
// 节次时间
|
||||
const PERIOD_TIMES = {
|
||||
1: { start: '08:30', end: '09:15' }, 2: { start: '09:20', end: '10:05' },
|
||||
3: { start: '10:25', end: '11:10' }, 4: { start: '11:15', end: '12:00' },
|
||||
5: { start: '14:00', end: '14:45' }, 6: { start: '14:55', end: '15:40' },
|
||||
7: { start: '16:00', end: '16:45' }, 8: { start: '16:55', end: '17:40' },
|
||||
9: { start: '19:00', end: '19:45' }, 10: { start: '19:55', end: '20:40' },
|
||||
11: { start: '20:45', end: '21:30' },
|
||||
};
|
||||
|
||||
// 全局变量
|
||||
let teacherModalData = null; // 当前教师的 kbList
|
||||
let teacherModalWeek = 1; // 当前选择的周次
|
||||
let teacherModalWeekCount = 20; // 最大周次
|
||||
|
||||
// ─── 弹窗控制 ─────────────────────────────────────────────────────────
|
||||
|
||||
function openTeacherModal(jgh_id, jgh, xm, jgmc, zcmc) {
|
||||
const modal = document.getElementById('teacherModal');
|
||||
document.getElementById('modalTeacherName').textContent = xm || jgh;
|
||||
document.getElementById('modalTeacherInfo').textContent = [jgmc, zcmc].filter(Boolean).join(' · ') || jgh;
|
||||
document.getElementById('modalLoading').classList.remove('hidden');
|
||||
document.getElementById('modalError').classList.add('hidden');
|
||||
document.getElementById('modalContent').classList.add('hidden');
|
||||
document.getElementById('modalEmpty').classList.add('hidden');
|
||||
|
||||
// 当前页面的学年学期
|
||||
const xnm = document.getElementById('fXnm').value || '2026';
|
||||
const xqm = document.getElementById('fXqm').value || '3';
|
||||
|
||||
fetch(`/api/jwxt/teacher-schedule-detail?jgh_id=${encodeURIComponent(jgh_id)}&xnm=${xnm}&xqm=${xqm}`)
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
document.getElementById('modalLoading').classList.add('hidden');
|
||||
if (!data.success) {
|
||||
document.getElementById('modalErrorText').textContent = data.message || '加载失败';
|
||||
document.getElementById('modalError').classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
teacherModalData = data.kbList || [];
|
||||
|
||||
// 计算最大周次
|
||||
teacherModalWeekCount = 20;
|
||||
teacherModalData.forEach(item => {
|
||||
const w = parseWeekRange(item.zcd);
|
||||
if (w.end > 0 && w.end < 25) teacherModalWeekCount = Math.max(teacherModalWeekCount, w.end);
|
||||
});
|
||||
|
||||
// 填充周次选择
|
||||
const weekSelect = document.getElementById('modalWeekSelect');
|
||||
weekSelect.innerHTML = '';
|
||||
for (let i = 1; i <= teacherModalWeekCount; i++) {
|
||||
weekSelect.innerHTML += `<option value="${i}">第${i}周</option>`;
|
||||
}
|
||||
weekSelect.value = 1;
|
||||
teacherModalWeek = 1;
|
||||
|
||||
document.getElementById('modalCourseCount').textContent = `${teacherModalData.length}门课`;
|
||||
document.getElementById('modalContent').classList.remove('hidden');
|
||||
renderTeacherScheduleInModal();
|
||||
})
|
||||
.catch(err => {
|
||||
document.getElementById('modalLoading').classList.add('hidden');
|
||||
document.getElementById('modalErrorText').textContent = '网络错误: ' + err.message;
|
||||
document.getElementById('modalError').classList.remove('hidden');
|
||||
});
|
||||
|
||||
modal.classList.add('modal-open');
|
||||
document.documentElement.style.overflow = 'hidden';
|
||||
document.body.style.overflow = 'hidden';
|
||||
}
|
||||
|
||||
function closeTeacherModal() {
|
||||
const modal = document.getElementById('teacherModal');
|
||||
modal.classList.remove('modal-open');
|
||||
document.documentElement.style.overflow = '';
|
||||
document.body.style.overflow = '';
|
||||
teacherModalData = null;
|
||||
}
|
||||
|
||||
function renderTeacherScheduleInModal() {
|
||||
if (!teacherModalData) return;
|
||||
const week = parseInt(document.getElementById('modalWeekSelect').value);
|
||||
teacherModalWeek = week;
|
||||
|
||||
const grid = document.getElementById('teacherScheduleGrid');
|
||||
const emptyDiv = document.getElementById('modalEmpty');
|
||||
|
||||
// 表头
|
||||
let html = `
|
||||
<!-- 空角 -->
|
||||
<div class="bg-white/50 dark:bg-gray-900/50 rounded-lg flex items-center justify-center text-[10px] font-bold text-gray-500 dark:text-gray-400" style="grid-column:1;grid-row:1;"></div>
|
||||
<div class="bg-white/50 dark:bg-gray-900/50 rounded-lg text-center text-[10px] font-bold text-gray-600 dark:text-gray-300 flex items-center justify-center" style="grid-column:2;grid-row:1;">周一</div>
|
||||
<div class="bg-white/50 dark:bg-gray-900/50 rounded-lg text-center text-[10px] font-bold text-gray-600 dark:text-gray-300 flex items-center justify-center" style="grid-column:3;grid-row:1;">周二</div>
|
||||
<div class="bg-white/50 dark:bg-gray-900/50 rounded-lg text-center text-[10px] font-bold text-gray-600 dark:text-gray-300 flex items-center justify-center" style="grid-column:4;grid-row:1;">周三</div>
|
||||
<div class="bg-white/50 dark:bg-gray-900/50 rounded-lg text-center text-[10px] font-bold text-gray-600 dark:text-gray-300 flex items-center justify-center" style="grid-column:5;grid-row:1;">周四</div>
|
||||
<div class="bg-white/50 dark:bg-gray-900/50 rounded-lg text-center text-[10px] font-bold text-gray-600 dark:text-gray-300 flex items-center justify-center" style="grid-column:6;grid-row:1;">周五</div>
|
||||
<div class="bg-white/50 dark:bg-gray-900/50 rounded-lg text-center text-[10px] font-bold text-gray-600 dark:text-gray-300 flex items-center justify-center" style="grid-column:7;grid-row:1;">周六</div>
|
||||
<div class="bg-white/50 dark:bg-gray-900/50 rounded-lg text-center text-[10px] font-bold text-gray-600 dark:text-gray-300 flex items-center justify-center" style="grid-column:8;grid-row:1;">周日</div>
|
||||
`;
|
||||
|
||||
// 节次行
|
||||
for (let p = 1; p <= 11; p++) {
|
||||
const ti = PERIOD_TIMES[p] || { start: '', end: '' };
|
||||
html += `
|
||||
<div class="bg-white/30 dark:bg-gray-900/30 rounded-lg flex flex-col items-center justify-center text-[9px] text-gray-500 dark:text-gray-400" style="grid-column:1;grid-row:${p+1};">
|
||||
<div class="font-bold text-gray-700 dark:text-gray-300">${p}</div>
|
||||
<div>${ti.start}</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// 课程格子占位(7列)
|
||||
for (let d = 0; d < 7; d++) {
|
||||
for (let p = 1; p <= 11; p++) {
|
||||
html += `<div class="bg-gray-50/20 dark:bg-gray-800/10 rounded border border-gray-200/30 dark:border-gray-700/20" style="grid-column:${d+2};grid-row:${p+1};"></div>`;
|
||||
}
|
||||
}
|
||||
|
||||
grid.innerHTML = html;
|
||||
|
||||
// 渲染课程
|
||||
const courseGrid = Array(11).fill(null).map(() => Array(7).fill(null));
|
||||
let courseCount = 0;
|
||||
|
||||
teacherModalData.forEach(item => {
|
||||
if (!isCourseInWeek(item, week)) return;
|
||||
const dayIndex = item.xqj - 1;
|
||||
if (isNaN(dayIndex) || dayIndex < 0 || dayIndex > 6) return;
|
||||
const pr = parsePeriodRange(item.skjc);
|
||||
for (let p = pr.start; p <= pr.end; p++) {
|
||||
if (p >= 1 && p <= 11) {
|
||||
const pi = p - 1;
|
||||
if (!courseGrid[pi][dayIndex]) {
|
||||
courseGrid[pi][dayIndex] = { item, isStart: p === pr.start, rowSpan: pr.end - pr.start + 1 };
|
||||
}
|
||||
}
|
||||
}
|
||||
courseCount++;
|
||||
});
|
||||
|
||||
// 写入课程
|
||||
courseGrid.forEach((row, pi) => {
|
||||
row.forEach((cell, di) => {
|
||||
if (cell && cell.isStart) {
|
||||
const color = getCourseColor(cell.item.kcmc);
|
||||
const delay = Math.min(di * 40 + pi * 15, 300);
|
||||
const cls = `course-cell rounded-lg overflow-hidden ${color.bg} ${color.text} border-l-4 ${color.border} flex flex-col justify-center p-1`;
|
||||
const rowStyle = `grid-column:${di+2};grid-row:${pi+2}/span ${cell.rowSpan};animation-delay:${delay}ms;`;
|
||||
const parts = [cell.item.kcmc, cell.item.cdmc || '无地点', cell.item.zcd || ''];
|
||||
if (cell.item.jxbzcbjjc) parts.push('班级: ' + cell.item.jxbzcbjjc);
|
||||
if (cell.item.jxbrs) parts.push('人数: ' + cell.item.jxbrs);
|
||||
if (cell.item.khfsmc) parts.push(cell.item.khfsmc);
|
||||
const title = parts.join('\n');
|
||||
grid.innerHTML += `<div class="${cls}" style="${rowStyle}" title="${title.replace(/\n/g,' ')}">
|
||||
<div class="font-bold text-[10px] leading-tight mb-0.5">${cell.item.kcmc}</div>
|
||||
<div class="text-[9px] opacity-80">${cell.item.cdmc || ''}</div>
|
||||
<div class="text-[9px] opacity-60">${cell.item.skjc}</div>
|
||||
</div>`;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
emptyDiv.classList.toggle('hidden', courseCount > 0);
|
||||
renderListView(week);
|
||||
}
|
||||
|
||||
// ─── 视图切换 ─────────────────────────────────────────────────────
|
||||
|
||||
let currentView = 'grid';
|
||||
|
||||
function switchView(view) {
|
||||
currentView = view;
|
||||
const grid = document.getElementById('gridView');
|
||||
const list = document.getElementById('listView');
|
||||
const gridBtn = document.getElementById('viewGridBtn');
|
||||
const listBtn = document.getElementById('viewListBtn');
|
||||
if (view === 'grid') {
|
||||
grid.classList.remove('hidden');
|
||||
list.classList.add('hidden');
|
||||
gridBtn.className = 'px-3 py-1 rounded-md text-xs font-medium bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm transition-all';
|
||||
listBtn.className = 'px-3 py-1 rounded-md text-xs font-medium text-gray-500 dark:text-gray-400 transition-all';
|
||||
} else {
|
||||
grid.classList.add('hidden');
|
||||
list.classList.remove('hidden');
|
||||
listBtn.className = 'px-3 py-1 rounded-md text-xs font-medium bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm transition-all';
|
||||
gridBtn.className = 'px-3 py-1 rounded-md text-xs font-medium text-gray-500 dark:text-gray-400 transition-all';
|
||||
}
|
||||
}
|
||||
|
||||
function renderListView(week) {
|
||||
const tbody = document.getElementById('listTableBody');
|
||||
if (!tbody) return;
|
||||
const weekItems = teacherModalData.filter(item => isCourseInWeek(item, week));
|
||||
const dayNames = ['', '周一', '周二', '周三', '周四', '周五', '周六', '周日'];
|
||||
if (weekItems.length === 0) {
|
||||
tbody.innerHTML = '<tr><td colspan="8" class="py-4 text-center text-gray-400 dark:text-gray-500">该周次暂无课程</td></tr>';
|
||||
return;
|
||||
}
|
||||
tbody.innerHTML = weekItems.map((item, idx) => {
|
||||
const color = getCourseColor(item.kcmc);
|
||||
return `<tr class="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50/50 dark:hover:bg-gray-800/30">
|
||||
<td class="py-2 px-2 text-gray-600 dark:text-gray-300">${dayNames[item.xqj] || '--'}</td>
|
||||
<td class="py-2 px-2 text-gray-500 dark:text-gray-400">${item.skjc || '--'}</td>
|
||||
<td class="py-2 px-2 font-medium text-gray-900 dark:text-white">${escHtml(item.kcmc || '--')}${item.xslxbj ? ' <span class="text-amber-500">' + escHtml(item.xslxbj) + '</span>' : ''}</td>
|
||||
<td class="py-2 px-2 text-gray-500 dark:text-gray-400">${escHtml(item.jxbzcbjjc || '--')}</td>
|
||||
<td class="py-2 px-2 text-gray-500 dark:text-gray-400 text-center">${item.jxbrs || '--'}</td>
|
||||
<td class="py-2 px-2 text-gray-500 dark:text-gray-400">${escHtml(item.cdmc || '--')}</td>
|
||||
<td class="py-2 px-2 text-gray-500 dark:text-gray-400 whitespace-nowrap">${item.zcd || '--'}</td>
|
||||
<td class="py-2 px-2 text-gray-500 dark:text-gray-400">${item.khfsmc || '--'}</td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
// ─── ECharts 图表 ─────────────────────────────────────────────────
|
||||
let titleChart = null;
|
||||
let deptChart = null;
|
||||
|
||||
function renderTitleChart(items) {
|
||||
const dom = document.getElementById('titleChart');
|
||||
if (!dom) return;
|
||||
|
||||
const titleMap = {};
|
||||
items.forEach(item => { const t = item.zcmc || '未评级'; titleMap[t] = (titleMap[t] || 0) + 1; });
|
||||
const data = Object.entries(titleMap).map(([name, value]) => ({ name, value }));
|
||||
|
||||
const dark = isDarkMode();
|
||||
if (!titleChart) titleChart = echarts.init(dom);
|
||||
titleChart.setOption({
|
||||
tooltip: { trigger: 'item', formatter: '{b}: {c} 人 ({d}%)' },
|
||||
legend: { bottom: 0, textStyle: { color: dark ? '#9ca3af' : '#6b7280', fontSize: 11 } },
|
||||
series: [{
|
||||
type: 'pie', radius: ['45%', '72%'], center: ['50%', '48%'],
|
||||
itemStyle: { borderRadius: 6, borderColor: dark ? '#1f2937' : '#fff', borderWidth: 2 },
|
||||
label: { color: dark ? '#d1d5db' : '#374151', fontSize: 11 },
|
||||
data: data
|
||||
}]
|
||||
}, { notMerge: true });
|
||||
titleChart.resize();
|
||||
}
|
||||
|
||||
function renderDeptChart(items) {
|
||||
const dom = document.getElementById('deptChart');
|
||||
if (!dom) return;
|
||||
|
||||
const deptMap = {};
|
||||
items.forEach(item => { const d = item.jgmc || '未知'; deptMap[d] = (deptMap[d] || 0) + 1; });
|
||||
const sorted = Object.entries(deptMap).sort((a, b) => b[1] - a[1]);
|
||||
|
||||
const dark = isDarkMode();
|
||||
if (!deptChart) deptChart = echarts.init(dom);
|
||||
deptChart.setOption({
|
||||
tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
|
||||
grid: { left: '3%', right: '10%', top: 10, bottom: 30, containLabel: true },
|
||||
xAxis: {
|
||||
type: 'value', name: '教师数',
|
||||
nameTextStyle: { color: dark ? '#9ca3af' : '#6b7280' },
|
||||
axisLabel: { color: dark ? '#9ca3af' : '#6b7280' }
|
||||
},
|
||||
yAxis: {
|
||||
type: 'category', data: sorted.map(s => s[0]),
|
||||
axisLabel: { color: dark ? '#9ca3af' : '#6b7280', fontSize: 10 },
|
||||
inverse: true
|
||||
},
|
||||
series: [{
|
||||
type: 'bar', data: sorted.map(s => s[1]),
|
||||
itemStyle: { color: dark ? '#818cf8' : '#4f46e5', borderRadius: [0, 6, 6, 0] },
|
||||
emphasis: { itemStyle: { color: dark ? '#a5b4fc' : '#6366f1' } }
|
||||
}]
|
||||
}, { notMerge: true });
|
||||
deptChart.resize();
|
||||
}
|
||||
|
||||
function setupDarkObserver() {
|
||||
const observer = new MutationObserver(() => {
|
||||
if (titleChart) { titleChart.dispose(); titleChart = null; }
|
||||
if (deptChart) { deptChart.dispose(); deptChart = null; }
|
||||
const items = window._lastTeacherItems;
|
||||
if (items && items.length) {
|
||||
renderCharts(items);
|
||||
}
|
||||
});
|
||||
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
|
||||
}
|
||||
|
||||
function renderCharts(items) {
|
||||
const row = document.getElementById('chartsRow');
|
||||
if (row) row.classList.remove('hidden');
|
||||
renderTitleChart(items);
|
||||
renderDeptChart(items);
|
||||
}
|
||||
|
||||
window.addEventListener('resize', () => {
|
||||
if (titleChart) titleChart.resize();
|
||||
if (deptChart) deptChart.resize();
|
||||
});
|
||||
|
||||
// ─── 列表渲染 ─────────────────────────────────────────────────────────
|
||||
|
||||
async function refresh() {
|
||||
document.getElementById('loadingIndicator').classList.remove('hidden');
|
||||
document.getElementById('errorMessage').classList.add('hidden');
|
||||
document.getElementById('dataContainer').classList.add('hidden');
|
||||
document.getElementById('chartsRow').classList.add('hidden');
|
||||
|
||||
const xnm = document.getElementById('fXnm').value;
|
||||
const xqm = document.getElementById('fXqm').value;
|
||||
const xqh_id = document.getElementById('fXqh').value;
|
||||
const zcm = document.getElementById('fZcm').value;
|
||||
const jg_id = document.getElementById('fJg').value;
|
||||
const kkbm_id = document.getElementById('fKkbm').value;
|
||||
const jgh = document.getElementById('fJgh').value;
|
||||
const zxszjjs = document.getElementById('fZxszjjs').checked ? '1' : '0';
|
||||
const sfwp = document.getElementById('fSfwp').checked ? '1' : '0';
|
||||
|
||||
const params = new URLSearchParams({ page_size: 1000 });
|
||||
if (xnm) params.set('xnm', xnm);
|
||||
if (xqm) params.set('xqm', xqm);
|
||||
if (xqh_id) params.set('xqh_id', xqh_id);
|
||||
if (zcm) params.set('zcm', zcm);
|
||||
if (jg_id) params.set('jg_id', jg_id);
|
||||
if (kkbm_id) params.set('kkbm_id', kkbm_id);
|
||||
if (jgh) params.set('jgh', jgh);
|
||||
if (zxszjjs === '1') params.set('zxszjjs', '1');
|
||||
if (sfwp === '1') params.set('sfwp', '1');
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/teacher-schedule?' + params.toString());
|
||||
const data = await res.json();
|
||||
document.getElementById('loadingIndicator').classList.add('hidden');
|
||||
|
||||
if (!data.success) {
|
||||
document.getElementById('errorText').textContent = data.message || '查询失败';
|
||||
document.getElementById('errorMessage').classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
|
||||
const items = data.items || [];
|
||||
window._lastTeacherItems = items;
|
||||
document.getElementById('totalCount').textContent = data.total || items.length;
|
||||
if (!items.length) {
|
||||
document.getElementById('dataContainer').classList.remove('hidden');
|
||||
document.getElementById('emptyState').classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
renderTable(items);
|
||||
document.getElementById('dataContainer').classList.remove('hidden');
|
||||
renderCharts(items);
|
||||
} catch (e) {
|
||||
document.getElementById('loadingIndicator').classList.add('hidden');
|
||||
document.getElementById('errorText').textContent = '网络错误: ' + e.message;
|
||||
document.getElementById('errorMessage').classList.remove('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
function renderTable(items) {
|
||||
const tbody = document.getElementById('tableBody');
|
||||
tbody.innerHTML = items.map((item, idx) => {
|
||||
const campus = item.xqh_id === '1' ? '长清校区' : (item.xqh_id || '--');
|
||||
return `<tr class="clickable-row border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50/50 dark:hover:bg-gray-800/30 transition-colors row-animate" style="animation-delay:${idx * 30}ms;"
|
||||
onclick="openTeacherModal(${JSON.stringify(item.jgh_id||'').replace(/"/g,'"')}, ${JSON.stringify(item.jgh||'').replace(/"/g,'"')}, ${JSON.stringify(item.xm||'').replace(/"/g,'"')}, ${JSON.stringify(item.jgmc||'').replace(/"/g,'"')}, ${JSON.stringify(item.zcmc||'').replace(/"/g,'"')})">
|
||||
<td class="py-3 px-4 text-gray-400 dark:text-gray-500">${idx + 1}</td>
|
||||
<td class="py-3 px-4 font-mono text-xs text-gray-500 dark:text-gray-400">${item.jgh || '--'}</td>
|
||||
<td class="py-3 px-4 font-medium">${escHtml(item.xm || '--')}</td>
|
||||
<td class="py-3 px-4 text-gray-500 dark:text-gray-400">${item.zcmc || '--'}</td>
|
||||
<td class="py-3 px-4 text-gray-500 dark:text-gray-400">${escHtml(item.jgmc || '--')}</td>
|
||||
<td class="py-3 px-4 text-gray-500 dark:text-gray-400">${campus}</td>
|
||||
<td class="py-3 px-4 text-center text-gray-500 dark:text-gray-400 text-xs">${item.sjhm || '--'}</td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function escHtml(str) {
|
||||
return String(str).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
|
||||
}
|
||||
|
||||
// ─── 初始化 ────────────────────────────────────────────────────────────
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
// 将弹窗移到 body 直接子级
|
||||
const modal = document.getElementById('teacherModal');
|
||||
if (modal) document.body.appendChild(modal);
|
||||
|
||||
setupDarkObserver();
|
||||
initSession().then(() => refresh());
|
||||
|
||||
// ESC 关闭弹窗
|
||||
document.addEventListener('keydown', function (e) {
|
||||
if (e.key === 'Escape') closeTeacherModal();
|
||||
});
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,74 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
{% block title %}教学项目报名 - {{ brand_name }}{% endblock %}
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
@keyframes fadeSlideIn {
|
||||
from { opacity: 0; transform: translateY(8px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.row-animate { animation: fadeSlideIn 0.3s ease both; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.row-animate { animation: none !important; opacity: 1 !important; }
|
||||
.list-item-enter { animation: none !important; opacity: 1 !important; }
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 list-item-enter">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/></svg>
|
||||
教学项目报名
|
||||
</h2>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">各类教学项目报名</p>
|
||||
</div>
|
||||
<button onclick="loadData()" class="px-4 py-2 rounded-lg border"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>刷新</button>
|
||||
</div>
|
||||
<div id="loadingIndicator" class="text-center py-12 hidden"><div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div><p class="text-gray-500 dark:text-gray-400">加载中...</p></div>
|
||||
<div id="errorMessage" class="glass rounded-2xl p-6 mb-4 text-center hidden"><p id="errorText" class="text-red-500"></p></div>
|
||||
<div id="dataContainer" class="hidden">
|
||||
<div class="glass rounded-2xl overflow-hidden">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead><tr class="border-b border-gray-200 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-800/50"><th class="text-left py-3 px-4 font-semibold">项目名称</th><th class="text-left py-3 px-4 font-semibold">项目类别</th><th class="text-left py-3 px-4 font-semibold">报名时间</th><th class="text-left py-3 px-4 font-semibold">状态</th></tr></thead>
|
||||
<tbody id="tableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="emptyState" class="glass rounded-2xl p-12 text-center hidden"><p class="text-gray-500 dark:text-gray-400 text-lg">暂无教学项目</p></div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block extra_js %}
|
||||
<script>
|
||||
async function loadData() {
|
||||
document.getElementById('loadingIndicator').classList.remove('hidden');
|
||||
document.getElementById('errorMessage').classList.add('hidden');
|
||||
document.getElementById('dataContainer').classList.add('hidden');
|
||||
document.getElementById('emptyState').classList.add('hidden');
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/teaching-project');
|
||||
const data = await res.json();
|
||||
document.getElementById('loadingIndicator').classList.add('hidden');
|
||||
if (!data.success) { showError(data.message); return; }
|
||||
const items = data.items || [];
|
||||
if (!items.length) { document.getElementById('emptyState').classList.remove('hidden'); return; }
|
||||
const tbody = document.getElementById('tableBody');
|
||||
tbody.innerHTML = items.map((item, i) => {
|
||||
return `<tr class="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50/50 dark:hover:bg-gray-800/30 transition-colors">
|
||||
<td class="py-3 px-4">${escHtml(item.xmmc||item.项目名称||'--')}</td>
|
||||
<td class="py-3 px-4 text-gray-500">${escHtml(item.xmlb||item.项目类别||'--')}</td>
|
||||
<td class="py-3 px-4 text-gray-500">${escHtml(item.bmsj||item.报名时间||'--')}</td>
|
||||
<td class="py-3 px-4">${escHtml(item.zt||item.状态||'--')}</td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
document.getElementById('dataContainer').classList.remove('hidden');
|
||||
} catch(e) { document.getElementById('loadingIndicator').classList.add('hidden'); showError('网络错误: '+e.message); }
|
||||
}
|
||||
function showError(msg) { document.getElementById('errorText').textContent = msg; document.getElementById('errorMessage').classList.remove('hidden'); }
|
||||
function escHtml(s) { if(s==null) return ''; return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"'); }
|
||||
document.addEventListener('DOMContentLoaded', () => loadData());
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,68 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
|
||||
{% block title %}用户服务协议 - {{ brand_name }}{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
.prose h1 { font-size: 1.5rem; font-weight: 800; margin-bottom: 0.5rem; }
|
||||
.prose h2 { font-size: 1.1rem; font-weight: 700; margin-top: 2rem; margin-bottom: 0.75rem; padding-bottom: 0.4rem; border-bottom: 1px solid rgba(0,0,0,0.08); }
|
||||
.dark .prose h2 { border-bottom-color: rgba(255,255,255,0.08); }
|
||||
.prose h3 { font-size: 0.95rem; font-weight: 600; margin-top: 1.25rem; margin-bottom: 0.5rem; }
|
||||
.prose p { margin-bottom: 0.75rem; line-height: 1.75; color: #4b5563; }
|
||||
.dark .prose p { color: #9ca3af; }
|
||||
.prose ul, .prose ol { padding-left: 1.5rem; margin-bottom: 0.75rem; }
|
||||
.prose li { margin-bottom: 0.35rem; line-height: 1.7; color: #4b5563; }
|
||||
.dark .prose li { color: #9ca3af; }
|
||||
.prose ul li { list-style-type: disc; }
|
||||
.prose ol li { list-style-type: decimal; }
|
||||
.prose strong { font-weight: 600; color: #111827; }
|
||||
.dark .prose strong { color: #f3f4f6; }
|
||||
.prose table { width: 100%; border-collapse: collapse; margin: 1rem 0; font-size: 0.875rem; }
|
||||
.prose th { background: #f3f4f6; font-weight: 600; padding: 0.6rem 0.8rem; text-align: left; border: 1px solid #e5e7eb; }
|
||||
.dark .prose th { background: #1f2937; border-color: #374151; }
|
||||
.prose td { padding: 0.6rem 0.8rem; border: 1px solid #e5e7eb; }
|
||||
.dark .prose td { border-color: #374151; }
|
||||
.prose hr { border: none; border-top: 1px solid #e5e7eb; margin: 1.5rem 0; }
|
||||
.dark .prose hr { border-top-color: #374151; }
|
||||
.prose code { background: #f3f4f6; padding: 0.1em 0.4em; border-radius: 4px; font-size: 0.85em; }
|
||||
.dark .prose code { background: #1f2937; }
|
||||
.prose blockquote { border-left: 3px solid #e5e7eb; padding-left: 1rem; color: #6b7280; margin: 1rem 0; }
|
||||
.dark .prose blockquote { border-color: #374151; color: #9ca3af; }
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="max-w-3xl mx-auto py-4">
|
||||
<!-- 返回 -->
|
||||
<div class="mb-6 list-item-enter" style="animation-delay:0ms">
|
||||
<a href="javascript:history.back()" class="inline-flex items-center gap-1.5 text-sm text-neutral-500 hover:text-neutral-800 dark:hover:text-neutral-200 transition-colors">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"/>
|
||||
</svg>
|
||||
返回
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div class="glass rounded-3xl p-6 md:p-10 layer-3 list-item-enter" style="animation-delay:50ms">
|
||||
<!-- 头部 -->
|
||||
<div class="flex items-start gap-4 mb-8 pb-6 border-b border-neutral-200 dark:border-neutral-800">
|
||||
<div class="w-12 h-12 rounded-2xl bg-black dark:bg-white flex items-center justify-center text-white dark:text-black font-bold text-lg flex-shrink-0">S</div>
|
||||
<div>
|
||||
<h1 class="text-xl md:text-2xl font-bold text-neutral-900 dark:text-white">用户服务协议</h1>
|
||||
<p class="text-sm text-neutral-500 dark:text-neutral-400 mt-1">{{ brand_name }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 正文:由后端读取 docs/terms.md 渲染 -->
|
||||
<div class="prose text-sm md:text-base text-neutral-800 dark:text-neutral-200">
|
||||
{{ content | safe }}
|
||||
</div>
|
||||
|
||||
<!-- 底部链接 -->
|
||||
<div class="mt-8 pt-6 border-t border-neutral-200 dark:border-neutral-800 flex gap-4 text-sm text-neutral-500">
|
||||
<a href="{{ url_for('main.privacy') }}" class="hover:text-black dark:hover:text-white transition-colors underline underline-offset-2">隐私政策</a>
|
||||
<a href="{{ url_for('main.buy') }}" class="hover:text-black dark:hover:text-white transition-colors underline underline-offset-2">购买页面</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,287 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
|
||||
{% block title %}教材明细查询 - {{ brand_name }}{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
@keyframes fadeSlideIn {
|
||||
from { opacity: 0; transform: translateY(8px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.row-animate { animation: fadeSlideIn 0.3s ease both; }
|
||||
.tab-active { border-bottom: 2px solid currentColor; font-weight: 600; }
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 list-item-enter" style="animation-delay: 0ms;">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/>
|
||||
<path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/>
|
||||
</svg>
|
||||
教材明细查询
|
||||
</h2>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">查看课程使用教材明细</p>
|
||||
</div>
|
||||
<button onclick="refresh()"
|
||||
class="px-4 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm font-medium hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<polyline points="23 4 23 10 17 10"/>
|
||||
<path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>
|
||||
</svg>
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2 mb-4 flex-wrap" id="tabBar">
|
||||
<span class="text-sm text-gray-500 dark:text-gray-400 self-center mr-2">学年:</span>
|
||||
<select id="filterXnm" onchange="refresh()" class="px-3 py-1.5 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm">
|
||||
<option value="">全部</option>
|
||||
<option value="2025" selected>2025-2026</option>
|
||||
<option value="2024">2024-2025</option>
|
||||
<option value="2023">2023-2024</option>
|
||||
</select>
|
||||
<select id="filterXqm" onchange="refresh()" class="px-3 py-1.5 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm">
|
||||
<option value="">全部</option>
|
||||
<option value="3">第1学期</option>
|
||||
<option value="12">第2学期</option>
|
||||
</select>
|
||||
<select id="filterXyzt" onchange="refresh()" class="px-3 py-1.5 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm">
|
||||
<option value="">全部</option>
|
||||
<option value="1">已选</option>
|
||||
<option value="0">未选</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div id="loadingIndicator" class="text-center py-12 list-item-enter" style="animation-delay: 100ms;">
|
||||
<div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
|
||||
<p class="text-gray-500 dark:text-gray-400">正在查询教材明细...</p>
|
||||
</div>
|
||||
|
||||
<div id="errorMessage" class="glass rounded-2xl p-6 mb-4 text-center hidden">
|
||||
<p id="errorText" class="text-red-500"></p>
|
||||
</div>
|
||||
|
||||
<!-- ECharts 图表(独立于 dataContainer,避免在 display:none 中初始化) -->
|
||||
<div id="chartsRow" class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4 hidden list-item-enter" style="animation-delay: 150ms;">
|
||||
<div class="glass rounded-2xl p-4">
|
||||
<h3 class="text-sm font-semibold mb-2 text-gray-700 dark:text-gray-300">出版社分布</h3>
|
||||
<div id="publisherChart" style="height:300px;"></div>
|
||||
</div>
|
||||
<div class="glass rounded-2xl p-4">
|
||||
<h3 class="text-sm font-semibold mb-2 text-gray-700 dark:text-gray-300">选用状态分布</h3>
|
||||
<div id="xkStatusChart" style="height:300px;"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="dataContainer" class="hidden list-item-enter" style="animation-delay: 200ms;">
|
||||
<div class="glass rounded-2xl overflow-hidden">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead>
|
||||
<tr class="border-b border-gray-200 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-800/50">
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">#</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">课程名称</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">教材名称</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">ISBN</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">出版社</th>
|
||||
<th class="text-left py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">作者</th>
|
||||
<th class="text-center py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">定价</th>
|
||||
<th class="text-center py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">选用状态</th>
|
||||
<th class="text-center py-3 px-4 font-semibold text-gray-700 dark:text-gray-300">预订状态</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="tableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<div id="emptyState" class="glass rounded-2xl p-12 text-center hidden">
|
||||
<p class="text-gray-500 dark:text-gray-400 text-lg">暂无教材明细</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script src="{{ url_for('static', filename='echarts.min.js') }}"></script>
|
||||
<script>
|
||||
let publisherChart = null;
|
||||
let xkStatusChart = null;
|
||||
|
||||
function isDarkMode() { return document.documentElement.classList.contains('dark'); }
|
||||
|
||||
async function initSession() {
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/ping');
|
||||
const data = await res.json();
|
||||
if (!data.success) { console.warn('Session ping 失败:', data.message); return false; }
|
||||
if (data.refreshed) console.log('🔄 Session 已自动刷新');
|
||||
return true;
|
||||
} catch (e) { console.error('Session ping 异常:', e); return false; }
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
document.getElementById('loadingIndicator').classList.remove('hidden');
|
||||
document.getElementById('errorMessage').classList.add('hidden');
|
||||
document.getElementById('dataContainer').classList.add('hidden');
|
||||
document.getElementById('chartsRow').classList.add('hidden');
|
||||
|
||||
await initSession();
|
||||
|
||||
const xnm = document.getElementById('filterXnm').value;
|
||||
const xqm = document.getElementById('filterXqm').value;
|
||||
const xyzt = document.getElementById('filterXyzt').value;
|
||||
|
||||
const params = new URLSearchParams({ page_size: 200 });
|
||||
if (xnm) params.set('xnm', xnm);
|
||||
if (xqm) params.set('xqm', xqm);
|
||||
if (xyzt) params.set('xyzt', xyzt);
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/textbook-details?' + params.toString());
|
||||
const data = await res.json();
|
||||
document.getElementById('loadingIndicator').classList.add('hidden');
|
||||
|
||||
if (!data.success) {
|
||||
document.getElementById('errorText').textContent = data.message || '查询失败';
|
||||
document.getElementById('errorMessage').classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
|
||||
const items = data.items || [];
|
||||
if (!items.length) {
|
||||
document.getElementById('dataContainer').classList.remove('hidden');
|
||||
document.getElementById('emptyState').classList.remove('hidden');
|
||||
document.getElementById('chartsRow').classList.add('hidden');
|
||||
return;
|
||||
}
|
||||
renderTable(items);
|
||||
document.getElementById('dataContainer').classList.remove('hidden');
|
||||
document.getElementById('chartsRow').classList.remove('hidden');
|
||||
renderCharts(items);
|
||||
setupDarkObserver();
|
||||
} catch (e) {
|
||||
document.getElementById('loadingIndicator').classList.add('hidden');
|
||||
document.getElementById('errorText').textContent = '网络错误: ' + e.message;
|
||||
document.getElementById('errorMessage').classList.remove('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
function renderTable(items) {
|
||||
const tbody = document.getElementById('tableBody');
|
||||
tbody.innerHTML = items.map((item, idx) => {
|
||||
const price = item.price || item.price_sort || '--';
|
||||
const zkprice = item.zkprice || '--';
|
||||
const statusColor = item.xkzt === '已选课'
|
||||
? 'text-green-600 dark:text-green-400'
|
||||
: 'text-orange-500 dark:text-orange-400';
|
||||
return `<tr class="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50/50 dark:hover:bg-gray-800/30 transition-colors row-animate" style="animation-delay:${idx * 40}ms;">
|
||||
<td class="py-3 px-4 text-gray-400 dark:text-gray-500">${idx + 1}</td>
|
||||
<td class="py-3 px-4 font-medium">${escHtml(item.kcmc || '--')}</td>
|
||||
<td class="py-3 px-4 max-w-[200px] truncate" title="${escHtml(item.jcmc || '')}">${escHtml(item.jcmc || '--')}</td>
|
||||
<td class="py-3 px-4 text-gray-500 dark:text-gray-400 font-mono text-xs">${item.isbn || '--'}</td>
|
||||
<td class="py-3 px-4 text-gray-500 dark:text-gray-400">${escHtml(item.cbs || '--')}</td>
|
||||
<td class="py-3 px-4 text-gray-500 dark:text-gray-400">${escHtml(item.jczz || '--')}</td>
|
||||
<td class="py-3 px-4 text-center">${price}${zkprice && zkprice !== price ? `<span class="text-xs text-orange-400 ml-1">(${zkprice})</span>` : ''}</td>
|
||||
<td class="py-3 px-4 text-center ${statusColor} font-medium">${item.xkzt || '--'}</td>
|
||||
<td class="py-3 px-4 text-center text-gray-500 dark:text-gray-400">${item.ydzt || '--'}</td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function escHtml(str) {
|
||||
return String(str).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
|
||||
}
|
||||
|
||||
// ── ECharts 图表渲染 ──
|
||||
let _lastTextbookItems = [];
|
||||
|
||||
function renderCharts(items) {
|
||||
_lastTextbookItems = items;
|
||||
renderPublisherChart(items);
|
||||
renderXkStatusChart(items);
|
||||
}
|
||||
|
||||
function renderPublisherChart(items) {
|
||||
const dom = document.getElementById('publisherChart');
|
||||
if (!dom) return;
|
||||
if (publisherChart) publisherChart.dispose();
|
||||
|
||||
const counts = {};
|
||||
items.forEach(it => {
|
||||
const k = it.cbs || '未知';
|
||||
counts[k] = (counts[k] || 0) + 1;
|
||||
});
|
||||
const sorted = Object.entries(counts).sort((a, b) => b[1] - a[1]);
|
||||
// 取前10,其余归为"其他"
|
||||
let data;
|
||||
if (sorted.length > 10) {
|
||||
const top10 = sorted.slice(0, 10);
|
||||
const otherCount = sorted.slice(10).reduce((s, e) => s + e[1], 0);
|
||||
data = [...top10.map(([n, v]) => ({ name: n, value: v })), { name: '其他', value: otherCount }];
|
||||
} else {
|
||||
data = sorted.map(([name, value]) => ({ name, value }));
|
||||
}
|
||||
|
||||
publisherChart = echarts.init(dom);
|
||||
publisherChart.setOption({
|
||||
tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
|
||||
legend: { type: 'scroll', bottom: 0, textStyle: { fontSize: 10, color: isDarkMode() ? '#9ca3af' : '#6b7280' } },
|
||||
series: [{
|
||||
type: 'pie', radius: ['35%', '65%'], center: ['50%', '45%'],
|
||||
data: data,
|
||||
label: { formatter: '{b}\n{d}%', fontSize: 10 },
|
||||
itemStyle: { borderColor: isDarkMode() ? '#1f2937' : '#fff', borderWidth: 2 }
|
||||
}]
|
||||
});
|
||||
}
|
||||
|
||||
function renderXkStatusChart(items) {
|
||||
const dom = document.getElementById('xkStatusChart');
|
||||
if (!dom) return;
|
||||
if (xkStatusChart) xkStatusChart.dispose();
|
||||
|
||||
const counts = {};
|
||||
items.forEach(it => {
|
||||
const k = it.xkzt || '未知';
|
||||
counts[k] = (counts[k] || 0) + 1;
|
||||
});
|
||||
const data = Object.entries(counts).map(([name, value]) => ({ name, value }));
|
||||
|
||||
xkStatusChart = echarts.init(dom);
|
||||
xkStatusChart.setOption({
|
||||
tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
|
||||
legend: { bottom: 0, textStyle: { fontSize: 11, color: isDarkMode() ? '#9ca3af' : '#6b7280' } },
|
||||
series: [{
|
||||
type: 'pie', radius: ['45%', '70%'], center: ['50%', '45%'],
|
||||
data: data,
|
||||
label: { formatter: '{b}\n{d}%', fontSize: 11 },
|
||||
itemStyle: { borderColor: isDarkMode() ? '#1f2937' : '#fff', borderWidth: 2 }
|
||||
}]
|
||||
});
|
||||
}
|
||||
|
||||
// ── 深色模式观察 ──
|
||||
let _darkObserverTextbook = null;
|
||||
function setupDarkObserver() {
|
||||
if (_darkObserverTextbook) _darkObserverTextbook.disconnect();
|
||||
_darkObserverTextbook = new MutationObserver(() => {
|
||||
if (publisherChart) { publisherChart.dispose(); publisherChart = null; }
|
||||
if (xkStatusChart) { xkStatusChart.dispose(); xkStatusChart = null; }
|
||||
if (_lastTextbookItems.length) renderCharts(_lastTextbookItems);
|
||||
});
|
||||
_darkObserverTextbook.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
|
||||
}
|
||||
window.addEventListener('resize', () => {
|
||||
if (publisherChart) publisherChart.resize();
|
||||
if (xkStatusChart) xkStatusChart.resize();
|
||||
});
|
||||
|
||||
refresh();
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,485 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
|
||||
{% block title %}教材预订 - {{ brand_name }}{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
@keyframes fadeSlideIn {
|
||||
from { opacity: 0; transform: translateY(8px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.row-animate {
|
||||
animation: fadeSlideIn 0.3s ease both;
|
||||
}
|
||||
|
||||
.tb-card {
|
||||
transition: all 0.25s ease;
|
||||
}
|
||||
.tb-card:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 8px 25px rgba(0,0,0,0.08);
|
||||
}
|
||||
.dark .tb-card:hover {
|
||||
box-shadow: 0 8px 25px rgba(0,0,0,0.4);
|
||||
}
|
||||
|
||||
.status-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
padding: 0.125rem 0.75rem;
|
||||
border-radius: 9999px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
.status-ordered {
|
||||
background: #d1fae5;
|
||||
color: #065f46;
|
||||
}
|
||||
.status-unordered {
|
||||
background: #fee2e2;
|
||||
color: #991b1b;
|
||||
}
|
||||
.dark .status-ordered {
|
||||
background: #064e3b;
|
||||
color: #6ee7b7;
|
||||
}
|
||||
.dark .status-unordered {
|
||||
background: #7f1d1d;
|
||||
color: #fca5a5;
|
||||
}
|
||||
|
||||
.toast-notification {
|
||||
position: fixed; top: 20px; right: 20px; z-index: 9999;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
<!-- 页面标题 -->
|
||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 list-item-enter" style="animation-delay: 0ms;">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/>
|
||||
<path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/>
|
||||
<path d="M8 7h8"/>
|
||||
<path d="M8 11h6"/>
|
||||
</svg>
|
||||
教材预订
|
||||
</h2>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">管理已选课程的教材预订与退订</p>
|
||||
</div>
|
||||
<button onclick="refresh()"
|
||||
class="px-4 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm font-medium hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors flex items-center gap-2 flex-shrink-0">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<polyline points="23 4 23 10 17 10"/>
|
||||
<path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>
|
||||
</svg>
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Toast 通知 -->
|
||||
<div id="toast" class="toast-notification hidden"></div>
|
||||
|
||||
<!-- 筛选栏 -->
|
||||
<div class="flex flex-wrap gap-3 items-center mb-4 list-item-enter" style="animation-delay: 50ms;">
|
||||
<select id="filterXnm" onchange="refresh()"
|
||||
class="px-4 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-black dark:focus:ring-white">
|
||||
<option value="">全部学年</option>
|
||||
<option value="2026" selected>2026-2027</option>
|
||||
<option value="2025">2025-2026</option>
|
||||
<option value="2024">2024-2025</option>
|
||||
</select>
|
||||
<select id="filterXqm" onchange="refresh()"
|
||||
class="px-4 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-black dark:focus:ring-white">
|
||||
<option value="">全部学期</option>
|
||||
<option value="3">第1学期</option>
|
||||
<option value="12">第2学期</option>
|
||||
</select>
|
||||
<select id="filterStatus" onchange="filterCards()"
|
||||
class="px-4 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-black/30 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-black dark:focus:ring-white">
|
||||
<option value="">全部状态</option>
|
||||
<option value="已订">已预订</option>
|
||||
<option value="未订">未预订</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- 图表区 -->
|
||||
<div id="chartsRow" class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6 hidden list-item-enter" style="animation-delay: 120ms;">
|
||||
<div class="glass rounded-2xl p-4">
|
||||
<h3 class="text-sm font-semibold text-gray-600 dark:text-gray-400 mb-3">课程性质分布</h3>
|
||||
<div id="courseTypeChart" class="h-64"></div>
|
||||
</div>
|
||||
<div class="glass rounded-2xl p-4">
|
||||
<h3 class="text-sm font-semibold text-gray-600 dark:text-gray-400 mb-3">教材信息覆盖</h3>
|
||||
<div id="textbookCoverageChart" class="h-64"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 统计卡片 -->
|
||||
<div id="statsRow" class="grid grid-cols-2 md:grid-cols-4 gap-3 mb-4 hidden list-item-enter" style="animation-delay: 100ms;">
|
||||
<div class="glass rounded-xl p-4 text-center">
|
||||
<div class="text-2xl font-bold" id="statTotal">0</div>
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400 mt-1">总课程数</div>
|
||||
</div>
|
||||
<div class="glass rounded-xl p-4 text-center">
|
||||
<div class="text-2xl font-bold text-green-600 dark:text-green-400" id="statOrdered">0</div>
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400 mt-1">已预订</div>
|
||||
</div>
|
||||
<div class="glass rounded-xl p-4 text-center">
|
||||
<div class="text-2xl font-bold text-red-500 dark:text-red-400" id="statUnordered">0</div>
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400 mt-1">未预订</div>
|
||||
</div>
|
||||
<div class="glass rounded-xl p-4 text-center">
|
||||
<div class="text-2xl font-bold text-blue-600 dark:text-blue-400" id="statHasTextbook">0</div>
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400 mt-1">有教材信息</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 加载提示 -->
|
||||
<div id="loadingIndicator" class="text-center py-12 list-item-enter" style="animation-delay: 100ms;">
|
||||
<div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
|
||||
<p class="text-gray-500 dark:text-gray-400">正在加载教材预订信息...</p>
|
||||
</div>
|
||||
|
||||
<!-- 错误提示 -->
|
||||
<div id="errorMessage" class="glass rounded-2xl p-6 mb-4 text-center hidden list-item-enter" style="animation-delay: 100ms;">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"
|
||||
class="mx-auto mb-4 text-red-500">
|
||||
<circle cx="12" cy="12" r="10"/>
|
||||
<line x1="15" y1="9" x2="9" y2="15"/>
|
||||
<line x1="9" y1="9" x2="15" y2="15"/>
|
||||
</svg>
|
||||
<p id="errorText" class="text-gray-600 dark:text-gray-400"></p>
|
||||
</div>
|
||||
|
||||
<!-- 教材卡片列表 -->
|
||||
<div id="cardsContainer" class="hidden grid grid-cols-1 lg:grid-cols-2 gap-4 list-item-enter" style="animation-delay: 150ms;">
|
||||
</div>
|
||||
|
||||
<!-- 空状态 -->
|
||||
<div id="emptyState" class="glass rounded-2xl p-12 text-center hidden list-item-enter" style="animation-delay: 150ms;">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round"
|
||||
class="mx-auto mb-4 text-gray-300 dark:text-gray-600">
|
||||
<path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/>
|
||||
<path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/>
|
||||
</svg>
|
||||
<p class="text-gray-500 dark:text-gray-400 text-lg">暂无教材预订信息</p>
|
||||
<p class="text-gray-400 dark:text-gray-500 text-sm mt-1">当前学期可能没有选课或教材数据</p>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script src="{{ url_for('static', filename='echarts.min.js') }}"></script>
|
||||
<script>
|
||||
let allItems = [];
|
||||
let courseTypeChart = null;
|
||||
let textbookCoverageChart = null;
|
||||
|
||||
function isDarkMode() { return document.documentElement.classList.contains('dark'); }
|
||||
|
||||
function showToast(message, type) {
|
||||
const toast = document.getElementById('toast');
|
||||
const colors = {
|
||||
success: 'bg-green-500 text-white',
|
||||
error: 'bg-red-500 text-white',
|
||||
info: 'bg-blue-500 text-white',
|
||||
};
|
||||
toast.className = `toast-notification ${colors[type] || colors.info} px-6 py-3 rounded-lg shadow-lg text-sm font-medium`;
|
||||
toast.textContent = message;
|
||||
toast.classList.remove('hidden');
|
||||
setTimeout(() => toast.classList.add('hidden'), 3000);
|
||||
}
|
||||
|
||||
async function initSession() {
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/ping');
|
||||
const data = await res.json();
|
||||
if (!data.success) { console.warn('Session ping 失败:', data.message); return false; }
|
||||
if (data.refreshed) console.log('🔄 Session 已自动刷新');
|
||||
return true;
|
||||
} catch (e) { console.error('Session ping 异常:', e); return false; }
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
document.getElementById('loadingIndicator').classList.remove('hidden');
|
||||
document.getElementById('errorMessage').classList.add('hidden');
|
||||
document.getElementById('cardsContainer').classList.add('hidden');
|
||||
document.getElementById('emptyState').classList.add('hidden');
|
||||
document.getElementById('statsRow').classList.add('hidden');
|
||||
document.getElementById('chartsRow').classList.add('hidden');
|
||||
|
||||
await initSession();
|
||||
|
||||
const xnm = document.getElementById('filterXnm').value;
|
||||
const xqm = document.getElementById('filterXqm').value;
|
||||
const params = new URLSearchParams({ page_size: 1500 });
|
||||
if (xnm) params.set('xnm', xnm);
|
||||
if (xqm) params.set('xqm', xqm);
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/textbook-orders?' + params.toString());
|
||||
const data = await res.json();
|
||||
document.getElementById('loadingIndicator').classList.add('hidden');
|
||||
|
||||
if (!data.success) {
|
||||
document.getElementById('errorText').textContent = data.message || '查询失败';
|
||||
document.getElementById('errorMessage').classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
|
||||
allItems = data.items || [];
|
||||
if (!allItems.length) {
|
||||
document.getElementById('emptyState').classList.remove('hidden');
|
||||
document.getElementById('chartsRow').classList.add('hidden');
|
||||
return;
|
||||
}
|
||||
|
||||
renderStats(allItems);
|
||||
renderCards(allItems);
|
||||
document.getElementById('cardsContainer').classList.remove('hidden');
|
||||
document.getElementById('statsRow').classList.remove('hidden');
|
||||
document.getElementById('chartsRow').classList.remove('hidden');
|
||||
// 确保容器可见后再初始化 ECharts(避免 display:none 下 0 尺寸)
|
||||
setTimeout(() => renderCharts(allItems), 50);
|
||||
} catch (e) {
|
||||
document.getElementById('loadingIndicator').classList.add('hidden');
|
||||
document.getElementById('errorText').textContent = '网络错误: ' + e.message;
|
||||
document.getElementById('errorMessage').classList.remove('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
function renderStats(items) {
|
||||
const total = items.length;
|
||||
const ordered = items.filter(i => i.zdzt === '已订').length;
|
||||
const unordered = total - ordered;
|
||||
const hasTextbook = items.filter(i => i.jcxx && i.jcxx.trim()).length;
|
||||
document.getElementById('statTotal').textContent = total;
|
||||
document.getElementById('statOrdered').textContent = ordered;
|
||||
document.getElementById('statUnordered').textContent = unordered;
|
||||
document.getElementById('statHasTextbook').textContent = hasTextbook;
|
||||
}
|
||||
|
||||
function filterCards() {
|
||||
const status = document.getElementById('filterStatus').value;
|
||||
if (!status) {
|
||||
renderCards(allItems);
|
||||
} else {
|
||||
renderCards(allItems.filter(i => i.zdzt === status));
|
||||
}
|
||||
}
|
||||
|
||||
function renderCards(items) {
|
||||
const container = document.getElementById('cardsContainer');
|
||||
container.innerHTML = '';
|
||||
|
||||
items.forEach((item, idx) => {
|
||||
const ordered = item.zdzt === '已订';
|
||||
const statusClass = ordered ? 'status-ordered' : 'status-unordered';
|
||||
const statusLabel = ordered ? '✓ 已预订' : '✗ 未预订';
|
||||
|
||||
const textbookInfo = item.jcxx || '';
|
||||
// 解析教材信息: "书名/作者/出版社/版次"
|
||||
const tbParts = textbookInfo.split('/');
|
||||
const tbName = tbParts[0] || '';
|
||||
const tbAuthor = tbParts[1] || '';
|
||||
const tbPublisher = tbParts[2] || '';
|
||||
|
||||
const delay = idx * 60;
|
||||
const hasTextbook = textbookInfo.trim().length > 0;
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'tb-card glass rounded-2xl p-5 row-animate';
|
||||
card.style.animationDelay = delay + 'ms';
|
||||
|
||||
card.innerHTML = `
|
||||
<div class="flex flex-col sm:flex-row sm:items-start justify-between gap-3">
|
||||
<!-- 左侧信息 -->
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex items-start gap-3 mb-3">
|
||||
<div class="w-10 h-10 rounded-xl bg-gray-100 dark:bg-gray-800 flex items-center justify-center flex-shrink-0">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"
|
||||
class="text-gray-600 dark:text-gray-400">
|
||||
<path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/>
|
||||
<path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<h3 class="text-base font-semibold truncate">${escHtml(item.kcmc || '--')}</h3>
|
||||
<div class="flex flex-wrap gap-x-4 gap-y-1 mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
<span>${escHtml(item.kcxzmc || '--')}</span>
|
||||
<span>${escHtml(item.jsxx || '--')}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 sm:grid-cols-3 gap-3">
|
||||
<div>
|
||||
<div class="text-xs text-gray-400 dark:text-gray-500 mb-0.5">上课地点</div>
|
||||
<div class="text-sm font-medium truncate">${escHtml(item.jxdd || '--')}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-xs text-gray-400 dark:text-gray-500 mb-0.5">选课时间</div>
|
||||
<div class="text-sm font-medium">${item.xksj || '--'}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-xs text-gray-400 dark:text-gray-500 mb-0.5">预订时间</div>
|
||||
<div class="text-sm font-medium">${item.jcydsj || '--'}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
${hasTextbook ? `
|
||||
<div class="mt-3 pt-3 border-t border-gray-100 dark:border-gray-800">
|
||||
<div class="text-xs text-gray-400 dark:text-gray-500 mb-1">教材信息</div>
|
||||
<div class="text-sm text-gray-700 dark:text-gray-300">
|
||||
<span class="font-medium">${escHtml(tbName)}</span>
|
||||
${tbAuthor ? `<span class="text-gray-400 mx-1">/</span><span class="text-gray-500 dark:text-gray-400 text-xs">${escHtml(tbAuthor)}</span>` : ''}
|
||||
${tbPublisher ? `<span class="text-gray-400 mx-1">/</span><span class="text-gray-500 dark:text-gray-400 text-xs">${escHtml(tbPublisher)}</span>` : ''}
|
||||
</div>
|
||||
</div>
|
||||
` : ''}
|
||||
</div>
|
||||
|
||||
<!-- 右侧操作区域 -->
|
||||
<div class="flex sm:flex-col items-center sm:items-end gap-3 sm:gap-2 flex-shrink-0">
|
||||
<span class="status-badge ${statusClass}">${statusLabel}</span>
|
||||
${ordered
|
||||
? `<button onclick="toggleOrder('${item.jxb_id}', 'cancel')" class="px-4 py-1.5 rounded-lg text-xs font-medium border border-orange-300 dark:border-orange-700 text-orange-600 dark:text-orange-400 hover:bg-orange-50 dark:hover:bg-orange-900/30 transition-colors whitespace-nowrap">退订</button>`
|
||||
: `<button onclick="toggleOrder('${item.jxb_id}', 'order')" class="px-4 py-1.5 rounded-lg text-xs font-medium bg-blue-500 text-white hover:bg-blue-600 transition-colors whitespace-nowrap">预订</button>`
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
container.appendChild(card);
|
||||
});
|
||||
}
|
||||
|
||||
function escHtml(str) {
|
||||
return String(str).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
|
||||
}
|
||||
|
||||
async function toggleOrder(jxbId, action) {
|
||||
const actionName = action === 'order' ? '预订' : '退订';
|
||||
if (!confirm(`确定${actionName}该课程的教材吗?`)) return;
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/textbook-order', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ jxb_id: jxbId, action: action }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.success) {
|
||||
showToast(data.message || `${actionName}成功`, 'success');
|
||||
refresh();
|
||||
} else {
|
||||
showToast(data.message || `${actionName}失败`, 'error');
|
||||
}
|
||||
} catch (e) {
|
||||
showToast('网络错误: ' + e.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
// ── ECharts 图表渲染 ──
|
||||
|
||||
function renderCharts(items) {
|
||||
renderCourseTypeChart(items);
|
||||
renderTextbookCoverageChart(items);
|
||||
setupDarkObserver(items);
|
||||
}
|
||||
|
||||
function renderCourseTypeChart(items) {
|
||||
const dom = document.getElementById('courseTypeChart');
|
||||
if (!dom) return;
|
||||
if (courseTypeChart) courseTypeChart.dispose();
|
||||
|
||||
const counts = {};
|
||||
items.forEach(it => {
|
||||
const k = it.kcxzmc || '其他';
|
||||
counts[k] = (counts[k] || 0) + 1;
|
||||
});
|
||||
const entries = Object.entries(counts).sort((a, b) => b[1] - a[1]);
|
||||
|
||||
const dark = isDarkMode();
|
||||
const colors = dark
|
||||
? ['#60a5fa', '#34d399', '#fbbf24', '#f87171', '#a78bfa', '#f472b6', '#38bdf8']
|
||||
: ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899', '#0ea5e9'];
|
||||
|
||||
courseTypeChart = echarts.init(dom);
|
||||
courseTypeChart.setOption({
|
||||
tooltip: { trigger: 'item', formatter: '{b}: {c} 门 ({d}%)' },
|
||||
legend: { bottom: 0, type: 'scroll', textStyle: { fontSize: 11, color: dark ? '#d1d5db' : '#374151' } },
|
||||
series: [{
|
||||
type: 'pie', radius: ['40%', '70%'], center: ['50%', '45%'],
|
||||
itemStyle: { borderRadius: 4, borderColor: dark ? '#1f2937' : '#fff', borderWidth: 2 },
|
||||
label: { fontSize: 11, color: dark ? '#d1d5db' : '#374151' },
|
||||
data: entries.map(([name, value], i) => ({ name, value, itemStyle: { color: colors[i % colors.length] } }))
|
||||
}]
|
||||
}, true);
|
||||
}
|
||||
|
||||
function renderTextbookCoverageChart(items) {
|
||||
const dom = document.getElementById('textbookCoverageChart');
|
||||
if (!dom) return;
|
||||
if (textbookCoverageChart) textbookCoverageChart.dispose();
|
||||
|
||||
const has = items.filter(i => i.jcxx && i.jcxx.trim()).length;
|
||||
const none = items.length - has;
|
||||
|
||||
const dark = isDarkMode();
|
||||
const colors = dark ? ['#34d399', '#6b7280'] : ['#10b981', '#9ca3af'];
|
||||
|
||||
textbookCoverageChart = echarts.init(dom);
|
||||
textbookCoverageChart.setOption({
|
||||
tooltip: { trigger: 'item', formatter: '{b}: {c} 门 ({d}%)' },
|
||||
legend: { bottom: 0, textStyle: { fontSize: 11, color: dark ? '#d1d5db' : '#374151' } },
|
||||
series: [{
|
||||
type: 'pie', radius: ['45%', '70%'], center: ['50%', '45%'],
|
||||
itemStyle: { borderRadius: 4, borderColor: dark ? '#1f2937' : '#fff', borderWidth: 2 },
|
||||
label: { fontSize: 11, color: dark ? '#d1d5db' : '#374151' },
|
||||
data: [
|
||||
{ name: '有教材信息', value: has, itemStyle: { color: colors[0] } },
|
||||
{ name: '无教材信息', value: none, itemStyle: { color: colors[1] } }
|
||||
]
|
||||
}]
|
||||
}, true);
|
||||
}
|
||||
|
||||
// ── 深色模式观察 ──
|
||||
let _darkObserverTextbook = null;
|
||||
function setupDarkObserver(items) {
|
||||
if (_darkObserverTextbook) _darkObserverTextbook.disconnect();
|
||||
_darkObserverTextbook = new MutationObserver(() => {
|
||||
if (courseTypeChart) { courseTypeChart.dispose(); courseTypeChart = null; }
|
||||
if (textbookCoverageChart) { textbookCoverageChart.dispose(); textbookCoverageChart = null; }
|
||||
renderCharts(items);
|
||||
});
|
||||
_darkObserverTextbook.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
|
||||
}
|
||||
|
||||
window.addEventListener('resize', () => {
|
||||
courseTypeChart?.resize();
|
||||
textbookCoverageChart?.resize();
|
||||
});
|
||||
|
||||
// 初始化
|
||||
initSession().then(sessionOk => {
|
||||
if (!sessionOk) {
|
||||
document.getElementById('errorText').innerHTML = '教务系统 Session 已失效,请尝试<a href="/dashboard" class="underline">重新配置教务账号</a>';
|
||||
document.getElementById('errorMessage').classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
refresh();
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,78 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
{% block title %}毕业论文成绩 - {{ brand_name }}{% endblock %}
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
@keyframes fadeSlideIn {
|
||||
from { opacity: 0; transform: translateY(8px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.row-animate { animation: fadeSlideIn 0.3s ease both; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.row-animate { animation: none !important; opacity: 1 !important; }
|
||||
.list-item-enter { animation: none !important; opacity: 1 !important; }
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 list-item-enter">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 10v6M2 10l10-5 10 5-10 5z"/><path d="M6 12v5c3 3 9 3 12 0v-5"/></svg>
|
||||
毕业论文成绩
|
||||
</h2>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">查看毕业论文(设计)成绩</p>
|
||||
</div>
|
||||
<button onclick="loadData()" class="px-4 py-2 rounded-lg border"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>刷新</button>
|
||||
</div>
|
||||
<div id="loadingIndicator" class="text-center py-12 hidden"><div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div><p class="text-gray-500 dark:text-gray-400">加载中...</p></div>
|
||||
<div id="errorMessage" class="glass rounded-2xl p-6 mb-4 text-center hidden"><p id="errorText" class="text-red-500"></p></div>
|
||||
<div id="dataContainer" class="hidden">
|
||||
<div class="glass rounded-2xl overflow-hidden">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead><tr class="border-b border-gray-200 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-800/50"><th class="text-left py-3 px-4 font-semibold">课题名称</th><th class="text-left py-3 px-4 font-semibold">指导教师</th><th class="text-left py-3 px-4 font-semibold">成绩</th><th class="text-left py-3 px-4 font-semibold">等级</th><th class="text-left py-3 px-4 font-semibold">评语</th></tr></thead>
|
||||
<tbody id="tableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="emptyState" class="glass rounded-2xl p-12 text-center hidden"><p class="text-gray-500 dark:text-gray-400 text-lg">暂无成绩信息</p></div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block extra_js %}
|
||||
<script>
|
||||
async function loadData() {
|
||||
document.getElementById('loadingIndicator').classList.remove('hidden');
|
||||
document.getElementById('errorMessage').classList.add('hidden');
|
||||
document.getElementById('dataContainer').classList.add('hidden');
|
||||
document.getElementById('emptyState').classList.add('hidden');
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/thesis-grades');
|
||||
const data = await res.json();
|
||||
document.getElementById('loadingIndicator').classList.add('hidden');
|
||||
if (!data.success) { showError(data.message); return; }
|
||||
const items = data.items || [];
|
||||
if (!items.length) { document.getElementById('emptyState').classList.remove('hidden'); return; }
|
||||
const tbody = document.getElementById('tableBody');
|
||||
tbody.innerHTML = items.map((item, i) => {
|
||||
const score = item.cj||item.成绩||item.zcj||'--';
|
||||
const grade = item.dj||item.等级||'--';
|
||||
return `<tr class="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50/50 dark:hover:bg-gray-800/30 transition-colors">
|
||||
<td class="py-3 px-4">${escHtml(item.ktmc||item.课题名称||'--')}</td>
|
||||
<td class="py-3 px-4">${escHtml(item.zdjs||item.指导教师||item.xm||'--')}</td>
|
||||
<td class="py-3 px-4 font-medium ${parseFloat(score)>=90?'text-green-600':parseFloat(score)>=80?'text-blue-600':parseFloat(score)>=70?'text-yellow-600':'text-gray-600'}">${escHtml(score)}</td>
|
||||
<td class="py-3 px-4">${escHtml(grade)}</td>
|
||||
<td class="py-3 px-4 text-gray-500 text-xs max-w-xs truncate">${escHtml(item.py||item.评语||'--')}</td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
document.getElementById('dataContainer').classList.remove('hidden');
|
||||
} catch(e) { document.getElementById('loadingIndicator').classList.add('hidden'); showError('网络错误: '+e.message); }
|
||||
}
|
||||
function showError(msg) { document.getElementById('errorText').textContent = msg; document.getElementById('errorMessage').classList.remove('hidden'); }
|
||||
function escHtml(s) { if(s==null) return ''; return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"'); }
|
||||
function escAttr(s) { if(s==null) return ''; return String(s).replace(/&/g,'&').replace(/"/g,'"').replace(/</g,'<').replace(/>/g,'>'); }
|
||||
document.addEventListener('DOMContentLoaded', () => loadData());
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,88 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
{% block title %}毕业论文查重 - {{ brand_name }}{% endblock %}
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
@keyframes fadeSlideIn {
|
||||
from { opacity: 0; transform: translateY(8px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.row-animate { animation: fadeSlideIn 0.3s ease both; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.row-animate { animation: none !important; opacity: 1 !important; }
|
||||
.list-item-enter { animation: none !important; opacity: 1 !important; }
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 list-item-enter">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/><line x1="8" y1="11" x2="14" y2="11"/></svg>
|
||||
论文查重
|
||||
</h2>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">毕业论文(设计)查重检测</p>
|
||||
</div>
|
||||
<button onclick="loadData()" class="px-4 py-2 rounded-lg border"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>刷新</button>
|
||||
</div>
|
||||
<div id="statusBar" class="glass rounded-2xl p-4 mb-4 hidden">
|
||||
<div class="flex items-center gap-2 text-sm">
|
||||
<span class="text-xs font-medium text-gray-500 dark:text-gray-400">查重状态</span>
|
||||
<span id="checkStatus" class="px-2 py-0.5 rounded text-xs bg-gray-100">加载中...</span>
|
||||
</div>
|
||||
</div>
|
||||
<div id="loadingIndicator" class="text-center py-12 hidden"><div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div><p class="text-gray-500 dark:text-gray-400">加载中...</p></div>
|
||||
<div id="errorMessage" class="glass rounded-2xl p-6 mb-4 text-center hidden"><p id="errorText" class="text-red-500"></p></div>
|
||||
<div id="dataContainer" class="hidden">
|
||||
<div class="glass rounded-2xl overflow-hidden">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead><tr class="border-b border-gray-200 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-800/50"><th class="text-left py-3 px-4 font-semibold">检测论文</th><th class="text-left py-3 px-4 font-semibold">检测时间</th><th class="text-left py-3 px-4 font-semibold">相似比</th><th class="text-left py-3 px-4 font-semibold">检测结果</th></tr></thead>
|
||||
<tbody id="tableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="emptyState" class="glass rounded-2xl p-12 text-center hidden"><p class="text-gray-500 dark:text-gray-400 text-lg">暂无查重记录</p></div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block extra_js %}
|
||||
<script>
|
||||
async function loadData() {
|
||||
document.getElementById('loadingIndicator').classList.remove('hidden');
|
||||
document.getElementById('errorMessage').classList.add('hidden');
|
||||
document.getElementById('dataContainer').classList.add('hidden');
|
||||
document.getElementById('emptyState').classList.add('hidden');
|
||||
document.getElementById('statusBar').classList.add('hidden');
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/thesis-plagiarism-check');
|
||||
const data = await res.json();
|
||||
document.getElementById('loadingIndicator').classList.add('hidden');
|
||||
if (!data.success) { showError(data.message); return; }
|
||||
if (data.check_status) {
|
||||
document.getElementById('statusBar').classList.remove('hidden');
|
||||
const st = document.getElementById('checkStatus');
|
||||
st.textContent = data.check_status;
|
||||
st.className = 'px-2 py-0.5 rounded text-xs ' + (data.check_status.includes('通过')||data.check_status.includes('合格')?'bg-green-100 text-green-700':data.check_status.includes('待检')||data.check_status.includes('未检')?'bg-yellow-100 text-yellow-700':'bg-gray-100 text-gray-600');
|
||||
}
|
||||
const items = data.items || [];
|
||||
if (!items.length) { document.getElementById('emptyState').classList.remove('hidden'); return; }
|
||||
const tbody = document.getElementById('tableBody');
|
||||
tbody.innerHTML = items.map((item, i) => {
|
||||
return `<tr class="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50/50 dark:hover:bg-gray-800/30 transition-colors">
|
||||
<td class="py-3 px-4">${escHtml(item.lwmc||item.论文名称||'--')}</td>
|
||||
<td class="py-3 px-4 text-gray-500">${escHtml(item.jcsj||item.检测时间||'--')}</td>
|
||||
<td class="py-3 px-4">${escHtml(item.xsb||item.相似比||item.查重率||'--')}</td>
|
||||
<td class="py-3 px-4">${escHtml(item.jcjg||item.检测结果||'--')}</td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
document.getElementById('dataContainer').classList.remove('hidden');
|
||||
} catch(e) { document.getElementById('loadingIndicator').classList.add('hidden'); showError('网络错误: '+e.message); }
|
||||
}
|
||||
function showError(msg) { document.getElementById('errorText').textContent = msg; document.getElementById('errorMessage').classList.remove('hidden'); }
|
||||
function escHtml(s) { if(s==null) return ''; return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"'); }
|
||||
function escAttr(s) { if(s==null) return ''; return String(s).replace(/&/g,'&').replace(/"/g,'"').replace(/</g,'<').replace(/>/g,'>'); }
|
||||
document.addEventListener('DOMContentLoaded', () => loadData());
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,76 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
{% block title %}毕业论文过程资料 - {{ brand_name }}{% endblock %}
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
@keyframes fadeSlideIn {
|
||||
from { opacity: 0; transform: translateY(8px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.row-animate { animation: fadeSlideIn 0.3s ease both; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.row-animate { animation: none !important; opacity: 1 !important; }
|
||||
.list-item-enter { animation: none !important; opacity: 1 !important; }
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 list-item-enter">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"/><polyline points="13 2 13 9 20 9"/></svg>
|
||||
过程资料
|
||||
</h2>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">提交和查看毕业论文(设计)过程文档</p>
|
||||
</div>
|
||||
<button onclick="loadData()" class="px-4 py-2 rounded-lg border"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>刷新</button>
|
||||
</div>
|
||||
<div id="loadingIndicator" class="text-center py-12 hidden"><div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div><p class="text-gray-500 dark:text-gray-400">加载中...</p></div>
|
||||
<div id="errorMessage" class="glass rounded-2xl p-6 mb-4 text-center hidden"><p id="errorText" class="text-red-500"></p></div>
|
||||
<div id="dataContainer" class="hidden">
|
||||
<div class="glass rounded-2xl overflow-hidden">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead><tr class="border-b border-gray-200 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-800/50"><th class="text-left py-3 px-4 font-semibold">文档名称</th><th class="text-left py-3 px-4 font-semibold">文档类型</th><th class="text-left py-3 px-4 font-semibold">提交时间</th><th class="text-left py-3 px-4 font-semibold">审核状态</th><th class="text-left py-3 px-4 font-semibold">操作</th></tr></thead>
|
||||
<tbody id="tableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="emptyState" class="glass rounded-2xl p-12 text-center hidden"><p class="text-gray-500 dark:text-gray-400 text-lg">暂无过程资料</p></div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block extra_js %}
|
||||
<script>
|
||||
async function loadData() {
|
||||
document.getElementById('loadingIndicator').classList.remove('hidden');
|
||||
document.getElementById('errorMessage').classList.add('hidden');
|
||||
document.getElementById('dataContainer').classList.add('hidden');
|
||||
document.getElementById('emptyState').classList.add('hidden');
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/thesis-process-docs');
|
||||
const data = await res.json();
|
||||
document.getElementById('loadingIndicator').classList.add('hidden');
|
||||
if (!data.success) { showError(data.message); return; }
|
||||
const items = data.items || [];
|
||||
if (!items.length) { document.getElementById('emptyState').classList.remove('hidden'); return; }
|
||||
const tbody = document.getElementById('tableBody');
|
||||
tbody.innerHTML = items.map((item, i) => {
|
||||
return `<tr class="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50/50 dark:hover:bg-gray-800/30 transition-colors">
|
||||
<td class="py-3 px-4">${escHtml(item.wdmc||item.文档名称||'--')}</td>
|
||||
<td class="py-3 px-4 text-gray-500">${escHtml(item.wdlxmc||item.文档类型||'--')}</td>
|
||||
<td class="py-3 px-4 text-gray-500">${escHtml(item.tjsj||item.提交时间||'--')}</td>
|
||||
<td class="py-3 px-4">${escHtml(item.shztmc||item.审核状态||'--')}</td>
|
||||
<td class="py-3 px-4"><a href="${item.file_url||'#'}" class="text-xs text-blue-500 hover:text-blue-600 ${item.file_url?'':'pointer-events-none text-gray-400'}" target="_blank">${item.file_url?'查看':'未上传'}</a></td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
document.getElementById('dataContainer').classList.remove('hidden');
|
||||
} catch(e) { document.getElementById('loadingIndicator').classList.add('hidden'); showError('网络错误: '+e.message); }
|
||||
}
|
||||
function showError(msg) { document.getElementById('errorText').textContent = msg; document.getElementById('errorMessage').classList.remove('hidden'); }
|
||||
function escHtml(s) { if(s==null) return ''; return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"'); }
|
||||
function escAttr(s) { if(s==null) return ''; return String(s).replace(/&/g,'&').replace(/"/g,'"').replace(/</g,'<').replace(/>/g,'>'); }
|
||||
document.addEventListener('DOMContentLoaded', () => loadData());
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,84 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
{% block title %}毕业论文选题 - {{ brand_name }}{% endblock %}
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
@keyframes fadeSlideIn {
|
||||
from { opacity: 0; transform: translateY(8px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.row-animate { animation: fadeSlideIn 0.3s ease both; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.row-animate { animation: none !important; opacity: 1 !important; }
|
||||
.list-item-enter { animation: none !important; opacity: 1 !important; }
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 list-item-enter">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/><line x1="8" y1="7" x2="16" y2="7"/><line x1="8" y1="11" x2="14" y2="11"/></svg>
|
||||
学生选题
|
||||
</h2>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">毕业论文(设计)选题</p>
|
||||
</div>
|
||||
<button onclick="loadData()" class="px-4 py-2 rounded-lg border"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>刷新</button>
|
||||
</div>
|
||||
<div class="glass rounded-2xl p-4 mb-4">
|
||||
<div class="flex items-center gap-2 text-sm">
|
||||
<span class="text-xs font-medium text-gray-500 dark:text-gray-400 mr-2">选题状态</span>
|
||||
<span id="topicStatus" class="px-2 py-0.5 rounded text-xs bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400">加载中...</span>
|
||||
</div>
|
||||
</div>
|
||||
<div id="loadingIndicator" class="text-center py-12 hidden"><div class="w-10 h-10 border-2 border-black dark:border-white border-t-transparent rounded-full animate-spin mx-auto mb-4"></div><p class="text-gray-500 dark:text-gray-400">加载中...</p></div>
|
||||
<div id="errorMessage" class="glass rounded-2xl p-6 mb-4 text-center hidden"><p id="errorText" class="text-red-500"></p></div>
|
||||
<div id="dataContainer" class="hidden">
|
||||
<div class="glass rounded-2xl overflow-hidden">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead><tr class="border-b border-gray-200 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-800/50"><th class="text-left py-3 px-4 font-semibold">课题名称</th><th class="text-left py-3 px-4 font-semibold">指导教师</th><th class="text-left py-3 px-4 font-semibold">课题来源</th><th class="text-left py-3 px-4 font-semibold">选题状态</th></tr></thead>
|
||||
<tbody id="tableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="emptyState" class="glass rounded-2xl p-12 text-center hidden"><p class="text-gray-500 dark:text-gray-400 text-lg">暂无选题信息</p></div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block extra_js %}
|
||||
<script>
|
||||
async function loadData() {
|
||||
document.getElementById('loadingIndicator').classList.remove('hidden');
|
||||
document.getElementById('errorMessage').classList.add('hidden');
|
||||
document.getElementById('dataContainer').classList.add('hidden');
|
||||
document.getElementById('emptyState').classList.add('hidden');
|
||||
try {
|
||||
const res = await fetch('/api/jwxt/thesis-topic');
|
||||
const data = await res.json();
|
||||
document.getElementById('loadingIndicator').classList.add('hidden');
|
||||
if (!data.success) { showError(data.message); return; }
|
||||
const items = data.items || data.available_topics || [];
|
||||
const statusText = data.status || (items.length > 0 ? '已选题' : '未选题');
|
||||
document.getElementById('topicStatus').textContent = statusText;
|
||||
document.getElementById('topicStatus').className = 'px-2 py-0.5 rounded text-xs ' + (statusText.includes('已选')?'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400':'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400');
|
||||
if (!items.length) { document.getElementById('emptyState').classList.remove('hidden'); return; }
|
||||
const tbody = document.getElementById('tableBody');
|
||||
tbody.innerHTML = items.map((item, i) => {
|
||||
return `<tr class="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50/50 dark:hover:bg-gray-800/30 transition-colors">
|
||||
<td class="py-3 px-4">${escHtml(item.ktmc||item.课题名称||'--')}</td>
|
||||
<td class="py-3 px-4">${escHtml(item.zdjs||item.指导教师||item.xm||'--')}</td>
|
||||
<td class="py-3 px-4 text-gray-500">${escHtml(item.ktlymc||item.课题来源||'--')}</td>
|
||||
<td class="py-3 px-4">${escHtml(item.xtztmc||item.选题状态||'--')}</td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
document.getElementById('dataContainer').classList.remove('hidden');
|
||||
} catch(e) { document.getElementById('loadingIndicator').classList.add('hidden'); showError('网络错误: '+e.message); }
|
||||
}
|
||||
function showError(msg) { document.getElementById('errorText').textContent = msg; document.getElementById('errorMessage').classList.remove('hidden'); }
|
||||
function escHtml(s) { if(s==null) return ''; return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"'); }
|
||||
function escAttr(s) { if(s==null) return ''; return String(s).replace(/&/g,'&').replace(/"/g,'"').replace(/</g,'<').replace(/>/g,'>'); }
|
||||
document.addEventListener('DOMContentLoaded', () => loadData());
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,28 @@
|
||||
{% extends "base_tailwind.html" %}
|
||||
|
||||
{% block title %}选课模式进行中 - {{ brand_name }}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="min-h-[60vh] flex items-center justify-center px-4">
|
||||
<div class="glass rounded-2xl p-8 md:p-12 max-w-lg w-full text-center layer-2">
|
||||
<div class="w-16 h-16 mx-auto rounded-2xl bg-amber-100 dark:bg-amber-900/30 flex items-center justify-center">
|
||||
<svg class="w-8 h-8 text-amber-600 dark:text-amber-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
||||
d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
|
||||
</svg>
|
||||
</div>
|
||||
<h1 class="text-xl md:text-2xl font-bold text-neutral-900 dark:text-white mt-6">选课模式进行中</h1>
|
||||
<p class="text-neutral-500 dark:text-neutral-400 mt-3 leading-relaxed">
|
||||
为了选课需求,选课时间段内暂时关闭其他服务。<br>
|
||||
课程搜索、选课、退课、已选查询和抢课任务不受影响,<br>
|
||||
其他功能将在选课结束后自动恢复。
|
||||
</p>
|
||||
<div class="mt-8 flex gap-3 justify-center flex-wrap">
|
||||
<a href="{% if current_user.is_authenticated %}{{ url_for('main.courses') }}{% else %}{{ url_for('main.login') }}{% endif %}"
|
||||
class="btn-primary px-6 py-2.5 rounded-full text-sm font-bold inline-block">{% if current_user.is_authenticated %}去选课{% else %}先登录{% endif %}</a>
|
||||
<a href="{{ url_for('main.dashboard') }}"
|
||||
class="px-6 py-2.5 rounded-full text-sm font-bold border border-neutral-300 dark:border-neutral-600 text-neutral-700 dark:text-neutral-200 inline-block">返回首页</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,233 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
测试账号数据模拟器
|
||||
|
||||
当检测到当前用户是测试账号(username = "注册账号")时,
|
||||
所有需要调用教务系统接口的 API 直接返回模拟数据,不走上游。
|
||||
|
||||
数据格式参照真实教务系统 253051601132 的返回结构。
|
||||
"""
|
||||
from typing import Dict, List
|
||||
|
||||
# ── 测试账号标识 ─────────────────────────────────────────────
|
||||
TEST_USERNAME = "测试账号"
|
||||
FAKE_XH = "2024123456"
|
||||
|
||||
# ── 模拟个人信息 ─────────────────────────────────────────────
|
||||
|
||||
def fake_student_info() -> Dict:
|
||||
"""模拟学生基本信息(与 JwxtApi.get_student_info 返回格式一致)
|
||||
|
||||
真实数据格式: {'success': True, 'info': { '学号': '...', '姓名': '...', ...}}
|
||||
"""
|
||||
return {
|
||||
'success': True,
|
||||
'info': {
|
||||
'学号': FAKE_XH,
|
||||
'姓名': '测试账号',
|
||||
'性别': '男',
|
||||
'出生日期': '2005-06-15',
|
||||
'民族': '汉族',
|
||||
'政治面貌': '共青团员',
|
||||
'入学日期': '2024-09-01',
|
||||
'年级': '2024',
|
||||
'学院名称': '信息工程学院',
|
||||
'专业名称': '虚拟现实技术(051601)',
|
||||
'班级名称': '虚拟现实2024-1班',
|
||||
'学制': '4',
|
||||
'学籍状态': '在读',
|
||||
'是否在校': '是',
|
||||
'报到注册状态': '已报到已注册',
|
||||
'学历层次': '本科',
|
||||
'培养层次': '本科',
|
||||
'所属学院': '信息工程学院',
|
||||
'招生年度': '2024',
|
||||
'考生号': '24370203109999',
|
||||
'xxdm': '14438',
|
||||
'curXh_id': FAKE_XH,
|
||||
'xh_id': FAKE_XH,
|
||||
'xqm': '12',
|
||||
'xnm': '2025',
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def fake_personal_info() -> Dict:
|
||||
"""与 /api/jwxt/personal-info 格式一致(同 get_student_info 返回)"""
|
||||
return fake_student_info()
|
||||
|
||||
|
||||
# ── 模拟学期信息 ─────────────────────────────────────────────
|
||||
|
||||
def fake_semester_info() -> Dict:
|
||||
"""模拟学期信息(与 /api/timetable/semester 格式一致)"""
|
||||
weeks = []
|
||||
for i in range(1, 19):
|
||||
start_day = 9 + (i - 1) * 7
|
||||
end_day = start_day + 6
|
||||
month_s = 3 if start_day <= 31 else 4
|
||||
month_e = 3 if end_day <= 31 else 4
|
||||
day_s = start_day if start_day <= 31 else start_day - 31
|
||||
day_e = end_day if end_day <= 31 else end_day - 31
|
||||
weeks.append({
|
||||
'zs': str(i),
|
||||
'zcrq': f'{i}(2026-{month_s:02d}-{day_s:02d}至2026-{month_e:02d}-{day_e:02d})',
|
||||
'zcrq2': f'第{i}周(2026-{month_s:02d}-{day_s:02d}至2026-{month_e:02d}-{day_e:02d})',
|
||||
'rq': f'2026-{month_s:02d}-{day_s:02d}/2026-{month_e:02d}-{day_e:02d}',
|
||||
})
|
||||
return {
|
||||
'success': True,
|
||||
'data': {
|
||||
'xnm': '2025',
|
||||
'xqm': '12',
|
||||
'xqh_id': '1',
|
||||
'weeks': weeks,
|
||||
'current_week': 3,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
# ── 模拟课表数据 ─────────────────────────────────────────────
|
||||
|
||||
def _jc_time_range(jcor: str) -> tuple:
|
||||
"""根据节次范围返回 (jc_start, jc_end, time_start, time_end)"""
|
||||
parts = jcor.split('-')
|
||||
s = int(parts[0])
|
||||
e = int(parts[1]) if len(parts) > 1 else s
|
||||
times = {
|
||||
1: ('08:00', '08:45'), 2: ('08:55', '09:40'),
|
||||
3: ('10:00', '10:45'), 4: ('10:55', '11:40'),
|
||||
5: ('14:00', '14:45'), 6: ('14:55', '15:40'),
|
||||
7: ('16:00', '16:45'), 8: ('16:55', '17:40'),
|
||||
}
|
||||
ts = times.get(s, ('', ''))
|
||||
te = times.get(e, ('', ''))
|
||||
return s, e, ts[0], te[1], f'{ts[0]}~{te[1]}'
|
||||
|
||||
|
||||
# 模拟课程列表(贴近真实课程结构,但课程名/教师名均为虚构)
|
||||
_FAKE_COURSES: List[Dict] = [
|
||||
# 星期一
|
||||
{'kcmc': '习近平新时代中国特色社会主义思想概论', 'xm': '张教授', 'cdmc': '博识楼201', 'jcor': '1-2', 'xqj': 1, 'zcd': '1-16周', 'xf': '3.0', 'kclb': '通识类', 'kcxz': '通必'},
|
||||
{'kcmc': '大学英语(四级)', 'xm': '李老师', 'cdmc': '博识楼306', 'jcor': '3-4', 'xqj': 1, 'zcd': '1-16周', 'xf': '2.0', 'kclb': '通识类', 'kcxz': '通必'},
|
||||
{'kcmc': '数据库原理及应用实验', 'xm': '王老师', 'cdmc': '明远楼C101实验室', 'jcor': '5-6', 'xqj': 1, 'zcd': '2-16周(双)', 'xf': '1.0', 'kclb': '专业类', 'kcxz': '实践'},
|
||||
# 星期二
|
||||
{'kcmc': '高等数学A(下)', 'xm': '赵教授', 'cdmc': '博识楼204', 'jcor': '1-2', 'xqj': 2, 'zcd': '1-16周', 'xf': '5.0', 'kclb': '通识类', 'kcxz': '通必'},
|
||||
{'kcmc': '线性代数', 'xm': '孙老师', 'cdmc': '博识楼302', 'jcor': '3-4', 'xqj': 2, 'zcd': '1-16周', 'xf': '3.0', 'kclb': '通识类', 'kcxz': '通必'},
|
||||
{'kcmc': '体育(选项课)', 'xm': '刘教练', 'cdmc': '体育馆', 'jcor': '5-6', 'xqj': 2, 'zcd': '1-18周', 'xf': '1.0', 'kclb': '通识类', 'kcxz': '通必'},
|
||||
# 星期三
|
||||
{'kcmc': '面向对象程序设计(Java)', 'xm': '陈教授', 'cdmc': '博识楼305', 'jcor': '1-2', 'xqj': 3, 'zcd': '1-16周', 'xf': '3.0', 'kclb': '专业类', 'kcxz': '专必'},
|
||||
{'kcmc': '面向对象程序设计实验', 'xm': '陈教授', 'cdmc': '明远楼C201实验室', 'jcor': '3-4', 'xqj': 3, 'zcd': '3-16周', 'xf': '1.0', 'kclb': '专业类', 'kcxz': '实践'},
|
||||
{'kcmc': '大学生心理健康教育', 'xm': '周老师', 'cdmc': '博识楼103', 'jcor': '7-8', 'xqj': 3, 'zcd': '5-12周', 'xf': '2.0', 'kclb': '通识类', 'kcxz': '通必'},
|
||||
# 星期四
|
||||
{'kcmc': '计算机组成原理', 'xm': '吴教授', 'cdmc': '博识楼201', 'jcor': '1-2', 'xqj': 4, 'zcd': '1-16周', 'xf': '3.0', 'kclb': '专业类', 'kcxz': '专必'},
|
||||
{'kcmc': '概率论与数理统计', 'xm': '郑老师', 'cdmc': '博识楼306', 'jcor': '3-4', 'xqj': 4, 'zcd': '1-16周', 'xf': '3.0', 'kclb': '通识类', 'kcxz': '通必'},
|
||||
{'kcmc': '军事理论', 'xm': '高老师', 'cdmc': '博识楼204', 'jcor': '5-6', 'xqj': 4, 'zcd': '11周', 'xf': '2.0', 'kclb': '通识类', 'kcxz': '通必'},
|
||||
# 星期五
|
||||
{'kcmc': '大学英语听力', 'xm': '李老师', 'cdmc': '外语楼语音室302', 'jcor': '1-2', 'xqj': 5, 'zcd': '1-16周', 'xf': '1.0', 'kclb': '通识类', 'kcxz': '通必'},
|
||||
{'kcmc': '形势与政策', 'xm': '王教授', 'cdmc': '报告厅', 'jcor': '3-4', 'xqj': 5, 'zcd': '3-16周', 'xf': '2.0', 'kclb': '通识类', 'kcxz': '通必'},
|
||||
]
|
||||
|
||||
# 实践课(sjkList)
|
||||
_FAKE_SJK: List[Dict] = [
|
||||
{'kcmc': '创业设计与实验', 'jsxm': '赵老师', 'qsjsz': '1-16周', 'xf': '2.0', 'kclb': '通识类', 'khfsmc': '考查'},
|
||||
]
|
||||
|
||||
|
||||
def _build_kb_item(course: Dict) -> Dict:
|
||||
"""构建与真实教务系统格式一致的课表项"""
|
||||
jc_s, jc_e, ts, te, tr = _jc_time_range(course['jcor'])
|
||||
return {
|
||||
'kcmc': course['kcmc'],
|
||||
'xm': course['xm'],
|
||||
'cdmc': course['cdmc'],
|
||||
'jcor': course['jcor'],
|
||||
'jcs': course['jcor'].replace('-', '-'),
|
||||
'xqj': str(course['xqj']),
|
||||
'xqjmc': ['', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'][course['xqj']],
|
||||
'zcd': course['zcd'],
|
||||
'xnm': '2025',
|
||||
'xqm': '12',
|
||||
'xqh_id': '1',
|
||||
'xqmc': '长清校区',
|
||||
'cdbh': course['cdmc'].split()[-1] if ' ' in course['cdmc'] else '001',
|
||||
'cd_id': 'FAKE_CD_ID',
|
||||
'jgh_id': 'FAKE_JGH_ID',
|
||||
'jxb_id': 'FAKE_JXB_ID',
|
||||
'kch_id': 'FAKE_KCH_ID',
|
||||
'kclb': course.get('kclb', '通识类'),
|
||||
'kcxz': course.get('kcxz', '通必'),
|
||||
'kczxs': str(int(float(course.get('xf', '2.0')) * 16)),
|
||||
'xf': course.get('xf', '2.0'),
|
||||
'xsdm': '02' if course.get('kcxz') == '实践' else '01',
|
||||
'xslxbj': '△' if course.get('kcxz') == '实践' else '☆',
|
||||
'jxbmc': f'{course["kcmc"]}-教学班',
|
||||
'jxbzc': '虚拟现实2024-1班',
|
||||
'qsjsz': course['zcd'],
|
||||
'sjbz': '0',
|
||||
|
||||
# 前端渲染用的额外字段
|
||||
'jc_start': jc_s,
|
||||
'jc_end': jc_e,
|
||||
'time_start': ts,
|
||||
'time_end': te,
|
||||
'time_range': tr,
|
||||
}
|
||||
|
||||
|
||||
def fake_timetable(kblx: str = '2', week: int = 0) -> Dict:
|
||||
"""
|
||||
模拟课表数据(与 KbcxAPI.get_timetable 返回格式一致)
|
||||
|
||||
kblx=2 返回全学期,kblx=1 返回指定周
|
||||
"""
|
||||
from copy import deepcopy
|
||||
|
||||
kb_list = []
|
||||
for course in _FAKE_COURSES:
|
||||
item = _build_kb_item(course)
|
||||
|
||||
if kblx == '1' and week > 0:
|
||||
# 按周查询:过滤不含当前周的课程
|
||||
zcd = course['zcd']
|
||||
if not _zcd_contains_week(zcd, week):
|
||||
continue
|
||||
|
||||
kb_list.append(item)
|
||||
|
||||
# 按 xqj 升序、jcor 升序排列
|
||||
kb_list.sort(key=lambda x: (int(x['xqj']), int(x['jcor'].split('-')[0])))
|
||||
|
||||
# 实践课列表
|
||||
sjk_list = deepcopy(_FAKE_SJK) if kblx == '2' else []
|
||||
|
||||
result = {
|
||||
'kbList': kb_list,
|
||||
'sjkList': sjk_list,
|
||||
'xsxx': {
|
||||
'XM': '测试账号',
|
||||
'BJMC': '虚拟现实2024-1班',
|
||||
'XH': FAKE_XH,
|
||||
'XNMC': '2025-2026',
|
||||
'XQM': '12',
|
||||
'XNM': '2025',
|
||||
'NJDM_ID': '2024',
|
||||
},
|
||||
'kblx': kblx,
|
||||
'xkkg': False,
|
||||
'jfckbkg': False,
|
||||
'rqazcList': [],
|
||||
'qsxqj': '1',
|
||||
'zckbsfxssj': '1',
|
||||
}
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def _zcd_contains_week(zcd: str, week: int) -> bool:
|
||||
"""判断周次描述是否包含指定周(与 KbcxAPI.parse_zcd_weeks 同一套分段解析逻辑)"""
|
||||
if not zcd:
|
||||
return True
|
||||
from app.kbcx_api import KbcxAPI
|
||||
return week in KbcxAPI.parse_zcd_weeks(zcd)
|
||||
@@ -0,0 +1,356 @@
|
||||
"""
|
||||
注册码(激活码)管理模块
|
||||
管理注册码的生成、验证和使用
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
import secrets
|
||||
import string
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional, Dict, List, Tuple
|
||||
from flask import current_app
|
||||
from app.time_utils import now as bj_now, from_iso
|
||||
|
||||
|
||||
def _file_locked(method):
|
||||
"""装饰器:串行化 JSON 文件读-改-写,防并发双花/互相覆盖"""
|
||||
import functools
|
||||
@functools.wraps(method)
|
||||
def wrapper(*args, **kwargs):
|
||||
with TicketManager._file_lock:
|
||||
return method(*args, **kwargs)
|
||||
return wrapper
|
||||
|
||||
|
||||
class TicketManager:
|
||||
"""注册码管理器"""
|
||||
|
||||
TICKETS_FILE = 'tickets.json'
|
||||
|
||||
# 串行化 tickets.json 的"读-改-写",防同一注册码并发双激活
|
||||
_file_lock = threading.RLock() # RLock:锁内调用同类的其他加锁方法(如 use_ticket→verify_ticket)不会自死锁
|
||||
|
||||
@classmethod
|
||||
def _get_file_path(cls) -> str:
|
||||
"""获取 tickets.json 文件路径"""
|
||||
return os.path.join(current_app.root_path, '..', cls.TICKETS_FILE)
|
||||
|
||||
@classmethod
|
||||
def _load_data(cls) -> Dict:
|
||||
"""加载注册码数据(自动清理过期记录)"""
|
||||
file_path = cls._get_file_path()
|
||||
data = None
|
||||
if os.path.exists(file_path):
|
||||
try:
|
||||
with open(file_path, 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
except (json.JSONDecodeError, IOError):
|
||||
pass
|
||||
|
||||
if data is None:
|
||||
data = {
|
||||
'tickets': {}, # 注册码信息
|
||||
'user_tickets': {}, # 用户使用的注册码记录 {user_id: ticket_code}
|
||||
'orders': [] # 订单记录
|
||||
}
|
||||
|
||||
# 自动清理过期记录
|
||||
original_count = len(data.get('user_tickets', {}))
|
||||
data = cls._cleanup_expired_records(data)
|
||||
cleaned_count = original_count - len(data.get('user_tickets', {}))
|
||||
|
||||
# 如果有清理,保存更新后的数据
|
||||
if cleaned_count > 0:
|
||||
cls._save_data(data)
|
||||
|
||||
return data
|
||||
|
||||
@classmethod
|
||||
def _save_data(cls, data: Dict):
|
||||
"""保存注册码数据"""
|
||||
file_path = cls._get_file_path()
|
||||
with open(file_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=2)
|
||||
|
||||
@classmethod
|
||||
def _cleanup_expired_records(cls, data: Dict) -> Dict:
|
||||
"""清理过期记录:删除已不存在注册码对应的 user_tickets 记录"""
|
||||
valid_codes = set(data['tickets'].keys())
|
||||
user_tickets = data.get('user_tickets', {})
|
||||
|
||||
# 找出需要删除的记录(注册码已不存在)
|
||||
to_remove = []
|
||||
for user_id, user_ticket in user_tickets.items():
|
||||
code = user_ticket.get('code', '')
|
||||
clean_code = ''.join(c for c in code.upper() if c.isalnum())
|
||||
if clean_code not in valid_codes:
|
||||
to_remove.append(user_id)
|
||||
|
||||
# 删除过期记录
|
||||
for user_id in to_remove:
|
||||
del user_tickets[user_id]
|
||||
|
||||
if to_remove:
|
||||
data['user_tickets'] = user_tickets
|
||||
|
||||
return data
|
||||
|
||||
@classmethod
|
||||
@_file_locked
|
||||
def generate_ticket(cls, max_uses: int = 1, expiry_days: int = 365,
|
||||
created_by: str = 'admin', valid_days: int = None,
|
||||
school_ids=None) -> str:
|
||||
"""
|
||||
生成新的注册码(格式:XXXX-XXXX-XXXX-XXXX)
|
||||
|
||||
Args:
|
||||
max_uses: 最大使用次数
|
||||
expiry_days: 有效期(天);传 0 表示不预设到期时间(激活后计时模式)
|
||||
created_by: 创建者
|
||||
valid_days: 激活后计时模式下的有效天数(expiry_days 为 0 时生效)
|
||||
|
||||
Returns:
|
||||
生成的注册码(带横线格式)
|
||||
"""
|
||||
# 生成16位随机注册码(大写字母+数字)
|
||||
raw_code = ''.join(secrets.choice(string.ascii_uppercase + string.digits) for _ in range(16))
|
||||
|
||||
# 格式化为 XXXX-XXXX-XXXX-XXXX
|
||||
formatted_code = f"{raw_code[:4]}-{raw_code[4:8]}-{raw_code[8:12]}-{raw_code[12:16]}"
|
||||
|
||||
data = cls._load_data()
|
||||
data['tickets'][raw_code] = {
|
||||
'created_at': bj_now().isoformat(),
|
||||
'expiry_days': int(expiry_days or 0),
|
||||
'valid_days': int(valid_days) if valid_days else None,
|
||||
'activated_at': None,
|
||||
'max_uses': max_uses,
|
||||
'used_count': 0,
|
||||
'created_by': created_by,
|
||||
'school_ids': school_ids, # None = all schools, including future schools
|
||||
'is_active': True
|
||||
}
|
||||
cls._save_data(data)
|
||||
|
||||
return formatted_code
|
||||
|
||||
@classmethod
|
||||
def _ticket_expiry_date(cls, ticket: Dict):
|
||||
"""计算注册码到期时间;未激活(激活后计时模式)返回 None"""
|
||||
expiry_days = ticket.get('expiry_days', 0)
|
||||
if not expiry_days:
|
||||
return None
|
||||
base = from_iso(ticket['activated_at']) if ticket.get('activated_at') else from_iso(ticket['created_at'])
|
||||
return base + timedelta(days=expiry_days)
|
||||
|
||||
@classmethod
|
||||
@_file_locked
|
||||
def verify_ticket(cls, code: str) -> Tuple[bool, str]:
|
||||
"""
|
||||
验证注册码是否有效
|
||||
|
||||
Args:
|
||||
code: 注册码(支持带横线格式 XXXX-XXXX-XXXX-XXXX)
|
||||
|
||||
Returns:
|
||||
(是否有效, 错误信息)
|
||||
"""
|
||||
# 清理注册码:去掉所有非字母数字字符,转大写
|
||||
code = ''.join(c for c in code.upper() if c.isalnum())
|
||||
|
||||
if not code or len(code) != 16:
|
||||
return False, '注册码格式不正确'
|
||||
|
||||
data = cls._load_data()
|
||||
ticket = data['tickets'].get(code)
|
||||
|
||||
if not ticket:
|
||||
return False, '注册码不存在'
|
||||
|
||||
if not ticket.get('is_active', True):
|
||||
return False, '注册码已被禁用'
|
||||
|
||||
# 检查是否过期(expiry_days 为 0 表示激活后计时,未激活不过期)
|
||||
expiry_date = cls._ticket_expiry_date(ticket)
|
||||
if expiry_date is not None and bj_now() > expiry_date:
|
||||
return False, '注册码已过期'
|
||||
|
||||
# 检查使用次数
|
||||
if ticket['used_count'] >= ticket['max_uses']:
|
||||
return False, '注册码使用次数已达上限'
|
||||
|
||||
return True, '注册码有效'
|
||||
|
||||
@classmethod
|
||||
@_file_locked
|
||||
def use_ticket(cls, code: str, user_id: int, school_id: str = 'sdmu') -> Tuple[bool, str]:
|
||||
"""
|
||||
使用注册码
|
||||
|
||||
Args:
|
||||
code: 注册码(支持带横线格式)
|
||||
user_id: 使用用户ID
|
||||
|
||||
Returns:
|
||||
(是否成功, 错误信息)
|
||||
"""
|
||||
# 清理注册码
|
||||
code = ''.join(c for c in code.upper() if c.isalnum())
|
||||
|
||||
# 先验证
|
||||
is_valid, msg = cls.verify_ticket(code)
|
||||
if not is_valid:
|
||||
return False, msg
|
||||
|
||||
data = cls._load_data()
|
||||
allowed = data['tickets'][code].get('school_ids')
|
||||
if allowed is not None and school_id not in allowed:
|
||||
return False, '该注册码不适用于所选学校'
|
||||
|
||||
# 检查用户是否已经使用过注册码
|
||||
if str(user_id) in data['user_tickets']:
|
||||
return False, '您已经使用过注册码,请勿重复使用'
|
||||
|
||||
# 更新使用次数
|
||||
data['tickets'][code]['used_count'] += 1
|
||||
|
||||
# 激活后计时模式:首次使用时开始计时
|
||||
ticket = data['tickets'][code]
|
||||
if not ticket.get('expiry_days') and not ticket.get('activated_at'):
|
||||
ticket['activated_at'] = bj_now().isoformat()
|
||||
if ticket.get('valid_days'):
|
||||
ticket['expiry_days'] = ticket['valid_days']
|
||||
|
||||
# 记录用户使用
|
||||
data['user_tickets'][str(user_id)] = {
|
||||
'code': code,
|
||||
'used_at': bj_now().isoformat()
|
||||
}
|
||||
|
||||
cls._save_data(data)
|
||||
return True, '注册码使用成功'
|
||||
|
||||
@classmethod
|
||||
def get_ticket_info(cls, code: str) -> Optional[Dict]:
|
||||
"""获取注册码信息(支持带横线格式)"""
|
||||
code = ''.join(c for c in code.upper() if c.isalnum())
|
||||
data = cls._load_data()
|
||||
return data['tickets'].get(code)
|
||||
|
||||
@classmethod
|
||||
def get_user_ticket(cls, user_id: int) -> Optional[Dict]:
|
||||
"""获取用户使用的注册码信息"""
|
||||
data = cls._load_data()
|
||||
user_ticket = data['user_tickets'].get(str(user_id))
|
||||
if user_ticket:
|
||||
code = user_ticket['code']
|
||||
ticket_info = data['tickets'].get(code, {})
|
||||
return {
|
||||
'code': code,
|
||||
'used_at': user_ticket['used_at'],
|
||||
'created_at': ticket_info.get('created_at'),
|
||||
'expiry_days': ticket_info.get('expiry_days')
|
||||
}
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def list_tickets(cls) -> List[Dict]:
|
||||
"""列出所有注册码"""
|
||||
data = cls._load_data()
|
||||
tickets = []
|
||||
|
||||
# 构建注册码到用户的映射
|
||||
ticket_users = {} # {code: [username1, username2, ...]}
|
||||
for user_id, user_ticket in data.get('user_tickets', {}).items():
|
||||
code = user_ticket['code']
|
||||
if code not in ticket_users:
|
||||
ticket_users[code] = []
|
||||
ticket_users[code].append(user_id)
|
||||
|
||||
for code, info in data['tickets'].items():
|
||||
ticket = info.copy()
|
||||
ticket['code'] = code
|
||||
|
||||
# 计算过期时间(None 表示未激活/激活后计时模式)
|
||||
expiry_date = cls._ticket_expiry_date(info)
|
||||
ticket['pending_activation'] = expiry_date is None
|
||||
ticket['activated_at'] = info.get('activated_at')
|
||||
ticket['expiry_date'] = expiry_date.isoformat() if expiry_date else None
|
||||
ticket['expires_at'] = ticket['expiry_date'] # 兼容前端字段名
|
||||
ticket['is_expired'] = expiry_date is not None and bj_now() > expiry_date
|
||||
|
||||
# 兼容前端字段名
|
||||
ticket['uses'] = info.get('used_count', 0)
|
||||
ticket['used_by'] = ticket_users.get(code, [])
|
||||
ticket['enabled'] = info.get('is_active', True)
|
||||
|
||||
tickets.append(ticket)
|
||||
|
||||
# 按创建时间倒序
|
||||
tickets.sort(key=lambda x: x['created_at'], reverse=True)
|
||||
return tickets
|
||||
|
||||
@classmethod
|
||||
def disable_ticket(cls, code: str) -> bool:
|
||||
"""禁用注册码(支持带横线格式)"""
|
||||
code = ''.join(c for c in code.upper() if c.isalnum())
|
||||
data = cls._load_data()
|
||||
if code in data['tickets']:
|
||||
data['tickets'][code]['is_active'] = False
|
||||
cls._save_data(data)
|
||||
return True
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def enable_ticket(cls, code: str) -> bool:
|
||||
"""启用注册码(支持带横线格式)"""
|
||||
code = ''.join(c for c in code.upper() if c.isalnum())
|
||||
data = cls._load_data()
|
||||
if code in data['tickets']:
|
||||
data['tickets'][code]['is_active'] = True
|
||||
cls._save_data(data)
|
||||
return True
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def delete_ticket(cls, code: str) -> bool:
|
||||
"""删除注册码(支持带横线格式)"""
|
||||
code = ''.join(c for c in code.upper() if c.isalnum())
|
||||
data = cls._load_data()
|
||||
if code in data['tickets']:
|
||||
del data['tickets'][code]
|
||||
cls._save_data(data)
|
||||
return True
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def get_stats(cls) -> Dict:
|
||||
"""获取注册码统计信息"""
|
||||
data = cls._load_data()
|
||||
tickets = data['tickets']
|
||||
|
||||
total = len(tickets)
|
||||
used = sum(1 for t in tickets.values() if t['used_count'] > 0)
|
||||
active = sum(1 for t in tickets.values() if t.get('is_active', True))
|
||||
|
||||
# 计算过期数量(未激活的注册码不算过期)
|
||||
expired = 0
|
||||
pending = 0
|
||||
for t in tickets.values():
|
||||
expiry_date = cls._ticket_expiry_date(t)
|
||||
if expiry_date is None:
|
||||
pending += 1
|
||||
elif bj_now() > expiry_date:
|
||||
expired += 1
|
||||
|
||||
return {
|
||||
'total': total,
|
||||
'used': used,
|
||||
'unused': total - used,
|
||||
'active': active,
|
||||
'inactive': total - active,
|
||||
'expired': expired,
|
||||
'pending': pending,
|
||||
'available': total - used - expired - sum(1 for t in tickets.values() if not t.get('is_active', True))
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
统一时间工具模块 - 使用北京时间(Asia/Shanghai)存储为 ISO 格式
|
||||
"""
|
||||
from datetime import datetime, timezone, timedelta
|
||||
|
||||
# 北京时区(兼容 Python 3.8 及以下)
|
||||
BJ_TZ = timezone(timedelta(hours=8))
|
||||
|
||||
|
||||
def now() -> datetime:
|
||||
"""返回当前北京时间(带时区信息的 aware datetime)"""
|
||||
return datetime.now(BJ_TZ)
|
||||
|
||||
|
||||
def utc_now() -> datetime:
|
||||
"""返回当前 UTC 时间(兼容旧代码)"""
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def today() -> datetime:
|
||||
"""返回今天的日期(北京时间,零点)"""
|
||||
return datetime.now(BJ_TZ).replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
|
||||
|
||||
def to_iso(dt: datetime | None) -> str | None:
|
||||
"""将 datetime 转为 ISO 格式字符串(北京时间)"""
|
||||
if dt is None:
|
||||
return None
|
||||
if dt.tzinfo is None:
|
||||
# naive datetime,视为北京时间
|
||||
dt = dt.replace(tzinfo=BJ_TZ)
|
||||
return dt.isoformat()
|
||||
|
||||
|
||||
def from_iso(iso_str: str | None) -> datetime | None:
|
||||
"""从 ISO 格式字符串解析为北京时间(带时区)"""
|
||||
if not iso_str:
|
||||
return None
|
||||
dt = datetime.fromisoformat(iso_str.replace('Z', '+00:00'))
|
||||
if dt.tzinfo is None:
|
||||
dt = dt.replace(tzinfo=BJ_TZ)
|
||||
return dt
|
||||
|
||||
|
||||
def timestamp() -> float:
|
||||
"""返回当前时间戳(秒)"""
|
||||
return now().timestamp()
|
||||
|
||||
|
||||
def timestamp_ms() -> int:
|
||||
"""返回当前时间戳(毫秒)"""
|
||||
return int(now().timestamp() * 1000)
|
||||
@@ -0,0 +1,211 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
批量获取/更新教务系统 Session
|
||||
|
||||
用法:
|
||||
# 直接运行(默认读取 accounts.json,跳过未过期的 session)
|
||||
python app/update_session.py
|
||||
|
||||
# 指定账号文件(JSON 或 CSV)
|
||||
python app/update_session.py -f accounts.csv
|
||||
|
||||
# 单账号(密码从 accounts.json 自动读取)
|
||||
python app/update_session.py -u 学号
|
||||
|
||||
# 单账号(手动指定密码,优先级高于 accounts.json)
|
||||
python app/update_session.py -u 学号 -p 密码
|
||||
|
||||
# 强制全部重新登录(忽略 session 有效性检查)
|
||||
python app/update_session.py --force
|
||||
|
||||
accounts.json 格式(默认文件,放在脚本同目录):
|
||||
[
|
||||
{"username": "253051601132", "password": "your_password"},
|
||||
{"username": "253051601133", "password": "your_password"}
|
||||
]
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
# 添加项目根目录到路径
|
||||
BASE_DIR = Path(__file__).parent.parent
|
||||
sys.path.insert(0, str(BASE_DIR))
|
||||
|
||||
from app.url_manager import get_base_url
|
||||
from app.settings import SESSION_DIR, ACCOUNTS_FILE
|
||||
|
||||
from app.jwxt_login import JWXTLogin
|
||||
|
||||
BASE_DIR = Path(__file__).parent.parent
|
||||
|
||||
def save_session(username: str, login_obj: JWXTLogin):
|
||||
"""将登录后的 cookies 保存为 sessions/{username}.json(原子写,防读半截)"""
|
||||
from app.session_manager import SessionManager
|
||||
sf = SessionManager.get_session_file(username)
|
||||
data = {
|
||||
"cookies": dict(login_obj.session.cookies),
|
||||
"headers": dict(login_obj.session.headers),
|
||||
}
|
||||
try:
|
||||
from app.multi_line import _atomic_write_json
|
||||
_atomic_write_json(sf, data)
|
||||
except Exception:
|
||||
sf.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print(f" [已保存] {sf}")
|
||||
|
||||
def is_session_valid(username: str) -> bool:
|
||||
"""检查已有 session 是否仍然有效,有效返回 True"""
|
||||
import requests
|
||||
from app.session_manager import SessionManager
|
||||
sf = SessionManager.get_session_file(username)
|
||||
if not sf.exists():
|
||||
return False
|
||||
try:
|
||||
data = json.loads(sf.read_text(encoding="utf-8"))
|
||||
s = requests.Session()
|
||||
s.cookies.update(data.get("cookies", {}))
|
||||
r = s.get(get_base_url() + "/xtgl/index_initMenu.html", allow_redirects=False, timeout=8)
|
||||
return r.status_code == 200
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def login_one(username: str, password: str, max_retries: int = 3, force: bool = False) -> bool:
|
||||
"""对单个账号执行登录,成功则保存 session,返回是否成功"""
|
||||
# 先检查 session 是否还有效
|
||||
if not force:
|
||||
print(f"\n>>> 检查 session: {username}", end=" ... ", flush=True)
|
||||
if is_session_valid(username):
|
||||
print("有效,跳过")
|
||||
return True
|
||||
print("已过期,重新登录")
|
||||
|
||||
print(f" 正在登录: {username}")
|
||||
login = JWXTLogin()
|
||||
|
||||
for attempt in range(1, max_retries + 1):
|
||||
print(f" 第 {attempt}/{max_retries} 次尝试...")
|
||||
result = login.login(username, password)
|
||||
if isinstance(result, dict) and result.get('success'):
|
||||
save_session(username, login)
|
||||
print(f" [OK] {username} 登录成功")
|
||||
return True
|
||||
else:
|
||||
if attempt < max_retries:
|
||||
print(f" 登录失败,1 秒后重试...")
|
||||
time.sleep(1)
|
||||
login = JWXTLogin() # 重新初始化(刷新验证码 session)
|
||||
|
||||
print(f" [FAIL] {username} 登录失败,已达最大重试次数")
|
||||
return False
|
||||
|
||||
def load_accounts_from_file(filepath: str) -> list:
|
||||
"""从 JSON 或 CSV 文件加载账号列表"""
|
||||
p = Path(filepath)
|
||||
if not p.exists():
|
||||
print(f"[错误] 文件不存在: {filepath}")
|
||||
sys.exit(1)
|
||||
|
||||
accounts = []
|
||||
if p.suffix.lower() == ".json":
|
||||
data = json.loads(p.read_text(encoding="utf-8"))
|
||||
if not isinstance(data, list):
|
||||
print("[错误] JSON 文件格式应为列表: [{\"username\":\"...\",\"password\":\"...\"}]")
|
||||
sys.exit(1)
|
||||
for item in data:
|
||||
u = item.get("username", "").strip()
|
||||
pw = item.get("password", "").strip()
|
||||
if u:
|
||||
accounts.append((u, pw))
|
||||
elif p.suffix.lower() == ".csv":
|
||||
with open(p, encoding="utf-8-sig") as f:
|
||||
reader = csv.reader(f)
|
||||
for row in reader:
|
||||
if len(row) >= 2:
|
||||
u, pw = row[0].strip(), row[1].strip()
|
||||
if u:
|
||||
accounts.append((u, pw))
|
||||
else:
|
||||
print("[错误] 仅支持 .json 或 .csv 文件")
|
||||
sys.exit(1)
|
||||
|
||||
return accounts
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="批量获取/更新教务系统 Session")
|
||||
parser.add_argument("-u", "--username", help="学号(单账号模式)")
|
||||
parser.add_argument("-p", "--password", help="密码(可选,不填则交互式输入)")
|
||||
parser.add_argument("-f", "--file", help="账号文件路径(JSON 或 CSV,默认 accounts.json)")
|
||||
parser.add_argument("--retries", type=int, default=3, help="每账号最大重试次数(默认3)")
|
||||
parser.add_argument("--force", action="store_true", help="强制重新登录,忽略 session 有效性检查")
|
||||
args = parser.parse_args()
|
||||
|
||||
# ── 单账号模式 ─────────────────────────────────────────────
|
||||
if args.username:
|
||||
username = args.username.strip()
|
||||
|
||||
# 密码优先级:命令行 -p > accounts.json 查找 > 报错
|
||||
if args.password:
|
||||
password = args.password
|
||||
else:
|
||||
# 从默认账号文件里查
|
||||
accounts_file = args.file or str(ACCOUNTS_FILE)
|
||||
all_accounts = load_accounts_from_file(accounts_file) if Path(accounts_file).exists() else []
|
||||
lookup = {u: pw for u, pw in all_accounts}
|
||||
if username in lookup:
|
||||
password = lookup[username]
|
||||
print(f"[accounts.json] 已找到 {username} 的密码")
|
||||
else:
|
||||
print(f"[错误] 在 {accounts_file} 中未找到账号 {username},请用 -p 手动指定密码")
|
||||
sys.exit(1)
|
||||
|
||||
ok = login_one(username, password, max_retries=args.retries, force=args.force)
|
||||
sys.exit(0 if ok else 1)
|
||||
|
||||
# ── 批量模式(默认读 accounts.json,也可 -f 指定其他文件) ──
|
||||
accounts_file = args.file or str(ACCOUNTS_FILE)
|
||||
accounts = load_accounts_from_file(accounts_file)
|
||||
if not accounts:
|
||||
print("[错误] 账号文件为空")
|
||||
sys.exit(1)
|
||||
|
||||
print(f"共加载 {len(accounts)} 个账号,开始批量处理...\n")
|
||||
results = {"success": [], "skipped": [], "fail": []}
|
||||
|
||||
for username, password in accounts:
|
||||
if not password:
|
||||
print(f"[警告] {username} 密码为空,跳过")
|
||||
results["fail"].append(username)
|
||||
continue
|
||||
|
||||
# 未过期则 login_one 内部会直接返回 True(标记为 skipped)
|
||||
from app.session_manager import SessionManager
|
||||
sf = SessionManager.get_session_file(username)
|
||||
already_valid = (not args.force) and is_session_valid(username)
|
||||
|
||||
ok = login_one(username, password, max_retries=args.retries, force=args.force)
|
||||
if ok:
|
||||
if already_valid:
|
||||
results["skipped"].append(username)
|
||||
else:
|
||||
results["success"].append(username)
|
||||
else:
|
||||
results["fail"].append(username)
|
||||
time.sleep(0.5) # 避免请求过快
|
||||
|
||||
print("\n" + "=" * 50)
|
||||
total = len(accounts)
|
||||
print(f"批量处理完成(共 {total} 个账号):")
|
||||
print(f" 跳过(session 有效): {len(results['skipped'])}")
|
||||
print(f" 重新登录成功: {len(results['success'])}")
|
||||
print(f" 失败: {len(results['fail'])}")
|
||||
if results["fail"]:
|
||||
print(f" 失败账号: {', '.join(results['fail'])}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,204 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
URL 地址管理器
|
||||
|
||||
功能:
|
||||
1. 管理当前生效的教务系统 BASE_URL
|
||||
2. 并发测量多个地址的延迟
|
||||
3. 当延迟 > 10s 时自动切换到最优地址
|
||||
4. 切换后通知外部刷新 session(分两级:抢课中的用户立即刷,其余懒刷)
|
||||
|
||||
使用方式:
|
||||
from app.url_manager import get_base_url, switch_if_needed
|
||||
url = get_base_url()
|
||||
"""
|
||||
import time
|
||||
import logging
|
||||
import threading
|
||||
import concurrent.futures
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
import requests
|
||||
|
||||
from app.settings import BASE_URLS
|
||||
from app.school_manager import DEFAULT_SCHOOL_ID, school_urls
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ── 当前生效的 URL(启动时自动 picks 最优) ──
|
||||
_current_base_url: str = BASE_URLS[0] # 初始默认第一个
|
||||
_school_current_urls = {DEFAULT_SCHOOL_ID: BASE_URLS[0]}
|
||||
|
||||
# ── 线程级覆盖:用户固定线路时,其请求线程/抢课线程临时覆盖全局地址 ──
|
||||
_req_ctx = threading.local()
|
||||
|
||||
|
||||
def push_base_url(url: str):
|
||||
"""当前线程临时使用指定线路(请求结束/任务结束务必 pop_base_url)"""
|
||||
_req_ctx.override = url.rstrip('/')
|
||||
|
||||
|
||||
def pop_base_url():
|
||||
_req_ctx.override = None
|
||||
|
||||
|
||||
def push_school(school_id: str, preferred_url: str = None):
|
||||
"""Bind a request or worker thread to its owner's school."""
|
||||
_req_ctx.school_id = school_id or DEFAULT_SCHOOL_ID
|
||||
_req_ctx.override = preferred_url.rstrip('/') if preferred_url else None
|
||||
|
||||
|
||||
def pop_school():
|
||||
_req_ctx.school_id = None
|
||||
_req_ctx.override = None
|
||||
|
||||
|
||||
def current_school_id():
|
||||
return getattr(_req_ctx, 'school_id', None)
|
||||
|
||||
# 请求超时(秒)
|
||||
LATENCY_TIMEOUT = 5
|
||||
# 触发切换的延迟阈值(秒)
|
||||
SWITCH_THRESHOLD = 10
|
||||
|
||||
|
||||
# ══════════════════════════════════════════════════════════
|
||||
# 公开接口
|
||||
# ══════════════════════════════════════════════════════════
|
||||
|
||||
def get_base_url() -> str:
|
||||
"""返回当前线程生效的教务系统基础 URL(线程级覆盖优先于全局)"""
|
||||
override = getattr(_req_ctx, 'override', None)
|
||||
if override:
|
||||
return override
|
||||
return get_global_base_url(getattr(_req_ctx, 'school_id', None))
|
||||
|
||||
|
||||
def get_global_base_url(school_id=None) -> str:
|
||||
"""返回全局生效的 URL(忽略线程级覆盖,用于状态展示/后台切换逻辑)"""
|
||||
school_id = school_id or getattr(_req_ctx, 'school_id', None) or DEFAULT_SCHOOL_ID
|
||||
urls = school_urls(school_id)
|
||||
current = _school_current_urls.get(school_id)
|
||||
return current if current in urls else urls[0]
|
||||
|
||||
|
||||
def set_base_url(url: str, school_id=DEFAULT_SCHOOL_ID):
|
||||
"""设置当前生效的 URL(由 switch_if_needed 调用)"""
|
||||
global _current_base_url
|
||||
_current_base_url = url.rstrip('/')
|
||||
_school_current_urls[school_id] = _current_base_url
|
||||
logger.info(f"[url_manager] 当前地址切换为: {_current_base_url}")
|
||||
|
||||
|
||||
def get_all_urls(school_id=None) -> List[str]:
|
||||
"""返回所有可用的教务系统 URL"""
|
||||
return school_urls(school_id or getattr(_req_ctx, 'school_id', None) or DEFAULT_SCHOOL_ID)
|
||||
|
||||
|
||||
# ══════════════════════════════════════════════════════════
|
||||
# 延迟测量
|
||||
# ══════════════════════════════════════════════════════════
|
||||
|
||||
def measure_latency(url: str, timeout: int = LATENCY_TIMEOUT) -> Optional[float]:
|
||||
"""
|
||||
测量单个地址的延迟(秒)。
|
||||
发一个 GET 请求到首页,测量响应时间。
|
||||
超时或异常返回 None。
|
||||
"""
|
||||
test_url = url.rstrip('/') + "/xtgl/index_initMenu.html"
|
||||
start = time.time()
|
||||
try:
|
||||
r = requests.get(test_url, timeout=timeout, allow_redirects=False)
|
||||
elapsed = time.time() - start
|
||||
if r.status_code in (200, 302):
|
||||
return elapsed
|
||||
else:
|
||||
logger.debug(f"[url_manager] {url} 返回状态码 {r.status_code}")
|
||||
return None
|
||||
except requests.RequestException as e:
|
||||
logger.debug(f"[url_manager] {url} 延迟测量失败: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def pick_best_url(school_id=None) -> Tuple[str, float]:
|
||||
"""
|
||||
并发测量所有地址的延迟,返回 (最优URL, 延迟秒数)。
|
||||
|
||||
策略:
|
||||
- 用 ThreadPoolExecutor 并发发起 HEAD/GET 请求
|
||||
- 哪个先返回且成功就取哪个,不等慢的
|
||||
- 全部超时则保留当前地址
|
||||
"""
|
||||
school_id = school_id or getattr(_req_ctx, 'school_id', None) or DEFAULT_SCHOOL_ID
|
||||
urls = get_all_urls(school_id)
|
||||
best_url = get_global_base_url(school_id)
|
||||
best_latency = float('inf')
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=len(urls)) as executor:
|
||||
fut_to_url = {
|
||||
executor.submit(measure_latency, url): url
|
||||
for url in urls
|
||||
}
|
||||
for future in concurrent.futures.as_completed(fut_to_url, timeout=LATENCY_TIMEOUT + 1):
|
||||
url = fut_to_url[future]
|
||||
try:
|
||||
latency = future.result()
|
||||
if latency is not None and latency < best_latency:
|
||||
best_latency = latency
|
||||
best_url = url
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
if best_latency == float('inf'):
|
||||
# 全部超时,保持当前地址不变
|
||||
logger.warning("[url_manager] 所有地址均不可达,保留当前地址")
|
||||
return get_global_base_url(school_id), float('inf')
|
||||
|
||||
return best_url, best_latency
|
||||
|
||||
|
||||
# ══════════════════════════════════════════════════════════
|
||||
# 切换逻辑
|
||||
# ══════════════════════════════════════════════════════════
|
||||
|
||||
def switch_if_needed(school_id=DEFAULT_SCHOOL_ID) -> Tuple[bool, Optional[str], Optional[str]]:
|
||||
"""
|
||||
检测当前地址延迟,如果 >10s 则切换到最优地址。
|
||||
|
||||
返回:
|
||||
(switched: bool, old_url: str|None, new_url: str|None)
|
||||
switched=True 表示发生了切换
|
||||
"""
|
||||
old_url = get_global_base_url(school_id)
|
||||
|
||||
# 1. 测当前地址
|
||||
current_latency = measure_latency(old_url)
|
||||
if current_latency is not None and current_latency <= SWITCH_THRESHOLD:
|
||||
logger.info(f"[url_manager] 当前地址延迟 {current_latency:.1f}s,无需切换")
|
||||
return False, old_url, old_url
|
||||
|
||||
if current_latency is None:
|
||||
logger.info(f"[url_manager] 当前地址不可达,准备切换")
|
||||
else:
|
||||
logger.info(f"[url_manager] 当前地址延迟 {current_latency:.1f}s > {SWITCH_THRESHOLD}s,准备切换")
|
||||
|
||||
# 2. 测全部地址,取最优
|
||||
new_url, new_latency = pick_best_url(school_id)
|
||||
|
||||
if new_url == old_url:
|
||||
logger.info(f"[url_manager] 最优地址仍是当前地址,不切换")
|
||||
return False, old_url, old_url
|
||||
|
||||
# 3. 切换
|
||||
# 多线路模式开启时,先把目标线路的预热 session 原子换入各用户的
|
||||
# 生效 session 文件(本地文件复制,毫秒级),再切全局地址,
|
||||
# 避免切换后走 OCR 重登。
|
||||
try:
|
||||
from app.multi_line import prewarm_switch
|
||||
prewarm_switch(new_url, school_id=school_id)
|
||||
except Exception as e:
|
||||
logger.warning(f"[url_manager] 预热秒切不可用,走原逻辑: {e}")
|
||||
set_base_url(new_url, school_id)
|
||||
logger.info(f"[url_manager] 已切换: {old_url} → {new_url} (延迟 {new_latency:.1f}s)")
|
||||
return True, old_url, new_url
|
||||
@@ -0,0 +1,219 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
盲水印工具模块 — 截图表溯源
|
||||
|
||||
使用 blind-watermark (DWT-DCT-SVD) 在极弱噪点纹理中嵌入用户ID,
|
||||
页面作为 CSS 背景平铺。用户肉眼不可见,但截图包含水印,可解码溯源。
|
||||
|
||||
工作流:
|
||||
嵌入: 生成噪点纹理 -> 嵌入 "uid=xxx|ts=..." -> 返回 PNG 字节
|
||||
解码: 截图(PNG/JPG) -> extract -> 解析 uid
|
||||
"""
|
||||
import io
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
from blind_watermark import WaterMark, bw_notes
|
||||
|
||||
bw_notes.close()
|
||||
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
CARRIER_PATH = os.path.join(BASE_DIR, "static", "carrier.png")
|
||||
CARRIER_DARK_PATH = os.path.join(BASE_DIR, "static", "carrier_dark.png")
|
||||
CARRIER_SIZE = 256 # 纹理尺寸
|
||||
# 浅色载体:匹配 bg-gray-50 (#f9fafb ≈ 250)
|
||||
CARRIER_BASE = 248
|
||||
# 暗色载体:匹配 dark mode 背景 (#0a0a0a ≈ 10)
|
||||
CARRIER_BASE_DARK = 12
|
||||
# 噪点范围(±4,单像素差异 ≤1.5%,肉眼完全不可分辨)
|
||||
CARRIER_NOISE_RANGE = 4
|
||||
WM_BYTES = 96 # 水印最大字节数(UTF-8 编码后)
|
||||
WM_BITS = WM_BYTES * 8 # 768 bit — 使用 mode='bit' 精确编码,每字节固定 8 bit
|
||||
WM_SHAPE = WM_BITS # 兼容旧代码的引用名
|
||||
|
||||
|
||||
# ==================== 纹理生成 ====================
|
||||
|
||||
def _generate_noise_carrier(path: str, base: int, noise_range: int, seed: int = 42) -> str:
|
||||
"""内部:生成噪点纹理载体图。"""
|
||||
np.random.seed(seed)
|
||||
half_range = noise_range
|
||||
noise = np.random.randint(
|
||||
base - half_range, base + half_range + 1,
|
||||
(CARRIER_SIZE, CARRIER_SIZE), dtype=np.uint8
|
||||
)
|
||||
noise_rgb = cv2.cvtColor(noise, cv2.COLOR_GRAY2BGR)
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
cv2.imwrite(path, noise_rgb)
|
||||
return path
|
||||
|
||||
|
||||
def generate_carrier(path: str = None) -> str:
|
||||
"""生成浅色噪点纹理载体图(匹配 bg-gray-50 ≈ 250)。"""
|
||||
if path is None:
|
||||
path = CARRIER_PATH
|
||||
return _generate_noise_carrier(path, CARRIER_BASE, CARRIER_NOISE_RANGE)
|
||||
|
||||
|
||||
def generate_carrier_dark(path: str = None) -> str:
|
||||
"""生成暗色噪点纹理载体图(匹配 dark mode 背景 #0a0a0a ≈ 10)。"""
|
||||
if path is None:
|
||||
path = CARRIER_DARK_PATH
|
||||
return _generate_noise_carrier(path, CARRIER_BASE_DARK, CARRIER_NOISE_RANGE, seed=43)
|
||||
|
||||
|
||||
def ensure_carrier() -> str:
|
||||
"""确保浅色载体图存在,不存在则生成。"""
|
||||
if not os.path.exists(CARRIER_PATH):
|
||||
generate_carrier(CARRIER_PATH)
|
||||
return CARRIER_PATH
|
||||
|
||||
|
||||
def ensure_carrier_dark() -> str:
|
||||
"""确保暗色载体图存在,不存在则生成。"""
|
||||
if not os.path.exists(CARRIER_DARK_PATH):
|
||||
generate_carrier_dark(CARRIER_DARK_PATH)
|
||||
return CARRIER_DARK_PATH
|
||||
|
||||
|
||||
# ==================== 比特编解码(mode='bit') ====================
|
||||
|
||||
def _str_to_bits(s: str, num_bits: int = None) -> np.ndarray:
|
||||
"""字符串 → 固定宽度比特数组(UTF-8 编码,每字节精确 8 bit)。
|
||||
|
||||
与 blind-watermark mode='str' 不同,mode='str' 使用
|
||||
bin(int(hex(utf8_bytes))) 丢弃前导零,导致可变比特宽度;
|
||||
本函数保证每字节固定 8 bit,中文/ASCII 统一对待。
|
||||
"""
|
||||
if num_bits is None:
|
||||
num_bits = WM_BITS
|
||||
content_bytes = s.encode('utf-8')
|
||||
max_bytes = num_bits // 8
|
||||
if len(content_bytes) > max_bytes:
|
||||
# 截断:留最后一字节给截断标记
|
||||
content_bytes = content_bytes[:max_bytes - 1] + b'.'
|
||||
content_bytes = content_bytes.ljust(max_bytes, b'\x00')
|
||||
bits = []
|
||||
for b in content_bytes:
|
||||
bits.extend(int(bit) for bit in format(b, '08b'))
|
||||
return np.array(bits[:num_bits], dtype=bool)
|
||||
|
||||
|
||||
def _bits_to_str(bits: np.ndarray) -> str:
|
||||
"""比特数组 → UTF-8 字符串(去尾部空字节)。"""
|
||||
byte_vals = []
|
||||
for i in range(0, len(bits), 8):
|
||||
byte_bits = bits[i:i + 8]
|
||||
if len(byte_bits) < 8:
|
||||
break
|
||||
val = int(''.join(str(int(b)) for b in byte_bits), 2)
|
||||
byte_vals.append(val)
|
||||
return bytes(byte_vals).decode('utf-8', errors='replace').rstrip('\x00')
|
||||
|
||||
|
||||
# ==================== 嵌入 ====================
|
||||
|
||||
def _embed_into_carrier(user_identifier: str, carrier_path: str,
|
||||
password_img: int = 1, password_wm: int = 1) -> bytes:
|
||||
"""内部:将水印嵌入指定载体(使用 mode='bit' 避免中文乱码)。"""
|
||||
bits = _str_to_bits(user_identifier, WM_BITS)
|
||||
|
||||
bwm = WaterMark(password_img=password_img, password_wm=password_wm)
|
||||
bwm.read_img(carrier_path)
|
||||
bwm.read_wm(bits, mode="bit")
|
||||
|
||||
tmp_path = os.path.join(os.path.dirname(carrier_path), "_wm_tmp.png")
|
||||
bwm.embed(tmp_path)
|
||||
|
||||
img = cv2.imread(tmp_path)
|
||||
compact_path = tmp_path + ".compact.png"
|
||||
cv2.imwrite(compact_path, img, [cv2.IMWRITE_PNG_COMPRESSION, 9])
|
||||
with open(compact_path, "rb") as f:
|
||||
data = f.read()
|
||||
return data
|
||||
|
||||
|
||||
def embed_watermark(user_identifier: str, password_img: int = 1, password_wm: int = 1) -> bytes:
|
||||
"""将用户标识嵌入浅色载体纹理,返回带水印的 PNG 字节。"""
|
||||
return _embed_into_carrier(user_identifier, ensure_carrier(),
|
||||
password_img, password_wm)
|
||||
|
||||
|
||||
def embed_watermark_dark(user_identifier: str, password_img: int = 1, password_wm: int = 1) -> bytes:
|
||||
"""将用户标识嵌入暗色载体纹理,返回带水印的 PNG 字节。"""
|
||||
return _embed_into_carrier(user_identifier, ensure_carrier_dark(),
|
||||
password_img, password_wm)
|
||||
|
||||
|
||||
# ==================== 解码 ====================
|
||||
|
||||
def extract_watermark(screenshot_path: str, password_img: int = 1, password_wm: int = 1) -> dict:
|
||||
"""从截图中提取盲水印(使用 mode='bit' 支持中文)。
|
||||
|
||||
Args:
|
||||
screenshot_path: 截图文件路径
|
||||
password_img: 图片密钥
|
||||
password_wm: 水印密钥
|
||||
|
||||
Returns:
|
||||
dict:
|
||||
success: bool
|
||||
raw: 提取到的原始字符串(去尾部空字节)
|
||||
info: 解析后的 dict (u, n, m, j, t, i 等字段)
|
||||
"""
|
||||
try:
|
||||
result = {"success": False, "raw": "", "info": {}}
|
||||
|
||||
img = cv2.imread(screenshot_path)
|
||||
if img is None:
|
||||
result["raw"] = f"无法读取图片: {screenshot_path}"
|
||||
return result
|
||||
|
||||
h, w = img.shape[:2]
|
||||
|
||||
# 从截图边角裁出多个 CARRIER_SIZE×CARRIER_SIZE 块尝试解码
|
||||
corners = [
|
||||
("top_left", 0, 0),
|
||||
("top_right", max(0, w - CARRIER_SIZE), 0),
|
||||
("bottom_left", 0, max(0, h - CARRIER_SIZE)),
|
||||
("bottom_right", max(0, w - CARRIER_SIZE), max(0, h - CARRIER_SIZE)),
|
||||
]
|
||||
|
||||
for label, x, y in corners:
|
||||
if x + CARRIER_SIZE > w or y + CARRIER_SIZE > h:
|
||||
continue
|
||||
crop = img[y:y + CARRIER_SIZE, x:x + CARRIER_SIZE]
|
||||
tmp = os.path.join(os.path.dirname(CARRIER_PATH), f"_decode_{label}.png")
|
||||
cv2.imwrite(tmp, crop)
|
||||
|
||||
try:
|
||||
bwm = WaterMark(password_img=password_img, password_wm=password_wm)
|
||||
extracted_bits = bwm.extract(tmp, wm_shape=WM_BITS, mode="bit")
|
||||
raw = _bits_to_str(extracted_bits)
|
||||
if raw and len(raw.strip()) >= 2:
|
||||
result["success"] = True
|
||||
result["raw"] = raw.strip()
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
# 解析 key=value|key=value 格式
|
||||
for part in result["raw"].split("|"):
|
||||
if "=" in part:
|
||||
k, v = part.split("=", 1)
|
||||
result["info"][k.strip()] = v.strip()
|
||||
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
return {"success": False, "raw": str(e), "info": {}}
|
||||
|
||||
|
||||
# ==================== 首次导入时确保载体存在 ====================
|
||||
|
||||
ensure_carrier()
|
||||
ensure_carrier_dark()
|
||||
@@ -0,0 +1,358 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
教务系统选课后端 API 服务
|
||||
|
||||
基于 Flask 的示例后端,集成 xk_api.CourseAPI 模块
|
||||
|
||||
使用方法:
|
||||
pip install flask flask-cors
|
||||
python xk_backend.py
|
||||
|
||||
然后访问:
|
||||
GET /api/status?user=253051601132
|
||||
GET /api/tabs?user=253051601132
|
||||
GET /api/courses?user=253051601132&search=体育&kklxdm=03
|
||||
GET /api/search_full?user=253051601132&search=体育&kklxdm=03 ← 推荐,搜索+教学班一步到位
|
||||
GET /api/chosen?user=253051601132
|
||||
POST /api/add (form: user, jxb_id, do_jxb_id, kch_id, kklxdm, jxbzls)
|
||||
POST /api/drop (form: user, jxb_id, do_jxb_id, kch_id, kklxdm, jxbzls)
|
||||
"""
|
||||
|
||||
from flask import Flask, request, jsonify
|
||||
from flask_cors import CORS
|
||||
import json
|
||||
from app.xk_api import CourseAPI
|
||||
|
||||
|
||||
app = Flask(__name__)
|
||||
CORS(app) # 允许跨域请求
|
||||
|
||||
|
||||
# ── 错误处理 ────────────────────────────────────────
|
||||
@app.errorhandler(400)
|
||||
def bad_request(error):
|
||||
return jsonify({"success": False, "message": "Bad Request"}), 400
|
||||
|
||||
|
||||
@app.errorhandler(404)
|
||||
def not_found(error):
|
||||
return jsonify({"success": False, "message": "Not Found"}), 404
|
||||
|
||||
|
||||
@app.errorhandler(500)
|
||||
def internal_error(error):
|
||||
return jsonify({"success": False, "message": str(error)}), 500
|
||||
|
||||
|
||||
# ── 工具函数 ────────────────────────────────────────
|
||||
def get_user_param() -> str:
|
||||
"""从请求参数中获取用户名(学号)"""
|
||||
user = request.args.get("user") or request.form.get("user")
|
||||
if not user:
|
||||
raise ValueError("缺少必要参数: user (学号)")
|
||||
return user
|
||||
|
||||
|
||||
# ── API 端点 ────────────────────────────────────────
|
||||
|
||||
@app.route("/", methods=["GET"])
|
||||
def index():
|
||||
"""API 主页"""
|
||||
return jsonify({
|
||||
"service": "教务系统选课 API",
|
||||
"version": "2.0",
|
||||
"endpoints": {
|
||||
"GET /api/status": "查询选课状态",
|
||||
"GET /api/tabs": "获取所有课程类型标签页(kklxdm 列表)",
|
||||
"GET /api/courses": "分页查询可选课程(不展开教学班)",
|
||||
"GET /api/search_full": "搜索课程并展开所有教学班(推荐)",
|
||||
"GET /api/chosen": "查询已选课程",
|
||||
"POST /api/add": "选课(需要 jxb_id + do_jxb_id + kch_id)",
|
||||
"POST /api/drop": "退课(同上)",
|
||||
},
|
||||
"params": {
|
||||
"user": "学号(所有接口必需)",
|
||||
"kklxdm": "课程类型代码,如 01/02/03(可选,空=默认第一个 tab)",
|
||||
"search/q": "搜索关键词",
|
||||
"jxb_id": "教学班ID(选课/退课必需)",
|
||||
"do_jxb_id": "加密ID/志愿场次ID(选课/退课必需,可空串)",
|
||||
"kch_id": "课程ID(选课/退课必需)",
|
||||
"jxbzls": "教学班总量/志愿序号(选课/退课,默认0)",
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@app.route("/api/status", methods=["GET"])
|
||||
def api_status():
|
||||
"""
|
||||
查询选课状态
|
||||
|
||||
GET /api/status?user=253051601132
|
||||
"""
|
||||
try:
|
||||
user = get_user_param()
|
||||
api = CourseAPI(user)
|
||||
result = api.get_status()
|
||||
return jsonify(result)
|
||||
except FileNotFoundError as e:
|
||||
return jsonify({"success": False, "message": str(e)}), 404
|
||||
except ValueError as e:
|
||||
return jsonify({"success": False, "message": str(e)}), 400
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "message": f"Error: {str(e)}"}), 500
|
||||
|
||||
|
||||
@app.route("/api/tabs", methods=["GET"])
|
||||
def api_tabs():
|
||||
"""
|
||||
获取所有课程类型标签页列表(kklxdm + kklxmc)。
|
||||
|
||||
GET /api/tabs?user=253051601132
|
||||
|
||||
响应:
|
||||
{
|
||||
"success": bool,
|
||||
"tabs": [
|
||||
{"kklxdm": "01", "kklxmc": "通识必修课", "xkkz_id": "...", ...},
|
||||
{"kklxdm": "03", "kklxmc": "通识选修网络课", ...},
|
||||
...
|
||||
],
|
||||
"message": str
|
||||
}
|
||||
|
||||
前端可用此接口替代硬编码的 course_tabs 列表。
|
||||
"""
|
||||
try:
|
||||
user = get_user_param()
|
||||
api = CourseAPI(user)
|
||||
result = api.get_tab_list()
|
||||
return jsonify(result)
|
||||
except FileNotFoundError as e:
|
||||
return jsonify({"success": False, "message": str(e), "tabs": []}), 404
|
||||
except ValueError as e:
|
||||
return jsonify({"success": False, "message": str(e), "tabs": []}), 400
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "message": f"Error: {str(e)}", "tabs": []}), 500
|
||||
|
||||
|
||||
@app.route("/api/courses", methods=["GET"])
|
||||
def api_courses():
|
||||
"""
|
||||
查询可选课程(仅课程列表,不展开教学班)。
|
||||
如需同时拿教学班详情,请用 /api/search_full。
|
||||
|
||||
GET /api/courses?user=253051601132&search=体育&kklxdm=02&page_size=50
|
||||
"""
|
||||
try:
|
||||
user = get_user_param()
|
||||
keyword = request.args.get("search", "")
|
||||
kklxdm = request.args.get("kklxdm", "")
|
||||
try:
|
||||
page_size = int(request.args.get("page_size", "50"))
|
||||
except ValueError:
|
||||
page_size = 50
|
||||
|
||||
api = CourseAPI(user)
|
||||
result = api.query_courses(keyword=keyword, kklxdm=kklxdm, page_size=page_size)
|
||||
return jsonify(result)
|
||||
except FileNotFoundError as e:
|
||||
return jsonify({"success": False, "message": str(e), "total": 0, "courses": []}), 404
|
||||
except ValueError as e:
|
||||
return jsonify({"success": False, "message": str(e), "total": 0, "courses": []}), 400
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "message": f"Error: {str(e)}", "total": 0, "courses": []}), 500
|
||||
|
||||
|
||||
@app.route("/api/search_full", methods=["GET"])
|
||||
def api_search_full():
|
||||
"""
|
||||
搜索课程并自动展开所有教学班(推荐接口)。
|
||||
|
||||
对齐 webdriver.py 的完整流程:
|
||||
load_courses_by_search → extract_all_courses → chooseCourseZzxk 参数
|
||||
|
||||
GET /api/search_full?user=253051601132&search=英语&kklxdm=03
|
||||
|
||||
响应:
|
||||
{
|
||||
"success": bool,
|
||||
"is_open": bool,
|
||||
"kklxdm": str,
|
||||
"kklxmc": str, # Tab名称,如"通识选修网络课"
|
||||
"total": int,
|
||||
"courses": [
|
||||
{
|
||||
"kch_id": str,
|
||||
"kcmc": str, # 课程名称
|
||||
"xf": str, # 学分
|
||||
"has_vacancy": bool,
|
||||
"jxb_count": int,
|
||||
"jxbs": [
|
||||
{
|
||||
"jxb_id": str, # ← 选课时传 jxb_id
|
||||
"do_jxb_id": str, # ← 选课时传 do_jxb_id(可空)
|
||||
"jxbzls": str, # ← 选课时传 jxbzls
|
||||
"sksj": str, # 上课时间(如"周一3-4节;周三1-2节")
|
||||
"jsxx": str, # 教师信息
|
||||
"yxzrs": str, # 已选人数(实时)
|
||||
"jxbrl": str, # 容量
|
||||
"can_select": bool, # 是否有余量
|
||||
}, ...
|
||||
]
|
||||
}, ...
|
||||
],
|
||||
"message": str
|
||||
}
|
||||
"""
|
||||
try:
|
||||
user = get_user_param()
|
||||
keyword = request.args.get("search", "") or request.args.get("q", "")
|
||||
kklxdm = request.args.get("kklxdm", "")
|
||||
try:
|
||||
page_size = int(request.args.get("page_size", "100"))
|
||||
except ValueError:
|
||||
page_size = 100
|
||||
|
||||
api = CourseAPI(user)
|
||||
result = api.search_with_jxb(keyword=keyword, kklxdm=kklxdm, page_size=page_size)
|
||||
return jsonify(result)
|
||||
except FileNotFoundError as e:
|
||||
return jsonify({"success": False, "message": str(e), "total": 0, "courses": []}), 404
|
||||
except ValueError as e:
|
||||
return jsonify({"success": False, "message": str(e), "total": 0, "courses": []}), 400
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "message": f"Error: {str(e)}", "total": 0, "courses": []}), 500
|
||||
|
||||
|
||||
@app.route("/api/search", methods=["GET"])
|
||||
def api_search():
|
||||
"""
|
||||
搜索可选课程(便利端点,等同于 /api/courses?search=...)
|
||||
"""
|
||||
try:
|
||||
user = get_user_param()
|
||||
keyword = request.args.get("q", "") or request.args.get("search", "")
|
||||
kklxdm = request.args.get("kklxdm", "")
|
||||
api = CourseAPI(user)
|
||||
result = api.search_courses(keyword=keyword, kklxdm=kklxdm)
|
||||
return jsonify(result)
|
||||
except FileNotFoundError as e:
|
||||
return jsonify({"success": False, "message": str(e), "total": 0, "courses": []}), 404
|
||||
except ValueError as e:
|
||||
return jsonify({"success": False, "message": str(e), "total": 0, "courses": []}), 400
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "message": f"Error: {str(e)}", "total": 0, "courses": []}), 500
|
||||
|
||||
|
||||
@app.route("/api/chosen", methods=["GET"])
|
||||
def api_chosen():
|
||||
"""
|
||||
查询已选课程
|
||||
|
||||
GET /api/chosen?user=253051601132
|
||||
"""
|
||||
try:
|
||||
user = get_user_param()
|
||||
api = CourseAPI(user)
|
||||
result = api.get_chosen_courses()
|
||||
return jsonify(result)
|
||||
except FileNotFoundError as e:
|
||||
return jsonify({"success": False, "message": str(e), "total": 0, "courses": []}), 404
|
||||
except ValueError as e:
|
||||
return jsonify({"success": False, "message": str(e), "total": 0, "courses": []}), 400
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "message": f"Error: {str(e)}", "total": 0, "courses": []}), 500
|
||||
|
||||
|
||||
@app.route("/api/add", methods=["POST", "GET"])
|
||||
def api_add():
|
||||
"""
|
||||
选课操作(对齐 webdriver 的 chooseCourseZzxk 参数)
|
||||
|
||||
POST /api/add
|
||||
form data:
|
||||
user = 253051601132 (学号)
|
||||
jxb_id = ... (教学班ID,来自 search_full 的 jxbs[i].jxb_id)
|
||||
do_jxb_id = ... (加密ID,来自 jxbs[i].do_jxb_id,可空串)
|
||||
kch_id = ... (课程ID,来自 courses[i].kch_id)
|
||||
kklxdm = 03 (课程类型代码,来自 courses[i].kklxdm)
|
||||
jxbzls = 0 (志愿序号,来自 jxbs[i].jxbzls,默认"0")
|
||||
|
||||
响应: {"success": bool, "jxb_id": str, "message": str}
|
||||
"""
|
||||
try:
|
||||
user = get_user_param()
|
||||
jxb_id = request.form.get("jxb_id") or request.args.get("jxb_id")
|
||||
do_jxb_id = request.form.get("do_jxb_id") or request.args.get("do_jxb_id", "")
|
||||
kch_id = request.form.get("kch_id") or request.args.get("kch_id", "")
|
||||
kklxdm = request.form.get("kklxdm") or request.args.get("kklxdm", "")
|
||||
jxbzls = request.form.get("jxbzls") or request.args.get("jxbzls", "0")
|
||||
|
||||
if not jxb_id:
|
||||
raise ValueError("缺少必要参数: jxb_id")
|
||||
|
||||
api = CourseAPI(user)
|
||||
result = api.add_course(
|
||||
jxb_id=jxb_id,
|
||||
do_jxb_id=do_jxb_id,
|
||||
kch_id=kch_id,
|
||||
jxbzls=jxbzls,
|
||||
kklxdm=kklxdm,
|
||||
)
|
||||
return jsonify(result)
|
||||
except FileNotFoundError as e:
|
||||
return jsonify({"success": False, "message": str(e)}), 404
|
||||
except ValueError as e:
|
||||
return jsonify({"success": False, "message": str(e)}), 400
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "message": f"Error: {str(e)}"}), 500
|
||||
|
||||
|
||||
@app.route("/api/drop", methods=["POST", "GET"])
|
||||
def api_drop():
|
||||
"""
|
||||
退课操作
|
||||
|
||||
POST /api/drop
|
||||
form data: 同 /api/add
|
||||
|
||||
响应: {"success": bool, "jxb_id": str, "message": str}
|
||||
"""
|
||||
try:
|
||||
user = get_user_param()
|
||||
jxb_id = request.form.get("jxb_id") or request.args.get("jxb_id")
|
||||
do_jxb_id = request.form.get("do_jxb_id") or request.args.get("do_jxb_id", "")
|
||||
kch_id = request.form.get("kch_id") or request.args.get("kch_id", "")
|
||||
kklxdm = request.form.get("kklxdm") or request.args.get("kklxdm", "")
|
||||
jxbzls = request.form.get("jxbzls") or request.args.get("jxbzls", "0")
|
||||
|
||||
if not jxb_id:
|
||||
raise ValueError("缺少必要参数: jxb_id")
|
||||
|
||||
api = CourseAPI(user)
|
||||
result = api.drop_course(
|
||||
jxb_id=jxb_id,
|
||||
do_jxb_id=do_jxb_id,
|
||||
kch_id=kch_id,
|
||||
jxbzls=jxbzls,
|
||||
kklxdm=kklxdm,
|
||||
)
|
||||
return jsonify(result)
|
||||
except FileNotFoundError as e:
|
||||
return jsonify({"success": False, "message": str(e)}), 404
|
||||
except ValueError as e:
|
||||
return jsonify({"success": False, "message": str(e)}), 400
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "message": f"Error: {str(e)}"}), 500
|
||||
|
||||
|
||||
# ── 启动服务 ────────────────────────────────────────
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("启动教务系统选课后端服务...")
|
||||
print("监听地址: http://localhost:5000")
|
||||
print("API 文档: http://localhost:5000/")
|
||||
print()
|
||||
app.run(host="0.0.0.0", port=5000, debug=True)
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
教务系统选课工具
|
||||
用法:
|
||||
python xk_tool.py -u 253051601132 list # 查询可选课程(需在选课时间内)
|
||||
python xk_tool.py -u 253051601132 chosen # 查询已选课程
|
||||
python xk_tool.py -u 253051601132 add <jxb_id> # 选课
|
||||
python xk_tool.py -u 253051601132 drop <jxb_id> # 退课
|
||||
python xk_tool.py -u 253051601132 search <课程名> # 搜索课程
|
||||
|
||||
说明:
|
||||
- 查询可选课程、选课、退课 均需在学校开放的选课时间段内操作
|
||||
- 查询已选课程随时可查
|
||||
- jxb_id 可从 list/search 命令的输出中获取
|
||||
"""
|
||||
|
||||
import sys
|
||||
import json
|
||||
import re
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
# 添加项目根目录到路径
|
||||
BASE_DIR = Path(__file__).parent.parent
|
||||
sys.path.insert(0, str(BASE_DIR))
|
||||
|
||||
from app.url_manager import get_base_url
|
||||
from app.settings import GNMKDM, SESSION_DIR
|
||||
|
||||
import requests
|
||||
|
||||
# ── 路径配置 ──────────────────────────────────────────────
|
||||
|
||||
# ── Session 管理 ──────────────────────────────────────────
|
||||
def load_session(username: str) -> requests.Session:
|
||||
from app.session_manager import SessionManager
|
||||
sf = SessionManager.get_session_file(username)
|
||||
if not sf.exists():
|
||||
print(f"[ERROR] session 文件不存在: {sf}")
|
||||
print("请先运行: python app/update_session.py -u", username)
|
||||
sys.exit(1)
|
||||
|
||||
data = json.loads(sf.read_text(encoding="utf-8"))
|
||||
session = requests.Session()
|
||||
session.cookies.update(data.get("cookies", {}))
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
|
||||
"Referer": get_base_url() + "/xtgl/index_initMenu.html",
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
})
|
||||
return session
|
||||
|
||||
def check_session(session: requests.Session, username: str) -> bool:
|
||||
"""检测 session 是否有效,无效则提示重新登录"""
|
||||
r = session.get(get_base_url() + "/xtgl/index_initMenu.html", allow_redirects=False)
|
||||
if r.status_code == 302:
|
||||
print(f"[WARN] session 已过期,请先执行: python app/update_session.py -u {username}")
|
||||
return False
|
||||
return True
|
||||
|
||||
# ── 工具函数 ──────────────────────────────────────────────
|
||||
def get_hidden_val(html: str, field_id: str) -> str:
|
||||
"""从 HTML 里提取 hidden input 的 value"""
|
||||
m = re.search(r'id="' + re.escape(field_id) + r'"[^>]*value="([^"]*)"', html)
|
||||
if not m:
|
||||
m = re.search(r'value="([^"]*)"[^>]*id="' + re.escape(field_id) + r'"', html)
|
||||
return m.group(1) if m else ""
|
||||
|
||||
def strip_tags(html: str) -> str:
|
||||
return re.sub(r"<[^>]+>", "", html).strip()
|
||||
|
||||
def get_index_params(session: requests.Session) -> dict:
|
||||
"""
|
||||
访问选课入口页,获取基础参数。
|
||||
选课时间外:iskxk=0,firstXkkzId 等为空。
|
||||
选课时间内:iskxk=1,firstXkkzId 等有值。
|
||||
"""
|
||||
r = session.get(
|
||||
get_base_url() + "/xsxk/zzxkyzb_cxZzxkYzbIndex.html",
|
||||
params={"gnmkdm": GNMKDM, "layout": "default"},
|
||||
)
|
||||
session.headers["Referer"] = r.url
|
||||
html = r.text
|
||||
|
||||
# 检查是否在选课时间内
|
||||
iskxk = get_hidden_val(html, "iskxk")
|
||||
|
||||
# 提取公共参数
|
||||
params = {
|
||||
"iskxk": iskxk,
|
||||
"csrftoken": get_hidden_val(html, "csrftoken"),
|
||||
"gnmkdm": GNMKDM,
|
||||
"xkkz_id": get_hidden_val(html, "firstXkkzId"),
|
||||
"kklxdm": get_hidden_val(html, "firstKklxdm"),
|
||||
"kklxmc": get_hidden_val(html, "firstKklxmc"),
|
||||
"njdm_id": get_hidden_val(html, "firstNjdmId"),
|
||||
"zyh_id": get_hidden_val(html, "firstZyhId"),
|
||||
"xkxnm": get_hidden_val(html, "xkxnm"),
|
||||
"xkxqm": get_hidden_val(html, "xkxqm"),
|
||||
"sessionUserKey": get_hidden_val(html, "sessionUserKey"),
|
||||
}
|
||||
|
||||
# 若 first* 参数为空但页面有其他赋值方式(备用正则)
|
||||
if not params["xkkz_id"]:
|
||||
m = re.search(r'firstXkkzId[^=]*=[^"]*"([^"]+)"', html)
|
||||
if m:
|
||||
params["xkkz_id"] = m.group(1)
|
||||
|
||||
return params, html
|
||||
|
||||
# ── 核心操作 ──────────────────────────────────────────────
|
||||
|
||||
def cmd_status(session: requests.Session):
|
||||
"""检查当前是否在选课时间,并显示基本信息"""
|
||||
params, html = get_index_params(session)
|
||||
print(f"选课状态: {'[开放中]' if params['iskxk'] == '1' else '[未开放]'}")
|
||||
print(f"学年: {params['xkxnm']} 学期: {params['xkxqm']}")
|
||||
print(f"xkkz_id: {params['xkkz_id']}")
|
||||
print(f"kklxdm: {params['kklxdm']} ({params['kklxmc']})")
|
||||
|
||||
# 提取页面提示文字
|
||||
panels = re.findall(
|
||||
r'<div[^>]+class="[^"]*panel-body[^"]*"[^>]*>(.*?)</div>', html, re.DOTALL
|
||||
)
|
||||
for p in panels[:3]:
|
||||
txt = strip_tags(p)
|
||||
if txt:
|
||||
print(f"提示: {txt[:200]}")
|
||||
|
||||
def cmd_list(session: requests.Session, keyword: str = "", page_size: int = 20):
|
||||
"""查询可选课程列表(需在选课时间内)"""
|
||||
params, _ = get_index_params(session)
|
||||
|
||||
if params["iskxk"] != "1":
|
||||
print("[ERROR] 当前不在选课时间,无法查询可选课程")
|
||||
print("提示:可以用 'python xk_tool.py -u <用户名> chosen' 查询已选课程")
|
||||
return
|
||||
|
||||
query = {
|
||||
"xkkz_id": params["xkkz_id"],
|
||||
"kklxdm": params["kklxdm"],
|
||||
"xklc": "",
|
||||
"zyh_id": params["zyh_id"],
|
||||
"njdm_id": params["njdm_id"],
|
||||
"xkxnm": params["xkxnm"],
|
||||
"xkxqm": params["xkxqm"],
|
||||
"gnmkdm": GNMKDM,
|
||||
"kspage": "0",
|
||||
"jspage": str(page_size),
|
||||
"kcmc": keyword, # 课程名称关键词
|
||||
}
|
||||
|
||||
r = session.post(
|
||||
get_base_url() + "/xsxk/zzxkyzb_cxZzxkYzbPartDisplay.html", data=query
|
||||
)
|
||||
if r.status_code != 200:
|
||||
print(f"[ERROR] 请求失败: {r.status_code}")
|
||||
return
|
||||
|
||||
try:
|
||||
data = r.json()
|
||||
except Exception:
|
||||
print("[ERROR] 响应非 JSON:", r.text[:300])
|
||||
return
|
||||
|
||||
courses = data.get("tmpList", [])
|
||||
if not courses:
|
||||
print("没有找到可选课程" + (f"(关键词: {keyword})" if keyword else ""))
|
||||
return
|
||||
|
||||
print(f"\n找到 {len(courses)} 门课程:\n")
|
||||
print(f"{'序号':<4} {'课程名称':<24} {'教学班':<20} {'教师':<12} "
|
||||
f"{'学分':<6} {'已选/容量':<12} {'jxb_id'}")
|
||||
print("-" * 110)
|
||||
for i, c in enumerate(courses, 1):
|
||||
name = c.get("kcmc", "")[:22]
|
||||
cls_ = c.get("jxbmc", "")[:18]
|
||||
teacher = c.get("jsxm", "")[:10]
|
||||
credit = c.get("xf", "")
|
||||
cap = f"{c.get('yxrs','?')}/{c.get('jxbrs','?')}"
|
||||
jxb_id = c.get("jxb_id", "")
|
||||
print(f"{i:<4} {name:<24} {cls_:<20} {teacher:<12} {credit:<6} {cap:<12} {jxb_id}")
|
||||
|
||||
def cmd_search(session: requests.Session, keyword: str):
|
||||
"""搜索可选课程"""
|
||||
cmd_list(session, keyword=keyword, page_size=50)
|
||||
|
||||
def cmd_chosen(session: requests.Session):
|
||||
"""查询已选课程"""
|
||||
params, _ = get_index_params(session)
|
||||
|
||||
r = session.post(
|
||||
get_base_url() + "/xsxk/zzxkyzb_cxZzxkYzbChoosed.html",
|
||||
data={"gnmkdm": GNMKDM, "csrftoken": params["csrftoken"]},
|
||||
)
|
||||
html = r.text
|
||||
|
||||
# 解析已选课程表格
|
||||
rows = re.findall(
|
||||
r'<tr[^>]*class="[^"]*"[^>]*>(.*?)</tr>', html, re.DOTALL | re.IGNORECASE
|
||||
)
|
||||
if not rows:
|
||||
# 备用:找所有 tr
|
||||
rows = re.findall(r'<tr>(.*?)</tr>', html, re.DOTALL | re.IGNORECASE)
|
||||
|
||||
if not rows:
|
||||
print("未找到已选课程数据,页面内容:")
|
||||
print(html[:600])
|
||||
return
|
||||
|
||||
print(f"\n已选课程 ({len(rows)} 条):\n")
|
||||
for row in rows:
|
||||
tds = re.findall(r'<td[^>]*>(.*?)</td>', row, re.DOTALL | re.IGNORECASE)
|
||||
texts = [strip_tags(td) for td in tds]
|
||||
texts = [t for t in texts if t]
|
||||
if texts:
|
||||
print(" | ".join(texts)[:200])
|
||||
|
||||
def cmd_add(session: requests.Session, jxb_id: str):
|
||||
"""
|
||||
选课操作
|
||||
接口: POST /xsxk/zzxkyzb_xkZzxkYzb.html
|
||||
必要参数: jxb_id, xkkz_id, kklxdm, xklc, gnmkdm
|
||||
"""
|
||||
params, _ = get_index_params(session)
|
||||
|
||||
if params["iskxk"] != "1":
|
||||
print("[ERROR] 当前不在选课时间,无法选课")
|
||||
return
|
||||
|
||||
# 先查 jxb_id 对应的课程信息(获取 kklxdm 等)
|
||||
# 直接请求选课接口,服务器会校验
|
||||
data = {
|
||||
"jxb_id": jxb_id,
|
||||
"xkkz_id": params["xkkz_id"],
|
||||
"kklxdm": params["kklxdm"],
|
||||
"xklc": "",
|
||||
"gnmkdm": GNMKDM,
|
||||
"csrftoken": params["csrftoken"],
|
||||
}
|
||||
|
||||
print(f"正在选课: jxb_id={jxb_id}")
|
||||
r = session.post(get_base_url() + "/xsxk/zzxkyzb_xkZzxkYzb.html", data=data)
|
||||
print(f"状态码: {r.status_code}")
|
||||
|
||||
try:
|
||||
result = r.json()
|
||||
flag = result.get("flag", result.get("code", ""))
|
||||
msg = result.get("msg", result.get("message", str(result)))
|
||||
if str(flag) in ("1", "true", "success"):
|
||||
print(f"[OK] 选课成功!{msg}")
|
||||
else:
|
||||
print(f"[FAIL] 选课失败: {msg}")
|
||||
except Exception:
|
||||
# 可能是 HTML 响应
|
||||
if "成功" in r.text:
|
||||
print("[OK] 选课成功!")
|
||||
elif "失败" in r.text or "错误" in r.text:
|
||||
err = re.search(r'<[^>]*>(.*?(?:失败|错误)[^<]*)</[^>]*>', r.text)
|
||||
print(f"[FAIL] 选课失败: {err.group(1) if err else r.text[:200]}")
|
||||
else:
|
||||
print("响应:", r.text[:400])
|
||||
|
||||
def cmd_drop(session: requests.Session, jxb_id: str):
|
||||
"""
|
||||
退课操作
|
||||
接口: POST /xsxk/zzxkyzb_tkZzxkYzb.html
|
||||
"""
|
||||
params, _ = get_index_params(session)
|
||||
|
||||
if params["iskxk"] != "1":
|
||||
print("[ERROR] 当前不在选课时间,无法退课")
|
||||
return
|
||||
|
||||
data = {
|
||||
"jxb_id": jxb_id,
|
||||
"xkkz_id": params["xkkz_id"],
|
||||
"kklxdm": params["kklxdm"],
|
||||
"gnmkdm": GNMKDM,
|
||||
"csrftoken": params["csrftoken"],
|
||||
}
|
||||
|
||||
print(f"正在退课: jxb_id={jxb_id}")
|
||||
r = session.post(get_base_url() + "/xsxk/zzxkyzb_tkZzxkYzb.html", data=data)
|
||||
print(f"状态码: {r.status_code}")
|
||||
|
||||
try:
|
||||
result = r.json()
|
||||
flag = result.get("flag", result.get("code", ""))
|
||||
msg = result.get("msg", result.get("message", str(result)))
|
||||
if str(flag) in ("1", "true", "success"):
|
||||
print(f"[OK] 退课成功!{msg}")
|
||||
else:
|
||||
print(f"[FAIL] 退课失败: {msg}")
|
||||
except Exception:
|
||||
if "成功" in r.text:
|
||||
print("[OK] 退课成功!")
|
||||
else:
|
||||
print("响应:", r.text[:400])
|
||||
|
||||
# ── 主函数 ──────────────────────────────────────────────
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="教务系统选课工具",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog=__doc__,
|
||||
)
|
||||
parser.add_argument("-u", "--user", required=True, metavar="USERNAME",
|
||||
help="学号(用于加载 sessions/<学号>.json)")
|
||||
sub = parser.add_subparsers(dest="cmd", required=True)
|
||||
|
||||
sub.add_parser("status", help="查看选课开放状态")
|
||||
sub.add_parser("list", help="查询可选课程(需在选课时间内)")
|
||||
sub.add_parser("chosen", help="查询已选课程")
|
||||
|
||||
p_search = sub.add_parser("search", help="搜索可选课程")
|
||||
p_search.add_argument("keyword", help="课程名称关键词")
|
||||
|
||||
p_add = sub.add_parser("add", help="选课")
|
||||
p_add.add_argument("jxb_id", help="教学班 ID(从 list/search 结果中获取)")
|
||||
|
||||
p_drop = sub.add_parser("drop", help="退课")
|
||||
p_drop.add_argument("jxb_id", help="教学班 ID")
|
||||
|
||||
args = parser.parse_args()
|
||||
session = load_session(args.user)
|
||||
|
||||
if not check_session(session, args.user):
|
||||
sys.exit(1)
|
||||
|
||||
if args.cmd == "status":
|
||||
cmd_status(session)
|
||||
elif args.cmd == "list":
|
||||
cmd_list(session)
|
||||
elif args.cmd == "chosen":
|
||||
cmd_chosen(session)
|
||||
elif args.cmd == "search":
|
||||
cmd_search(session, args.keyword)
|
||||
elif args.cmd == "add":
|
||||
cmd_add(session, args.jxb_id)
|
||||
elif args.cmd == "drop":
|
||||
cmd_drop(session, args.jxb_id)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||