From 65039b232b613c5a3ea884e65d0400d4cc7114f9 Mon Sep 17 00:00:00 2001 From: ucmao <294323976@qq.com> Date: Thu, 10 Sep 2026 09:14:19 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E5=90=8E=E5=8F=B0=E8=A1=A8?= =?UTF-8?q?=E6=A0=BC=E4=BA=A4=E4=BA=92=E4=BD=93=E9=AA=8C=EF=BC=8C=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E8=B7=A8=E9=A1=B5=E5=85=A8=E9=80=89=E6=89=B9=E9=87=8F?= =?UTF-8?q?=E6=93=8D=E4=BD=9C=E4=B8=8E=E6=97=A0=E5=88=B7=E6=96=B0=E5=88=86?= =?UTF-8?q?=E9=A1=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/utils/table_query.py | 24 ++- src/web/admin.py | 244 +++++++++++++++++++++++++- src/web/portal.py | 46 ++++- static/js/table_manager.js | 253 +++++++++++++++++++++++---- templates/admin/keys.html | 19 +- templates/admin/logs.html | 19 +- templates/admin/platforms.html | 19 +- templates/admin/users.html | 19 +- templates/components/pagination.html | 124 +++++++++++++ templates/portal/keys.html | 19 +- templates/portal/logs.html | 19 +- templates/portal/platforms.html | 19 +- tests/test_management.py | 132 ++++++++++++++ 13 files changed, 793 insertions(+), 163 deletions(-) create mode 100644 templates/components/pagination.html diff --git a/src/utils/table_query.py b/src/utils/table_query.py index 4ec19dd..da0e472 100644 --- a/src/utils/table_query.py +++ b/src/utils/table_query.py @@ -11,10 +11,11 @@ def parse_table_params( default_order: str = "desc", default_page_size: int = 50, prefix: str = "", + cookies: Dict[str, str] = None, ) -> Dict[str, Any]: """ 从请求参数中解析通用表格参数(页码、每页条数、排序字段、排序方向、关键字等)。 - 前缀参数用于同页面多个表格区分(如 logs_page vs users_page)。 + 支持从浏览器持久化 Cookie 中自动恢复用户上次选择的每页条数偏好。 """ page_key = f"{prefix}page" if prefix else "page" page_size_key = f"{prefix}page_size" if prefix else "page_size" @@ -27,8 +28,27 @@ def parse_table_params( except (TypeError, ValueError): page = 1 + # 尝试从请求上下文或参数中获取 Cookie 偏好 + if cookies is None: + try: + from flask import has_request_context, request + if has_request_context() and hasattr(request, "cookies"): + cookies = request.cookies + except Exception: + cookies = None + + clean_prefix = prefix.rstrip("_") if prefix else "default" + cookie_key = f"mp_page_size_{clean_prefix}" + pref_size = None + if cookies and cookie_key in cookies: + try: + pref_size = int(cookies[cookie_key]) + except (TypeError, ValueError): + pref_size = None + + raw_size = args.get(page_size_key, pref_size if pref_size is not None else default_page_size) try: - page_size = int(args.get(page_size_key, default_page_size)) + page_size = int(raw_size) if page_size not in ALLOWED_PAGE_SIZES: page_size = default_page_size except (TypeError, ValueError): diff --git a/src/web/admin.py b/src/web/admin.py index 8ee815c..fadeec0 100644 --- a/src/web/admin.py +++ b/src/web/admin.py @@ -172,6 +172,7 @@ def users(): where_clauses=users_where, where_params=users_params, request_args=request.args, + default_page_size=20, prefix="users_", ) @@ -279,10 +280,82 @@ def reset_password(user_id): @csrf_protected def batch_users(): db = get_db() - ids_raw = request.form.get("ids", "").strip() action = request.form.get("action", "").strip() + select_mode = request.form.get("select_mode", "page").strip() - if not ids_raw or not action: + if not action: + flash("未指定批量操作类型", "error") + return redirect(url_for("admin.users")) + + if select_mode == "all": + users_where, users_params = [], [] + if u_q := (request.form.get("users_q") or request.form.get("q") or "").strip(): + users_where.append("u.username LIKE ?") + users_params.append(f"%{u_q}%") + if u_role := (request.form.get("users_role") or request.form.get("role") or "").strip(): + users_where.append("u.role = ?") + users_params.append(u_role) + if u_active := (request.form.get("users_active") or request.form.get("active") or "").strip(): + try: + val = int(u_active) + users_where.append("u.active = ?") + users_params.append(val) + except ValueError: + pass + users_where.append("u.role != 'admin'") + + where_sql = " WHERE " + " AND ".join(users_where) + subquery = f"SELECT u.id FROM users u{where_sql}" + matched_count = db.execute(f"SELECT COUNT(*) as c FROM users WHERE id IN ({subquery})", users_params).fetchone()["c"] + + if action == "enable": + db.execute(f"UPDATE users SET active=1 WHERE id IN ({subquery})", users_params) + flash(f"已批量启用符合筛选条件的全部 {matched_count} 个客户账号", "success") + elif action == "disable": + db.execute(f"UPDATE users SET active=0 WHERE id IN ({subquery})", users_params) + flash(f"已批量停用符合筛选条件的全部 {matched_count} 个客户账号", "success") + elif action == "adjust_credits": + mode = request.form.get("credits_mode", "add") + try: + amount = int(request.form.get("credits_amount", 0)) + except ValueError: + amount = 0 + + if mode == "set": + db.execute(f"UPDATE users SET credits=? WHERE id IN ({subquery})", [amount] + users_params) + elif mode == "add": + db.execute(f"UPDATE users SET credits=credits+? WHERE id IN ({subquery}) AND credits!=-1", [amount] + users_params) + elif mode == "deduct": + db.execute(f"UPDATE users SET credits=MAX(0, credits-?) WHERE id IN ({subquery}) AND credits!=-1", [amount] + users_params) + flash(f"已批量更新符合筛选条件的全部 {matched_count} 个客户账号积分", "success") + elif action == "set_qps": + try: + qps = _positive_int(request.form.get("qps_limit"), 2) + db.execute(f"UPDATE users SET qps_limit=? WHERE id IN ({subquery})", [qps] + users_params) + flash(f"已批量设置符合筛选条件的全部 {matched_count} 个客户并发 QPS 为 {qps}", "success") + except ValueError: + flash("QPS 格式无效", "error") + elif action == "set_expires": + expires = request.form.get("expires_at", "").strip() + expires_at = None + if expires: + try: + local_end = datetime.combine(datetime.strptime(expires, "%Y-%m-%d").date(), time.max) + expires_at = local_end.replace(tzinfo=ZoneInfo("Asia/Shanghai")).astimezone(timezone.utc).isoformat(timespec="seconds") + except ValueError: + flash("到期日期格式无效", "error") + return redirect(url_for("admin.users")) + db.execute(f"UPDATE users SET expires_at=? WHERE id IN ({subquery})", [expires_at] + users_params) + flash(f"已批量设置符合筛选条件的全部 {matched_count} 个客户账号到期时间", "success") + else: + flash("不支持的批量操作类型", "error") + return redirect(url_for("admin.users")) + + db.commit() + return redirect(url_for("admin.users")) + + ids_raw = request.form.get("ids", "").strip() + if not ids_raw: flash("请先勾选需要批量操作的客户账号", "error") return redirect(url_for("admin.users")) @@ -383,6 +456,7 @@ def keys(): where_clauses=keys_where, where_params=keys_params, request_args=request.args, + default_page_size=20, prefix="keys_", ) all_users = db.execute("SELECT id, username, role, active FROM users ORDER BY id ASC").fetchall() @@ -468,10 +542,57 @@ def delete_key(key_id): @csrf_protected def batch_keys(): db = get_db() - ids_raw = request.form.get("ids", "").strip() action = request.form.get("action", "").strip() + select_mode = request.form.get("select_mode", "page").strip() - if not ids_raw or not action: + if not action: + flash("未指定批量操作类型", "error") + return redirect(url_for("admin.keys")) + + if select_mode == "all": + keys_where, keys_params = [], [] + if k_q := (request.form.get("keys_q") or request.form.get("q") or "").strip(): + keys_where.append("(k.name LIKE ? OR u.username LIKE ?)") + keys_params.extend([f"%{k_q}%", f"%{k_q}%"]) + if k_user_id := (request.form.get("keys_user_id") or request.form.get("user_id") or "").strip(): + if k_user_id.isdigit(): + keys_where.append("k.user_id = ?") + keys_params.append(int(k_user_id)) + if k_active := (request.form.get("keys_active") or request.form.get("active") or "").strip(): + try: + val = int(k_active) + keys_where.append("k.active = ?") + keys_params.append(val) + except ValueError: + pass + + where_sql = (" WHERE " + " AND ".join(keys_where)) if keys_where else "" + subquery = f"SELECT k.id FROM api_keys k LEFT JOIN users u ON u.id=k.user_id{where_sql}" + matched_count = db.execute(f"SELECT COUNT(*) as c FROM api_keys WHERE id IN ({subquery})", keys_params).fetchone()["c"] + + if action == "enable": + db.execute(f"UPDATE api_keys SET active=1 WHERE id IN ({subquery})", keys_params) + flash(f"已批量启用符合筛选条件的全部 {matched_count} 个 API Key", "success") + elif action == "disable": + db.execute(f"UPDATE api_keys SET active=0 WHERE id IN ({subquery})", keys_params) + flash(f"已批量停用符合筛选条件的全部 {matched_count} 个 API Key", "success") + elif action == "set_qps": + qps_raw = request.form.get("qps_limit", "").strip() + qps = _positive_int(qps_raw) if qps_raw else None + db.execute(f"UPDATE api_keys SET qps_limit=? WHERE id IN ({subquery})", [qps] + keys_params) + flash(f"已批量更新符合筛选条件的全部 {matched_count} 个 API Key 限流", "success") + elif action == "delete": + db.execute(f"DELETE FROM api_keys WHERE id IN ({subquery})", keys_params) + flash(f"已批量彻底删除符合筛选条件的全部 {matched_count} 个 API Key", "success") + else: + flash("不支持的批量操作类型", "error") + return redirect(url_for("admin.keys")) + + db.commit() + return redirect(url_for("admin.keys")) + + ids_raw = request.form.get("ids", "").strip() + if not ids_raw: flash("请先勾选需要批量操作的 API Key", "error") return redirect(url_for("admin.keys")) @@ -500,6 +621,9 @@ def batch_keys(): elif action == "delete": db.execute(f"DELETE FROM api_keys WHERE id IN ({placeholders})", key_ids) flash(f"已批量彻底删除选中的 {len(key_ids)} 个 API Key", "success") + else: + flash("不支持的批量操作类型", "error") + return redirect(url_for("admin.keys")) db.commit() return redirect(url_for("admin.keys")) @@ -649,10 +773,71 @@ def update_platform(platform): @csrf_protected def batch_platforms(): db = get_db() - names_raw = request.form.get("names", "").strip() action = request.form.get("action", "").strip() + select_mode = request.form.get("select_mode", "page").strip() - if not names_raw or not action: + if not action: + flash("未指定批量操作类型", "error") + return redirect(url_for("admin.platforms")) + + if select_mode == "all": + configured = {row["platform"]: row for row in db.execute("SELECT * FROM platform_settings")} + platform_to_domains = {} + for domain, pname in DOMAIN_TO_NAME.items(): + platform_to_domains.setdefault(pname, []).append(domain) + + platforms_list = [] + for name in sorted(set(DOMAIN_TO_NAME.values())): + row = configured.get(name) + enabled = True if row is None else bool(row["enabled"]) + qps_limit = None if row is None else row["qps_limit"] + platforms_list.append({ + "name": name, + "enabled": enabled, + "qps_limit": qps_limit, + "domains": platform_to_domains.get(name, []), + }) + + p_q = (request.form.get("platforms_q") or request.form.get("q") or "").strip().lower() + p_status = (request.form.get("platforms_status") or request.form.get("status") or "").strip() + + filtered_platforms = [] + for p in platforms_list: + if p_q: + match_name = p_q in p["name"].lower() + match_domains = any(p_q in d.lower() for d in p["domains"]) + if not (match_name or match_domains): + continue + if p_status == "enabled" and not p["enabled"]: + continue + elif p_status == "disabled" and p["enabled"]: + continue + elif p_status == "limited" and not p["qps_limit"]: + continue + filtered_platforms.append(p) + + platform_names = [p["name"] for p in filtered_platforms] + if not platform_names: + flash("未找到符合筛选条件的支持平台", "error") + return redirect(url_for("admin.platforms")) + + qps_raw = request.form.get("qps_limit", "").strip() + qps = _positive_int(qps_raw) if qps_raw else None + + for name in platform_names: + if action == "enable": + db.execute("INSERT INTO platform_settings(platform,enabled,qps_limit) VALUES(?,1,NULL) ON CONFLICT(platform) DO UPDATE SET enabled=1", (name,)) + elif action == "disable": + db.execute("INSERT INTO platform_settings(platform,enabled,qps_limit) VALUES(?,0,NULL) ON CONFLICT(platform) DO UPDATE SET enabled=0", (name,)) + elif action == "set_qps": + db.execute("INSERT INTO platform_settings(platform,enabled,qps_limit) VALUES(?,1,?) ON CONFLICT(platform) DO UPDATE SET qps_limit=excluded.qps_limit", (name, qps)) + + db.commit() + flash(f"已成功批量更新符合筛选条件的全部 {len(platform_names)} 个支持平台配置", "success") + return redirect(url_for("admin.platforms")) + + names_raw = request.form.get("names", "").strip() + if not names_raw: flash("请先勾选需要批量操作的支持平台", "error") return redirect(url_for("admin.platforms")) @@ -875,10 +1060,51 @@ def delete_log(log_id): @csrf_protected def batch_logs(): db = get_db() - ids_raw = request.form.get("ids", "").strip() action = request.form.get("action", "").strip() + select_mode = request.form.get("select_mode", "page").strip() - if not ids_raw or not action: + if not action: + flash("未指定批量操作类型", "error") + return redirect(url_for("admin.logs")) + + if select_mode == "all": + where_clauses, params = [], [] + if l_q := (request.form.get("logs_q") or request.form.get("q") or "").strip(): + where_clauses.append("(l.input_url LIKE ? OR u.username LIKE ? OR l.error_code LIKE ?)") + params.extend([f"%{l_q}%", f"%{l_q}%", f"%{l_q}%"]) + if l_status := (request.form.get("logs_status") or request.form.get("status_code") or "").strip(): + if l_status == "200": + where_clauses.append("l.status_code < 400") + elif l_status == "error": + where_clauses.append("l.status_code >= 400") + elif l_status.isdigit(): + where_clauses.append("l.status_code = ?") + params.append(int(l_status)) + if l_platform := (request.form.get("logs_platform") or request.form.get("platform") or "").strip(): + where_clauses.append("l.platform = ?") + params.append(l_platform) + if utc_start := _parse_shanghai_to_utc_iso(request.form.get("logs_start_date") or request.form.get("start_date") or "", is_end=False): + where_clauses.append("l.created_at >= ?") + params.append(utc_start) + if utc_end := _parse_shanghai_to_utc_iso(request.form.get("logs_end_date") or request.form.get("end_date") or "", is_end=True): + where_clauses.append("l.created_at <= ?") + params.append(utc_end) + + where_sql = (" WHERE " + " AND ".join(where_clauses)) if where_clauses else "" + subquery = f"SELECT l.id FROM request_logs l LEFT JOIN users u ON u.id=l.user_id LEFT JOIN api_keys k ON k.id=l.api_key_id{where_sql}" + matched_count = db.execute(f"SELECT COUNT(*) as c FROM request_logs WHERE id IN ({subquery})", params).fetchone()["c"] + + if action == "delete": + db.execute(f"DELETE FROM request_logs WHERE id IN ({subquery})", params) + db.commit() + flash(f"已批量删除符合筛选条件的全部 {matched_count} 条日志记录", "success") + else: + flash("不支持的批量操作类型", "error") + + return redirect(url_for("admin.logs")) + + ids_raw = request.form.get("ids", "").strip() + if not ids_raw: flash("请先勾选需要批量操作的日志条目", "error") return redirect(url_for("admin.logs")) @@ -896,6 +1122,8 @@ def batch_logs(): if action == "delete": db.execute(f"DELETE FROM request_logs WHERE id IN ({placeholders})", log_ids) flash(f"已批量删除选中的 {len(log_ids)} 条日志记录", "success") + else: + flash("不支持的批量操作类型", "error") db.commit() return redirect(url_for("admin.logs")) diff --git a/src/web/portal.py b/src/web/portal.py index c6bef69..0402c10 100644 --- a/src/web/portal.py +++ b/src/web/portal.py @@ -111,6 +111,7 @@ def keys(): where_clauses=keys_where, where_params=keys_params, request_args=request.args, + default_page_size=20, prefix="keys_", ) @@ -129,10 +130,48 @@ def keys(): @csrf_protected def batch_keys(): db = get_db() - ids_raw = request.form.get("ids", "").strip() action = request.form.get("action", "").strip() + select_mode = request.form.get("select_mode", "page").strip() - if not ids_raw or not action: + if not action: + flash("未指定批量操作类型", "error") + return redirect(url_for("portal.keys")) + + if select_mode == "all": + keys_where = ["user_id = ?"] + keys_params = [g.user["id"]] + if k_q := (request.form.get("keys_q") or request.form.get("q") or "").strip(): + keys_where.append("name LIKE ?") + keys_params.append(f"%{k_q}%") + if k_active := (request.form.get("keys_active") or request.form.get("active") or "").strip(): + try: + val = int(k_active) + keys_where.append("active = ?") + keys_params.append(val) + except ValueError: + pass + + where_sql = " WHERE " + " AND ".join(keys_where) + matched_count = db.execute(f"SELECT COUNT(*) as c FROM api_keys{where_sql}", keys_params).fetchone()["c"] + + if action == "enable": + db.execute(f"UPDATE api_keys SET active=1{where_sql}", keys_params) + flash(f"已批量启用符合筛选条件的全部 {matched_count} 个 API Key", "success") + elif action == "disable": + db.execute(f"UPDATE api_keys SET active=0{where_sql}", keys_params) + flash(f"已批量停用符合筛选条件的全部 {matched_count} 个 API Key", "success") + elif action == "delete": + db.execute(f"DELETE FROM api_keys{where_sql}", keys_params) + flash(f"已批量删除符合筛选条件的全部 {matched_count} 个 API Key", "success") + else: + flash("不支持的批量操作类型", "error") + return redirect(url_for("portal.keys")) + + db.commit() + return redirect(url_for("portal.keys")) + + ids_raw = request.form.get("ids", "").strip() + if not ids_raw: flash("请先勾选需要批量操作的 API Key", "error") return redirect(url_for("portal.keys")) @@ -156,6 +195,9 @@ def batch_keys(): elif action == "delete": db.execute(f"DELETE FROM api_keys WHERE id IN ({placeholders}) AND user_id=?", key_ids + [g.user["id"]]) flash(f"已批量删除选中的 {len(key_ids)} 个 API Key", "success") + else: + flash("不支持的批量操作类型", "error") + return redirect(url_for("portal.keys")) db.commit() return redirect(url_for("portal.keys")) diff --git a/static/js/table_manager.js b/static/js/table_manager.js index 16d8b15..aab893f 100644 --- a/static/js/table_manager.js +++ b/static/js/table_manager.js @@ -1,7 +1,113 @@ /** - * Antigravity Table Manager JS - * 通用后台数据表格交互核心逻辑:排序、动态筛选、批量勾选/跨页全选、分页及条数切换、导出。 + * 局部无刷新热替换表格数据 (AJAX / PJAX Seamless Hot-Reload) */ +let isTableLoading = false; + +async function navigateTableAjax(targetUrl, pushState = true) { + if (isTableLoading) return; + isTableLoading = true; + + // 优先定位主内容区 main 容器 + const currentContainer = document.querySelector('main') || document.querySelector('.main-wrapper > div:last-child'); + if (currentContainer) { + currentContainer.classList.add('opacity-60', 'pointer-events-none', 'transition-opacity', 'duration-150'); + } + + try { + const response = await fetch(targetUrl, { + headers: { + 'X-Requested-With': 'XMLHttpRequest' + } + }); + + if (!response.ok) { + window.location.href = targetUrl; + return; + } + + const html = await response.text(); + const parser = new DOMParser(); + const doc = parser.parseFromString(html, 'text/html'); + + const newContainer = doc.querySelector('main') || doc.querySelector('.main-wrapper > div:last-child'); + if (currentContainer && newContainer) { + currentContainer.innerHTML = newContainer.innerHTML; + + // 更新标题 + if (doc.title) { + document.title = doc.title; + } + + // 更新浏览器地址栏与历史栈 + if (pushState) { + window.history.pushState({ path: targetUrl }, '', targetUrl); + } + + // 重新初始化动态组件(自定义下拉菜单、批量全选等) + initAll(); + + // 隐藏可能残留的批量悬浮栏 + document.querySelectorAll('.batch-floating-toolbar').forEach(tb => { + tb.classList.remove('opacity-100', 'translate-y-0', 'pointer-events-auto'); + tb.classList.add('opacity-0', 'translate-y-4', 'pointer-events-none'); + }); + + // 如果当前页面滚动较深,平滑定位到表格顶部 + const tableCard = currentContainer.querySelector('section') || currentContainer; + if (tableCard && window.scrollY > tableCard.offsetTop + 100) { + window.scrollTo({ top: tableCard.offsetTop - 70, behavior: 'smooth' }); + } + } else { + window.location.href = targetUrl; + } + } catch (err) { + console.warn('AJAX table navigation fallback to full load:', err); + window.location.href = targetUrl; + } finally { + if (currentContainer) { + currentContainer.classList.remove('opacity-60', 'pointer-events-none'); + } + isTableLoading = false; + } +} + +/** + * 表格筛选表单提交处理 + */ +function submitFormAjax(form) { + const action = form.getAttribute('action') || window.location.pathname; + const targetBase = action.split('?')[0]; + const targetHash = action.includes('#') ? action.substring(action.indexOf('#')) : window.location.hash; + + const formData = new FormData(form); + const searchParams = new URLSearchParams(); + + // 保留其它表格的前缀参数 + const currentParams = new URLSearchParams(window.location.search); + currentParams.forEach((val, key) => { + if (!form.elements[key]) { + searchParams.set(key, val); + } + }); + + for (const [key, value] of formData.entries()) { + const val = (value || '').toString().trim(); + if (val) { + searchParams.set(key, val); + } + } + + // 筛选变动时,将当前表格的分页重置为第 1 页 + currentParams.forEach((_, k) => { + if (k.endsWith('page') || k === 'page') { + searchParams.set(k, '1'); + } + }); + + const targetUrl = targetBase + (searchParams.toString() ? '?' + searchParams.toString() : '') + (targetHash || ''); + navigateTableAjax(targetUrl); +} + function initAll() { // 初始化页面自定义下拉组件 initCustomSelects(); @@ -9,18 +115,38 @@ function initAll() { // 监听全选框与单选框联动 initTableSelection(); - // 拦截表格筛选表单提交,确保提交时保持 #logs / #users / #keys hash 锚点 + // 拦截表格筛选表单提交,支持 AJAX 无刷新更新 document.querySelectorAll('.table-filter-form').forEach(form => { + if (form.dataset.ajaxInit === 'true') return; + form.dataset.ajaxInit = 'true'; + + // 覆盖原生 submit 防止内部 onchange="this.form.submit()" 导致整页刷新 + form.submit = function() { + submitFormAjax(form); + }; + form.addEventListener('submit', function(e) { - const action = form.getAttribute('action'); - if (action && action.includes('#')) { - const targetHash = action.substring(action.indexOf('#')); - window.location.hash = targetHash; + e.preventDefault(); + submitFormAjax(form); + }); + + // 监听表单内部普通输入控件的变动 + form.addEventListener('change', function(e) { + if (e.target.matches('select, input[type="date"]')) { + submitFormAjax(form); } }); }); } +// 监听浏览器后退/前进按钮 +if (!window._tablePopstateInit) { + window._tablePopstateInit = true; + window.addEventListener('popstate', () => { + navigateTableAjax(window.location.href, false); + }); +} + if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', initAll); } else { @@ -28,7 +154,7 @@ if (document.readyState === 'loading') { } /** - * 字段排序逻辑 + * 字段排序逻辑 (AJAX) */ function handleSort(prefix, field) { const urlParams = new URLSearchParams(window.location.search); @@ -49,14 +175,12 @@ function handleSort(prefix, field) { urlParams.set(pageKey, '1'); // 排序重置为第 1 页 const targetHash = prefix ? `#${prefix}` : window.location.hash; - window.location.search = urlParams.toString(); - if (targetHash) { - window.location.hash = targetHash; - } + const targetUrl = window.location.pathname + '?' + urlParams.toString() + (targetHash || ''); + navigateTableAjax(targetUrl); } /** - * 切换每页显示条数 (20, 50, 100, 200) + * 切换每页显示条数 (20, 50, 100, 200) 并持久化浏览器偏好 (AJAX) */ function handlePageSizeChange(prefix, pageSize) { const urlParams = new URLSearchParams(window.location.search); @@ -66,15 +190,24 @@ function handlePageSizeChange(prefix, pageSize) { urlParams.set(pageSizeKey, pageSize); urlParams.set(pageKey, '1'); // 重置为第 1 页 - const targetHash = prefix ? `#${prefix}` : window.location.hash; - window.location.search = urlParams.toString(); - if (targetHash) { - window.location.hash = targetHash; + // 双重持久化:localStorage + Cookie (有效期 1 年) + try { + const cleanPrefix = prefix ? prefix.replace(/_+$/, '') : 'default'; + const storageKey = `mp_page_size_${cleanPrefix}`; + localStorage.setItem(storageKey, pageSize); + localStorage.setItem('mp_page_size_last', pageSize); + document.cookie = `${storageKey}=${pageSize};path=/;max-age=31536000;SameSite=Lax`; + } catch (e) { + // 忽略私密模式下的存储受限异常 } + + const targetHash = prefix ? `#${prefix}` : window.location.hash; + const targetUrl = window.location.pathname + '?' + urlParams.toString() + (targetHash || ''); + navigateTableAjax(targetUrl); } /** - * 页码跳转 + * 页码跳转 (AJAX) */ function handlePageChange(prefix, page) { const urlParams = new URLSearchParams(window.location.search); @@ -83,14 +216,36 @@ function handlePageChange(prefix, page) { urlParams.set(pageKey, page); const targetHash = prefix ? `#${prefix}` : window.location.hash; - window.location.search = urlParams.toString(); - if (targetHash) { - window.location.hash = targetHash; - } + const targetUrl = window.location.pathname + '?' + urlParams.toString() + (targetHash || ''); + navigateTableAjax(targetUrl); } /** - * 表格筛选表单提交与重置 + * 指定页码跳转 (AJAX) + */ +function handlePageJump(prefix, maxPage, targetPage) { + let pageNum = parseInt(targetPage, 10); + if (isNaN(pageNum)) { + return; + } + if (pageNum < 1) { + pageNum = 1; + } else if (maxPage && pageNum > maxPage) { + pageNum = maxPage; + } + + const urlParams = new URLSearchParams(window.location.search); + const pageKey = prefix ? `${prefix}_page` : 'page'; + const currentPage = parseInt(urlParams.get(pageKey) || '1', 10); + if (currentPage === pageNum) { + return; + } + + handlePageChange(prefix, pageNum); +} + +/** + * 表格筛选表单重置 (AJAX) */ function resetTableFilter(prefix) { const urlParams = new URLSearchParams(window.location.search); @@ -107,10 +262,8 @@ function resetTableFilter(prefix) { keysToRemove.forEach(key => urlParams.delete(key)); const targetHash = prefix ? `#${prefix}` : window.location.hash; - window.location.search = urlParams.toString(); - if (targetHash) { - window.location.hash = targetHash; - } + const targetUrl = window.location.pathname + (urlParams.toString() ? '?' + urlParams.toString() : '') + (targetHash || ''); + navigateTableAjax(targetUrl); } /** @@ -309,6 +462,7 @@ async function executeBatchAction(tableId, targetUrl, action, extraPayload = {}, if (!table) return; const isAllMode = table.getAttribute('data-select-mode') === 'all'; + const totalCount = table.getAttribute('data-total-count') || ''; const checkedBoxes = table.querySelectorAll('.row-checkbox:checked'); const values = Array.from(checkedBoxes).map(cb => cb.value); @@ -319,16 +473,25 @@ async function executeBatchAction(tableId, targetUrl, action, extraPayload = {}, return; } - if (confirmPrompt) { + let actualPrompt = confirmPrompt; + if (confirmPrompt && isAllMode && totalCount) { + if (confirmPrompt.includes('选中的')) { + actualPrompt = confirmPrompt.replace('选中的', `符合当前筛选条件的全部 ${totalCount} 条`); + } else { + actualPrompt = `确定要对符合当前筛选条件的全部 ${totalCount} 条记录执行此操作吗?\n${confirmPrompt}`; + } + } + + if (actualPrompt) { if (window.confirmModal) { const ok = await window.confirmModal({ title: confirmTitle, - message: confirmPrompt, + message: actualPrompt, confirmText: '确定', type: confirmType }); if (!ok) return; - } else if (typeof confirm === 'function' && !confirm(confirmPrompt)) { + } else if (typeof confirm === 'function' && !confirm(actualPrompt)) { return; } } @@ -348,6 +511,16 @@ async function executeBatchAction(tableId, targetUrl, action, extraPayload = {}, ...extraPayload }; + // 全选模式下,将当前 URL 中的所有筛选过滤参数一并透传给后端 + if (isAllMode) { + const urlParams = new URLSearchParams(window.location.search); + urlParams.forEach((val, key) => { + if (!(key in fields) && val) { + fields[key] = val; + } + }); + } + for (const [key, val] of Object.entries(fields)) { const input = document.createElement('input'); input.type = 'hidden'; @@ -417,8 +590,10 @@ function triggerLogExport(exportType = 'auto') { function openBatchModal(modalId, tableId) { const m = document.getElementById(modalId); if (!m) return; + const table = document.getElementById(tableId); + const isAllMode = table && table.getAttribute('data-select-mode') === 'all'; const checked = document.querySelectorAll(`#${tableId} .row-checkbox:checked`); - if (checked.length === 0) { + if (!isAllMode && checked.length === 0) { if (window.showToast) { window.showToast('请先勾选需要批量操作的项!', 'warning'); } @@ -503,7 +678,7 @@ function initCustomSelects() { btnText.className = 'custom-select-btn-text'; const chevron = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); - chevron.setAttribute('class', 'custom-select-chevron'); + chevron.setAttribute('class', 'custom-select-chevron custom-select-btn-chevron'); chevron.setAttribute('width', '11'); chevron.setAttribute('height', '11'); chevron.setAttribute('viewBox', '0 0 24 24'); @@ -671,5 +846,19 @@ document.addEventListener('keydown', (e) => { } }); +document.addEventListener('DOMContentLoaded', () => { + // 自动同步 localStorage 分页偏好至 Cookie,确保首屏直出正确条数 + try { + ['logs', 'users', 'keys', 'platforms', 'default'].forEach(p => { + const key = `mp_page_size_${p}`; + const val = localStorage.getItem(key); + if (val && !document.cookie.includes(`${key}=`)) { + document.cookie = `${key}=${val};path=/;max-age=31536000;SameSite=Lax`; + } + }); + } catch (e) {} +}); + window.initCustomSelects = initCustomSelects; + diff --git a/templates/admin/keys.html b/templates/admin/keys.html index 49fbf2b..21cf1b2 100644 --- a/templates/admin/keys.html +++ b/templates/admin/keys.html @@ -1,4 +1,5 @@ {% extends 'base_console.html' %} +{% from 'components/pagination.html' import render_pagination %} {% block title %}API 密钥 · 管理员后台{% endblock %} {% block page_title %}API 密钥{% endblock %} {% block console_content %} @@ -168,23 +169,7 @@ -
-
- 共 {{ keys_table.pagination.total_count }} 条数据 - -
-
- 上一页 - 第 {{ keys_table.pagination.page }} / {{ keys_table.pagination.total_pages }} 页 - 下一页 -
-
+ {{ render_pagination(keys_table, 'keys', '个密钥') }}
diff --git a/templates/admin/logs.html b/templates/admin/logs.html index 7531286..ee0dd2a 100644 --- a/templates/admin/logs.html +++ b/templates/admin/logs.html @@ -1,4 +1,5 @@ {% extends 'base_console.html' %} +{% from 'components/pagination.html' import render_pagination %} {% block title %}运行日志 · 管理员后台{% endblock %} {% block page_title %}运行日志{% endblock %} {% block console_content %} @@ -127,23 +128,7 @@
-
-
- 共 {{ logs_table.pagination.total_count }} 条数据 - -
-
- 上一页 - 第 {{ logs_table.pagination.page }} / {{ logs_table.pagination.total_pages }} 页 - 下一页 -
-
+ {{ render_pagination(logs_table, 'logs', '条数据') }}
diff --git a/templates/admin/platforms.html b/templates/admin/platforms.html index 6c7476b..35140f8 100644 --- a/templates/admin/platforms.html +++ b/templates/admin/platforms.html @@ -1,4 +1,5 @@ {% extends 'base_console.html' %} +{% from 'components/pagination.html' import render_pagination %} {% block title %}支持平台 · 管理员后台{% endblock %} {% block page_title %}支持平台{% endblock %} {% block console_content %} @@ -142,23 +143,7 @@
-
-
- 共 {{ platforms_table.pagination.total_count }} 个平台 - -
-
- 上一页 - 第 {{ platforms_table.pagination.page }} / {{ platforms_table.pagination.total_pages }} 页 - 下一页 -
-
+ {{ render_pagination(platforms_table, 'platforms', '个平台') }}
diff --git a/templates/admin/users.html b/templates/admin/users.html index be7b1a7..d6e9354 100644 --- a/templates/admin/users.html +++ b/templates/admin/users.html @@ -1,4 +1,5 @@ {% extends 'base_console.html' %} +{% from 'components/pagination.html' import render_pagination %} {% block title %}客户账号 · 管理员后台{% endblock %} {% block page_title %}客户账号{% endblock %} {% block console_content %} @@ -178,23 +179,7 @@
-
-
- 共 {{ users_table.pagination.total_count }} 条数据 - -
-
- 上一页 - 第 {{ users_table.pagination.page }} / {{ users_table.pagination.total_pages }} 页 - 下一页 -
-
+ {{ render_pagination(users_table, 'users', '个账号') }}
diff --git a/templates/components/pagination.html b/templates/components/pagination.html new file mode 100644 index 0000000..2a3c96d --- /dev/null +++ b/templates/components/pagination.html @@ -0,0 +1,124 @@ +{% macro render_pagination(table_data, prefix='', unit='条数据') %} +{% set p = table_data.pagination %} +
+ +
+ 共 {{ p.total_count }} {{ unit }} +
+
+ 每页 + +
+
+ + +
+ + + + + + +
+ {% if p.total_pages <= 7 %} + {% for i in range(1, p.total_pages + 1) %} + {% if i == p.page %} + {{ i }} + {% else %} + {{ i }} + {% endif %} + {% endfor %} + {% else %} + {# 总页数大于 7 页 #} + {% if p.page <= 4 %} + {% for i in range(1, 6) %} + {% if i == p.page %} + {{ i }} + {% else %} + {{ i }} + {% endif %} + {% endfor %} + ··· + {{ p.total_pages }} + {% elif p.page >= p.total_pages - 3 %} + 1 + ··· + {% for i in range(p.total_pages - 4, p.total_pages + 1) %} + {% if i == p.page %} + {{ i }} + {% else %} + {{ i }} + {% endif %} + {% endfor %} + {% else %} + 1 + ··· + {% for i in range(p.page - 1, p.page + 2) %} + {% if i == p.page %} + {{ i }} + {% else %} + {{ i }} + {% endif %} + {% endfor %} + ··· + {{ p.total_pages }} + {% endif %} + {% endif %} +
+ + + + + + + + {% if p.total_pages > 1 %} + +
+ 跳至 + + 页 +
+ {% endif %} +
+
+{% endmacro %} diff --git a/templates/portal/keys.html b/templates/portal/keys.html index 5a4a2d0..aa3d5dd 100644 --- a/templates/portal/keys.html +++ b/templates/portal/keys.html @@ -1,4 +1,5 @@ {% extends 'base_console.html' %} +{% from 'components/pagination.html' import render_pagination %} {% block title %}API 密钥 · 客户控制台{% endblock %} {% block page_title %}API 密钥{% endblock %} {% block console_content %} @@ -154,23 +155,7 @@
-
-
- 共 {{ keys_table.pagination.total_count }} 条数据 - -
-
- 上一页 - 第 {{ keys_table.pagination.page }} / {{ keys_table.pagination.total_pages }} 页 - 下一页 -
-
+ {{ render_pagination(keys_table, 'keys', '个密钥') }}
diff --git a/templates/portal/logs.html b/templates/portal/logs.html index beab181..0c956c1 100644 --- a/templates/portal/logs.html +++ b/templates/portal/logs.html @@ -1,4 +1,5 @@ {% extends 'base_console.html' %} +{% from 'components/pagination.html' import render_pagination %} {% block title %}请求日志 · 客户控制台{% endblock %} {% block page_title %}请求日志{% endblock %} {% block console_content %} @@ -114,23 +115,7 @@
-
-
- 共 {{ logs_table.pagination.total_count }} 条数据 - -
-
- 上一页 - 第 {{ logs_table.pagination.page }} / {{ logs_table.pagination.total_pages }} 页 - 下一页 -
-
+ {{ render_pagination(logs_table, 'logs', '条数据') }}
diff --git a/templates/portal/platforms.html b/templates/portal/platforms.html index 01685d5..8d4e65d 100644 --- a/templates/portal/platforms.html +++ b/templates/portal/platforms.html @@ -1,4 +1,5 @@ {% extends 'base_console.html' %} +{% from 'components/pagination.html' import render_pagination %} {% block title %}支持平台 · 客户控制台{% endblock %} {% block page_title %}支持平台{% endblock %} {% block console_content %} @@ -106,23 +107,7 @@
-
-
- 共 {{ platforms_table.pagination.total_count }} 个平台 - -
-
- 上一页 - 第 {{ platforms_table.pagination.page }} / {{ platforms_table.pagination.total_pages }} 页 - 下一页 -
-
+ {{ render_pagination(platforms_table, 'platforms', '个平台') }} diff --git a/tests/test_management.py b/tests/test_management.py index e9a5326..42c978c 100644 --- a/tests/test_management.py +++ b/tests/test_management.py @@ -788,5 +788,137 @@ class ManagementTest(unittest.TestCase): self.assertNotIn("/admin", response.location) + def test_batch_logs_select_all(self): + self.client.post("/auth/setup", data={"csrf_token": self.csrf(), "username": "admin", "password": "password123", "confirm_password": "password123"}) + self.client.post("/auth/login", data={"csrf_token": self.csrf(), "username": "admin", "password": "password123"}) + + with self.app.app_context(): + db = get_db() + for i in range(3): + db.execute( + "INSERT INTO request_logs(path,platform,status_code,duration_ms,created_at) VALUES(?,?,?,?,?)", + ("/api/v1/parse", "抖音", 500, 10, utcnow()), + ) + for i in range(2): + db.execute( + "INSERT INTO request_logs(path,platform,status_code,duration_ms,created_at) VALUES(?,?,?,?,?)", + ("/api/v1/parse", "快手", 200, 10, utcnow()), + ) + db.commit() + + # Batch delete filtered by platform 抖音 + response = self.client.post( + "/admin/logs/batch", + data={ + "csrf_token": self.csrf(), + "select_mode": "all", + "logs_platform": "抖音", + "action": "delete", + }, + follow_redirects=True, + ) + self.assertEqual(response.status_code, 200) + self.assertIn("已批量删除符合筛选条件的全部 3 条日志记录", response.get_data(as_text=True)) + + with self.app.app_context(): + count = get_db().execute("SELECT COUNT(*) count FROM request_logs").fetchone()["count"] + self.assertEqual(count, 2) + + def test_batch_users_select_all(self): + self.client.post("/auth/setup", data={"csrf_token": self.csrf(), "username": "admin", "password": "password123", "confirm_password": "password123"}) + self.client.post("/auth/login", data={"csrf_token": self.csrf(), "username": "admin", "password": "password123"}) + + with self.app.app_context(): + db = get_db() + from werkzeug.security import generate_password_hash + db.execute( + "INSERT INTO users(username,password_hash,role,active,credits,created_at) VALUES(?,?,?,?,?,?)", + ("u1", generate_password_hash("p"), "user", 1, 100, utcnow()), + ) + db.execute( + "INSERT INTO users(username,password_hash,role,active,credits,created_at) VALUES(?,?,?,?,?,?)", + ("u2", generate_password_hash("p"), "user", 1, 200, utcnow()), + ) + db.commit() + + # Batch adjust credits in all mode + response = self.client.post( + "/admin/users/batch", + data={ + "csrf_token": self.csrf(), + "select_mode": "all", + "action": "adjust_credits", + "credits_mode": "add", + "credits_amount": "50", + }, + follow_redirects=True, + ) + self.assertEqual(response.status_code, 200) + self.assertIn("已批量更新符合筛选条件的全部 2 个客户账号积分", response.get_data(as_text=True)) + + with self.app.app_context(): + u1 = get_db().execute("SELECT credits FROM users WHERE username='u1'").fetchone() + u2 = get_db().execute("SELECT credits FROM users WHERE username='u2'").fetchone() + self.assertEqual(u1["credits"], 150) + self.assertEqual(u2["credits"], 250) + + def test_batch_keys_select_all(self): + self.client.post("/auth/setup", data={"csrf_token": self.csrf(), "username": "admin", "password": "password123", "confirm_password": "password123"}) + self.client.post("/auth/login", data={"csrf_token": self.csrf(), "username": "admin", "password": "password123"}) + + with self.app.app_context(): + db = get_db() + admin_id = db.execute("SELECT id FROM users WHERE username='admin'").fetchone()["id"] + db.execute("INSERT INTO api_keys(user_id,name,key_hash,key_prefix,active,created_at) VALUES(?,?,?,?,?,?)", (admin_id, "k1", "h1", "p1", 1, utcnow())) + db.execute("INSERT INTO api_keys(user_id,name,key_hash,key_prefix,active,created_at) VALUES(?,?,?,?,?,?)", (admin_id, "k2", "h2", "p2", 1, utcnow())) + db.commit() + + # Batch disable in all mode + response = self.client.post( + "/admin/keys/batch", + data={ + "csrf_token": self.csrf(), + "select_mode": "all", + "action": "disable", + }, + follow_redirects=True, + ) + self.assertEqual(response.status_code, 200) + self.assertIn("已批量停用符合筛选条件的全部 2 个 API Key", response.get_data(as_text=True)) + + with self.app.app_context(): + active_count = get_db().execute("SELECT COUNT(*) c FROM api_keys WHERE active=1").fetchone()["c"] + self.assertEqual(active_count, 0) + + def test_portal_batch_keys_select_all(self): + # Register user + self.client.post("/auth/register", data={"csrf_token": self.csrf(), "username": "portal_user", "password": "password123", "confirm_password": "password123"}) + self.client.post("/auth/login", data={"csrf_token": self.csrf(), "username": "portal_user", "password": "password123"}) + + with self.app.app_context(): + db = get_db() + uid = db.execute("SELECT id FROM users WHERE username='portal_user'").fetchone()["id"] + db.execute("INSERT INTO api_keys(user_id,name,key_hash,key_prefix,active,created_at) VALUES(?,?,?,?,?,?)", (uid, "pk1", "h1", "p1", 1, utcnow())) + db.execute("INSERT INTO api_keys(user_id,name,key_hash,key_prefix,active,created_at) VALUES(?,?,?,?,?,?)", (uid, "pk2", "h2", "p2", 1, utcnow())) + db.commit() + + response = self.client.post( + "/console/keys/batch", + data={ + "csrf_token": self.csrf(), + "select_mode": "all", + "action": "delete", + }, + follow_redirects=True, + ) + self.assertEqual(response.status_code, 200) + self.assertIn("已批量删除符合筛选条件的全部 2 个 API Key", response.get_data(as_text=True)) + + with self.app.app_context(): + count = get_db().execute("SELECT COUNT(*) c FROM api_keys WHERE user_id=?", (uid,)).fetchone()["c"] + self.assertEqual(count, 0) + + if __name__ == "__main__": unittest.main() +