5191 lines
182 KiB
Python
5191 lines
182 KiB
Python
#!/usr/bin/env python
|
||
# -*- coding: utf-8 -*-
|
||
"""
|
||
Flask路由定义
|
||
"""
|
||
import json
|
||
import os
|
||
import re
|
||
import time
|
||
import threading
|
||
from datetime import datetime
|
||
from functools import wraps
|
||
|
||
import markdown
|
||
|
||
import functools
|
||
|
||
from flask import (
|
||
Blueprint, render_template, request, jsonify,
|
||
redirect, url_for, flash, session, g
|
||
)
|
||
from flask_login import login_user, logout_user, login_required, current_user
|
||
from werkzeug.security import check_password_hash
|
||
|
||
from app.models import db, User, GrabTask, GrabLog, SystemConfig, AiConversation, AiConversationMessage
|
||
from app.school_manager import DEFAULT_SCHOOL_ID, get_school, list_schools, save_school
|
||
from app.grab_engine import grab_engine
|
||
from app.session_manager import SessionManager
|
||
from app.time_utils import now as bj_now, to_iso
|
||
|
||
# 创建蓝图
|
||
main_bp = Blueprint('main', __name__)
|
||
api_bp = Blueprint('api', __name__)
|
||
|
||
|
||
# ==================== 选课模式 & 多线路钩子 ====================
|
||
|
||
# 选课模式下仍然放行的 API(选课核心 + 基础账号功能 + 支付)
|
||
XK_MODE_API_WHITELIST = (
|
||
'/api/login', '/api/courses', '/api/tasks', '/api/logs',
|
||
'/api/ai',
|
||
'/api/jwxt/filter-options', # 选课页筛选下拉数据源(/courses 放行但页面依赖它)
|
||
'/api/lines', '/api/user', '/api/system/status',
|
||
'/api/orders', '/api/schools', '/api/tickets/schools',
|
||
'/api/api/orders', # 兼容历史路由双前缀(见 /orders/<id>/payment_params)
|
||
)
|
||
|
||
# 选课模式下仍然放行的页面(含支付回调,不能拦截)
|
||
XK_MODE_PAGE_WHITELIST = (
|
||
'/login', '/logout', '/register', '/blocked',
|
||
'/dashboard', '/courses', '/course-search', '/tasks', '/logs',
|
||
'/buy', '/terms', '/privacy', '/form', '/api-playground', '/api-examples',
|
||
'/notify', '/return', '/create-pay-order',
|
||
)
|
||
|
||
|
||
@api_bp.before_request
|
||
def _xk_mode_guard_api():
|
||
"""选课模式(按学校):拦截该校用户的非核心 API,集中服务器资源保障选课"""
|
||
from app.multi_line import is_xk_mode
|
||
school_id = current_user.school_id if current_user.is_authenticated else None
|
||
if not is_xk_mode(school_id):
|
||
return None
|
||
if request.method == 'OPTIONS':
|
||
return None # CORS 预检放行
|
||
# 管理员不受限
|
||
if current_user.is_authenticated and current_user.is_admin:
|
||
return None
|
||
if request.path.startswith(XK_MODE_API_WHITELIST):
|
||
return None
|
||
return jsonify({
|
||
'success': False,
|
||
'xk_mode': True,
|
||
'message': '为了选课需求,选课时间段内暂时关闭其他服务',
|
||
}), 503
|
||
|
||
|
||
@api_bp.before_request
|
||
def _apply_user_line_override():
|
||
"""Every authenticated API request uses the owner's school and line."""
|
||
from app.url_manager import push_school
|
||
from app.multi_line import get_user_line_url, is_enabled
|
||
try:
|
||
if current_user.is_authenticated:
|
||
jwxt_acc = current_user.get_jwxt_account() or {}
|
||
jwxt_username = jwxt_acc.get('username') or current_user.jwxt_username
|
||
line_url = get_user_line_url(jwxt_username, current_user.school_id) if jwxt_username and is_enabled(current_user.school_id) else None
|
||
push_school(current_user.school_id, line_url)
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
@api_bp.after_request
|
||
def _clear_user_line_override(response):
|
||
from app.url_manager import pop_school
|
||
pop_school()
|
||
return response
|
||
|
||
|
||
@api_bp.teardown_request
|
||
def _clear_user_line_override_on_error(exc):
|
||
"""视图抛未捕获异常时 after_request 不执行,teardown 兜底清理线程级线路覆盖,
|
||
防止 werkzeug 线程复用后把上一个用户的固定线路泄漏给后续请求。"""
|
||
from app.url_manager import pop_school
|
||
pop_school()
|
||
|
||
|
||
@main_bp.before_request
|
||
def _xk_mode_guard_page():
|
||
"""选课模式(按学校):非核心页面直接展示提示页"""
|
||
from app.multi_line import is_xk_mode
|
||
school_id = current_user.school_id if current_user.is_authenticated else None
|
||
if not is_xk_mode(school_id):
|
||
return None
|
||
if request.method == 'OPTIONS':
|
||
return None
|
||
if current_user.is_authenticated and current_user.is_admin:
|
||
return None
|
||
if request.path.startswith('/static'):
|
||
return None
|
||
if request.path == '/' or request.path.startswith(XK_MODE_PAGE_WHITELIST):
|
||
return None
|
||
return render_template('xk_mode.html'), 503
|
||
|
||
|
||
# ==================== Session 自动重试辅助 ====================
|
||
|
||
def _is_session_error(result: dict) -> bool:
|
||
"""
|
||
判断 API 调用结果是否是 session 失效引起的错误。
|
||
result 为业务逻辑返回的 dict(success=False 时才判断)。
|
||
"""
|
||
if result.get('success'):
|
||
return False
|
||
msg = str(result.get('message', '')).lower()
|
||
# 常见 session 失效特征
|
||
keywords = [
|
||
'session', '登录', 'login', '认证', 'unauthorized',
|
||
'非 json', '非json', 'html 错误', 'html错误', '请重新登录',
|
||
'401', 'token', 'cookie', '未登录', '过期', 'expired',
|
||
'无功能权限', '密码已到期',
|
||
]
|
||
return any(kw in msg for kw in keywords)
|
||
def with_session_retry(user, fn):
|
||
"""Execute fn(), auto-refresh session on error."""
|
||
import logging
|
||
logger = logging.getLogger(__name__)
|
||
t_start = time.perf_counter()
|
||
stages = []
|
||
if hasattr(g, 'jwxt_temp') and g.jwxt_temp:
|
||
try:
|
||
result = fn()
|
||
except Exception as e:
|
||
result = {'success': False, 'message': str(e)}
|
||
ms = int((time.perf_counter() - t_start) * 1000)
|
||
if isinstance(result, dict):
|
||
result['_timing'] = {'jwxt_api_ms': ms, 'backend_total_ms': ms, 'attempts': 1, 'refreshed': False, 'stages': [{'attempt': 1, 'ms': ms, 'ok': result.get('success', False), 'session_error': False}]}
|
||
return result, False
|
||
try:
|
||
result = fn()
|
||
except Exception as e:
|
||
result = {'success': False, 'message': str(e)}
|
||
attempt1_ms = int((time.perf_counter() - t_start) * 1000)
|
||
session_error = _is_session_error(result)
|
||
stages.append({'attempt': 1, 'ms': attempt1_ms, 'ok': result.get('success', False), 'session_error': session_error})
|
||
if not session_error:
|
||
if isinstance(result, dict):
|
||
result['_timing'] = {'jwxt_api_ms': attempt1_ms, 'backend_total_ms': attempt1_ms, 'attempts': 1, 'refreshed': False, 'stages': stages}
|
||
return result, False
|
||
logger.info(f"[session_retry] session error, refreshing user {user.id}")
|
||
from app.session_manager import SessionManager
|
||
t_refresh = time.perf_counter()
|
||
refresh_result = SessionManager.refresh_session(user, force=True)
|
||
refresh_ms = int((time.perf_counter() - t_refresh) * 1000)
|
||
if not refresh_result.get('success'):
|
||
timing = {'jwxt_api_ms': attempt1_ms, 'backend_total_ms': int((time.perf_counter() - t_start) * 1000), 'attempts': 1, 'refreshed': True, 'stages': stages, 'session': {'refresh_ms': refresh_ms, 'login': refresh_result.get('timing', {})}}
|
||
return {'success': False, 'message': f"Session expired, auto-refresh failed: {refresh_result.get('message', '')}", '_timing': timing}, True
|
||
logger.info(f"[session_retry] refresh ok ({refresh_ms}ms), retrying")
|
||
t_retry = time.perf_counter()
|
||
try:
|
||
result = fn()
|
||
except Exception as e:
|
||
result = {'success': False, 'message': str(e)}
|
||
attempt2_ms = int((time.perf_counter() - t_retry) * 1000)
|
||
stages.append({'attempt': 2, 'ms': attempt2_ms, 'ok': result.get('success', False), 'session_error': False})
|
||
if isinstance(result, dict):
|
||
result['_timing'] = {'jwxt_api_ms': attempt2_ms, 'backend_total_ms': int((time.perf_counter() - t_start) * 1000), 'attempts': 2, 'refreshed': True, 'stages': stages, 'session': {'refresh_ms': refresh_ms, 'login': refresh_result.get('timing', {})}}
|
||
return result, True
|
||
|
||
|
||
|
||
def _resolve_jwxt_acc():
|
||
"""
|
||
Resolve JWXT account from logged-in user's config.
|
||
"""
|
||
# 如果 @api_auth 已经设置,直接使用
|
||
if hasattr(g, 'jwxt_acc') and g.jwxt_acc:
|
||
return g.jwxt_acc
|
||
|
||
acc = current_user.get_jwxt_account()
|
||
if acc:
|
||
return {**acc, 'temp': False}
|
||
return None
|
||
|
||
|
||
def _decode_flask_session(cookie_value):
|
||
"""Decode a Flask signed session cookie, return the data dict or None."""
|
||
from itsdangerous import URLSafeTimedSerializer
|
||
from flask.sessions import TaggedJSONSerializer
|
||
from flask import current_app
|
||
try:
|
||
serializer = URLSafeTimedSerializer(
|
||
secret_key=current_app.secret_key,
|
||
salt='cookie-session',
|
||
serializer=TaggedJSONSerializer(),
|
||
signer_kwargs={'key_derivation': 'hmac'}
|
||
)
|
||
return serializer.loads(cookie_value)
|
||
except Exception:
|
||
return None
|
||
|
||
|
||
def api_auth(f):
|
||
"""
|
||
API 认证装饰器,替代 @login_required。
|
||
支持三种认证方式(三选一):
|
||
1. session 字段 — 传入 Flask session cookie 值
|
||
2. username + password — 直接传网站登录账号密码
|
||
3. Session cookie — 浏览器自动携带(原始方式)
|
||
|
||
用法:
|
||
@api_bp.route('/example')
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def example():
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.do_something()
|
||
"""
|
||
from flask_login import login_user as _login_user
|
||
|
||
@functools.wraps(f)
|
||
def wrapper(*args, **kwargs):
|
||
# 1. 检查 session 字段
|
||
_src = request.get_json(silent=True) or {}
|
||
sess_val = request.args.get('session') or _src.get('session') or ''
|
||
if sess_val:
|
||
data = _decode_flask_session(sess_val)
|
||
if data and data.get('_user_id'):
|
||
user = User.query.get(int(data['_user_id']))
|
||
if user:
|
||
_login_user(user, remember=False)
|
||
return f(*args, **kwargs)
|
||
return jsonify({'success': False, 'message': 'session 无效或已过期'}), 401
|
||
|
||
# 2. 检查网站账号密码
|
||
u = request.args.get('username') or _src.get('username') or ''
|
||
p = request.args.get('password') or _src.get('password') or ''
|
||
if u and p:
|
||
_user = User.query.filter_by(username=u).first()
|
||
if _user and _user.check_password(p):
|
||
_login_user(_user, remember=False)
|
||
return f(*args, **kwargs)
|
||
return jsonify({'success': False, 'message': '用户名或密码错误'}), 401
|
||
|
||
# 3. 回退到 cookie session(原始 @login_required 行为)
|
||
if not current_user.is_authenticated:
|
||
return jsonify({'success': False, 'message': '请先登录。支持三种方式:① session 字段 ② username+password ③ cookie'}), 401
|
||
return f(*args, **kwargs)
|
||
|
||
return wrapper
|
||
|
||
|
||
def ensure_jwxt_session(f):
|
||
"""
|
||
装饰器:确保当前用户已配置教务系统账号,自动注入 g.jwxt_acc。
|
||
被装饰的函数应返回 dict(含 success 字段),装饰器会用 with_session_retry
|
||
包装并自动 JSON 序列化。
|
||
|
||
用法:
|
||
@api_bp.route('/example')
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def example():
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.do_something()
|
||
|
||
若返回 dict 包含 'success' 字段且为 False,装饰器会尝试自动刷新 session 并重试。
|
||
"""
|
||
@functools.wraps(f)
|
||
def wrapper(*args, **kwargs):
|
||
# 如果 @api_auth 已经设置了 g.jwxt_acc(直接后端账号),直接使用
|
||
if not hasattr(g, 'jwxt_acc') or not g.jwxt_acc:
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未提供教务账号参数,也未配置教务系统账号'})
|
||
g.jwxt_acc = jwxt_acc
|
||
g.jwxt_temp = jwxt_acc.get('temp', False)
|
||
|
||
# 临时账号密码:session 刚创建,无需 with_session_retry
|
||
if g.jwxt_temp:
|
||
try:
|
||
result = f(*args, **kwargs)
|
||
return jsonify(result) if isinstance(result, dict) else result
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}'})
|
||
|
||
def _do_request():
|
||
return f(*args, **kwargs)
|
||
|
||
try:
|
||
result, refreshed = with_session_retry(current_user, _do_request)
|
||
return jsonify(result) if isinstance(result, dict) else result
|
||
except FileNotFoundError:
|
||
return jsonify({'success': False, 'message': 'Session不存在,请先配置教务系统账号'})
|
||
except RuntimeError as e:
|
||
return jsonify({'success': False, 'message': str(e)})
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}'})
|
||
|
||
return wrapper
|
||
|
||
|
||
# ==================== 页面路由 ====================
|
||
|
||
@main_bp.route('/')
|
||
def index():
|
||
"""首页 - 未登录重定向到购买页,已登录到仪表盘"""
|
||
if current_user.is_authenticated:
|
||
return redirect(url_for('main.dashboard'))
|
||
return redirect(url_for('main.buy'))
|
||
|
||
|
||
@main_bp.route('/login', methods=['GET', 'POST'])
|
||
def login():
|
||
"""登录页面"""
|
||
# 鸿蒙 App 已登录时返回 JSON,不重定向
|
||
if current_user.is_authenticated:
|
||
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
|
||
return jsonify({'status': 'success', 'message': '已登录'})
|
||
return redirect(url_for('main.dashboard'))
|
||
|
||
if request.method == 'POST':
|
||
username = request.form.get('username')
|
||
password = request.form.get('password')
|
||
|
||
# 登录频率限制
|
||
from app.ip_manager import check_login_rate_limit, record_login_attempt, _get_real_ip
|
||
client_ip = _get_real_ip(request)
|
||
limited, limit_msg = check_login_rate_limit(client_ip, window_minutes=10, max_attempts=10)
|
||
if limited:
|
||
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
|
||
return jsonify({'status': 'error', 'message': limit_msg}), 429
|
||
flash(limit_msg, 'danger')
|
||
return render_template('login.html')
|
||
|
||
user = User.query.filter_by(username=username).first()
|
||
|
||
if user and user.check_password(password):
|
||
login_user(user, remember=True)
|
||
user.last_login = bj_now()
|
||
db.session.commit()
|
||
record_login_attempt(client_ip, username, success=True)
|
||
|
||
# 返回JSON响应(鸿蒙 App 用)
|
||
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
|
||
return jsonify({
|
||
'status': 'success',
|
||
'message': '登录成功',
|
||
'redirect': url_for('main.dashboard')
|
||
})
|
||
|
||
next_page = request.args.get('next')
|
||
return redirect(next_page or url_for('main.dashboard'))
|
||
|
||
# 登录失败,记录
|
||
record_login_attempt(client_ip, username or '', success=False)
|
||
|
||
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
|
||
return jsonify({
|
||
'status': 'error',
|
||
'message': '用户名或密码错误'
|
||
}), 401
|
||
|
||
flash('用户名或密码错误', 'danger')
|
||
|
||
return render_template('login.html')
|
||
|
||
@api_bp.route('/login', methods=['POST'])
|
||
def api_login():
|
||
"""JSON login API for external callers"""
|
||
data = request.get_json(silent=True) or {}
|
||
username = data.get('username', '')
|
||
password = data.get('password', '')
|
||
|
||
if not username or not password:
|
||
return jsonify({'success': False, 'message': 'username and password required'}), 400
|
||
|
||
from app.ip_manager import check_login_rate_limit, record_login_attempt, _get_real_ip
|
||
client_ip = _get_real_ip(request)
|
||
limited, limit_msg = check_login_rate_limit(client_ip, window_minutes=10, max_attempts=10)
|
||
if limited:
|
||
return jsonify({'success': False, 'message': limit_msg}), 429
|
||
|
||
user = User.query.filter_by(username=username).first()
|
||
if user and user.check_password(password):
|
||
login_user(user, remember=True)
|
||
user.last_login = bj_now()
|
||
db.session.commit()
|
||
record_login_attempt(client_ip, username, success=True)
|
||
return jsonify({
|
||
'success': True,
|
||
'message': '登录成功',
|
||
'session': 'session cookie set via Set-Cookie header',
|
||
})
|
||
|
||
record_login_attempt(client_ip, username or '', success=False)
|
||
return jsonify({'success': False, 'message': 'wrong username or password'}), 401
|
||
|
||
|
||
@main_bp.route('/logout')
|
||
@login_required
|
||
def logout():
|
||
"""退出登录"""
|
||
logout_user()
|
||
flash('已成功退出登录', 'info')
|
||
return redirect(url_for('main.login'))
|
||
|
||
|
||
@main_bp.route('/dashboard')
|
||
@login_required
|
||
def dashboard():
|
||
"""用户仪表盘 - 管理员跳转到管理后台"""
|
||
if current_user.is_admin:
|
||
return redirect(url_for('main.admin_users'))
|
||
|
||
# 普通用户获取统计
|
||
task_count = GrabTask.query.filter_by(user_id=current_user.id).count()
|
||
pending_count = GrabTask.query.filter_by(
|
||
user_id=current_user.id,
|
||
status=GrabTask.STATUS_PENDING
|
||
).count()
|
||
success_count = GrabTask.query.filter_by(
|
||
user_id=current_user.id,
|
||
status=GrabTask.STATUS_SUCCESS
|
||
).count()
|
||
|
||
# 获取最近任务
|
||
recent_tasks = GrabTask.query.filter_by(user_id=current_user.id)\
|
||
.order_by(GrabTask.created_at.desc())\
|
||
.limit(5).all()
|
||
|
||
return render_template('dashboard.html',
|
||
task_count=task_count,
|
||
pending_count=pending_count,
|
||
success_count=success_count,
|
||
recent_tasks=recent_tasks)
|
||
|
||
|
||
@main_bp.route('/courses')
|
||
@login_required
|
||
def courses():
|
||
"""课程查询页面"""
|
||
return render_template('courses.html')
|
||
|
||
|
||
@main_bp.route('/course-search')
|
||
@login_required
|
||
def course_search():
|
||
"""按课程号/课程名搜索授课信息页面"""
|
||
return render_template('course_search.html')
|
||
|
||
|
||
@main_bp.route('/tasks')
|
||
@login_required
|
||
def tasks():
|
||
"""抢课任务管理页面"""
|
||
return render_template('tasks.html')
|
||
|
||
|
||
@main_bp.route('/logs')
|
||
@login_required
|
||
def logs():
|
||
"""抢课日志页面"""
|
||
return render_template('logs.html')
|
||
|
||
|
||
@main_bp.route('/admin/users')
|
||
@login_required
|
||
def admin_users():
|
||
"""管理后台页面(仅管理员)"""
|
||
if not current_user.is_admin:
|
||
flash('无权访问', 'danger')
|
||
return redirect(url_for('main.dashboard'))
|
||
return render_template('admin_dashboard.html')
|
||
|
||
|
||
@main_bp.route('/buy')
|
||
def buy():
|
||
"""购买页面"""
|
||
return render_template('buy.html')
|
||
|
||
|
||
@main_bp.route('/uploads/school_icons/<path:filename>')
|
||
def school_icon_file(filename):
|
||
"""学校 ICO 图标(公开访问,favicon 请求可能不带登录态)"""
|
||
from flask import send_from_directory
|
||
from app.school_manager import ICON_DIR
|
||
response = send_from_directory(ICON_DIR, filename)
|
||
response.headers['Cache-Control'] = 'public, max-age=86400'
|
||
return response
|
||
|
||
|
||
def _render_md(filename):
|
||
"""读取 docs/ 目录下的 md 文件,转成 HTML 返回"""
|
||
docs_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'docs')
|
||
md_path = os.path.join(docs_dir, filename)
|
||
try:
|
||
with open(md_path, encoding='utf-8') as f:
|
||
md_text = f.read()
|
||
# 剥离 YAML front matter(AIGC 水印等自动注入内容)
|
||
md_text = re.sub(r'^---\s*\n.*?\n---\s*\n', '', md_text, count=1, flags=re.DOTALL)
|
||
html = markdown.markdown(
|
||
md_text,
|
||
extensions=['tables', 'fenced_code', 'nl2br']
|
||
)
|
||
|
||
except FileNotFoundError:
|
||
html = '<p>文件未找到。</p>'
|
||
return html
|
||
|
||
|
||
@main_bp.route('/terms')
|
||
def terms():
|
||
"""用户服务协议页面"""
|
||
return render_template('terms.html', content=_render_md('terms.md'))
|
||
|
||
|
||
@main_bp.route('/privacy')
|
||
def privacy():
|
||
"""隐私政策页面"""
|
||
return render_template('privacy.html', content=_render_md('privacy.md'))
|
||
|
||
|
||
@main_bp.route('/timetable')
|
||
@login_required
|
||
def timetable():
|
||
"""课表查询页面"""
|
||
return render_template('timetable.html')
|
||
|
||
|
||
@main_bp.route('/register', methods=['GET', 'POST'])
|
||
def register():
|
||
"""用户注册页面"""
|
||
if current_user.is_authenticated:
|
||
return redirect(url_for('main.dashboard'))
|
||
|
||
# 检查是否允许注册
|
||
allow_register = SystemConfig.get('allow_register', 'true').lower() == 'true'
|
||
|
||
if request.method == 'POST':
|
||
data = request.get_json() if request.is_json else request.form
|
||
|
||
# 网站账号
|
||
username = data.get('username', '').strip()
|
||
password = data.get('password', '').strip()
|
||
|
||
# 教务系统账号
|
||
jwxt_username = data.get('jwxt_username', '').strip()
|
||
jwxt_password = data.get('jwxt_password', '').strip()
|
||
jwxt_name = data.get('jwxt_name', '').strip()
|
||
|
||
# 注册码(去掉横线,只保留字母数字)
|
||
ticket_code = ''.join(c for c in data.get('ticket_code', '').upper() if c.isalnum())
|
||
school_id = str(data.get('school_id', '')).strip()
|
||
|
||
# 验证必填字段
|
||
if not all([username, password, jwxt_username, jwxt_password, ticket_code, school_id]):
|
||
msg = '请填写所有必填字段,包括注册码'
|
||
if request.is_json:
|
||
return jsonify({'success': False, 'message': msg})
|
||
flash(msg, 'danger')
|
||
return render_template('register.html', allow_register=allow_register, schools=list_schools())
|
||
|
||
# 验证注册码
|
||
from app.ticket_manager import TicketManager
|
||
is_valid, ticket_msg = TicketManager.verify_ticket(ticket_code)
|
||
if not is_valid:
|
||
msg = f'注册码验证失败: {ticket_msg}'
|
||
if request.is_json:
|
||
return jsonify({'success': False, 'message': msg})
|
||
flash(msg, 'danger')
|
||
return render_template('register.html', allow_register=allow_register, schools=list_schools())
|
||
if not get_school(school_id):
|
||
return jsonify({'success': False, 'message': '请选择有效的学校'}), 400
|
||
ticket_info = TicketManager.get_ticket_info(ticket_code) or {}
|
||
allowed_schools = ticket_info.get('school_ids')
|
||
if allowed_schools is not None and school_id not in allowed_schools:
|
||
return jsonify({'success': False, 'message': '该注册码不适用于所选学校'}), 400
|
||
|
||
# 检查网站用户名是否已存在
|
||
if User.query.filter_by(username=username).first():
|
||
msg = '用户名已存在'
|
||
if request.is_json:
|
||
return jsonify({'success': False, 'message': msg})
|
||
flash(msg, 'danger')
|
||
return render_template('register.html', allow_register=allow_register, schools=list_schools())
|
||
|
||
# 验证教务系统账号(尝试登录10次)
|
||
from app.url_manager import push_school, pop_school
|
||
push_school(school_id)
|
||
try:
|
||
success, verify_msg = SessionManager.test_login(jwxt_username, jwxt_password, max_attempts=10)
|
||
finally:
|
||
pop_school()
|
||
|
||
if not success:
|
||
msg = f'教务系统账号验证失败: {verify_msg}'
|
||
if request.is_json:
|
||
return jsonify({'success': False, 'message': msg})
|
||
flash(msg, 'danger')
|
||
return render_template('register.html', allow_register=allow_register, schools=list_schools())
|
||
|
||
# 创建网站用户(只存网站账号密码)
|
||
user = User(
|
||
username=username,
|
||
jwxt_username=jwxt_username,
|
||
jwxt_name=jwxt_name,
|
||
school_id=school_id,
|
||
session_status='valid'
|
||
)
|
||
user.set_password(password)
|
||
user.session_updated_at = bj_now()
|
||
|
||
db.session.add(user)
|
||
db.session.commit()
|
||
|
||
# 使用注册码
|
||
used, use_msg = TicketManager.use_ticket(ticket_code, user.id, school_id)
|
||
if not used:
|
||
# 如果注册码使用失败,删除已创建的用户
|
||
db.session.delete(user)
|
||
db.session.commit()
|
||
msg = f'注册码使用失败: {use_msg}'
|
||
if request.is_json:
|
||
return jsonify({'success': False, 'message': msg})
|
||
flash(msg, 'danger')
|
||
return render_template('register.html', allow_register=allow_register, schools=list_schools())
|
||
|
||
# 保存教务系统账号到 accounts.json
|
||
from app.account_manager import AccountManager
|
||
AccountManager.set_jwxt_account(
|
||
user_id=user.id,
|
||
username=username,
|
||
jwxt_username=jwxt_username,
|
||
jwxt_password=jwxt_password,
|
||
jwxt_name=jwxt_name,
|
||
school_id=school_id
|
||
)
|
||
|
||
# 保存session文件
|
||
push_school(school_id)
|
||
try:
|
||
SessionManager.login_and_save(jwxt_username, jwxt_password)
|
||
finally:
|
||
pop_school()
|
||
|
||
msg = '注册成功,请登录'
|
||
if request.is_json:
|
||
return jsonify({'success': True, 'message': msg})
|
||
flash(msg, 'success')
|
||
return redirect(url_for('main.login'))
|
||
|
||
return render_template('register.html', allow_register=allow_register, schools=list_schools())
|
||
|
||
|
||
@api_bp.route('/schools')
|
||
def api_schools_public():
|
||
return jsonify({'success': True, 'schools': [
|
||
{'id': school['id'], 'name': school['name']} for school in list_schools()
|
||
]})
|
||
|
||
|
||
@api_bp.route('/tickets/schools/<code>')
|
||
def api_ticket_schools(code):
|
||
from app.ticket_manager import TicketManager
|
||
valid, message = TicketManager.verify_ticket(code)
|
||
if not valid:
|
||
return jsonify({'success': False, 'message': message}), 400
|
||
info = TicketManager.get_ticket_info(code) or {}
|
||
return jsonify({'success': True, 'school_ids': info.get('school_ids')})
|
||
|
||
|
||
# ==================== API路由 ====================
|
||
|
||
# ---- 用户相关API ----
|
||
|
||
@api_bp.route('/user/info')
|
||
@api_auth
|
||
def api_user_info():
|
||
"""获取当前用户信息"""
|
||
return jsonify({
|
||
'success': True,
|
||
'user': current_user.to_dict()
|
||
})
|
||
|
||
|
||
@api_bp.route('/user/change_password', methods=['POST'])
|
||
@api_auth
|
||
def api_change_password():
|
||
"""修改密码"""
|
||
data = request.get_json()
|
||
old_password = data.get('old_password')
|
||
new_password = data.get('new_password')
|
||
|
||
if not current_user.check_password(old_password):
|
||
return jsonify({'success': False, 'message': '原密码错误'})
|
||
|
||
if len(new_password) < 6:
|
||
return jsonify({'success': False, 'message': '新密码至少6位'})
|
||
|
||
current_user.set_password(new_password)
|
||
db.session.commit()
|
||
|
||
return jsonify({'success': True, 'message': '密码修改成功'})
|
||
|
||
|
||
# ---- 课程查询API ----
|
||
|
||
@api_bp.route('/courses/list')
|
||
@api_auth
|
||
def api_courses_list():
|
||
"""获取可选课程列表"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号', 'courses': []})
|
||
|
||
keyword = request.args.get('keyword', '')
|
||
kklxdm = request.args.get('kklxdm', '')
|
||
|
||
def _do_request():
|
||
from app.xk_api import CourseAPI
|
||
api = CourseAPI(jwxt_acc['username'])
|
||
return api.query_courses(keyword=keyword, kklxdm=kklxdm, page_size=100)
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except FileNotFoundError:
|
||
return jsonify({'success': False, 'message': 'Session不存在,请先更新登录状态', 'courses': []})
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}', 'courses': []})
|
||
|
||
|
||
@api_bp.route('/courses/jxb_list')
|
||
@api_auth
|
||
def api_courses_jxb_list():
|
||
"""获取课程的教学班列表(展开教学班)"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号', 'jxbs': []})
|
||
|
||
kch_id = request.args.get('kch_id', '')
|
||
cxbj = request.args.get('cxbj', '0')
|
||
fxbj = request.args.get('fxbj', '0')
|
||
kklxdm = request.args.get('kklxdm', '')
|
||
|
||
if not kch_id:
|
||
return jsonify({'success': False, 'message': '缺少课程ID(kch_id)', 'jxbs': []})
|
||
|
||
def _do_request():
|
||
from app.xk_api import CourseAPI
|
||
api = CourseAPI(jwxt_acc['username'])
|
||
return api.get_jxb_list(kch_id=kch_id, cxbj=cxbj, fxbj=fxbj, kklxdm=kklxdm)
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except FileNotFoundError:
|
||
return jsonify({'success': False, 'message': 'Session不存在,请先更新登录状态', 'jxbs': []})
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}', 'jxbs': []})
|
||
|
||
|
||
@api_bp.route('/courses/chosen')
|
||
@api_auth
|
||
def api_courses_chosen():
|
||
"""获取已选课程"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号', 'courses': []})
|
||
|
||
def _do_request():
|
||
from app.xk_api import CourseAPI
|
||
api = CourseAPI(jwxt_acc['username'])
|
||
return api.get_chosen_courses()
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except FileNotFoundError:
|
||
return jsonify({'success': False, 'message': 'Session不存在', 'courses': []})
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}', 'courses': []})
|
||
|
||
|
||
@api_bp.route('/courses/chosen-heatmap')
|
||
@api_auth
|
||
def api_courses_chosen_heatmap():
|
||
"""获取已选课程页面的空闲热度图 HTML 表格"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'html': ''})
|
||
|
||
def _do_request():
|
||
from app.kbcx_api import KbcxAPI
|
||
api = KbcxAPI(jwxt_acc['username'])
|
||
html = api.get_heatmap_html()
|
||
return {'success': True, 'html': html}
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except Exception:
|
||
return jsonify({'success': False, 'html': ''})
|
||
|
||
@api_bp.route('/courses/drop', methods=['POST'])
|
||
@api_auth
|
||
def api_courses_drop():
|
||
"""退课"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号'})
|
||
|
||
data = request.get_json()
|
||
jxb_id = data.get('jxb_id', '')
|
||
do_jxb_id = data.get('do_jxb_id', '')
|
||
kch_id = data.get('kch_id', '')
|
||
|
||
if not do_jxb_id or not kch_id:
|
||
return jsonify({'success': False, 'message': '缺少必填参数'})
|
||
|
||
def _do_request():
|
||
from app.xk_api import CourseAPI
|
||
api = CourseAPI(jwxt_acc['username'])
|
||
return api.drop_course(jxb_id=jxb_id, do_jxb_id=do_jxb_id, kch_id=kch_id)
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except FileNotFoundError:
|
||
return jsonify({'success': False, 'message': 'Session不存在'})
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'退课失败: {str(e)}'})
|
||
|
||
|
||
@api_bp.route('/courses/add', methods=['POST'])
|
||
@api_auth
|
||
def api_courses_add():
|
||
"""选课"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号'})
|
||
|
||
data = request.get_json()
|
||
jxb_id = data.get('jxb_id', '')
|
||
do_jxb_id = data.get('do_jxb_id', '')
|
||
kch_id = data.get('kch_id', '')
|
||
kklxdm = data.get('kklxdm', '')
|
||
kcmc = data.get('kcmc', '')
|
||
|
||
if not jxb_id:
|
||
return jsonify({'success': False, 'message': '缺少必填参数 jxb_id'})
|
||
|
||
def _do_request():
|
||
from app.xk_api import CourseAPI
|
||
api = CourseAPI(jwxt_acc['username'])
|
||
return api.add_course(jxb_id=jxb_id, do_jxb_id=do_jxb_id, kch_id=kch_id, kklxdm=kklxdm, kcmc=kcmc)
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except FileNotFoundError:
|
||
return jsonify({'success': False, 'message': 'Session不存在'})
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'选课失败: {str(e)}'})
|
||
|
||
|
||
@api_bp.route('/courses/status')
|
||
@api_auth
|
||
def api_courses_status():
|
||
"""获取选课系统状态(是否开放)"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号', 'is_open': False})
|
||
|
||
def _do_request():
|
||
from app.xk_api import CourseAPI
|
||
api = CourseAPI(jwxt_acc['username'])
|
||
return api.get_status()
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify({
|
||
'success': result.get('success', False),
|
||
'is_open': result.get('is_open', False),
|
||
'message': result.get('message', ''),
|
||
})
|
||
except FileNotFoundError:
|
||
return jsonify({'success': False, 'is_open': False, 'message': 'Session不存在,请先配置教务系统账号'})
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'is_open': False, 'message': f'查询失败: {str(e)}'})
|
||
|
||
|
||
# ---- 选课 AI 助手 API ----
|
||
|
||
@api_bp.route('/ai/status')
|
||
@api_auth
|
||
def api_ai_status():
|
||
"""返回 AI 助手是否可用,不暴露任何敏感配置。"""
|
||
from app.ai_assistant import get_ai_settings
|
||
settings = get_ai_settings()
|
||
return jsonify({'success': True, **settings})
|
||
|
||
|
||
@api_bp.route('/ai/conversation')
|
||
@api_auth
|
||
def api_ai_conversation():
|
||
"""读取当前账号的 AI 会话,供页面刷新后恢复。"""
|
||
conversation = AiConversation.query.filter_by(user_id=current_user.id).first()
|
||
if not conversation:
|
||
return jsonify({'success': True, 'messages': []})
|
||
messages = conversation.messages.order_by(AiConversationMessage.id.asc()).limit(200).all()
|
||
return jsonify({'success': True, 'messages': [item.to_dict() for item in messages]})
|
||
|
||
|
||
@api_bp.route('/ai/conversation', methods=['DELETE'])
|
||
@api_auth
|
||
def api_ai_clear_conversation():
|
||
"""清空当前账号的 AI 会话,不影响抢课任务、课程或日志。"""
|
||
conversation = AiConversation.query.filter_by(user_id=current_user.id).first()
|
||
if conversation:
|
||
db.session.delete(conversation)
|
||
db.session.commit()
|
||
return jsonify({'success': True})
|
||
|
||
|
||
@api_bp.route('/timetable/semester')
|
||
@api_auth
|
||
def api_timetable_semester():
|
||
"""获取学期信息(xnm, xqm, 周次列表等)
|
||
|
||
查询参数(均为可选):
|
||
xnm 学年(如 "2025"),不传则从教务系统自动推算
|
||
xqm 学期("3" 或 "12"),不传则自动推算
|
||
"""
|
||
from app.test_mock import TEST_USERNAME, fake_semester_info
|
||
if current_user.is_authenticated and current_user.username == TEST_USERNAME:
|
||
return jsonify(fake_semester_info())
|
||
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号'})
|
||
|
||
query_xnm = request.args.get('xnm', '')
|
||
query_xqm = request.args.get('xqm', '')
|
||
|
||
def _do_request():
|
||
from app.kbcx_api import KbcxAPI
|
||
api = KbcxAPI(jwxt_acc['username'])
|
||
|
||
# 先获取学期元数据(含学年学期下拉选项)
|
||
try:
|
||
meta = api.get_semester_meta()
|
||
# 检查是否缴费注册
|
||
if meta.get('sfbczc') == '0':
|
||
return {'success': False, 'message': '账号未完成缴费注册,无法查询课表'}
|
||
except Exception as e:
|
||
import logging
|
||
logging.getLogger(__name__).error(f'semester meta error: {e}')
|
||
meta = {}
|
||
|
||
if query_xnm and query_xqm:
|
||
xnm = query_xnm
|
||
xqm = query_xqm
|
||
else:
|
||
xnm = meta.get('xnm', '')
|
||
xqm = meta.get('xqm', '')
|
||
|
||
# 周次列表
|
||
weeks = api.get_week_list(xnm, xqm)
|
||
|
||
# 计算当前周次
|
||
from datetime import datetime, timedelta
|
||
import re
|
||
current_week_index = 1
|
||
try:
|
||
today = bj_now().date()
|
||
for i, week_info in enumerate(weeks):
|
||
zcrq = week_info.get('zcrq', '')
|
||
week_date = None
|
||
if '(' in zcrq and '至' in zcrq:
|
||
match = re.search(r'\((\d{4}-\d{2}-\d{2})至', zcrq)
|
||
if match:
|
||
week_date = datetime.strptime(match.group(1), '%Y-%m-%d').date()
|
||
else:
|
||
try:
|
||
week_date = datetime.strptime(zcrq, '%Y-%m-%d').date()
|
||
except Exception:
|
||
pass
|
||
if week_date:
|
||
week_sunday = week_date + timedelta(days=6)
|
||
if week_date <= today <= week_sunday:
|
||
current_week_index = i + 1
|
||
break
|
||
except Exception:
|
||
current_week_index = 1
|
||
|
||
return {
|
||
'success': True,
|
||
'data': {
|
||
'xnm': xnm,
|
||
'xqm': xqm,
|
||
'xqh_id': meta.get('xqh_id', '') if meta else '',
|
||
'weeks': weeks,
|
||
'current_week': current_week_index,
|
||
'xnm_options': meta.get('xnm_options', []) if meta else [],
|
||
'xqm_options': meta.get('xqm_options', []) if meta else [],
|
||
}
|
||
}
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except FileNotFoundError:
|
||
return jsonify({'success': False, 'message': 'Session不存在,请先配置教务系统账号'})
|
||
except RuntimeError as e:
|
||
return jsonify({'success': False, 'message': str(e)})
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}'})
|
||
|
||
|
||
@api_bp.route('/timetable')
|
||
@api_auth
|
||
def api_timetable():
|
||
"""
|
||
获取课表数据
|
||
|
||
查询参数:
|
||
kblx 课表类型:1=按周,2=全学期(默认)
|
||
week 按周时指定的周次(kblx=1时必填)
|
||
xnm 学年(可选),不传则从教务系统自动推算
|
||
xqm 学期(可选),不传则自动推算
|
||
"""
|
||
from app.test_mock import TEST_USERNAME, fake_timetable
|
||
if current_user.is_authenticated and current_user.username == TEST_USERNAME:
|
||
kblx = request.args.get('kblx', '2')
|
||
week_param = request.args.get('week', '0')
|
||
week = int(week_param) if week_param and week_param.isdigit() else 0
|
||
data = fake_timetable(kblx=kblx, week=week)
|
||
return jsonify({'success': True, 'data': data})
|
||
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号'})
|
||
|
||
kblx = request.args.get('kblx', '2')
|
||
week_param = request.args.get('week', '0')
|
||
query_xnm = request.args.get('xnm', '')
|
||
query_xqm = request.args.get('xqm', '')
|
||
|
||
def _do_request():
|
||
from app.kbcx_api import KbcxAPI
|
||
api = KbcxAPI(jwxt_acc['username'])
|
||
|
||
if query_xnm and query_xqm:
|
||
xnm = query_xnm
|
||
xqm = query_xqm
|
||
else:
|
||
meta = api.get_semester_meta()
|
||
xnm = meta['xnm']
|
||
xqm = meta['xqm']
|
||
|
||
if kblx == '1':
|
||
try:
|
||
week = int(week_param) if week_param else 0
|
||
except ValueError:
|
||
week = 0
|
||
weeks = api.get_week_list(xnm, xqm)
|
||
if week <= 0 or week > len(weeks):
|
||
week = 1
|
||
zs = str(weeks[week - 1].get('zs', week))
|
||
result = api.get_timetable(xnm, xqm, kblx=kblx, zs=zs)
|
||
return {'success': True, 'data': result}
|
||
else:
|
||
result = api.get_timetable(xnm, xqm, kblx=kblx)
|
||
return {'success': True, 'data': result}
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except FileNotFoundError:
|
||
return jsonify({'success': False, 'message': 'Session不存在,请先配置教务系统账号'})
|
||
except RuntimeError as e:
|
||
return jsonify({'success': False, 'message': str(e)})
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}'})
|
||
|
||
|
||
@api_bp.route('/timetable/jc_times')
|
||
@api_auth
|
||
def api_timetable_jc_times():
|
||
"""获取节次上下课时间
|
||
|
||
查询参数(均为可选):
|
||
xnm 学年,不传则从教务系统自动推算
|
||
xqm 学期,不传则自动推算
|
||
"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号'})
|
||
|
||
query_xnm = request.args.get('xnm', '')
|
||
query_xqm = request.args.get('xqm', '')
|
||
|
||
def _do_request():
|
||
from app.kbcx_api import KbcxAPI
|
||
api = KbcxAPI(jwxt_acc['username'])
|
||
|
||
if query_xnm and query_xqm:
|
||
xnm = query_xnm
|
||
xqm = query_xqm
|
||
meta = {}
|
||
else:
|
||
meta = api.get_semester_meta()
|
||
xnm = meta['xnm']
|
||
xqm = meta['xqm']
|
||
|
||
xqh_id = meta.get('xqh_id', '')
|
||
|
||
if not xqh_id:
|
||
kb = api.get_timetable(xnm, xqm, kblx='2')
|
||
kb_list = kb.get('kbList', [])
|
||
if kb_list:
|
||
xqh_id = kb_list[0].get('xqh_id', '')
|
||
|
||
if not xqh_id:
|
||
return {'success': False, 'message': '无法获取校区ID,无法查询节次时间'}
|
||
|
||
jc_times = api.get_jc_times(xnm, xqm, xqh_id)
|
||
|
||
formatted = {}
|
||
for item in jc_times:
|
||
try:
|
||
jcmc = item.get('jcmc', '').strip()
|
||
if not jcmc:
|
||
continue
|
||
jcmc = jcmc.replace('第', '').replace('节', '').strip()
|
||
if not jcmc:
|
||
continue
|
||
jc_no = int(jcmc)
|
||
if jc_no > 0:
|
||
formatted[jc_no] = {
|
||
'start': item.get('qssj', '')[:5],
|
||
'end': item.get('jssj', '')[:5],
|
||
'period': item.get('rsdmc', '')
|
||
}
|
||
except (ValueError, KeyError):
|
||
continue
|
||
|
||
return {'success': True, 'data': formatted}
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except FileNotFoundError:
|
||
return jsonify({'success': False, 'message': 'Session不存在,请先配置教务系统账号'})
|
||
except RuntimeError as e:
|
||
return jsonify({'success': False, 'message': str(e)})
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}'})
|
||
|
||
|
||
@api_bp.route('/courses/tabs')
|
||
@api_auth
|
||
def api_courses_tabs():
|
||
"""获取所有课程类型标签页列表(kklxdm + kklxmc)"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号', 'tabs': []})
|
||
|
||
def _do_request():
|
||
from app.xk_api import CourseAPI
|
||
api = CourseAPI(jwxt_acc['username'])
|
||
return api.get_tab_list()
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except FileNotFoundError:
|
||
return jsonify({'success': False, 'message': 'Session不存在', 'tabs': []})
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}', 'tabs': []})
|
||
|
||
|
||
@api_bp.route('/courses/search_full')
|
||
@api_auth
|
||
def api_courses_search_full():
|
||
"""
|
||
搜索课程并一次性展开所有教学班(推荐使用此接口替代 courses/list + courses/jxb_list 两步)。
|
||
|
||
参数:
|
||
keyword 课程名称/课程号关键词
|
||
kklxdm 课程类型标签页代码(空=默认第一个 tab)
|
||
|
||
返回值中 courses[i].jxbs[j] 包含选课所需全部参数:
|
||
jxb_id, do_jxb_id, kklxdm(直接传给 /tasks/create)
|
||
"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号', 'courses': []})
|
||
|
||
keyword = request.args.get('keyword', '')
|
||
kklxdm = request.args.get('kklxdm', '')
|
||
xkkz_id = request.args.get('xkkz_id', '')
|
||
try:
|
||
page = int(request.args.get('page', '1'))
|
||
except ValueError:
|
||
page = 1
|
||
try:
|
||
page_size = int(request.args.get('page_size', '50'))
|
||
except ValueError:
|
||
page_size = 50
|
||
|
||
# 收集高级筛选条件
|
||
filter_keys = [
|
||
'tjbj', 'kkbm_id_list', 'njdm_id_list', 'jg_id_list',
|
||
'zyh_id_list', 'zyfx_id_list', 'bh_id_list',
|
||
'kclb_id_list', 'kcxzdm_list', 'kcgs_list', 'kcz_list',
|
||
'xq_list', 'yq_list', 'jxms_list',
|
||
'sksj_list', 'skjc_list', 'xf_list', 'jxbmc_list',
|
||
'cxbj_list', 'yl_list', 'sksjct_list',
|
||
]
|
||
extra_filters = {}
|
||
for k in filter_keys:
|
||
v = request.args.get(k)
|
||
if v:
|
||
extra_filters[k] = v
|
||
|
||
def _do_request():
|
||
from app.xk_api import CourseAPI
|
||
api = CourseAPI(jwxt_acc['username'])
|
||
return api.search_with_jxb(
|
||
keyword=keyword, kklxdm=kklxdm, xkkz_id=xkkz_id,
|
||
page=page, page_size=page_size,
|
||
extra_filters=extra_filters or None,
|
||
)
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except FileNotFoundError:
|
||
return jsonify({'success': False, 'message': 'Session不存在', 'courses': []})
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}', 'courses': []})
|
||
|
||
@api_bp.route('/jwxt/filter-options')
|
||
@api_auth
|
||
def api_jwxt_filter_options():
|
||
"""
|
||
代理正方系统的筛选下拉数据(开课学院、年级、课程类别等)
|
||
|
||
参数:
|
||
type: 筛选类型(kkbm, nj, xy, zy, kclb, kcxz, kcgs, kcz, yqu, jxms, sksj, skjc, bh, xq, zyfx)
|
||
其他参数原样透传给正方
|
||
"""
|
||
from app.jwxt_api import JwxtApi
|
||
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号', 'options': []})
|
||
|
||
filter_type = request.args.get('type', '')
|
||
|
||
# 正方后端查询路径映射
|
||
PATH_MAP = {
|
||
'kkbm': '/xkgl/common_queryKkbmPaged.html',
|
||
'nj': '/xkgl/common_queryNjPaged.html',
|
||
'xy': '/xkgl/common_queryXyPaged.html',
|
||
'zy': '/xkgl/common_queryZyPaged.html',
|
||
'kclb': '/xkgl/common_queryKclbListPaged.html',
|
||
'kcxz': '/xkgl/common_queryKcxzPaged.html',
|
||
'kcgs': '/xkgl/common_queryKcgsPaged.html',
|
||
'kcz': '/xkgl/common_queryKczPaged.html',
|
||
'yqu': '/xkgl/common_queryYquListPaged.html',
|
||
'jxms': '/xtgl/comm_cxJcsjList.html?lxdm=0032',
|
||
'sksj': '/xtgl/comm_cxJcsjList.html?lxdm=0036',
|
||
'skjc': '/xkgl/common_querySkjcList.html',
|
||
'bh': '/xtgl/comm_cxBjdmPaged.html',
|
||
'xq': '/xkgl/common_queryXquListPaged.html',
|
||
'zyfx': '/xsxxxggl/xsxxwh_cxZyfxPaged.html',
|
||
}
|
||
|
||
path = PATH_MAP.get(filter_type)
|
||
if not path:
|
||
return jsonify({'success': False, 'message': f'未知筛选类型: {filter_type}', 'options': []})
|
||
|
||
# 透传所有 query params,去掉 type 和 t(时间戳)
|
||
proxy_params = {k: v for k, v in request.args.items() if k not in ('type', 't')}
|
||
|
||
def _do_request():
|
||
api = JwxtApi(jwxt_acc['username'])
|
||
from app.url_manager import get_base_url
|
||
r = api.session.get(get_base_url() + path, params=proxy_params, timeout=15)
|
||
return r.json()
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
# 统一包装成 options 数组
|
||
items = result if isinstance(result, list) else result.get('items', [])
|
||
return jsonify({'success': True, 'options': items})
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': str(e), 'options': []})
|
||
|
||
|
||
# ---- 抢课任务API ----
|
||
|
||
@api_bp.route('/tasks/list')
|
||
@api_auth
|
||
def api_tasks_list():
|
||
"""获取用户抢课任务列表"""
|
||
page = request.args.get('page', 1, type=int)
|
||
per_page = request.args.get('per_page', 20, type=int)
|
||
status = request.args.get('status')
|
||
target_user_id = request.args.get('user_id', type=int)
|
||
|
||
# 管理员可以查看指定用户的任务
|
||
if target_user_id and current_user.is_admin:
|
||
query = GrabTask.query.filter_by(user_id=target_user_id)
|
||
else:
|
||
query = GrabTask.query.filter_by(user_id=current_user.id)
|
||
|
||
if status:
|
||
query = query.filter_by(status=status)
|
||
|
||
pagination = query.order_by(GrabTask.created_at.desc()).paginate(
|
||
page=page, per_page=per_page, error_out=False
|
||
)
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'tasks': [t.to_dict() for t in pagination.items],
|
||
'total': pagination.total,
|
||
'pages': pagination.pages,
|
||
'current_page': page,
|
||
'viewing_user_id': target_user_id if target_user_id and current_user.is_admin else current_user.id,
|
||
})
|
||
|
||
|
||
@api_bp.route('/tasks/create', methods=['POST'])
|
||
@api_auth
|
||
def api_tasks_create():
|
||
"""创建抢课任务"""
|
||
data = request.get_json()
|
||
|
||
# 验证必填字段
|
||
required_fields = ['course_name', 'course_id']
|
||
for field in required_fields:
|
||
if not data.get(field):
|
||
return jsonify({'success': False, 'message': f'缺少必填字段: {field}'})
|
||
|
||
# task_type 白名单:任意值会变成永远不触发的"幽灵任务"
|
||
task_type = data.get('task_type', GrabTask.TYPE_IMMEDIATE)
|
||
if task_type not in (GrabTask.TYPE_IMMEDIATE, GrabTask.TYPE_SCHEDULED):
|
||
return jsonify({'success': False, 'message': f'task_type 无效: {task_type}'})
|
||
|
||
# rules 结构校验:坏结构会让抢课引擎每轮循环抛异常无限重试
|
||
rules = data.get('rules')
|
||
if rules is not None:
|
||
if not isinstance(rules, dict):
|
||
return jsonify({'success': False, 'message': 'rules 必须是对象'})
|
||
ohv = rules.get('on_has_vacancy')
|
||
if ohv is not None:
|
||
if not isinstance(ohv, list):
|
||
return jsonify({'success': False, 'message': 'rules.on_has_vacancy 必须为数组'})
|
||
for r in ohv:
|
||
if not isinstance(r, dict):
|
||
return jsonify({'success': False, 'message': 'rules.on_has_vacancy 元素必须是对象'})
|
||
action = r.get('action', '')
|
||
if action not in ('choose_course', 'drop_course', 'wait'):
|
||
return jsonify({'success': False, 'message': f'未知的规则 action: {action}'})
|
||
if action == 'drop_course' and (not r.get('kch_id') or not r.get('do_jxb_id')):
|
||
return jsonify({'success': False,
|
||
'message': '退课规则必须包含 kch_id 与 do_jxb_id(抢课失败后需要凭这两个字段自动恢复课程)'})
|
||
|
||
# 创建任务(包含完整的抢课参数)
|
||
task = GrabTask(
|
||
user_id=current_user.id,
|
||
course_name=data.get('course_name'),
|
||
course_id=data.get('course_id'),
|
||
teacher_name=data.get('teacher_name', ''),
|
||
credit=data.get('credit', ''),
|
||
class_info=data.get('class_info', ''),
|
||
# 抢课所需完整参数
|
||
do_jxb_id=data.get('do_jxb_id', ''),
|
||
kch_id=data.get('kch_id', ''),
|
||
jxbzls=data.get('jxbzls', '0'),
|
||
kklxdm=data.get('kklxdm', ''),
|
||
rules=json.dumps(data.get('rules', {}), ensure_ascii=False) if data.get('rules') else None,
|
||
task_type=task_type,
|
||
max_retries=data.get('max_retries', 0)
|
||
)
|
||
|
||
# 处理定时时间(统一换算为北京时间 naive,避免 aware/naive 混用与 MySQL 截断)
|
||
if task.task_type == GrabTask.TYPE_SCHEDULED:
|
||
scheduled_time_str = data.get('scheduled_time')
|
||
if scheduled_time_str:
|
||
try:
|
||
dt = datetime.fromisoformat(scheduled_time_str.replace('Z', '+00:00'))
|
||
if dt.tzinfo is not None:
|
||
from app.time_utils import BJ_TZ
|
||
dt = dt.astimezone(BJ_TZ).replace(tzinfo=None)
|
||
task.scheduled_time = dt
|
||
except:
|
||
return jsonify({'success': False, 'message': '定时时间格式错误'})
|
||
else:
|
||
return jsonify({'success': False, 'message': '定时任务需要指定执行时间'})
|
||
|
||
db.session.add(task)
|
||
db.session.commit()
|
||
|
||
# 立即执行或加入调度队列
|
||
if task.task_type == GrabTask.TYPE_IMMEDIATE:
|
||
grab_engine.submit_task(task.id, immediate=True)
|
||
message = '任务已创建并立即执行'
|
||
else:
|
||
message = f'定时任务已创建,将在 {task.scheduled_time} 执行'
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'message': message,
|
||
'task': task.to_dict()
|
||
})
|
||
|
||
|
||
@api_bp.route('/tasks/<int:task_id>/cancel', methods=['POST'])
|
||
@api_auth
|
||
def api_tasks_cancel(task_id):
|
||
"""取消抢课任务"""
|
||
if current_user.is_admin:
|
||
task = GrabTask.query.filter_by(id=task_id).first()
|
||
else:
|
||
task = GrabTask.query.filter_by(id=task_id, user_id=current_user.id).first()
|
||
|
||
if not task:
|
||
return jsonify({'success': False, 'message': '任务不存在'})
|
||
|
||
if task.status not in [GrabTask.STATUS_PENDING, GrabTask.STATUS_RUNNING]:
|
||
return jsonify({'success': False, 'message': '任务已结束,无法取消'})
|
||
|
||
if grab_engine.cancel_task(task_id):
|
||
return jsonify({'success': True, 'message': '任务已取消'})
|
||
else:
|
||
return jsonify({'success': False, 'message': '取消任务失败'})
|
||
|
||
|
||
@api_bp.route('/tasks/<int:task_id>')
|
||
@api_auth
|
||
def api_tasks_detail(task_id):
|
||
"""获取任务详情"""
|
||
if current_user.is_admin:
|
||
task = GrabTask.query.filter_by(id=task_id).first()
|
||
else:
|
||
task = GrabTask.query.filter_by(id=task_id, user_id=current_user.id).first()
|
||
|
||
if not task:
|
||
return jsonify({'success': False, 'message': '任务不存在'})
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'task': task.to_dict()
|
||
})
|
||
|
||
|
||
# ---- 抢课日志API ----
|
||
|
||
@api_bp.route('/logs/list')
|
||
@api_auth
|
||
def api_logs_list():
|
||
"""获取抢课日志"""
|
||
task_id = request.args.get('task_id', type=int)
|
||
page = request.args.get('page', 1, type=int)
|
||
per_page = request.args.get('per_page', 50, type=int)
|
||
|
||
if current_user.is_admin and task_id:
|
||
# 管理员可以查看任何任务的日志
|
||
task = GrabTask.query.filter_by(id=task_id).first()
|
||
if not task:
|
||
return jsonify({'success': False, 'message': '任务不存在'})
|
||
query = GrabLog.query.filter_by(task_id=task_id)
|
||
else:
|
||
query = GrabLog.query.filter_by(user_id=current_user.id)
|
||
|
||
if task_id:
|
||
# 验证任务所有权
|
||
task = GrabTask.query.filter_by(id=task_id, user_id=current_user.id).first()
|
||
if not task:
|
||
return jsonify({'success': False, 'message': '无权查看该任务日志'})
|
||
query = query.filter_by(task_id=task_id)
|
||
|
||
pagination = query.order_by(GrabLog.created_at.desc()).paginate(
|
||
page=page, per_page=per_page, error_out=False
|
||
)
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'logs': [l.to_dict() for l in pagination.items],
|
||
'total': pagination.total,
|
||
'pages': pagination.pages,
|
||
'current_page': page
|
||
})
|
||
|
||
|
||
@api_bp.route('/logs/recent')
|
||
@api_auth
|
||
def api_logs_recent():
|
||
"""获取最近日志(用于实时更新)"""
|
||
task_id = request.args.get('task_id', type=int)
|
||
after_id = request.args.get('after_id', 0, type=int)
|
||
|
||
if current_user.is_admin and task_id:
|
||
# 管理员可以查看任何任务的日志
|
||
task = GrabTask.query.filter_by(id=task_id).first()
|
||
if not task:
|
||
return jsonify({'success': False, 'message': '任务不存在'})
|
||
query = GrabLog.query.filter_by(task_id=task_id)
|
||
else:
|
||
query = GrabLog.query.filter_by(user_id=current_user.id)
|
||
if task_id:
|
||
query = query.filter_by(task_id=task_id)
|
||
|
||
logs = query.filter(GrabLog.id > after_id)\
|
||
.order_by(GrabLog.created_at.asc())\
|
||
.limit(100).all()
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'logs': [l.to_dict() for l in logs]
|
||
})
|
||
|
||
|
||
# ---- 管理员API ----
|
||
|
||
@api_bp.route('/admin/users/list')
|
||
@api_auth
|
||
def api_admin_users_list():
|
||
"""获取用户列表(仅管理员)"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
page = request.args.get('page', 1, type=int)
|
||
per_page = request.args.get('per_page', 20, type=int)
|
||
|
||
pagination = User.query.order_by(User.created_at.desc()).paginate(
|
||
page=page, per_page=per_page, error_out=False
|
||
)
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'users': [u.to_dict() for u in pagination.items],
|
||
'total': pagination.total,
|
||
'pages': pagination.pages
|
||
})
|
||
|
||
|
||
@api_bp.route('/admin/users/create', methods=['POST'])
|
||
@api_auth
|
||
def api_admin_users_create():
|
||
"""创建用户(仅管理员)"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
data = request.get_json()
|
||
username = data.get('username')
|
||
password = data.get('password')
|
||
is_admin = data.get('is_admin', False)
|
||
school_id = data.get('school_id') or DEFAULT_SCHOOL_ID
|
||
|
||
if not username or not password:
|
||
return jsonify({'success': False, 'message': '用户名和密码不能为空'})
|
||
|
||
if User.query.filter_by(username=username).first():
|
||
return jsonify({'success': False, 'message': '用户名已存在'})
|
||
if not get_school(school_id):
|
||
return jsonify({'success': False, 'message': '学校不存在'}), 400
|
||
|
||
user = User(username=username, is_admin=is_admin, school_id=school_id)
|
||
user.set_password(password)
|
||
db.session.add(user)
|
||
db.session.commit()
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'message': '用户创建成功',
|
||
'user': user.to_dict()
|
||
})
|
||
|
||
|
||
@api_bp.route('/admin/users/<int:user_id>/delete', methods=['POST'])
|
||
@api_auth
|
||
def api_admin_users_delete(user_id):
|
||
"""删除用户(仅管理员),同时清理关联数据"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
# 不能删除自己
|
||
if user_id == current_user.id:
|
||
return jsonify({'success': False, 'message': '不能删除当前登录的管理员账户'})
|
||
|
||
user = User.query.get(user_id)
|
||
if not user:
|
||
return jsonify({'success': False, 'message': '用户不存在'})
|
||
|
||
try:
|
||
# 删除用户的所有任务
|
||
GrabTask.query.filter_by(user_id=user_id).delete()
|
||
|
||
# 删除用户
|
||
db.session.delete(user)
|
||
db.session.commit()
|
||
|
||
# 清理关联数据(数据库已提交,这些清理失败不影响主流程)
|
||
cleanup_errors = []
|
||
|
||
# 1. 清理 tickets.json 中的 user_tickets 记录
|
||
try:
|
||
from app.ticket_manager import TicketManager
|
||
ticket_data = TicketManager._load_data()
|
||
user_id_str = str(user_id)
|
||
if user_id_str in ticket_data.get('user_tickets', {}):
|
||
del ticket_data['user_tickets'][user_id_str]
|
||
TicketManager._save_data(ticket_data)
|
||
except Exception as e:
|
||
cleanup_errors.append(f'tickets.json清理失败: {e}')
|
||
|
||
# 2. 清理 accounts.json 中的教务系统账号配置
|
||
try:
|
||
from app.account_manager import AccountManager
|
||
AccountManager.delete_jwxt_account(user_id=user_id)
|
||
except Exception as e:
|
||
cleanup_errors.append(f'accounts.json清理失败: {e}')
|
||
|
||
# 返回结果
|
||
message = '用户已删除'
|
||
if cleanup_errors:
|
||
message += f'(部分关联数据清理失败: {"; ".join(cleanup_errors)})'
|
||
|
||
return jsonify({'success': True, 'message': message})
|
||
except Exception as e:
|
||
db.session.rollback()
|
||
return jsonify({'success': False, 'message': f'删除失败: {str(e)}'})
|
||
|
||
|
||
@api_bp.route('/admin/stats')
|
||
@api_auth
|
||
def api_admin_stats():
|
||
"""获取系统统计(仅管理员)"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
# 统计数据
|
||
total_users = User.query.count()
|
||
total_tasks = GrabTask.query.count()
|
||
pending_tasks = GrabTask.query.filter_by(status=GrabTask.STATUS_PENDING).count()
|
||
running_tasks = GrabTask.query.filter_by(status=GrabTask.STATUS_RUNNING).count()
|
||
success_tasks = GrabTask.query.filter_by(status=GrabTask.STATUS_SUCCESS).count()
|
||
failed_tasks = GrabTask.query.filter_by(status=GrabTask.STATUS_FAILED).count()
|
||
|
||
# Session状态统计
|
||
session_valid = User.query.filter_by(session_status='valid').count()
|
||
session_invalid = User.query.filter_by(session_status='invalid').count()
|
||
session_unknown = User.query.filter_by(session_status='unknown').count()
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'stats': {
|
||
'total_users': total_users,
|
||
'total_tasks': total_tasks,
|
||
'pending_tasks': pending_tasks,
|
||
'running_tasks': running_tasks,
|
||
'success_tasks': success_tasks,
|
||
'failed_tasks': failed_tasks,
|
||
'session_stats': {
|
||
'valid': session_valid,
|
||
'invalid': session_invalid,
|
||
'unknown': session_unknown
|
||
}
|
||
}
|
||
})
|
||
|
||
|
||
@api_bp.route('/admin/ai/config', methods=['GET', 'POST'])
|
||
@api_auth
|
||
def api_admin_ai_config():
|
||
"""管理端配置 AI Key、模型和兼容 API 地址。"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
from app.ai_assistant import get_ai_settings, save_ai_settings
|
||
if request.method == 'GET':
|
||
return jsonify({'success': True, 'config': get_ai_settings()})
|
||
try:
|
||
save_ai_settings(request.get_json(silent=True) or {})
|
||
return jsonify({'success': True, 'message': 'AI 配置已保存', 'config': get_ai_settings()})
|
||
except ValueError as exc:
|
||
return jsonify({'success': False, 'message': str(exc)}), 400
|
||
except Exception as exc:
|
||
return jsonify({'success': False, 'message': f'保存失败:{str(exc)}'}), 500
|
||
|
||
|
||
@api_bp.route('/admin/ai/models', methods=['GET', 'POST'])
|
||
@api_auth
|
||
def api_admin_ai_models():
|
||
"""管理员通过服务端读取 AI 服务的可用模型,支持使用表单中的临时 Key。"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
from app.ai_assistant import list_available_models
|
||
data = request.get_json(silent=True) or {}
|
||
result = list_available_models(
|
||
api_key=str(data.get('api_key', '')).strip(),
|
||
base_url=str(data.get('base_url', '')).strip(),
|
||
)
|
||
if result.get('success'):
|
||
return jsonify(result), 200
|
||
status = 400 if result.get('message') == '请先在输入框填写 API Key' else 502
|
||
return jsonify(result), status
|
||
|
||
|
||
@api_bp.route('/admin/tasks/list')
|
||
@api_auth
|
||
def api_admin_tasks_list():
|
||
"""管理员获取所有用户的任务列表"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
page = request.args.get('page', 1, type=int)
|
||
per_page = request.args.get('per_page', 20, type=int)
|
||
status = request.args.get('status')
|
||
|
||
query = GrabTask.query
|
||
if status:
|
||
query = query.filter_by(status=status)
|
||
|
||
pagination = query.order_by(GrabTask.created_at.desc()).paginate(
|
||
page=page, per_page=per_page, error_out=False
|
||
)
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'tasks': [t.to_dict() for t in pagination.items],
|
||
'total': pagination.total,
|
||
'pages': pagination.pages,
|
||
'current_page': page
|
||
})
|
||
|
||
|
||
@api_bp.route('/admin/ai/usage')
|
||
@api_auth
|
||
def api_admin_ai_usage():
|
||
"""管理端 AI 用量统计:所有用户今日用量 + 生效限额 + 近 7 天趋势。"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
from app.ai_usage import get_all_users_daily_usage, get_default_daily_limit, get_usage_trend
|
||
users = get_all_users_daily_usage()
|
||
totals = {
|
||
'calls': sum(u['calls'] for u in users),
|
||
'input_tokens': sum(u['input_tokens'] for u in users),
|
||
'output_tokens': sum(u['output_tokens'] for u in users),
|
||
'total_tokens': sum(u['total_tokens'] for u in users),
|
||
}
|
||
return jsonify({
|
||
'success': True,
|
||
'default_limit': get_default_daily_limit(),
|
||
'totals': totals,
|
||
'users': users,
|
||
'trend': get_usage_trend(7),
|
||
})
|
||
|
||
|
||
@api_bp.route('/admin/ai/usage/limit', methods=['POST'])
|
||
@api_auth
|
||
def api_admin_ai_usage_limit():
|
||
"""设置单个用户的 AI 每日 token 上限。limit 传 null 恢复全局默认,0 表示不限制。"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
data = request.get_json(silent=True) or {}
|
||
user_id = data.get('user_id')
|
||
limit = data.get('limit')
|
||
if user_id is None:
|
||
return jsonify({'success': False, 'message': '缺少 user_id'}), 400
|
||
user = User.query.get(int(user_id))
|
||
if not user:
|
||
return jsonify({'success': False, 'message': '用户不存在'}), 404
|
||
if limit in (None, ''):
|
||
user.ai_daily_limit = None
|
||
message = '已恢复为全局默认限额'
|
||
else:
|
||
try:
|
||
value = int(str(limit).strip())
|
||
except (TypeError, ValueError):
|
||
return jsonify({'success': False, 'message': '限额必须是 >= 0 的整数(0 表示不限制)'}), 400
|
||
if value < 0:
|
||
return jsonify({'success': False, 'message': '限额必须是 >= 0 的整数(0 表示不限制)'}), 400
|
||
user.ai_daily_limit = value
|
||
message = '每日限额已更新(0 表示不限制)' if value == 0 else '每日限额已更新'
|
||
db.session.commit()
|
||
return jsonify({'success': True, 'message': message, 'user_id': user.id, 'ai_daily_limit': user.ai_daily_limit})
|
||
|
||
|
||
@api_bp.route('/admin/tasks/batch_cancel', methods=['POST'])
|
||
@api_auth
|
||
def api_admin_tasks_batch_cancel():
|
||
"""管理员批量取消任务"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
data = request.get_json(silent=True) or {}
|
||
task_ids = data.get('task_ids', [])
|
||
|
||
if not task_ids or not isinstance(task_ids, list):
|
||
return jsonify({'success': False, 'message': '请提供要取消的任务ID列表'})
|
||
|
||
results = []
|
||
for task_id in task_ids:
|
||
task = GrabTask.query.get(task_id)
|
||
if not task:
|
||
results.append({'id': task_id, 'success': False, 'message': '任务不存在'})
|
||
continue
|
||
if task.status not in [GrabTask.STATUS_PENDING, GrabTask.STATUS_RUNNING]:
|
||
results.append({'id': task_id, 'success': False, 'message': f'任务已结束({task.status}),无法取消'})
|
||
continue
|
||
|
||
if grab_engine.cancel_task(task_id):
|
||
results.append({'id': task_id, 'success': True, 'message': '已取消'})
|
||
else:
|
||
results.append({'id': task_id, 'success': False, 'message': '取消任务失败'})
|
||
|
||
success_count = sum(1 for r in results if r['success'])
|
||
return jsonify({
|
||
'success': True,
|
||
'success_count': success_count,
|
||
'total': len(task_ids),
|
||
'results': results
|
||
})
|
||
|
||
|
||
@api_bp.route('/admin/stats/requests')
|
||
@api_auth
|
||
def api_admin_request_stats():
|
||
"""获取请求速度统计(仅管理员)"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
from app.time_utils import now as bj_now
|
||
from datetime import timedelta
|
||
from app.models import GrabLog
|
||
from sqlalchemy import func
|
||
|
||
now = bj_now()
|
||
|
||
# 最近60秒(按秒聚合)
|
||
cutoff_60s = now - timedelta(seconds=60)
|
||
recent_logs = db.session.query(
|
||
func.date_format(GrabLog.created_at, '%H:%M:%S').label('sec'),
|
||
db.func.count(GrabLog.id).label('cnt')
|
||
).filter(
|
||
GrabLog.created_at >= cutoff_60s
|
||
).group_by('sec').all()
|
||
|
||
sec_map = {r.sec: r.cnt for r in recent_logs}
|
||
last_60s = []
|
||
for i in range(60, 0, -1):
|
||
t = now - timedelta(seconds=i)
|
||
key = t.strftime('%H:%M:%S')
|
||
last_60s.append({'time': key, 'count': sec_map.get(key, 0)})
|
||
|
||
# 最近24小时(按小时聚合)
|
||
cutoff_24h = now - timedelta(hours=24)
|
||
hourly_logs = db.session.query(
|
||
func.date_format(GrabLog.created_at, '%Y-%m-%d %H:00').label('hour'),
|
||
db.func.count(GrabLog.id).label('cnt')
|
||
).filter(
|
||
GrabLog.created_at >= cutoff_24h
|
||
).group_by('hour').order_by('hour').all()
|
||
|
||
hour_map = {r.hour: r.cnt for r in hourly_logs}
|
||
last_24h = []
|
||
for i in range(24, 0, -1):
|
||
t = now - timedelta(hours=i)
|
||
key = t.strftime('%Y-%m-%d %H:00')
|
||
last_24h.append({'time': t.strftime('%H:00'), 'count': hour_map.get(key, 0)})
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'last_60s': last_60s,
|
||
'last_24h': last_24h,
|
||
})
|
||
|
||
|
||
@api_bp.route('/admin/users/<int:user_id>/session/refresh', methods=['POST'])
|
||
@api_auth
|
||
def api_admin_user_session_refresh(user_id):
|
||
"""管理员刷新指定用户的session"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
user = User.query.get_or_404(user_id)
|
||
data = request.get_json() or {}
|
||
force = data.get('force', False)
|
||
jwxt_password = data.get('jwxt_password', '').strip()
|
||
|
||
# 获取当前教务系统账号
|
||
jwxt_acc = user.get_jwxt_account()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '该用户未配置教务系统账号'})
|
||
|
||
username = jwxt_acc['username']
|
||
from app.url_manager import push_school
|
||
push_school(user.school_id)
|
||
|
||
# 检查当前状态
|
||
if not force:
|
||
is_valid, _ = SessionManager.is_session_valid(username)
|
||
if is_valid:
|
||
return jsonify({
|
||
'success': True,
|
||
'status': 'valid',
|
||
'message': 'Session仍然有效,无需刷新'
|
||
})
|
||
|
||
# 如果提供了新密码,更新密码
|
||
if jwxt_password:
|
||
# 更新 accounts.json 中的密码
|
||
from app.account_manager import AccountManager
|
||
AccountManager.set_jwxt_account(
|
||
user_id=user.id,
|
||
username=user.username,
|
||
jwxt_username=user.jwxt_username or user.username,
|
||
jwxt_password=jwxt_password,
|
||
jwxt_name=user.jwxt_name,
|
||
school_id=user.school_id
|
||
)
|
||
|
||
# 执行刷新(使用 accounts.json 中的密码)
|
||
result = SessionManager.refresh_session(user, force=True)
|
||
db.session.commit()
|
||
|
||
return jsonify(result)
|
||
|
||
|
||
@api_bp.route('/admin/session/batch_check', methods=['POST'])
|
||
@api_auth
|
||
def api_admin_session_batch_check():
|
||
"""管理员批量检查session状态"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
users = User.query.all()
|
||
|
||
results = {
|
||
'total': len(users),
|
||
'valid': 0,
|
||
'invalid': 0,
|
||
'unknown': 0,
|
||
'no_account': 0,
|
||
'details': []
|
||
}
|
||
|
||
for user in users:
|
||
# 获取教务系统账号
|
||
jwxt_acc = user.get_jwxt_account()
|
||
|
||
if not jwxt_acc:
|
||
results['no_account'] += 1
|
||
results['details'].append({
|
||
'user_id': user.id,
|
||
'username': user.username,
|
||
'status': 'no_account',
|
||
'message': '未配置教务系统账号'
|
||
})
|
||
# 更新数据库
|
||
user.session_status = 'unknown'
|
||
continue
|
||
|
||
jwxt_username = jwxt_acc['username']
|
||
from app.url_manager import push_school
|
||
push_school(user.school_id)
|
||
is_valid, error_msg = SessionManager.is_session_valid(jwxt_username)
|
||
|
||
# 更新数据库
|
||
user.session_status = 'valid' if is_valid else 'invalid'
|
||
if not is_valid:
|
||
user.session_error_msg = error_msg
|
||
|
||
if is_valid:
|
||
results['valid'] += 1
|
||
else:
|
||
results['invalid'] += 1
|
||
|
||
results['details'].append({
|
||
'user_id': user.id,
|
||
'username': user.username,
|
||
'jwxt_username': jwxt_username,
|
||
'status': 'valid' if is_valid else 'invalid',
|
||
'message': error_msg if not is_valid else None
|
||
})
|
||
|
||
db.session.commit()
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'results': results
|
||
})
|
||
|
||
|
||
@api_bp.route('/admin/session/batch_refresh', methods=['POST'])
|
||
@api_auth
|
||
def api_admin_session_batch_refresh():
|
||
"""管理员批量刷新session(自动从 accounts.json 获取密码)"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
data = request.get_json() or {}
|
||
user_ids = data.get('user_ids', []) # 指定用户ID列表,空则全部
|
||
force = data.get('force', False)
|
||
|
||
query = User.query
|
||
if user_ids:
|
||
query = query.filter(User.id.in_(user_ids))
|
||
users = query.all()
|
||
|
||
results = {
|
||
'total': len(users),
|
||
'valid': 0,
|
||
'refreshed': 0,
|
||
'failed': 0,
|
||
'no_account': 0,
|
||
'details': []
|
||
}
|
||
|
||
for user in users:
|
||
# 获取教务系统账号
|
||
jwxt_acc = user.get_jwxt_account()
|
||
|
||
if not jwxt_acc:
|
||
results['no_account'] += 1
|
||
results['failed'] += 1
|
||
results['details'].append({
|
||
'user_id': user.id,
|
||
'username': user.username,
|
||
'status': 'no_account',
|
||
'message': '未配置教务系统账号'
|
||
})
|
||
continue
|
||
|
||
username = jwxt_acc['username']
|
||
from app.url_manager import push_school
|
||
push_school(user.school_id)
|
||
|
||
# 检查当前状态
|
||
if not force:
|
||
is_valid, _ = SessionManager.is_session_valid(username)
|
||
if is_valid:
|
||
results['valid'] += 1
|
||
# 更新数据库状态
|
||
user.session_status = 'valid'
|
||
results['details'].append({
|
||
'user_id': user.id,
|
||
'username': user.username,
|
||
'jwxt_username': username,
|
||
'status': 'valid',
|
||
'message': 'Session仍然有效'
|
||
})
|
||
continue
|
||
|
||
# 执行刷新
|
||
result = SessionManager.refresh_session(user, force=True)
|
||
|
||
if result['status'] == 'refreshed':
|
||
results['refreshed'] += 1
|
||
elif result['status'] == 'valid':
|
||
results['valid'] += 1
|
||
else:
|
||
results['failed'] += 1
|
||
|
||
results['details'].append({
|
||
'user_id': user.id,
|
||
'username': user.username,
|
||
'jwxt_username': username,
|
||
'status': result['status'],
|
||
'message': result['message']
|
||
})
|
||
|
||
db.session.commit()
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'results': results
|
||
})
|
||
|
||
|
||
# ---- Session管理API ----
|
||
|
||
@api_bp.route('/user/session/status')
|
||
@api_auth
|
||
def api_user_session_status():
|
||
"""获取当前用户session状态"""
|
||
from app.test_mock import TEST_USERNAME
|
||
if current_user.is_authenticated and current_user.username == TEST_USERNAME:
|
||
return jsonify({
|
||
'success': True,
|
||
'is_valid': True,
|
||
'status': 'valid',
|
||
'message': 'Session正常(模拟)',
|
||
'error_msg': None,
|
||
'user': current_user.to_dict()
|
||
})
|
||
|
||
# 获取教务系统账号
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
|
||
if not jwxt_acc:
|
||
return jsonify({
|
||
'success': False,
|
||
'is_valid': False,
|
||
'status': 'no_account',
|
||
'message': '未配置教务系统账号',
|
||
'error_msg': '请先配置教务系统账号'
|
||
})
|
||
|
||
username = jwxt_acc['username']
|
||
is_valid, error_msg = SessionManager.is_session_valid(username)
|
||
|
||
# 更新数据库状态
|
||
current_user.session_status = 'valid' if is_valid else 'invalid'
|
||
if not is_valid:
|
||
current_user.session_error_msg = error_msg
|
||
db.session.commit()
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'is_valid': is_valid,
|
||
'status': current_user.session_status,
|
||
'jwxt_username': username,
|
||
'updated_at': to_iso(current_user.session_updated_at),
|
||
'error_msg': error_msg
|
||
})
|
||
|
||
|
||
@api_bp.route('/user/session/refresh', methods=['POST'])
|
||
@api_auth
|
||
def api_user_session_refresh():
|
||
"""用户刷新自己的session"""
|
||
data = request.get_json() or {}
|
||
jwxt_password = data.get('jwxt_password', '').strip()
|
||
|
||
# 获取当前教务系统账号
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
|
||
if not jwxt_acc:
|
||
# 如果没有配置教务系统账号,需要用户提供
|
||
if not jwxt_password:
|
||
return jsonify({
|
||
'success': False,
|
||
'message': '请先配置教务系统账号和密码',
|
||
'need_config': True
|
||
})
|
||
# 使用提供的密码进行首次配置
|
||
jwxt_username = current_user.jwxt_username or current_user.username
|
||
else:
|
||
jwxt_username = jwxt_acc['username']
|
||
# 如果提供了新密码,更新密码
|
||
if jwxt_password:
|
||
from app.account_manager import AccountManager
|
||
AccountManager.set_jwxt_account(
|
||
user_id=current_user.id,
|
||
username=current_user.username,
|
||
jwxt_username=jwxt_username,
|
||
jwxt_password=jwxt_password,
|
||
jwxt_name=current_user.jwxt_name,
|
||
school_id=current_user.school_id
|
||
)
|
||
|
||
# 执行刷新(使用 accounts.json 中的密码)
|
||
result = SessionManager.refresh_session(current_user, force=True)
|
||
db.session.commit()
|
||
|
||
return jsonify(result)
|
||
|
||
|
||
@api_bp.route('/user/jwxt/config', methods=['POST'])
|
||
@api_auth
|
||
def api_user_jwxt_config():
|
||
"""用户配置/修改教务系统账号"""
|
||
data = request.get_json()
|
||
jwxt_username = data.get('jwxt_username', '').strip()
|
||
jwxt_password = data.get('jwxt_password', '').strip()
|
||
jwxt_name = data.get('jwxt_name', '').strip()
|
||
|
||
if not jwxt_username or not jwxt_password:
|
||
return jsonify({'success': False, 'message': '请填写教务系统账号和密码'})
|
||
|
||
# 验证账号密码(尝试登录10次)
|
||
success, msg = SessionManager.test_login(jwxt_username, jwxt_password, max_attempts=10)
|
||
if not success:
|
||
return jsonify({'success': False, 'message': f'验证失败: {msg}'})
|
||
|
||
# 更新用户信息(只存学号和姓名)
|
||
current_user.jwxt_username = jwxt_username
|
||
current_user.jwxt_name = jwxt_name
|
||
current_user.session_status = 'valid'
|
||
current_user.session_updated_at = bj_now()
|
||
current_user.session_error_msg = None
|
||
db.session.commit()
|
||
|
||
# 保存教务系统账号到 accounts.json
|
||
from app.account_manager import AccountManager
|
||
AccountManager.set_jwxt_account(
|
||
user_id=current_user.id,
|
||
username=current_user.username,
|
||
jwxt_username=jwxt_username,
|
||
jwxt_password=jwxt_password,
|
||
jwxt_name=jwxt_name,
|
||
school_id=current_user.school_id
|
||
)
|
||
|
||
# 保存session
|
||
SessionManager.login_and_save(jwxt_username, jwxt_password)
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'message': '教务系统账号配置成功',
|
||
'user': current_user.to_dict()
|
||
})
|
||
|
||
|
||
# ---- 系统API ----
|
||
|
||
@api_bp.route('/system/status')
|
||
def api_system_status():
|
||
"""获取系统状态"""
|
||
return jsonify({
|
||
'success': True,
|
||
'status': 'running',
|
||
'timestamp': bj_now().isoformat()
|
||
})
|
||
|
||
|
||
# ---- 注册码管理API ----
|
||
|
||
@api_bp.route('/admin/schools', methods=['GET', 'POST'])
|
||
@api_auth
|
||
def api_admin_schools():
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
if request.method == 'GET':
|
||
return jsonify({'success': True, 'schools': list_schools()})
|
||
try:
|
||
school = save_school(request.get_json(silent=True) or {})
|
||
except ValueError as exc:
|
||
return jsonify({'success': False, 'message': str(exc)}), 400
|
||
return jsonify({'success': True, 'school': school})
|
||
|
||
|
||
@api_bp.route('/admin/schools/<school_id>/icon', methods=['POST', 'DELETE'])
|
||
@api_auth
|
||
def api_admin_school_icon(school_id):
|
||
"""学校 ICO 图标上传/清除(仅管理员,multipart 文件上传)"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
from app.school_manager import clear_school_icon, get_school, save_school, save_school_icon
|
||
school = get_school(school_id)
|
||
if not school:
|
||
return jsonify({'success': False, 'message': '请先保存学校,再上传图标'}), 404
|
||
|
||
if request.method == 'DELETE':
|
||
try:
|
||
clear_school_icon(school_id)
|
||
except Exception as exc:
|
||
return jsonify({'success': False, 'message': f'清除失败: {exc}'}), 500
|
||
return jsonify({'success': True, 'message': '已清除图标', 'favicon': ''})
|
||
|
||
file = request.files.get('file')
|
||
if not file or not file.filename:
|
||
return jsonify({'success': False, 'message': '未选择图片'}), 400
|
||
try:
|
||
favicon_url = save_school_icon(school_id, file)
|
||
except ValueError as exc:
|
||
return jsonify({'success': False, 'message': str(exc)}), 400
|
||
except Exception as exc:
|
||
return jsonify({'success': False, 'message': f'图片处理失败: {exc}'}), 500
|
||
merged = dict(school)
|
||
merged['favicon'] = favicon_url
|
||
try:
|
||
save_school(merged)
|
||
except ValueError as exc:
|
||
return jsonify({'success': False, 'message': str(exc)}), 400
|
||
return jsonify({'success': True, 'message': '图标已上传', 'favicon': favicon_url})
|
||
|
||
@api_bp.route('/admin/tickets/list')
|
||
@api_auth
|
||
def api_admin_tickets_list():
|
||
"""获取注册码列表(仅管理员)"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
from app.ticket_manager import TicketManager
|
||
tickets = TicketManager.list_tickets()
|
||
stats = TicketManager.get_stats()
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'tickets': tickets,
|
||
'stats': stats
|
||
})
|
||
|
||
|
||
@api_bp.route('/admin/tickets/create', methods=['POST'])
|
||
@api_auth
|
||
def api_admin_tickets_create():
|
||
"""创建注册码(仅管理员)"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
data = request.get_json()
|
||
max_uses = data.get('max_uses', 1)
|
||
count = data.get('count', 1) # 批量生成数量
|
||
# activate_on_use 为 True 时:生成时不设到期时间,用户首次使用后按 valid_days 开始计时
|
||
activate_on_use = bool(data.get('activate_on_use', False))
|
||
expiry_days = 0 if activate_on_use else data.get('expiry_days', 365)
|
||
valid_days = data.get('valid_days') if activate_on_use else None
|
||
school_ids = data.get('school_ids')
|
||
if school_ids is not None:
|
||
if not isinstance(school_ids, list) or not school_ids or any(not get_school(sid) for sid in school_ids):
|
||
return jsonify({'success': False, 'message': '请选择有效的学校,或选择全部学校'}), 400
|
||
school_ids = list(dict.fromkeys(school_ids))
|
||
|
||
from app.ticket_manager import TicketManager
|
||
|
||
codes = []
|
||
for _ in range(count):
|
||
code = TicketManager.generate_ticket(
|
||
max_uses=max_uses,
|
||
expiry_days=expiry_days,
|
||
created_by=current_user.username,
|
||
valid_days=valid_days,
|
||
school_ids=school_ids
|
||
)
|
||
codes.append(code)
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'codes': codes,
|
||
'message': f'成功生成 {len(codes)} 个注册码'
|
||
})
|
||
|
||
|
||
@api_bp.route('/admin/tickets/<code>/disable', methods=['POST'])
|
||
@api_auth
|
||
def api_admin_tickets_disable(code):
|
||
"""禁用注册码(仅管理员)"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
from app.ticket_manager import TicketManager
|
||
if TicketManager.disable_ticket(code):
|
||
return jsonify({'success': True, 'message': '注册码已禁用'})
|
||
return jsonify({'success': False, 'message': '注册码不存在'})
|
||
|
||
|
||
@api_bp.route('/admin/tickets/<code>/enable', methods=['POST'])
|
||
@api_auth
|
||
def api_admin_tickets_enable(code):
|
||
"""启用注册码(仅管理员)"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
from app.ticket_manager import TicketManager
|
||
if TicketManager.enable_ticket(code):
|
||
return jsonify({'success': True, 'message': '注册码已启用'})
|
||
return jsonify({'success': False, 'message': '注册码不存在'})
|
||
|
||
|
||
@api_bp.route('/admin/tickets/<code>/delete', methods=['POST'])
|
||
@api_auth
|
||
def api_admin_tickets_delete(code):
|
||
"""删除注册码(仅管理员),同时删除使用该注册码的用户"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
from app.ticket_manager import TicketManager
|
||
|
||
# 清理注册码格式
|
||
clean_code = ''.join(c for c in code.upper() if c.isalnum())
|
||
|
||
# 获取使用该注册码的用户列表
|
||
ticket_data = TicketManager._load_data()
|
||
users_to_delete = []
|
||
for user_id, user_ticket in ticket_data.get('user_tickets', {}).items():
|
||
user_code = ''.join(c for c in user_ticket['code'].upper() if c.isalnum())
|
||
if user_code == clean_code:
|
||
users_to_delete.append(int(user_id))
|
||
|
||
# 删除数据库中的用户及其任务
|
||
deleted_users_count = 0
|
||
for user_id in users_to_delete:
|
||
# 不能删除当前登录的管理员
|
||
if user_id == current_user.id:
|
||
continue
|
||
user = User.query.get(user_id)
|
||
if user:
|
||
# 删除用户的所有任务
|
||
GrabTask.query.filter_by(user_id=user_id).delete()
|
||
# 删除用户
|
||
db.session.delete(user)
|
||
deleted_users_count += 1
|
||
|
||
if deleted_users_count > 0:
|
||
db.session.commit()
|
||
|
||
# 删除注册码
|
||
if TicketManager.delete_ticket(code):
|
||
msg = '注册码已删除'
|
||
if deleted_users_count > 0:
|
||
msg += f',同时删除了 {deleted_users_count} 个关联用户'
|
||
return jsonify({'success': True, 'message': msg})
|
||
return jsonify({'success': False, 'message': '注册码不存在'})
|
||
|
||
|
||
@api_bp.route('/admin/tickets/stats')
|
||
@api_auth
|
||
def api_admin_tickets_stats():
|
||
"""获取注册码统计(仅管理员)"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
from app.ticket_manager import TicketManager
|
||
stats = TicketManager.get_stats()
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'stats': stats
|
||
})
|
||
|
||
|
||
# ---- 支付管理API ----
|
||
|
||
@api_bp.route('/admin/orders')
|
||
@api_auth
|
||
def api_admin_orders():
|
||
"""获取订单列表(仅管理员)"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
from app.payment_manager import PaymentManager
|
||
|
||
status = request.args.get('status', 'all')
|
||
search = request.args.get('search', '').strip().lower()
|
||
|
||
# 获取所有订单
|
||
orders = PaymentManager.get_orders('all')
|
||
|
||
# 筛选状态
|
||
if status != 'all':
|
||
orders = [o for o in orders if o.get('status') == status]
|
||
|
||
# 搜索
|
||
if search:
|
||
orders = [o for o in orders if (
|
||
search in o.get('order_id', '').lower() or
|
||
search in o.get('email', '').lower() or
|
||
search in (o.get('invite_code') or '').lower()
|
||
)]
|
||
|
||
# 计算统计
|
||
all_orders = PaymentManager.get_orders('all')
|
||
stats = {
|
||
'total': len(all_orders),
|
||
'pending': len([o for o in all_orders if o.get('status') == 'pending']),
|
||
'paid': len([o for o in all_orders if o.get('status') == 'paid']),
|
||
'processed': len([o for o in all_orders if o.get('status') == 'processed']),
|
||
'revenue': sum(o.get('final_amount', 0) for o in all_orders if o.get('status') in ['paid', 'processed'])
|
||
}
|
||
|
||
# 按时间倒序
|
||
orders = sorted(orders, key=lambda x: x.get('created_at', ''), reverse=True)
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'orders': orders,
|
||
'stats': stats
|
||
})
|
||
|
||
|
||
@api_bp.route('/admin/orders/<order_id>/confirm-payment', methods=['POST'])
|
||
@api_auth
|
||
def api_admin_confirm_payment(order_id):
|
||
"""手动确认支付(仅管理员)"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
from app.payment_manager import PaymentManager
|
||
|
||
# 获取订单
|
||
order = PaymentManager.get_order(order_id)
|
||
if not order:
|
||
return jsonify({'success': False, 'message': '订单不存在'})
|
||
|
||
if order.get('status') != 'pending':
|
||
return jsonify({'success': False, 'message': '订单状态不是待支付'})
|
||
|
||
# 更新订单状态为已支付
|
||
success, message = PaymentManager.update_order_status(
|
||
order_id,
|
||
'paid',
|
||
platform_order_no='MANUAL_' + bj_now().strftime('%Y%m%d%H%M%S'),
|
||
actual_pay_amount=order.get('final_amount')
|
||
)
|
||
|
||
if not success:
|
||
return jsonify({'success': False, 'message': message})
|
||
|
||
# 处理订单:生成注册码并发送邮件
|
||
process_success, process_msg, ticket_codes = PaymentManager.process_paid_order(order_id, expiry_days=180)
|
||
|
||
if process_success:
|
||
return jsonify({
|
||
'success': True,
|
||
'message': '支付确认成功,注册码已生成并发送',
|
||
'ticket_codes': ticket_codes
|
||
})
|
||
else:
|
||
return jsonify({
|
||
'success': True,
|
||
'message': '支付已确认,但注册码生成失败: ' + process_msg,
|
||
'warning': True
|
||
})
|
||
|
||
|
||
# ---- 推广码管理API ----
|
||
|
||
@api_bp.route('/admin/affiliates/list')
|
||
@api_auth
|
||
def api_admin_affiliates_list():
|
||
"""获取推广码列表(仅管理员)"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
from app.affiliate_manager import AffiliateManager
|
||
affiliates = AffiliateManager.list_affiliates()
|
||
|
||
# 转换为列表格式
|
||
affiliates_list = []
|
||
for code, info in affiliates.items():
|
||
affiliates_list.append({
|
||
'code': code,
|
||
'name': info.get('name', ''),
|
||
'commission_rate': info.get('commission_rate', 30),
|
||
'discount_amount': info.get('discount_amount', 2),
|
||
'created_at': info.get('created_at', '')
|
||
})
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'affiliates': affiliates_list
|
||
})
|
||
|
||
|
||
@api_bp.route('/admin/affiliates/<code>')
|
||
@api_auth
|
||
def api_admin_affiliate_detail(code):
|
||
"""获取单个推广人信息和销售统计(仅管理员)"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
from app.affiliate_manager import AffiliateManager
|
||
from app.payment_manager import PaymentManager
|
||
|
||
affiliate = AffiliateManager.get_affiliate(code)
|
||
|
||
if not affiliate:
|
||
return jsonify({'success': False, 'message': '推广人不存在'})
|
||
|
||
# 获取该推广人的订单统计
|
||
orders = PaymentManager.get_orders('all')
|
||
affiliate_orders = [o for o in orders if (o.get('invite_code') or '').upper() == code.upper()]
|
||
|
||
# 计算统计数据
|
||
total_orders = len(affiliate_orders)
|
||
paid_orders = [o for o in affiliate_orders if o.get('status') in ['paid', 'processed']]
|
||
total_sales = sum(o.get('final_amount', 0) for o in paid_orders)
|
||
total_commission = sum(o.get('commission_amount', 0) for o in paid_orders)
|
||
total_quantity = sum(o.get('quantity', 0) for o in paid_orders)
|
||
|
||
# 获取结算信息
|
||
total_settled = affiliate.get('total_settled_amount', 0)
|
||
pending_commission = total_commission - total_settled
|
||
|
||
# 最近订单
|
||
recent_orders = sorted(
|
||
paid_orders,
|
||
key=lambda x: x.get('paid_at', x.get('created_at', '')),
|
||
reverse=True
|
||
)[:10]
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'affiliate': {
|
||
'code': code.upper(),
|
||
'name': affiliate.get('name', ''),
|
||
'commission_rate': affiliate.get('commission_rate', 30),
|
||
'discount_amount': affiliate.get('discount_amount', 2),
|
||
'created_at': affiliate.get('created_at', ''),
|
||
'stats': {
|
||
'total_orders': total_orders,
|
||
'paid_orders': len(paid_orders),
|
||
'total_sales': total_sales,
|
||
'total_commission': total_commission,
|
||
'total_quantity': total_quantity,
|
||
'total_settled': total_settled,
|
||
'pending_commission': pending_commission
|
||
},
|
||
'settlement_info': {
|
||
'total_settled_amount': total_settled,
|
||
'last_settled_at': affiliate.get('last_settled_at'),
|
||
'settlement_history': affiliate.get('settlement_history', [])
|
||
},
|
||
'recent_orders': [
|
||
{
|
||
'order_id': o.get('order_id'),
|
||
'email': o.get('email'),
|
||
'quantity': o.get('quantity'),
|
||
'final_amount': o.get('final_amount'),
|
||
'commission_amount': o.get('commission_amount'),
|
||
'paid_at': o.get('paid_at'),
|
||
'ticket_codes': o.get('ticket_codes', [])
|
||
}
|
||
for o in recent_orders
|
||
]
|
||
}
|
||
})
|
||
|
||
|
||
@api_bp.route('/admin/affiliates/create', methods=['POST'])
|
||
@api_auth
|
||
def api_admin_affiliates_create():
|
||
"""创建推广人(仅管理员)"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
data = request.get_json()
|
||
if not data:
|
||
return jsonify({'success': False, 'message': '请求数据为空'})
|
||
|
||
code = data.get('code', '').strip().upper()
|
||
name = data.get('name', '').strip()
|
||
commission_rate = data.get('commission_rate', 30)
|
||
discount_amount = data.get('discount_amount', 2)
|
||
|
||
if not code or not name:
|
||
return jsonify({'success': False, 'message': '推广码和姓名不能为空'})
|
||
|
||
from app.affiliate_manager import AffiliateManager
|
||
|
||
# 检查是否已存在
|
||
if AffiliateManager.get_affiliate(code):
|
||
return jsonify({'success': False, 'message': '推广码已存在'})
|
||
|
||
# 创建推广人
|
||
AffiliateManager.add_affiliate(
|
||
code=code,
|
||
name=name,
|
||
commission_rate=commission_rate,
|
||
discount_amount=discount_amount
|
||
)
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'message': '推广人创建成功',
|
||
'affiliate': {
|
||
'code': code,
|
||
'name': name,
|
||
'commission_rate': commission_rate,
|
||
'discount_amount': discount_amount
|
||
}
|
||
})
|
||
|
||
|
||
@api_bp.route('/admin/affiliates/<code>/update', methods=['POST'])
|
||
@api_auth
|
||
def api_admin_affiliates_update(code):
|
||
"""更新推广人信息(仅管理员)"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
data = request.get_json()
|
||
if not data:
|
||
return jsonify({'success': False, 'message': '请求数据为空'})
|
||
|
||
from app.affiliate_manager import AffiliateManager
|
||
|
||
# 检查是否存在
|
||
if not AffiliateManager.get_affiliate(code):
|
||
return jsonify({'success': False, 'message': '推广人不存在'})
|
||
|
||
# 更新信息
|
||
AffiliateManager.update_affiliate(
|
||
code=code,
|
||
name=data.get('name'),
|
||
commission_rate=data.get('commission_rate'),
|
||
discount_amount=data.get('discount_amount')
|
||
)
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'message': '推广人更新成功'
|
||
})
|
||
|
||
|
||
@api_bp.route('/admin/affiliates/<code>/delete', methods=['POST'])
|
||
@api_auth
|
||
def api_admin_affiliates_delete(code):
|
||
"""删除推广人(仅管理员)"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
from app.affiliate_manager import AffiliateManager
|
||
|
||
if AffiliateManager.delete_affiliate(code):
|
||
return jsonify({'success': True, 'message': '推广人已删除'})
|
||
|
||
return jsonify({'success': False, 'message': '推广人不存在'})
|
||
|
||
|
||
@api_bp.route('/admin/affiliates/<code>/settle', methods=['POST'])
|
||
@api_auth
|
||
def api_admin_affiliates_settle(code):
|
||
"""结清推广人佣金(仅管理员)"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
data = request.get_json()
|
||
if not data:
|
||
return jsonify({'success': False, 'message': '请求数据为空'})
|
||
|
||
settle_amount = data.get('settle_amount', 0)
|
||
note = data.get('note', '')
|
||
|
||
if settle_amount <= 0:
|
||
return jsonify({'success': False, 'message': '结算金额必须大于0'})
|
||
|
||
from app.affiliate_manager import AffiliateManager
|
||
|
||
# 检查推广人是否存在
|
||
affiliate = AffiliateManager.get_affiliate(code)
|
||
if not affiliate:
|
||
return jsonify({'success': False, 'message': '推广人不存在'})
|
||
|
||
# 执行结算
|
||
if AffiliateManager.settle_affiliate(code, settle_amount, note):
|
||
return jsonify({
|
||
'success': True,
|
||
'message': '结算成功',
|
||
'settlement': {
|
||
'settle_amount': settle_amount,
|
||
'note': note,
|
||
'settled_at': bj_now().isoformat()
|
||
}
|
||
})
|
||
|
||
return jsonify({'success': False, 'message': '结算失败'})
|
||
|
||
|
||
# ==================== 支付相关API ====================
|
||
|
||
@main_bp.route('/form')
|
||
def form_page():
|
||
"""订单填写表单页面"""
|
||
amount = request.args.get('amount', 9, type=int)
|
||
quantity = request.args.get('quantity', 1, type=int)
|
||
product = request.args.get('product', 'default', type=str)
|
||
|
||
return render_template('form.html',
|
||
amount=amount,
|
||
quantity=quantity,
|
||
product=product)
|
||
|
||
|
||
@main_bp.route('/success/<order_id>')
|
||
def success_page(order_id):
|
||
"""支付成功页面 - 显示注册码"""
|
||
from app.payment_manager import PaymentManager
|
||
|
||
# 获取订单信息
|
||
order = PaymentManager.get_order(order_id)
|
||
|
||
if not order:
|
||
# 订单不存在,显示错误页面
|
||
return render_template('payment_failed.html',
|
||
order_id=order_id,
|
||
error='订单不存在'), 404
|
||
|
||
# 如果订单已支付但未处理,先处理订单
|
||
if order.get('status') == 'paid' and not order.get('ticket_codes'):
|
||
PaymentManager.process_paid_order(order_id, expiry_days=180)
|
||
# 重新获取订单信息
|
||
order = PaymentManager.get_order(order_id)
|
||
|
||
# 如果订单未支付,重定向到购买页面
|
||
if order.get('status') not in ['paid', 'processed']:
|
||
return redirect(url_for('main.buy'))
|
||
|
||
# 获取注册码列表
|
||
ticket_codes = order.get('ticket_codes', [])
|
||
|
||
# 获取登录地址(从配置或默认)
|
||
login_url = "https://jwxt.bansonic.top"
|
||
|
||
return render_template('success.html',
|
||
order_id=order_id,
|
||
ticket_codes=ticket_codes,
|
||
login_url=login_url,
|
||
email=order.get('email', ''))
|
||
|
||
|
||
@api_bp.route('/verify-invite-code', methods=['GET'])
|
||
def api_verify_invite_code():
|
||
"""验证推广码是否有效"""
|
||
try:
|
||
from app.affiliate_manager import AffiliateManager
|
||
|
||
code = request.args.get('code', '').strip()
|
||
if not code:
|
||
return jsonify({'valid': False, 'message': '请输入推广码'})
|
||
|
||
result = AffiliateManager.verify_code(code)
|
||
if result:
|
||
return jsonify(result)
|
||
else:
|
||
return jsonify({'valid': False, 'message': '推广码不存在或已过期'})
|
||
|
||
except Exception as e:
|
||
return jsonify({'valid': False, 'message': f'验证失败: {str(e)}'})
|
||
|
||
|
||
@api_bp.route('/orders/create', methods=['POST'])
|
||
def api_create_order():
|
||
"""创建订单(无需登录)"""
|
||
try:
|
||
data = request.get_json()
|
||
if not data:
|
||
return jsonify({'success': False, 'message': '请求数据为空'}), 400
|
||
|
||
email = data.get('email', '').strip()
|
||
quantity = data.get('quantity', 1)
|
||
invite_code = data.get('invite_code', '').strip() or None
|
||
|
||
if not email:
|
||
return jsonify({'success': False, 'message': '邮箱不能为空'}), 400
|
||
|
||
if quantity < 1 or quantity > 100:
|
||
return jsonify({'success': False, 'message': '购买数量必须在1-100之间'}), 400
|
||
|
||
from app.payment_manager import PaymentManager
|
||
success, message, order_data = PaymentManager.create_order(email, quantity, invite_code)
|
||
|
||
if not success:
|
||
return jsonify({'success': False, 'message': message}), 400
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'message': message,
|
||
'order': order_data
|
||
})
|
||
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'创建订单失败: {str(e)}'}), 500
|
||
|
||
|
||
@api_bp.route('/api/orders/<order_id>/payment_params')
|
||
def api_get_payment_params(order_id):
|
||
"""获取支付参数(无需登录)"""
|
||
try:
|
||
from app.payment_manager import PaymentManager
|
||
order = PaymentManager.get_order(order_id)
|
||
|
||
if not order:
|
||
return jsonify({'success': False, 'message': '订单不存在'}), 404
|
||
|
||
if order['status'] != 'pending':
|
||
return jsonify({'success': False, 'message': f'订单状态不允许支付: {order["status"]}'}), 400
|
||
|
||
# 获取支付参数
|
||
pay_type = request.args.get('type', 'alipay')
|
||
params = PaymentManager.create_payment_params(order_id, pay_type)
|
||
|
||
if not params:
|
||
return jsonify({'success': False, 'message': '生成支付参数失败'}), 500
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'params': params,
|
||
'order': order
|
||
})
|
||
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'获取支付参数失败: {str(e)}'}), 500
|
||
|
||
|
||
@main_bp.route('/create-pay-order', methods=['POST'])
|
||
def create_pay_order():
|
||
"""创建支付订单(FormData格式,兼容前端buy.html)"""
|
||
try:
|
||
from app.payment_manager import PaymentManager, calculate_price
|
||
from datetime import datetime
|
||
|
||
# 获取表单数据
|
||
amount = request.form.get('amount', type=int)
|
||
quantity = request.form.get('quantity', type=int)
|
||
email = request.form.get('email', '').strip()
|
||
invite_code = request.form.get('invite_code', '').strip() or None
|
||
|
||
# 验证参数
|
||
if not email:
|
||
return jsonify({'error': '邮箱不能为空'}), 400
|
||
|
||
if not amount or amount < 1:
|
||
return jsonify({'error': '金额不正确'}), 400
|
||
|
||
if not quantity or quantity < 1:
|
||
quantity = 1
|
||
|
||
# 计算提前预约天数(与前端算法一致)
|
||
# 注意:JavaScript 月份从0开始(0=1月),Python 月份从1开始,需要+1
|
||
# naive 北京时间:与下面的 naive 日期比较(aware/naive 比较会 TypeError)
|
||
now = bj_now().replace(tzinfo=None)
|
||
current_year = now.year
|
||
|
||
# 定义选课日期(与前端一致)
|
||
# JS: new Date(currentYear, 11, 9, 12, 0, 0) -> 12月9日
|
||
# JS: new Date(currentYear, 5, 17, 10, 0, 0) -> 6月17日
|
||
spring_date = datetime(current_year, 12, 9, 12, 0, 0) # 12月9日 12:00
|
||
fall_date = datetime(current_year, 6, 17, 10, 0, 0) # 6月17日 10:00
|
||
|
||
if now < fall_date:
|
||
target_date = fall_date
|
||
elif now < spring_date:
|
||
target_date = spring_date
|
||
else:
|
||
# JS: new Date(currentYear + 1, 5, 17, 10, 0, 0) -> 6月17日
|
||
target_date = datetime(current_year + 1, 6, 17, 10, 0, 0)
|
||
|
||
diff_time = target_date - now
|
||
days_in_advance = min(max(diff_time.days, 0), 180)
|
||
|
||
# 创建订单(传递 days_in_advance)
|
||
success, message, order_data = PaymentManager.create_order(email, quantity, invite_code, days_in_advance)
|
||
|
||
if not success:
|
||
return jsonify({'error': message}), 400
|
||
|
||
order_id = order_data['order_id']
|
||
|
||
# 生成支付参数
|
||
pay_params = PaymentManager.create_payment_params(order_id, 'alipay')
|
||
|
||
if not pay_params:
|
||
return jsonify({'error': '生成支付参数失败'}), 500
|
||
|
||
# 导入支付配置
|
||
from app.payment_manager import PAY_API_URL
|
||
|
||
# 返回前端需要的格式
|
||
return jsonify({
|
||
'orderNo': order_id,
|
||
'merchantNum': pay_params['merchantNum'],
|
||
'amount': pay_params['amount'],
|
||
'notifyUrl': pay_params['notifyUrl'],
|
||
'returnUrl': pay_params['returnUrl'],
|
||
'payType': pay_params['payType'],
|
||
'sign': pay_params['sign'],
|
||
'returnType': pay_params['returnType'],
|
||
'subject': pay_params['subject'],
|
||
'body': f'授权数量:{quantity}份',
|
||
'attch': json.dumps({
|
||
'qty': quantity,
|
||
'order': order_id,
|
||
'invite_code': invite_code,
|
||
'original_amount': amount,
|
||
'final_amount': order_data['final_amount']
|
||
}),
|
||
'api_url': PAY_API_URL
|
||
})
|
||
|
||
except Exception as e:
|
||
return jsonify({'error': f'创建订单失败: {str(e)}'}), 500
|
||
|
||
|
||
@api_bp.route('/orders/<order_id>')
|
||
def api_get_order(order_id):
|
||
"""获取订单信息(无需登录)"""
|
||
try:
|
||
from app.payment_manager import PaymentManager
|
||
order = PaymentManager.get_order(order_id)
|
||
|
||
if not order:
|
||
return jsonify({'success': False, 'message': '订单不存在'}), 404
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'order': order
|
||
})
|
||
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'获取订单失败: {str(e)}'}), 500
|
||
|
||
|
||
@api_bp.route('/orders/<order_id>/status')
|
||
def api_get_order_status(order_id):
|
||
"""获取订单状态(包含过期倒计时,无需登录)"""
|
||
try:
|
||
from app.payment_manager import PaymentManager
|
||
status_info = PaymentManager.get_order_status(order_id)
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'order_id': order_id,
|
||
**status_info
|
||
})
|
||
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'获取订单状态失败: {str(e)}'}), 500
|
||
|
||
|
||
@api_bp.route('/orders/<order_id>/cancel', methods=['POST'])
|
||
def api_cancel_order(order_id):
|
||
"""取消订单(无需登录)"""
|
||
try:
|
||
from app.payment_manager import PaymentManager
|
||
|
||
# 获取取消原因
|
||
data = request.get_json() or {}
|
||
reason = data.get('reason', '用户主动取消')
|
||
|
||
success, message = PaymentManager.cancel_order(order_id, reason)
|
||
|
||
if success:
|
||
return jsonify({
|
||
'success': True,
|
||
'message': message
|
||
})
|
||
else:
|
||
return jsonify({
|
||
'success': False,
|
||
'message': message
|
||
}), 400
|
||
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'取消订单失败: {str(e)}'}), 500
|
||
|
||
|
||
@main_bp.route('/notify', methods=['GET', 'POST'])
|
||
def pay_notify():
|
||
"""支付回调接口(支付平台调用)"""
|
||
try:
|
||
from app.payment_manager import PaymentManager
|
||
import json
|
||
|
||
# 获取参数(支持多种格式)
|
||
if request.method == 'POST':
|
||
# 尝试从 form 获取,如果没有则尝试 JSON
|
||
data = request.form.to_dict()
|
||
if not data and request.is_json:
|
||
data = request.get_json()
|
||
if not data:
|
||
# 尝试从原始 body 解析
|
||
try:
|
||
data = json.loads(request.data.decode('utf-8'))
|
||
except:
|
||
pass
|
||
else:
|
||
data = request.args.to_dict()
|
||
|
||
print(f"[支付回调] 收到请求: method={request.method}, data={data}")
|
||
|
||
# 签名验证:默认关闭(与支付FM确认签名规则后,设环境变量 PAY_VERIFY_SIGN=1 开启)
|
||
verify_sign = os.environ.get('PAY_VERIFY_SIGN', '0') == '1'
|
||
if verify_sign:
|
||
if not PaymentManager.verify_pay_sign(data):
|
||
print(f"[支付回调] 签名验证失败: data={data}")
|
||
return "SIGN ERROR", 400
|
||
|
||
# 获取订单号(支持多种参数名)
|
||
order_id = data.get('orderNo') or data.get('order_no') or data.get('order_id')
|
||
state = (data.get('state') or data.get('status') or '').lower()
|
||
platform_order_no = data.get('platformOrderNo') or data.get('platform_order_no') or data.get('trade_no')
|
||
actual_pay_amount = data.get('actualPayAmount') or data.get('pay_amount') or data.get('total_amount')
|
||
|
||
if not verify_sign and not state and not platform_order_no:
|
||
# 无签名验证时,至少要求有状态或平台交易号:否则任何人伪造
|
||
# /notify?orderNo=xxx 即可把 pending 订单刷成已支付
|
||
print(f"[支付回调] 拒绝:无 state 且无平台交易号(疑似伪造回调)")
|
||
return "SIGN REQUIRED", 400
|
||
|
||
print(f"[支付回调] 解析参数: order_id={order_id}, state={state}, platform_order_no={platform_order_no}, amount={actual_pay_amount}")
|
||
|
||
if not order_id:
|
||
return "ORDER NO ERROR", 400
|
||
|
||
# 金额校验:回调金额必须 ≥ 订单应付金额(防止低价伪造回调)
|
||
def _amount_ok():
|
||
try:
|
||
if actual_pay_amount in (None, ''):
|
||
return True, "回调未带金额,跳过校验"
|
||
order_info = PaymentManager.get_order(order_id)
|
||
if not order_info:
|
||
return False, "订单不存在"
|
||
final_amount = float(order_info.get('final_amount') or 0)
|
||
if final_amount <= 0:
|
||
return True, "订单金额异常,跳过校验"
|
||
if float(actual_pay_amount) + 0.001 < final_amount:
|
||
return False, f"回调金额 {actual_pay_amount} < 应付 {final_amount}"
|
||
return True, ""
|
||
except Exception as amount_err:
|
||
print(f"[支付回调] 金额校验异常(放行): {amount_err}")
|
||
return True, ""
|
||
|
||
# 检查订单是否已过期或被取消
|
||
order_status = PaymentManager.get_order_status(order_id)
|
||
if order_status.get('status') in ['cancelled']:
|
||
print(f"[支付回调] 订单 {order_id} 已取消,忽略回调")
|
||
return "ORDER CANCELLED"
|
||
if order_status.get('is_expired') or order_status.get('status') == 'expired':
|
||
# 过期≠未付款:用户可能在上一次回调丢失后完成支付。直接丢弃会导致
|
||
# "钱收了码不发"。已支付凭证齐全(成功状态+平台交易号+金额)时仍受理。
|
||
if state in ['success', 'completed', 'paid', '1'] and platform_order_no:
|
||
print(f"[支付回调] 订单 {order_id} 已过期但平台确认支付成功,继续补处理")
|
||
else:
|
||
print(f"[支付回调] 订单 {order_id} 已过期,忽略回调")
|
||
return "ORDER EXPIRED"
|
||
|
||
# 根据支付状态更新订单
|
||
if state in ['success', 'completed', 'paid', '1']:
|
||
# 支付成功
|
||
ok, amount_msg = _amount_ok()
|
||
if not ok:
|
||
print(f"[支付回调] 订单 {order_id} {amount_msg},拒绝标记为已支付")
|
||
return "AMOUNT ERROR", 400
|
||
success, message = PaymentManager.update_order_status(
|
||
order_id,
|
||
'paid',
|
||
platform_order_no,
|
||
actual_pay_amount
|
||
)
|
||
|
||
if success:
|
||
# 处理订单:生成注册码并发送邮件
|
||
print(f"[支付回调] 订单 {order_id} 状态更新为 paid,开始处理订单...")
|
||
process_success, process_msg, ticket_codes = PaymentManager.process_paid_order(order_id, expiry_days=180)
|
||
print(f"[支付回调] 订单处理结果: success={process_success}, msg={process_msg}, codes={ticket_codes}")
|
||
return "SUCCESS"
|
||
else:
|
||
return f"UPDATE ERROR: {message}", 400
|
||
|
||
elif state in ['failed', 'fail', 'cancelled', '0']:
|
||
# 支付失败
|
||
PaymentManager.update_order_status(order_id, 'failed')
|
||
return "FAILED NOTIFIED"
|
||
|
||
else:
|
||
# 其他状态:历史上"直接当成功处理"是白嫖漏洞(伪造回调零成本)。
|
||
# 现在要求至少有平台交易号 + 金额校验通过,二者缺一即拒绝。
|
||
if not platform_order_no:
|
||
print(f"[支付回调] 未知状态 '{state}' 且无平台交易号,拒绝处理")
|
||
return "UNKNOWN STATE", 400
|
||
ok, amount_msg = _amount_ok()
|
||
if not ok:
|
||
print(f"[支付回调] 订单 {order_id} {amount_msg},拒绝标记为已支付")
|
||
return "AMOUNT ERROR", 400
|
||
print(f"[支付回调] 未知状态 '{state}',但有平台交易号 {platform_order_no},按成功处理")
|
||
success, message = PaymentManager.update_order_status(
|
||
order_id,
|
||
'paid',
|
||
platform_order_no,
|
||
actual_pay_amount
|
||
)
|
||
if success:
|
||
PaymentManager.process_paid_order(order_id, expiry_days=180)
|
||
return "SUCCESS"
|
||
return "UNKNOWN STATE", 400
|
||
|
||
except Exception as e:
|
||
import traceback
|
||
print(f"[支付回调] 异常: {e}")
|
||
print(traceback.format_exc())
|
||
return f"ERROR: {str(e)}", 500
|
||
|
||
|
||
@main_bp.route('/return')
|
||
def pay_return():
|
||
"""支付返回页面(用户支付后跳转)"""
|
||
order_id = request.args.get('orderNo', '')
|
||
state = request.args.get('state', '').lower()
|
||
|
||
if not order_id:
|
||
return redirect(url_for('main.buy'))
|
||
|
||
if state == 'success':
|
||
# 支付成功,跳转到成功页面
|
||
return redirect(url_for('main.success_page', order_id=order_id))
|
||
else:
|
||
# 支付失败,显示错误信息
|
||
return render_template('payment_failed.html', order_id=order_id)
|
||
|
||
|
||
@api_bp.route('/admin/payments/orders')
|
||
@api_auth
|
||
def api_admin_payments_orders():
|
||
"""获取所有订单(仅管理员)"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
try:
|
||
status = request.args.get('status', 'all')
|
||
from app.payment_manager import PaymentManager
|
||
orders = PaymentManager.get_orders(status)
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'orders': orders,
|
||
'total': len(orders)
|
||
})
|
||
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'获取订单失败: {str(e)}'}), 500
|
||
|
||
|
||
@api_bp.route('/admin/payments/stats')
|
||
@api_auth
|
||
def api_admin_payments_stats():
|
||
"""获取支付统计(仅管理员)"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
try:
|
||
from app.payment_manager import PaymentManager
|
||
stats = PaymentManager.get_order_stats()
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'stats': stats
|
||
})
|
||
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'获取统计失败: {str(e)}'}), 500
|
||
|
||
|
||
@api_bp.route('/admin/payments/orders/<order_id>/process', methods=['POST'])
|
||
@api_auth
|
||
def api_admin_payments_process_order(order_id):
|
||
"""手动处理订单(仅管理员)"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
try:
|
||
data = request.get_json() or {}
|
||
expiry_days = data.get('expiry_days', 7)
|
||
|
||
from app.payment_manager import PaymentManager
|
||
success, message, ticket_codes = PaymentManager.process_paid_order(order_id, expiry_days)
|
||
|
||
if not success:
|
||
return jsonify({'success': False, 'message': message}), 400
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'message': message,
|
||
'ticket_codes': ticket_codes
|
||
})
|
||
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'处理订单失败: {str(e)}'}), 500
|
||
|
||
|
||
@api_bp.route('/admin/payments/orders/<order_id>/update_status', methods=['POST'])
|
||
@api_auth
|
||
def api_admin_payments_update_status(order_id):
|
||
"""更新订单状态(仅管理员)"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
|
||
try:
|
||
data = request.get_json()
|
||
if not data:
|
||
return jsonify({'success': False, 'message': '请求数据为空'}), 400
|
||
|
||
status = data.get('status')
|
||
if not status:
|
||
return jsonify({'success': False, 'message': '状态不能为空'}), 400
|
||
|
||
from app.payment_manager import PaymentManager
|
||
|
||
if status == 'processed':
|
||
# 处理订单
|
||
expiry_days = data.get('expiry_days', 7)
|
||
success, message, ticket_codes = PaymentManager.process_paid_order(order_id, expiry_days)
|
||
else:
|
||
# 更新状态
|
||
success, message = PaymentManager.update_order_status(order_id, status)
|
||
ticket_codes = []
|
||
|
||
if not success:
|
||
return jsonify({'success': False, 'message': message}), 400
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'message': message,
|
||
'ticket_codes': ticket_codes
|
||
})
|
||
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'更新状态失败: {str(e)}'}), 500
|
||
|
||
|
||
# ==================== 拦截页面 ====================
|
||
|
||
@main_bp.route('/blocked')
|
||
def blocked():
|
||
"""IP被拦截提示页面(中间件直接render,此路由用于直接访问测试)"""
|
||
from flask import g
|
||
ip = getattr(g, 'client_ip', request.remote_addr)
|
||
return render_template('blocked.html',
|
||
ip=ip,
|
||
reason='您的访问已被拦截',
|
||
block_type='banned'), 403
|
||
|
||
|
||
# ==================== IP管理页面(管理员) ====================
|
||
|
||
@main_bp.route('/admin/ip')
|
||
@login_required
|
||
def admin_ip():
|
||
"""IP管理页面"""
|
||
if not current_user.is_admin:
|
||
flash('无权访问', 'danger')
|
||
return redirect(url_for('main.dashboard'))
|
||
return render_template('admin_ip.html')
|
||
|
||
|
||
# ==================== IP管理 API ====================
|
||
|
||
@api_bp.route('/admin/ip/stats')
|
||
@api_auth
|
||
def api_ip_stats():
|
||
"""IP统计数据"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
try:
|
||
hours = int(request.args.get('hours', 24))
|
||
from app.ip_manager import get_ip_stats
|
||
stats = get_ip_stats(hours=hours)
|
||
return jsonify({'success': True, 'stats': stats})
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': str(e)}), 500
|
||
|
||
|
||
@api_bp.route('/admin/ip/logs')
|
||
@api_auth
|
||
def api_ip_logs():
|
||
"""IP访问日志列表"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
try:
|
||
from app.models import IPAccessLog
|
||
page = int(request.args.get('page', 1))
|
||
per_page = int(request.args.get('per_page', 50))
|
||
ip_filter = request.args.get('ip', '').strip()
|
||
blocked_only = request.args.get('blocked', '').lower() == 'true'
|
||
country_filter = request.args.get('country', '').strip().upper()
|
||
|
||
query = IPAccessLog.query
|
||
if ip_filter:
|
||
query = query.filter(IPAccessLog.ip.like(f'%{ip_filter}%'))
|
||
if blocked_only:
|
||
query = query.filter(IPAccessLog.blocked == True)
|
||
if country_filter:
|
||
query = query.filter(IPAccessLog.country == country_filter)
|
||
|
||
total = query.count()
|
||
logs = query.order_by(IPAccessLog.created_at.desc())\
|
||
.offset((page - 1) * per_page).limit(per_page).all()
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'logs': [l.to_dict() for l in logs],
|
||
'total': total,
|
||
'page': page,
|
||
'per_page': per_page,
|
||
'pages': (total + per_page - 1) // per_page
|
||
})
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': str(e)}), 500
|
||
|
||
|
||
@api_bp.route('/admin/ip/bans')
|
||
@api_auth
|
||
def api_ip_bans():
|
||
"""获取封禁列表"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
try:
|
||
from app.models import IPBan
|
||
from app.time_utils import now as bj_now, to_iso, BJ_TZ
|
||
from datetime import datetime
|
||
|
||
bans = IPBan.query.order_by(IPBan.created_at.desc()).all()
|
||
now = bj_now()
|
||
result = []
|
||
|
||
for b in bans:
|
||
# 安全地处理时间比较,避免 naive/aware 冲突
|
||
expires_at_iso = None
|
||
if b.expires_at:
|
||
if b.expires_at.tzinfo is None:
|
||
expires_aware = b.expires_at.replace(tzinfo=BJ_TZ)
|
||
else:
|
||
expires_aware = b.expires_at
|
||
expires_at_iso = expires_aware.isoformat()
|
||
|
||
created_at_iso = None
|
||
if b.created_at:
|
||
if b.created_at.tzinfo is None:
|
||
created_aware = b.created_at.replace(tzinfo=BJ_TZ)
|
||
else:
|
||
created_aware = b.created_at
|
||
created_at_iso = created_aware.isoformat()
|
||
|
||
# 判断是否活跃
|
||
is_active = b.is_permanent
|
||
if not is_active and b.expires_at:
|
||
is_active = expires_aware > now
|
||
|
||
result.append({
|
||
'id': b.id,
|
||
'ban_type': b.ban_type,
|
||
'value': b.value,
|
||
'reason': b.reason,
|
||
'is_permanent': b.is_permanent,
|
||
'expires_at': expires_at_iso,
|
||
'created_at': created_at_iso,
|
||
'created_by': b.created_by,
|
||
'is_active': is_active
|
||
})
|
||
|
||
return jsonify({'success': True, 'bans': result})
|
||
except Exception as e:
|
||
import traceback
|
||
traceback.print_exc()
|
||
return jsonify({'success': False, 'message': str(e)}), 500
|
||
|
||
|
||
@api_bp.route('/admin/ip/ban', methods=['POST'])
|
||
@api_auth
|
||
def api_ip_ban():
|
||
"""添加封禁"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
try:
|
||
data = request.get_json() or {}
|
||
value = data.get('value', '').strip()
|
||
ban_type = data.get('ban_type', 'ip') # ip/cidr/country
|
||
reason = data.get('reason', '')
|
||
duration = data.get('duration', None) # None=永久, '1h','1d','1w','1m'
|
||
|
||
if not value:
|
||
return jsonify({'success': False, 'message': '封禁值不能为空'}), 400
|
||
|
||
from app.ip_manager import ban_ip
|
||
result = ban_ip(value, reason=reason, duration_str=duration,
|
||
ban_type=ban_type, created_by=current_user.username)
|
||
return jsonify(result)
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': str(e)}), 500
|
||
|
||
|
||
@api_bp.route('/admin/ip/unban', methods=['POST'])
|
||
@api_auth
|
||
def api_ip_unban():
|
||
"""解封IP"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
try:
|
||
data = request.get_json() or {}
|
||
ban_id = data.get('id')
|
||
value = data.get('value', '').strip()
|
||
ban_type = data.get('ban_type', 'ip')
|
||
|
||
from app.models import db, IPBan, LoginAttempt
|
||
if ban_id:
|
||
ban = IPBan.query.get(ban_id)
|
||
if not ban:
|
||
return jsonify({'success': False, 'message': '未找到封禁记录'}), 404
|
||
ip_value = ban.value
|
||
db.session.delete(ban)
|
||
LoginAttempt.query.filter_by(ip=ip_value).delete()
|
||
db.session.commit()
|
||
return jsonify({'success': True, 'message': f'已解封 {ip_value}'})
|
||
elif value:
|
||
from app.ip_manager import unban_ip
|
||
result = unban_ip(value, ban_type=ban_type)
|
||
return jsonify(result)
|
||
else:
|
||
return jsonify({'success': False, 'message': '需要提供id或value'}), 400
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': str(e)}), 500
|
||
|
||
|
||
@api_bp.route('/admin/ip/ban_from_log', methods=['POST'])
|
||
@api_auth
|
||
def api_ip_ban_from_log():
|
||
"""从访问日志快速封禁"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
try:
|
||
data = request.get_json() or {}
|
||
ip = data.get('ip', '').strip()
|
||
reason = data.get('reason', '管理员从日志封禁')
|
||
duration = data.get('duration', None)
|
||
|
||
if not ip:
|
||
return jsonify({'success': False, 'message': 'IP不能为空'}), 400
|
||
|
||
from app.ip_manager import ban_ip
|
||
result = ban_ip(ip, reason=reason, duration_str=duration,
|
||
ban_type='ip', created_by=current_user.username)
|
||
return jsonify(result)
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': str(e)}), 500
|
||
|
||
|
||
@api_bp.route('/admin/ip/query', methods=['GET'])
|
||
@api_auth
|
||
def api_ip_query():
|
||
"""查询单个IP的地理信息"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
try:
|
||
ip = request.args.get('ip', '').strip()
|
||
if not ip:
|
||
return jsonify({'success': False, 'message': 'IP不能为空'}), 400
|
||
from app.ip_manager import query_ip_geo, is_ip_banned, _utc_to_timestamp
|
||
geo = query_ip_geo(ip)
|
||
banned, reason, expires_at = is_ip_banned(ip, geo.get('country', ''))
|
||
return jsonify({
|
||
'success': True,
|
||
'geo': geo,
|
||
'banned': banned,
|
||
'ban_reason': reason,
|
||
'expires_at': _utc_to_timestamp(expires_at)
|
||
})
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': str(e)}), 500
|
||
|
||
|
||
@api_bp.route('/admin/ip/config', methods=['GET', 'POST'])
|
||
@api_auth
|
||
def api_ip_config():
|
||
"""获取/设置IP管理配置(登录频率限制参数)"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
try:
|
||
if request.method == 'GET':
|
||
return jsonify({
|
||
'success': True,
|
||
'config': {
|
||
'login_window_minutes': int(SystemConfig.get('login_window_minutes', '10')),
|
||
'login_max_attempts': int(SystemConfig.get('login_max_attempts', '10')),
|
||
'enable_china_only': SystemConfig.get('enable_china_only', 'true'),
|
||
}
|
||
})
|
||
else:
|
||
data = request.get_json() or {}
|
||
if 'login_window_minutes' in data:
|
||
SystemConfig.set('login_window_minutes', str(int(data['login_window_minutes'])))
|
||
if 'login_max_attempts' in data:
|
||
SystemConfig.set('login_max_attempts', str(int(data['login_max_attempts'])))
|
||
if 'enable_china_only' in data:
|
||
SystemConfig.set('enable_china_only', 'true' if data['enable_china_only'] else 'false')
|
||
return jsonify({'success': True, 'message': '配置已保存'})
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': str(e)}), 500
|
||
|
||
|
||
@api_bp.route('/admin/ip/clean_logs', methods=['POST'])
|
||
@api_auth
|
||
def api_ip_clean_logs():
|
||
"""清理旧访问日志"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
try:
|
||
data = request.get_json() or {}
|
||
days = int(data.get('days', 7))
|
||
from app.models import IPAccessLog
|
||
from datetime import timedelta
|
||
cutoff = bj_now() - timedelta(days=days)
|
||
deleted = IPAccessLog.query.filter(IPAccessLog.created_at < cutoff).delete()
|
||
db.session.commit()
|
||
return jsonify({'success': True, 'message': f'已清理 {deleted} 条日志'})
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': str(e)}), 500
|
||
|
||
|
||
# ==================== 教务通用功能 API ====================
|
||
|
||
# ── 页面路由 ──
|
||
|
||
@main_bp.route('/grades')
|
||
@login_required
|
||
def page_grades():
|
||
"""成绩查询页面 — 需先配置教务账号"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
flash('请先配置教务系统账号', 'warning')
|
||
return redirect(url_for('main.dashboard'))
|
||
return render_template('grades.html')
|
||
|
||
|
||
@main_bp.route('/exams')
|
||
@login_required
|
||
def page_exams():
|
||
"""考试安排页面"""
|
||
return render_template('exams.html')
|
||
|
||
|
||
@main_bp.route('/personal-info')
|
||
@login_required
|
||
def page_personal_info():
|
||
"""个人信息页面"""
|
||
return render_template('personal_info.html')
|
||
|
||
|
||
@main_bp.route('/academic-warning')
|
||
@login_required
|
||
def page_academic_warning():
|
||
"""学业预警页面"""
|
||
return render_template('academic_warning.html')
|
||
|
||
|
||
@main_bp.route('/classrooms')
|
||
@login_required
|
||
def page_classrooms():
|
||
"""空闲教室查询页面"""
|
||
return render_template('classrooms.html')
|
||
|
||
|
||
@main_bp.route('/retake-courses')
|
||
@login_required
|
||
def page_retake_courses():
|
||
"""重修课程查询页面"""
|
||
return render_template('retake_courses.html')
|
||
|
||
|
||
@main_bp.route('/textbook-details')
|
||
@login_required
|
||
def page_textbook_details():
|
||
"""教材明细查询页面"""
|
||
return render_template('textbook_details.html')
|
||
|
||
|
||
@main_bp.route('/textbook-order')
|
||
@login_required
|
||
def page_textbook_order():
|
||
"""教材预订页面"""
|
||
return render_template('textbook_order.html')
|
||
|
||
|
||
@main_bp.route('/teacher-schedule')
|
||
@login_required
|
||
def page_teacher_schedule():
|
||
"""教师课表页面"""
|
||
return render_template('teacher_schedule.html')
|
||
|
||
|
||
@main_bp.route('/classroom-schedule')
|
||
@login_required
|
||
def page_classroom_schedule():
|
||
"""场地课表页面"""
|
||
return render_template('classroom_schedule.html')
|
||
|
||
|
||
@main_bp.route('/academic-status')
|
||
@login_required
|
||
def page_academic_status():
|
||
"""学业情况页面"""
|
||
return render_template('academic_status.html')
|
||
|
||
|
||
@main_bp.route('/teaching-plan')
|
||
@login_required
|
||
def page_teaching_plan():
|
||
"""教学执行计划页面"""
|
||
from app.url_manager import get_base_url
|
||
from app.url_manager import get_global_base_url
|
||
return render_template('teaching_plan.html', jwxt_base_url=get_global_base_url(current_user.school_id))
|
||
|
||
|
||
@main_bp.route('/api-playground')
|
||
@login_required
|
||
def page_api_playground():
|
||
"""API 接口测试页面"""
|
||
return render_template('api_playground.html')
|
||
|
||
|
||
@main_bp.route('/api-examples')
|
||
@login_required
|
||
def page_api_examples():
|
||
"""API 调用示例页面"""
|
||
return render_template('api_examples.html', content=_render_md('api_examples.md'))
|
||
|
||
|
||
# ── API 路由 ──
|
||
|
||
@api_bp.route('/jwxt/ping')
|
||
@api_auth
|
||
def api_jwxt_ping():
|
||
"""
|
||
Session 健康检查 + 自动刷新。
|
||
页面加载时调用,检查教务 session 是否有效,若失效则自动刷新。
|
||
"""
|
||
from app.test_mock import TEST_USERNAME
|
||
if current_user.is_authenticated and current_user.username == TEST_USERNAME:
|
||
return jsonify({
|
||
'success': True,
|
||
'menu': [],
|
||
'message': '模拟测试账号',
|
||
})
|
||
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号'})
|
||
|
||
def _do_request():
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(jwxt_acc['username'])
|
||
return api.get_menu_tree()
|
||
|
||
try:
|
||
result, refreshed = with_session_retry(current_user, _do_request)
|
||
timing = result.pop('_timing', None)
|
||
if result.get('success'):
|
||
resp = {
|
||
'success': True,
|
||
'refreshed': refreshed,
|
||
'message': 'Session 有效' if not refreshed else 'Session 已自动刷新',
|
||
}
|
||
else:
|
||
resp = {
|
||
'success': False,
|
||
'refreshed': refreshed,
|
||
'message': result.get('message', 'Session 检查失败'),
|
||
}
|
||
if timing:
|
||
resp['_timing'] = timing
|
||
return jsonify(resp)
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'Session 检查失败: {str(e)}'})
|
||
|
||
|
||
@api_bp.route('/jwxt/semesters')
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_semesters():
|
||
"""获取可用学年和学期列表(从教务系统 HTML 解析)"""
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.get_semester_list()
|
||
|
||
|
||
@api_bp.route('/jwxt/grades')
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_grades():
|
||
"""成绩查询"""
|
||
# 支持两种传参方式(semester 为旧版兼容)
|
||
semester = request.args.get('semester', '')
|
||
xnm = request.args.get('xnm', '')
|
||
xqm = request.args.get('xqm', '')
|
||
kcbj = request.args.get('kcbj', '')
|
||
if semester and not xnm:
|
||
parts = semester.split('-')
|
||
if len(parts) >= 3:
|
||
xnm = parts[0]
|
||
xqm = parts[2]
|
||
|
||
try:
|
||
page = int(request.args.get('page', 1))
|
||
page_size = int(request.args.get('page_size', 100))
|
||
except (ValueError, TypeError):
|
||
page, page_size = 1, 100
|
||
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
kwargs = {'page': page, 'page_size': page_size}
|
||
if xnm:
|
||
kwargs['xnm'] = xnm
|
||
if xqm:
|
||
kwargs['xqm'] = xqm
|
||
if kcbj:
|
||
kwargs['kcbj'] = kcbj
|
||
return api.get_grades(**kwargs)
|
||
|
||
|
||
@api_bp.route('/jwxt/exams')
|
||
@api_auth
|
||
def api_jwxt_exams():
|
||
"""考试安排查询"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号'})
|
||
|
||
# 支持 semester="2025-2026-2" 或 xnm/xqm 分开传
|
||
semester = request.args.get('semester', '')
|
||
xnm = request.args.get('xnm', '')
|
||
xqm = request.args.get('xqm', '')
|
||
if semester and not xnm:
|
||
parts = semester.split('-')
|
||
if len(parts) >= 3:
|
||
xnm = parts[0]
|
||
xqm = parts[2]
|
||
|
||
def _do_request():
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(jwxt_acc['username'])
|
||
return api.get_exam_schedule(xnm=xnm, xqm=xqm)
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}', 'items': []})
|
||
|
||
|
||
@api_bp.route('/jwxt/student-info')
|
||
@api_auth
|
||
def api_jwxt_student_info():
|
||
"""学生基本信息"""
|
||
from app.test_mock import TEST_USERNAME, fake_student_info
|
||
if current_user.is_authenticated and current_user.username == TEST_USERNAME:
|
||
return jsonify(fake_student_info())
|
||
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号'})
|
||
|
||
def _do_request():
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(jwxt_acc['username'])
|
||
return api.get_student_info()
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}'})
|
||
|
||
|
||
@api_bp.route('/jwxt/menu')
|
||
@api_auth
|
||
def api_jwxt_menu():
|
||
"""教务系统菜单树"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号'})
|
||
|
||
def _do_request():
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(jwxt_acc['username'])
|
||
return api.get_menu_tree()
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}'})
|
||
|
||
|
||
# ── 新增教务功能 API ────────────────────────
|
||
|
||
@api_bp.route('/jwxt/personal-info')
|
||
@api_auth
|
||
def api_jwxt_personal_info():
|
||
"""个人信息(HTML 页面解析版,学生可访问端点)"""
|
||
from app.test_mock import TEST_USERNAME, fake_personal_info
|
||
if current_user.is_authenticated and current_user.username == TEST_USERNAME:
|
||
return jsonify(fake_personal_info())
|
||
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号'})
|
||
|
||
def _do_request():
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(jwxt_acc['username'])
|
||
return api.get_student_info()
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}', 'info': {}})
|
||
|
||
|
||
@api_bp.route('/jwxt/academic-warning')
|
||
@api_auth
|
||
def api_jwxt_academic_warning():
|
||
"""学业预警查询"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号'})
|
||
|
||
jg_id = request.args.get('jg_id', '')
|
||
njdm_id = request.args.get('njdm_id', '')
|
||
zyh_id = request.args.get('zyh_id', '')
|
||
|
||
def _do_request():
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(jwxt_acc['username'])
|
||
kwargs = {}
|
||
if jg_id:
|
||
kwargs['jg_id'] = jg_id
|
||
if njdm_id:
|
||
kwargs['njdm_id'] = njdm_id
|
||
if zyh_id:
|
||
kwargs['zyh_id'] = zyh_id
|
||
return api.get_academic_warning(**kwargs)
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}', 'items': []})
|
||
|
||
|
||
@api_bp.route('/jwxt/academic-warning/params')
|
||
@api_auth
|
||
def api_jwxt_academic_warning_params():
|
||
"""获取学业预警页面下拉框选项和默认值"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号'})
|
||
|
||
def _do_request():
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(jwxt_acc['username'])
|
||
return api.get_academic_warning_params()
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': str(e)})
|
||
|
||
|
||
@api_bp.route('/jwxt/classroom/params')
|
||
@api_auth
|
||
def api_jwxt_classroom_params():
|
||
"""空闲教室查询页面参数(下拉框选项和默认值)"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号'})
|
||
|
||
def _do_request():
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(jwxt_acc['username'])
|
||
return api.get_classroom_params()
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'获取参数失败: {str(e)}'})
|
||
|
||
|
||
@api_bp.route('/jwxt/classrooms')
|
||
@api_auth
|
||
def api_jwxt_classrooms():
|
||
"""空闲教室查询"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号'})
|
||
|
||
xnm = request.args.get('xnm', '')
|
||
xqm = request.args.get('xqm', '')
|
||
xqh_id = request.args.get('xqh_id', '1')
|
||
lh = request.args.get('lh', '')
|
||
cdlb_id = request.args.get('cdlb_id', '')
|
||
cdejlb_id = request.args.get('cdejlb_id', '')
|
||
qszws = request.args.get('qszws', '')
|
||
jszws = request.args.get('jszws', '')
|
||
cdmc = request.args.get('cdmc', '')
|
||
jyfs = request.args.get('jyfs', '1')
|
||
zcd = request.args.get('zcd', '')
|
||
xqj = request.args.get('xqj', '')
|
||
jcd = request.args.get('jcd', '')
|
||
try:
|
||
page = int(request.args.get('page', 1))
|
||
page_size = int(request.args.get('page_size', 10))
|
||
except (ValueError, TypeError):
|
||
page, page_size = 1, 10
|
||
|
||
def _do_request():
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(jwxt_acc['username'])
|
||
return api.get_available_classrooms(
|
||
xnm=xnm, xqm=xqm, xqh_id=xqh_id, lh=lh,
|
||
cdlb_id=cdlb_id, cdejlb_id=cdejlb_id,
|
||
qszws=qszws, jszws=jszws, cdmc=cdmc, jyfs=jyfs,
|
||
zcd=zcd, xqj=xqj, jcd=jcd,
|
||
page=page, page_size=page_size,
|
||
)
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}', 'items': []})
|
||
|
||
|
||
@api_bp.route('/jwxt/classroom-filter-options')
|
||
@api_auth
|
||
def api_jwxt_classroom_filter_options():
|
||
"""空闲教室筛选选项"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号'})
|
||
|
||
xnm = request.args.get('xnm', '')
|
||
xqm = request.args.get('xqm', '')
|
||
|
||
def _do_request():
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(jwxt_acc['username'])
|
||
return api.get_classroom_filter_options(xnm=xnm, xqm=xqm)
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}', 'items': []})
|
||
|
||
|
||
@api_bp.route('/jwxt/classroom-periods')
|
||
@api_auth
|
||
def api_jwxt_classroom_periods():
|
||
"""空闲教室节次数据"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号'})
|
||
|
||
xnm = request.args.get('xnm', '')
|
||
xqm = request.args.get('xqm', '')
|
||
xqh_id = request.args.get('xqh_id', '1')
|
||
|
||
def _do_request():
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(jwxt_acc['username'])
|
||
return api.get_period_data(xnm=xnm, xqm=xqm, xqh_id=xqh_id)
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}', 'jcList': []})
|
||
|
||
|
||
def _match_failed_to_retake(failed_courses: list, retake_items: list) -> list:
|
||
"""将不及格课程匹配到可重修课程,返回增强后的重修课程列表"""
|
||
import re
|
||
|
||
def _normalize_name(name: str) -> str:
|
||
"""
|
||
标准化课程名用于模糊匹配:
|
||
- 去掉末尾的单个大写字母(A/B/C等)以匹配同一门课的不同分组
|
||
- 不去掉"实践/实验"等后缀,因为这些代表不同的课程类型
|
||
"""
|
||
name = name.strip()
|
||
name = re.sub(r'[A-Z]$', '', name).strip()
|
||
return name
|
||
|
||
# 建立重修课程索引
|
||
retake_by_kch = {}
|
||
for r in retake_items:
|
||
kch = r.get('kch', '')
|
||
if kch:
|
||
retake_by_kch.setdefault(kch, []).append(r)
|
||
|
||
failed_kchs = {f['kch'] for f in failed_courses}
|
||
matched_items = []
|
||
matched_kchs = set()
|
||
|
||
for fc in failed_courses:
|
||
f_kch = fc['kch']
|
||
f_name = fc['kcmc']
|
||
f_name_norm = _normalize_name(f_name)
|
||
|
||
# 1. 精确课程号匹配
|
||
if f_kch in retake_by_kch:
|
||
for r in retake_by_kch[f_kch]:
|
||
enhanced = dict(r)
|
||
enhanced['_failed_kch'] = f_kch
|
||
enhanced['_failed_kcmc'] = f_name
|
||
enhanced['_original_cj'] = fc['cj']
|
||
enhanced['_match_type'] = 'exact'
|
||
matched_items.append(enhanced)
|
||
matched_kchs.add(r.get('kch', ''))
|
||
continue
|
||
|
||
# 2. 课程名模糊匹配
|
||
for r in retake_items:
|
||
r_kch = r.get('kch', '')
|
||
r_name = r.get('kcmc', '')
|
||
r_name_norm = _normalize_name(r_name)
|
||
|
||
if f_name_norm == r_name_norm or f_name in r_name or r_name in f_name:
|
||
enhanced = dict(r)
|
||
enhanced['_failed_kch'] = f_kch
|
||
enhanced['_failed_kcmc'] = f_name
|
||
enhanced['_original_cj'] = fc['cj']
|
||
enhanced['_match_type'] = 'fuzzy'
|
||
matched_items.append(enhanced)
|
||
matched_kchs.add(r_kch)
|
||
|
||
return matched_items
|
||
|
||
|
||
@api_bp.route('/jwxt/retake-courses')
|
||
@api_auth
|
||
def api_jwxt_retake_courses():
|
||
"""重修课程查询 — 自动匹配学生的不及格课程"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号'})
|
||
|
||
xnm = request.args.get('xnm', '')
|
||
xqm = request.args.get('xqm', '')
|
||
kkbm_id = request.args.get('kkbm_id', '')
|
||
kclbdm = request.args.get('kclbdm', '')
|
||
kkxbm = request.args.get('kkxbm', '')
|
||
show_all = request.args.get('show_all', '0') == '1'
|
||
try:
|
||
page = int(request.args.get('page', 1))
|
||
page_size = int(request.args.get('page_size', 500))
|
||
except (ValueError, TypeError):
|
||
page, page_size = 1, 500
|
||
|
||
def _do_request():
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(jwxt_acc['username'])
|
||
|
||
kwargs = {'page': page, 'page_size': page_size}
|
||
if xnm:
|
||
kwargs['xnm'] = xnm
|
||
if xqm:
|
||
kwargs['xqm'] = xqm
|
||
if kkbm_id:
|
||
kwargs['kkbm_id'] = kkbm_id
|
||
if kclbdm:
|
||
kwargs['kclbdm'] = kclbdm
|
||
if kkxbm:
|
||
kwargs['kkxbm'] = kkxbm
|
||
|
||
retake_result = api.get_retake_courses(**kwargs)
|
||
|
||
if not show_all:
|
||
# 获取不及格课程并匹配
|
||
try:
|
||
grades_result = api.get_grades(page_size=500)
|
||
grade_items = grades_result.get('items', [])
|
||
|
||
failed_courses = []
|
||
for g in grade_items:
|
||
cj_str = str(g.get('cj', '')).strip()
|
||
try:
|
||
cj = float(cj_str)
|
||
except ValueError:
|
||
continue
|
||
if 0 < cj < 60:
|
||
failed_courses.append({
|
||
'kch': g.get('kch', ''),
|
||
'kcmc': g.get('kcmc', ''),
|
||
'cj': cj,
|
||
'xf': g.get('xf', ''),
|
||
})
|
||
|
||
if failed_courses:
|
||
matched = _match_failed_to_retake(
|
||
failed_courses,
|
||
retake_result.get('items', [])
|
||
)
|
||
retake_result['items'] = matched
|
||
retake_result['total'] = len(matched)
|
||
retake_result['failed_courses'] = failed_courses
|
||
retake_result['matched'] = True
|
||
else:
|
||
retake_result['failed_courses'] = []
|
||
retake_result['matched'] = True
|
||
except Exception as e:
|
||
from app.jwxt_api import logger
|
||
logger.warning(f'成绩匹配失败,降级显示全部: {e}')
|
||
retake_result['matched'] = False
|
||
else:
|
||
retake_result['matched'] = False
|
||
|
||
return retake_result
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}', 'items': []})
|
||
|
||
|
||
@api_bp.route('/jwxt/textbook-details')
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_textbook_details():
|
||
"""教材明细查询"""
|
||
xnm = request.args.get('xnm', '')
|
||
xqm = request.args.get('xqm', '')
|
||
xyzt = request.args.get('xyzt', '')
|
||
try:
|
||
page = int(request.args.get('page', 1))
|
||
page_size = int(request.args.get('page_size', 200))
|
||
except (ValueError, TypeError):
|
||
page, page_size = 1, 200
|
||
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
kwargs = {'page': page, 'page_size': page_size}
|
||
if xnm:
|
||
kwargs['xnm'] = xnm
|
||
if xqm:
|
||
kwargs['xqm'] = xqm
|
||
if xyzt:
|
||
kwargs['xyzt'] = xyzt
|
||
return api.get_textbook_details(**kwargs)
|
||
|
||
|
||
@api_bp.route('/jwxt/teacher-schedule')
|
||
@api_auth
|
||
def api_jwxt_teacher_schedule():
|
||
"""教师列表查询"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号'})
|
||
|
||
xnm = request.args.get('xnm', '')
|
||
xqm = request.args.get('xqm', '')
|
||
xqh_id = request.args.get('xqh_id', '')
|
||
jg_id = request.args.get('jg_id', '')
|
||
zcm = request.args.get('zcm', '')
|
||
jgh = request.args.get('jgh', '')
|
||
sfwp = request.args.get('sfwp', '')
|
||
kkbm_id = request.args.get('kkbm_id', '')
|
||
zxszjjs = request.args.get('zxszjjs', '0') == '1'
|
||
try:
|
||
page = int(request.args.get('page', 1))
|
||
page_size = int(request.args.get('page_size', 1000))
|
||
except (ValueError, TypeError):
|
||
page, page_size = 1, 1000
|
||
|
||
def _do_request():
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(jwxt_acc['username'])
|
||
kwargs = {
|
||
'page': page,
|
||
'page_size': page_size,
|
||
'zxszjjs': zxszjjs,
|
||
}
|
||
if xnm: kwargs['xnm'] = xnm
|
||
if xqm: kwargs['xqm'] = xqm
|
||
if xqh_id: kwargs['xqh_id'] = xqh_id
|
||
if jg_id: kwargs['jg_id'] = jg_id
|
||
if zcm: kwargs['zcm'] = zcm
|
||
if jgh: kwargs['jgh'] = jgh
|
||
if sfwp: kwargs['sfwp'] = sfwp
|
||
if kkbm_id: kwargs['kkbm_id'] = kkbm_id
|
||
return api.get_teacher_schedule(**kwargs)
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}', 'items': []})
|
||
|
||
|
||
@api_bp.route('/jwxt/teacher-schedule-detail')
|
||
@api_auth
|
||
def api_jwxt_teacher_schedule_detail():
|
||
"""
|
||
获取指定教师的课程表明细(用于预览弹窗)。
|
||
|
||
使用教师课表打印 API(jskbdy_cxJsKb),按 jgh_id(教师内部ID)查询。
|
||
jgh_id 来自教师列表 API 返回的字段,直接精确查询,无需二次过滤。
|
||
"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号'})
|
||
|
||
jgh_id = request.args.get('jgh_id', '')
|
||
xnm = request.args.get('xnm', '')
|
||
xqm = request.args.get('xqm', '')
|
||
|
||
if not jgh_id:
|
||
return jsonify({'success': False, 'message': '缺少参数 jgh_id'})
|
||
|
||
def _do_request():
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(jwxt_acc['username'])
|
||
return api.get_teacher_schedule_detail(jgh_id, xnm, xqm)
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}', 'kbList': []})
|
||
|
||
|
||
@api_bp.route('/jwxt/course-index/status')
|
||
@api_auth
|
||
def api_jwxt_course_index_status():
|
||
"""检查课程索引状态(纯读本地文件,不需要教务系统 session)"""
|
||
xnm = request.args.get('xnm', '2026')
|
||
xqm = request.args.get('xqm', '3')
|
||
from app.jwxt_api import JwxtApi
|
||
acc = _resolve_jwxt_acc()
|
||
api = JwxtApi(acc['username'] if acc else '')
|
||
return jsonify(api.get_course_index_status(xnm, xqm))
|
||
|
||
|
||
@api_bp.route('/jwxt/course-index/build', methods=['POST'])
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_course_index_build():
|
||
"""构建课程索引(全量拉取教师课表,后台线程执行)"""
|
||
xnm = request.args.get('xnm', '2026')
|
||
xqm = request.args.get('xqm', '3')
|
||
force = request.args.get('force', '0') == '1'
|
||
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
|
||
# 检查是否已在构建中
|
||
status = api.get_course_index_status(xnm, xqm)
|
||
if status.get('building'):
|
||
return {'success': True, 'message': '索引正在构建中', 'building': True,
|
||
'current': status.get('current', 0),
|
||
'total_teachers': status.get('total_teachers', 0)}
|
||
|
||
# 先标记为构建中(写入一个空的中间状态)
|
||
api._save_index({}, xnm, xqm, 0, 0, done=False, current=0, current_teacher='')
|
||
|
||
username = g.jwxt_acc['username']
|
||
|
||
def _build_in_background():
|
||
try:
|
||
api.build_course_index(xnm, xqm, force=force)
|
||
except Exception as e:
|
||
import logging
|
||
logging.getLogger(__name__).error(f'[课程索引] 后台构建异常: {e}')
|
||
|
||
import threading
|
||
t = threading.Thread(target=_build_in_background, daemon=True)
|
||
t.start()
|
||
|
||
return {'success': True, 'message': '索引构建已启动', 'building': True}
|
||
|
||
|
||
@api_bp.route('/jwxt/course-search')
|
||
@api_auth
|
||
def api_jwxt_course_search():
|
||
"""全字段搜索授课信息(纯读本地索引,不需要教务系统 session)"""
|
||
keyword = request.args.get('keyword', '').strip()
|
||
xnm = request.args.get('xnm', '2026')
|
||
xqm = request.args.get('xqm', '3')
|
||
field = request.args.get('field', 'auto')
|
||
|
||
if not keyword:
|
||
return jsonify({'success': False, 'message': '请输入搜索关键词', 'courses': []})
|
||
|
||
from app.jwxt_api import JwxtApi
|
||
acc = _resolve_jwxt_acc()
|
||
api = JwxtApi(acc['username'] if acc else '')
|
||
result = api.search_courses(keyword, xnm, xqm, field=field)
|
||
return jsonify(result)
|
||
|
||
|
||
@api_bp.route('/jwxt/course-browse')
|
||
@api_auth
|
||
def api_jwxt_course_browse():
|
||
"""浏览课程索引概览(课程/教师/地点/班级列表,纯读本地索引)"""
|
||
xnm = request.args.get('xnm', '2026')
|
||
xqm = request.args.get('xqm', '3')
|
||
from app.jwxt_api import JwxtApi
|
||
acc = _resolve_jwxt_acc()
|
||
api = JwxtApi(acc['username'] if acc else '')
|
||
result = api.browse_course_index(xnm, xqm)
|
||
return jsonify(result)
|
||
|
||
|
||
@api_bp.route('/jwxt/classroom-schedule')
|
||
@api_auth
|
||
def api_jwxt_classroom_schedule():
|
||
"""场地课表查询"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号'})
|
||
|
||
xnm = request.args.get('xnm', '')
|
||
xqm = request.args.get('xqm', '')
|
||
xqh_id = request.args.get('xqh_id', '')
|
||
lh = request.args.get('lh', '')
|
||
cdbh = request.args.get('cdbh', '')
|
||
cdlbid = request.args.get('cdlbid', '')
|
||
try:
|
||
page = int(request.args.get('page', 1))
|
||
page_size = int(request.args.get('page_size', 100))
|
||
except (ValueError, TypeError):
|
||
page, page_size = 1, 100
|
||
|
||
def _do_request():
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(jwxt_acc['username'])
|
||
kwargs = {'page': page, 'page_size': page_size}
|
||
if xnm:
|
||
kwargs['xnm'] = xnm
|
||
if xqm:
|
||
kwargs['xqm'] = xqm
|
||
if xqh_id:
|
||
kwargs['xqh_id'] = xqh_id
|
||
if lh:
|
||
kwargs['lh'] = lh
|
||
if cdbh:
|
||
kwargs['cdbh'] = cdbh
|
||
if cdlbid:
|
||
kwargs['cdlbid'] = cdlbid
|
||
return api.get_classroom_schedule(**kwargs)
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}', 'items': []})
|
||
|
||
|
||
@api_bp.route('/jwxt/academic-status')
|
||
@api_auth
|
||
def api_jwxt_academic_status():
|
||
"""学业情况查询(培养方案完成度)"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号'})
|
||
|
||
def _do_request():
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(jwxt_acc['username'])
|
||
return api.get_academic_status()
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}', 'tree': [], 'nodes': []})
|
||
|
||
|
||
@api_bp.route('/jwxt/academic-status/courses')
|
||
@api_auth
|
||
def api_jwxt_academic_status_courses():
|
||
"""学业情况节点课程明细"""
|
||
xfyqjd_id = request.args.get('xfyqjd_id', '')
|
||
if not xfyqjd_id:
|
||
return jsonify({'success': False, 'message': '缺少 xfyqjd_id 参数', 'courses': [], 'total': 0, 'passed': 0})
|
||
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号'})
|
||
|
||
def _do_request():
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(jwxt_acc['username'])
|
||
return api.get_academic_status_courses(xfyqjd_id)
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}', 'courses': [], 'total': 0, 'passed': 0})
|
||
|
||
|
||
@api_bp.route('/jwxt/teaching-plan')
|
||
@api_auth
|
||
def api_jwxt_teaching_plan():
|
||
"""教学执行计划查询"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号'})
|
||
|
||
jg_id = request.args.get('jg_id', '')
|
||
njdm_id = request.args.get('njdm_id', '')
|
||
dlbs = request.args.get('dlbs', '')
|
||
zyh_id = request.args.get('zyh_id', '')
|
||
try:
|
||
page = int(request.args.get('page', 1))
|
||
page_size = int(request.args.get('page_size', 100))
|
||
except (ValueError, TypeError):
|
||
page, page_size = 1, 100
|
||
|
||
def _do_request():
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(jwxt_acc['username'])
|
||
kwargs = {'page': page, 'page_size': page_size}
|
||
if jg_id:
|
||
kwargs['jg_id'] = jg_id
|
||
if njdm_id:
|
||
kwargs['njdm_id'] = njdm_id
|
||
if dlbs:
|
||
kwargs['dlbs'] = dlbs
|
||
if zyh_id:
|
||
kwargs['zyh_id'] = zyh_id
|
||
return api.get_teaching_plan(**kwargs)
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}', 'items': []})
|
||
|
||
|
||
@api_bp.route('/jwxt/teaching-plan/requirements/<jxzxjhxx_id>')
|
||
@api_auth
|
||
def api_jwxt_teaching_plan_requirements(jxzxjhxx_id):
|
||
"""教学执行计划 - 修读要求(HTML片段)"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号'})
|
||
|
||
def _do_request():
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(jwxt_acc['username'])
|
||
return api.get_teaching_plan_requirements(jxzxjhxx_id)
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}'})
|
||
|
||
|
||
@api_bp.route('/jwxt/teaching-plan/courses')
|
||
@api_auth
|
||
def api_jwxt_teaching_plan_courses():
|
||
"""教学执行计划 - 课程信息(jqGrid分页)"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号'})
|
||
|
||
jxzxjhxx_id = request.args.get('jxzxjhxx_id', '')
|
||
jyxdxnm = request.args.get('jyxdxnm', '')
|
||
jyxdxqm = request.args.get('jyxdxqm', '')
|
||
yxxdxnm = request.args.get('yxxdxnm', '')
|
||
yxxdxqm = request.args.get('yxxdxqm', '')
|
||
shzt = request.args.get('shzt', '')
|
||
kch = request.args.get('kch', '')
|
||
xdlx = request.args.get('xdlx', '')
|
||
try:
|
||
page = int(request.args.get('page', 1))
|
||
page_size = int(request.args.get('page_size', 100))
|
||
except (ValueError, TypeError):
|
||
page, page_size = 1, 100
|
||
|
||
if not jxzxjhxx_id:
|
||
return jsonify({'success': False, 'message': '缺少 jxzxjhxx_id 参数', 'items': []})
|
||
|
||
def _do_request():
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(jwxt_acc['username'])
|
||
return api.get_teaching_plan_courses(
|
||
jxzxjhxx_id=jxzxjhxx_id,
|
||
jyxdxnm=jyxdxnm,
|
||
jyxdxqm=jyxdxqm,
|
||
yxxdxnm=yxxdxnm,
|
||
yxxdxqm=yxxdxqm,
|
||
shzt=shzt,
|
||
kch=kch,
|
||
xdlx=xdlx,
|
||
page=page,
|
||
page_size=page_size,
|
||
)
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}', 'items': []})
|
||
|
||
|
||
@api_bp.route('/jwxt/teaching-plan/preview/<jxzxjhxx_id>')
|
||
@api_auth
|
||
def api_jwxt_teaching_plan_preview(jxzxjhxx_id):
|
||
"""教学执行计划 - 执行计划预览(完整HTML页面)"""
|
||
jwxt_acc = _resolve_jwxt_acc()
|
||
if not jwxt_acc:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号'})
|
||
|
||
def _do_request():
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(jwxt_acc['username'])
|
||
return api.get_teaching_plan_preview_html(jxzxjhxx_id)
|
||
|
||
try:
|
||
result, _ = with_session_retry(current_user, _do_request)
|
||
return jsonify(result)
|
||
except Exception as e:
|
||
return jsonify({'success': False, 'message': f'查询失败: {str(e)}'})
|
||
|
||
|
||
# ── 教材预订 API ──────────────────────────────────────────
|
||
|
||
@api_bp.route('/jwxt/textbook-orders')
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_textbook_orders():
|
||
"""查询教材预订列表"""
|
||
xnm = request.args.get('xnm', '')
|
||
xqm = request.args.get('xqm', '')
|
||
try:
|
||
page = int(request.args.get('page', 1))
|
||
page_size = int(request.args.get('page_size', 1500))
|
||
except (ValueError, TypeError):
|
||
page, page_size = 1, 1500
|
||
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
kwargs = {'page': page, 'page_size': page_size}
|
||
if xnm:
|
||
kwargs['xnm'] = xnm
|
||
if xqm:
|
||
kwargs['xqm'] = xqm
|
||
return api.get_textbook_orders(**kwargs)
|
||
|
||
|
||
@api_bp.route('/jwxt/textbook-order', methods=['POST'])
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_textbook_order():
|
||
"""预订或取消预订教材"""
|
||
data = request.get_json(silent=True)
|
||
if not data:
|
||
data = request.form
|
||
|
||
jxb_id = data.get('jxb_id', '')
|
||
action = data.get('action', 'order') # 'order' 或 'cancel'
|
||
|
||
if not jxb_id:
|
||
return {'success': False, 'message': '缺少 jxb_id 参数'}
|
||
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.order_textbook(jxb_id, order=(action == 'order'))
|
||
|
||
|
||
# ════════════════════════════════════════════════════════════════
|
||
# 报名申请模块 — 页面路由
|
||
# ════════════════════════════════════════════════════════════════
|
||
|
||
@main_bp.route('/enrollment-change')
|
||
@login_required
|
||
def page_enrollment_change():
|
||
"""学籍异动申请页面"""
|
||
return render_template('enrollment_change.html',
|
||
active_nav='enrollment-change')
|
||
|
||
|
||
@main_bp.route('/retake-registration')
|
||
@login_required
|
||
def page_retake_registration():
|
||
"""重修报名页面"""
|
||
return render_template('retake_registration.html',
|
||
active_nav='retake-registration')
|
||
|
||
|
||
@main_bp.route('/exam-registration')
|
||
@login_required
|
||
def page_exam_registration():
|
||
"""考级项目报名页面"""
|
||
return render_template('exam_registration.html',
|
||
active_nav='exam-registration')
|
||
|
||
|
||
@main_bp.route('/teaching-project')
|
||
@login_required
|
||
def page_teaching_project():
|
||
"""教学项目报名页面"""
|
||
return render_template('teaching_project.html',
|
||
active_nav='teaching-project')
|
||
|
||
|
||
@main_bp.route('/credit-recognition')
|
||
@login_required
|
||
def page_credit_recognition():
|
||
"""成绩学分认定申请页面"""
|
||
return render_template('credit_recognition.html',
|
||
active_nav='credit-recognition')
|
||
|
||
|
||
@main_bp.route('/course-substitution')
|
||
@login_required
|
||
def page_course_substitution():
|
||
"""校内课程替代申请页面"""
|
||
return render_template('course_substitution.html',
|
||
active_nav='course-substitution')
|
||
|
||
|
||
@main_bp.route('/grade-review')
|
||
@login_required
|
||
def page_grade_review():
|
||
"""成绩复查申请页面"""
|
||
return render_template('grade_review.html',
|
||
active_nav='grade-review')
|
||
|
||
|
||
# ════════════════════════════════════════════════════════════════
|
||
# 信息维护模块 — 页面路由
|
||
# ════════════════════════════════════════════════════════════════
|
||
|
||
@main_bp.route('/personal-info-edit')
|
||
@login_required
|
||
def page_personal_info_edit():
|
||
"""个人信息编辑页面"""
|
||
return render_template('personal_info_edit.html',
|
||
active_nav='personal-info-edit')
|
||
|
||
|
||
# ════════════════════════════════════════════════════════════════
|
||
# 毕业论文(设计)模块 — 页面路由
|
||
# ════════════════════════════════════════════════════════════════
|
||
|
||
@main_bp.route('/thesis-topic')
|
||
@login_required
|
||
def page_thesis_topic():
|
||
"""毕业论文选题页面"""
|
||
return render_template('thesis_topic.html',
|
||
active_nav='thesis-topic')
|
||
|
||
|
||
@main_bp.route('/supervisor-change')
|
||
@login_required
|
||
def page_supervisor_change():
|
||
"""更换指导教师申请页面"""
|
||
return render_template('supervisor_change.html',
|
||
active_nav='supervisor-change')
|
||
|
||
|
||
@main_bp.route('/thesis-process-docs')
|
||
@login_required
|
||
def page_thesis_process_docs():
|
||
"""毕业论文过程资料页面"""
|
||
return render_template('thesis_process_docs.html',
|
||
active_nav='thesis-process-docs')
|
||
|
||
|
||
@main_bp.route('/thesis-plagiarism-check')
|
||
@login_required
|
||
def page_thesis_plagiarism_check():
|
||
"""毕业论文查重页面"""
|
||
return render_template('thesis_plagiarism_check.html',
|
||
active_nav='thesis-plagiarism-check')
|
||
|
||
|
||
@main_bp.route('/thesis-grades')
|
||
@login_required
|
||
def page_thesis_grades():
|
||
"""毕业论文成绩查看页面"""
|
||
return render_template('thesis_grades.html',
|
||
active_nav='thesis-grades')
|
||
|
||
|
||
# ════════════════════════════════════════════════════════════════
|
||
# 报名申请模块 — API 路由
|
||
# ════════════════════════════════════════════════════════════════
|
||
|
||
@api_bp.route('/jwxt/enrollment-change')
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_enrollment_change():
|
||
"""学籍异动申请 — 查询"""
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.get_student_status_change()
|
||
|
||
|
||
@api_bp.route('/jwxt/enrollment-change/submit', methods=['POST'])
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_enrollment_change_submit():
|
||
"""学籍异动申请 — 提交"""
|
||
data = request.get_json(silent=True) or request.form
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.submit_status_change(**data)
|
||
|
||
|
||
@api_bp.route('/jwxt/retake-registration')
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_retake_registration():
|
||
"""重修报名信息 — 查询"""
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.get_retake_registration_info()
|
||
|
||
|
||
@api_bp.route('/jwxt/retake-registration/submit', methods=['POST'])
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_retake_registration_submit():
|
||
"""重修报名 — 提交"""
|
||
data = request.get_json(silent=True) or request.form
|
||
kch_id = data.get('kch_id', '')
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.submit_retake_registration(kch_id=kch_id)
|
||
|
||
|
||
@api_bp.route('/jwxt/exam-registration')
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_exam_registration():
|
||
"""考级项目报名 — 查询"""
|
||
xmlbfl = request.args.get('xmlbfl', '1001')
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.get_exam_registration(xmlbfl=xmlbfl)
|
||
|
||
|
||
@api_bp.route('/jwxt/exam-registration/submit', methods=['POST'])
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_exam_registration_submit():
|
||
"""考级项目报名 — 提交"""
|
||
data = request.get_json(silent=True) or request.form
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.submit_exam_registration(**data)
|
||
|
||
|
||
@api_bp.route('/jwxt/exam-registration/expired')
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_exam_registration_expired():
|
||
"""考级过期项目报名信息 — 查询"""
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.get_expired_exam_registration()
|
||
|
||
|
||
@api_bp.route('/jwxt/teaching-project')
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_teaching_project():
|
||
"""教学项目报名 — 查询"""
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.get_teaching_project_registration()
|
||
|
||
|
||
@api_bp.route('/jwxt/teaching-project/submit', methods=['POST'])
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_teaching_project_submit():
|
||
"""教学项目报名 — 提交"""
|
||
data = request.get_json(silent=True) or request.form
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.submit_teaching_project(**data)
|
||
|
||
|
||
@api_bp.route('/jwxt/credit-recognition')
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_credit_recognition():
|
||
"""成绩学分认定申请 — 查询"""
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.get_credit_recognition()
|
||
|
||
|
||
@api_bp.route('/jwxt/credit-recognition/submit', methods=['POST'])
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_credit_recognition_submit():
|
||
"""成绩学分认定申请 — 提交"""
|
||
data = request.get_json(silent=True) or request.form
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.submit_credit_recognition(**data)
|
||
|
||
|
||
@api_bp.route('/jwxt/course-substitution')
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_course_substitution():
|
||
"""校内课程替代申请 — 查询"""
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.get_course_substitution()
|
||
|
||
|
||
@api_bp.route('/jwxt/course-substitution/submit', methods=['POST'])
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_course_substitution_submit():
|
||
"""校内课程替代申请 — 提交"""
|
||
data = request.get_json(silent=True) or request.form
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.submit_course_substitution(**data)
|
||
|
||
|
||
@api_bp.route('/jwxt/grade-review')
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_grade_review():
|
||
"""成绩复查申请 — 查询"""
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.get_grade_review()
|
||
|
||
|
||
@api_bp.route('/jwxt/grade-review/submit', methods=['POST'])
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_grade_review_submit():
|
||
"""成绩复查申请 — 提交"""
|
||
data = request.get_json(silent=True) or request.form
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.submit_grade_review(**data)
|
||
|
||
|
||
# ════════════════════════════════════════════════════════════════
|
||
# 信息维护模块 — API 路由
|
||
# ════════════════════════════════════════════════════════════════
|
||
|
||
@api_bp.route('/jwxt/personal-info-editable')
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_personal_info_editable():
|
||
"""获取个人信息中可编辑的字段"""
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.get_editable_fields()
|
||
|
||
|
||
@api_bp.route('/jwxt/personal-info/update', methods=['POST'])
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_personal_info_update():
|
||
"""更新个人信息"""
|
||
data = request.get_json(silent=True) or request.form
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.update_student_info(**data)
|
||
|
||
|
||
# ════════════════════════════════════════════════════════════════
|
||
# 毕业论文(设计)模块 — API 路由
|
||
# ════════════════════════════════════════════════════════════════
|
||
|
||
@api_bp.route('/jwxt/thesis-topic')
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_thesis_topic():
|
||
"""毕业论文选题 — 查询"""
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.get_thesis_topic_selection()
|
||
|
||
|
||
@api_bp.route('/jwxt/thesis-topic/submit', methods=['POST'])
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_thesis_topic_submit():
|
||
"""毕业论文选题 — 提交"""
|
||
data = request.get_json(silent=True) or request.form
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.submit_topic_selection(**data)
|
||
|
||
|
||
@api_bp.route('/jwxt/supervisor-change')
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_supervisor_change():
|
||
"""更换指导教师申请 — 查询"""
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.get_supervisor_change_requests()
|
||
|
||
|
||
@api_bp.route('/jwxt/supervisor-change/submit', methods=['POST'])
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_supervisor_change_submit():
|
||
"""更换指导教师申请 — 提交"""
|
||
data = request.get_json(silent=True) or request.form
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.submit_supervisor_change(**data)
|
||
|
||
|
||
@api_bp.route('/jwxt/thesis-process-docs')
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_thesis_process_docs():
|
||
"""毕业论文过程资料 — 查询"""
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.get_thesis_process_docs()
|
||
|
||
|
||
@api_bp.route('/jwxt/thesis-plagiarism-check')
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_thesis_plagiarism_check():
|
||
"""毕业论文查重 — 查询"""
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.get_thesis_plagiarism_check()
|
||
|
||
|
||
@api_bp.route('/jwxt/thesis-grades')
|
||
@api_auth
|
||
@ensure_jwxt_session
|
||
def api_jwxt_thesis_grades():
|
||
"""毕业论文成绩 — 查询"""
|
||
from app.jwxt_api import JwxtApi
|
||
api = JwxtApi(g.jwxt_acc['username'])
|
||
return api.get_thesis_grades()
|
||
|
||
|
||
# ==================== 多线路 & 选课模式 API ====================
|
||
|
||
@api_bp.route('/lines')
|
||
@api_auth
|
||
def api_lines_list():
|
||
"""线路列表:延迟、当前线路、我的选择(所有登录用户可看)"""
|
||
from app.multi_line import get_status, get_user_preference
|
||
status = get_status(current_user.school_id or DEFAULT_SCHOOL_ID)
|
||
# 用户不暴露别人的偏好
|
||
status.pop('user_preferences', None)
|
||
from app.account_manager import AccountManager
|
||
jwxt_acc = current_user.get_jwxt_account() or {}
|
||
jwxt_username = jwxt_acc.get('username') or current_user.jwxt_username
|
||
status['my_line'] = get_user_preference(jwxt_username) if jwxt_username else 'auto'
|
||
return jsonify({'success': True, **status})
|
||
|
||
|
||
@api_bp.route('/lines/select', methods=['POST'])
|
||
@api_auth
|
||
def api_lines_select():
|
||
"""用户选择线路:line = "auto" 或线路 tag(切换预热 session,毫秒级)"""
|
||
from app.multi_line import activate_user_line, set_user_preference, is_enabled
|
||
if not is_enabled(current_user.school_id):
|
||
return jsonify({'success': False, 'message': '多线路模式未开启'}), 400
|
||
|
||
data = request.get_json(silent=True) or {}
|
||
line = (data.get('line') or 'auto').strip()
|
||
|
||
jwxt_acc = current_user.get_jwxt_account() or {}
|
||
jwxt_username = jwxt_acc.get('username') or current_user.jwxt_username
|
||
if not jwxt_username:
|
||
return jsonify({'success': False, 'message': '未配置教务系统账号'}), 400
|
||
|
||
if line in ('auto', ''):
|
||
from app.url_manager import get_global_base_url
|
||
from app.multi_line import line_tag
|
||
active = activate_user_line(jwxt_username, line_tag(get_global_base_url(current_user.school_id)))
|
||
if not active.get('success'):
|
||
return jsonify(active), 400
|
||
set_user_preference(jwxt_username, 'auto')
|
||
return jsonify({'success': True, 'message': '已切换为智能线路(自动跟随最优线路)'})
|
||
|
||
result = activate_user_line(jwxt_username, line)
|
||
code = 200 if result.get('success') else 400
|
||
return jsonify(result), code
|
||
|
||
|
||
@api_bp.route('/admin/lines/status')
|
||
@api_auth
|
||
def api_admin_lines_status():
|
||
"""多线路状态(仅管理员):?school_id= 指定学校,缺省为管理员所属学校"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
from app.multi_line import get_status
|
||
from app.school_manager import list_schools
|
||
school_id = request.args.get('school_id') or current_user.school_id or DEFAULT_SCHOOL_ID
|
||
if school_id not in {s['id'] for s in list_schools()}:
|
||
return jsonify({'success': False, 'message': '未知学校'}), 400
|
||
return jsonify({'success': True, **get_status(school_id)})
|
||
|
||
|
||
@api_bp.route('/admin/lines/toggle', methods=['POST'])
|
||
@api_auth
|
||
def api_admin_lines_toggle():
|
||
"""多线路预热开关(仅管理员,按学校)"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
from app.multi_line import set_enabled
|
||
from app.school_manager import get_school
|
||
data = request.get_json(silent=True) or {}
|
||
school_id = data.get('school_id') or current_user.school_id or DEFAULT_SCHOOL_ID
|
||
if not get_school(school_id):
|
||
return jsonify({'success': False, 'message': '未知学校'}), 400
|
||
enabled = bool(data.get('enabled'))
|
||
set_enabled(enabled, school_id)
|
||
school = get_school(school_id) or {}
|
||
return jsonify({
|
||
'success': True,
|
||
'message': (f"「{school.get('name', school_id)}」多线路预热已开启,正在后台为该校账号预热线路"
|
||
if enabled else f"「{school.get('name', school_id)}」多线路预热已关闭"),
|
||
'multi_line_enabled': enabled,
|
||
'school_id': school_id,
|
||
})
|
||
|
||
|
||
@api_bp.route('/admin/lines/prelogin', methods=['POST'])
|
||
@api_auth
|
||
def api_admin_lines_prelogin():
|
||
"""手动触发预热(后台执行,立即返回):body.school_id 指定学校,缺省为管理员所属学校"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
from app.multi_line import is_enabled, prelogin_all
|
||
from app.school_manager import get_school
|
||
data = request.get_json(silent=True) or {}
|
||
school_id = data.get('school_id') or current_user.school_id or DEFAULT_SCHOOL_ID
|
||
if not get_school(school_id):
|
||
return jsonify({'success': False, 'message': '未知学校'}), 400
|
||
if not is_enabled(school_id):
|
||
return jsonify({'success': False, 'message': '请先开启该校的多线路预热'}), 400
|
||
threading.Thread(target=prelogin_all, kwargs={'force': True, 'school_id': school_id},
|
||
daemon=True, name='multi-line-prelogin').start()
|
||
return jsonify({'success': True, 'message': '该校全量预热已在后台启动'})
|
||
|
||
|
||
@api_bp.route('/admin/xk_mode', methods=['GET', 'POST'])
|
||
@api_auth
|
||
def api_admin_xk_mode():
|
||
"""选课模式开关(仅管理员,按学校):开启后暂停该校的非核心后台任务并拦截非核心查询"""
|
||
if not current_user.is_admin:
|
||
return jsonify({'success': False, 'message': '无权访问'}), 403
|
||
from app.multi_line import is_xk_mode, set_xk_mode
|
||
from app.school_manager import get_school
|
||
if request.method == 'GET':
|
||
school_id = request.args.get('school_id') or current_user.school_id or DEFAULT_SCHOOL_ID
|
||
if not get_school(school_id):
|
||
return jsonify({'success': False, 'message': '未知学校'}), 400
|
||
return jsonify({'success': True, 'xk_mode': is_xk_mode(school_id), 'school_id': school_id})
|
||
data = request.get_json(silent=True) or {}
|
||
school_id = data.get('school_id') or current_user.school_id or DEFAULT_SCHOOL_ID
|
||
if not get_school(school_id):
|
||
return jsonify({'success': False, 'message': '未知学校'}), 400
|
||
enabled = bool(data.get('enabled'))
|
||
set_xk_mode(enabled, school_id)
|
||
school = get_school(school_id) or {}
|
||
return jsonify({
|
||
'success': True,
|
||
'xk_mode': enabled,
|
||
'school_id': school_id,
|
||
'message': (f"「{school.get('name', school_id)}」选课模式已开启:该校非核心服务已暂停"
|
||
if enabled else f"「{school.get('name', school_id)}」选课模式已关闭:其他服务已恢复"),
|
||
})
|