mirror of
https://github.com/ucmao/media-parser.git
synced 2026-11-20 08:04:56 +08:00
优化后台表格交互体验,支持跨页全选批量操作与无刷新分页
This commit is contained in:
@@ -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):
|
||||
|
||||
+236
-8
@@ -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"))
|
||||
|
||||
+44
-2
@@ -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"))
|
||||
|
||||
+221
-32
@@ -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;
|
||||
|
||||
|
||||
|
||||
@@ -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 @@
|
||||
</div>
|
||||
|
||||
<!-- 分页控件与每页条数 Selector -->
|
||||
<div class="pagination-bar flex flex-col sm:flex-row items-center justify-between gap-4 mt-5 pt-4 border-t border-slate-100 text-xs text-slate-500">
|
||||
<div class="pagination-info flex items-center gap-3">
|
||||
<span>共 {{ keys_table.pagination.total_count }} 条数据</span>
|
||||
<label class="flex items-center gap-1.5">每页显示:
|
||||
<select class="page-size-select px-2 py-1 rounded border border-slate-200 bg-white text-slate-700 text-xs focus:outline-none" onchange="handlePageSizeChange('keys', this.value)">
|
||||
{% for size in keys_table.pagination.page_sizes %}
|
||||
<option value="{{ size }}" {{ 'selected' if keys_table.pagination.page_size == size }}>{{ size }} 条</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div class="pagination-pages flex items-center gap-2">
|
||||
<a href="javascript:void(0)" class="page-btn px-2.5 py-1 rounded border border-slate-200 bg-white text-slate-700 hover:bg-slate-50 transition {{ 'opacity-50 pointer-events-none' if not keys_table.pagination.has_prev }}" onclick="handlePageChange('keys', {{ keys_table.pagination.page - 1 }})">上一页</a>
|
||||
<span class="px-1 text-slate-600 font-medium">第 {{ keys_table.pagination.page }} / {{ keys_table.pagination.total_pages }} 页</span>
|
||||
<a href="javascript:void(0)" class="page-btn px-2.5 py-1 rounded border border-slate-200 bg-white text-slate-700 hover:bg-slate-50 transition {{ 'opacity-50 pointer-events-none' if not keys_table.pagination.has_next }}" onclick="handlePageChange('keys', {{ keys_table.pagination.page + 1 }})">下一页</a>
|
||||
</div>
|
||||
</div>
|
||||
{{ render_pagination(keys_table, 'keys', '个密钥') }}
|
||||
|
||||
<!-- 底部悬浮胶囊批量工具栏 -->
|
||||
<div id="keys-table-floating-toolbar" class="batch-floating-toolbar fixed bottom-6 left-1/2 -translate-x-1/2 bg-white/95 backdrop-blur-md text-slate-800 px-4 py-2.5 rounded-2xl shadow-xl border border-slate-200/90 flex items-center gap-2.5 z-40 text-xs font-semibold transition-all duration-200 opacity-0 pointer-events-none translate-y-4">
|
||||
|
||||
@@ -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 @@
|
||||
</div>
|
||||
|
||||
<!-- 分页控件与每页条数 Selector -->
|
||||
<div class="pagination-bar flex flex-col sm:flex-row items-center justify-between gap-4 mt-5 pt-4 border-t border-slate-100 text-xs text-slate-500">
|
||||
<div class="pagination-info flex items-center gap-3">
|
||||
<span>共 {{ logs_table.pagination.total_count }} 条数据</span>
|
||||
<label class="flex items-center gap-1.5">每页显示:
|
||||
<select class="page-size-select px-2 py-1 rounded border border-slate-200 bg-white text-slate-700 text-xs focus:outline-none" onchange="handlePageSizeChange('logs', this.value)">
|
||||
{% for size in logs_table.pagination.page_sizes %}
|
||||
<option value="{{ size }}" {{ 'selected' if logs_table.pagination.page_size == size }}>{{ size }} 条</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div class="pagination-pages flex items-center gap-2">
|
||||
<a href="javascript:void(0)" class="page-btn px-2.5 py-1 rounded border border-slate-200 bg-white text-slate-700 hover:bg-slate-50 transition {{ 'opacity-50 pointer-events-none' if not logs_table.pagination.has_prev }}" onclick="handlePageChange('logs', {{ logs_table.pagination.page - 1 }})">上一页</a>
|
||||
<span class="px-1 text-slate-600 font-medium">第 {{ logs_table.pagination.page }} / {{ logs_table.pagination.total_pages }} 页</span>
|
||||
<a href="javascript:void(0)" class="page-btn px-2.5 py-1 rounded border border-slate-200 bg-white text-slate-700 hover:bg-slate-50 transition {{ 'opacity-50 pointer-events-none' if not logs_table.pagination.has_next }}" onclick="handlePageChange('logs', {{ logs_table.pagination.page + 1 }})">下一页</a>
|
||||
</div>
|
||||
</div>
|
||||
{{ render_pagination(logs_table, 'logs', '条数据') }}
|
||||
|
||||
<!-- 底部悬浮胶囊批量工具栏 -->
|
||||
<div id="logs-table-floating-toolbar" class="batch-floating-toolbar fixed bottom-6 left-1/2 -translate-x-1/2 bg-white/95 backdrop-blur-md text-slate-800 px-4 py-2.5 rounded-2xl shadow-xl border border-slate-200/90 flex items-center gap-2.5 z-40 text-xs font-semibold transition-all duration-200 opacity-0 pointer-events-none translate-y-4">
|
||||
|
||||
@@ -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 @@
|
||||
</div>
|
||||
|
||||
<!-- 分页控件与每页条数 Selector -->
|
||||
<div class="pagination-bar flex flex-col sm:flex-row items-center justify-between gap-4 mt-5 pt-4 border-t border-slate-100 text-xs text-slate-500">
|
||||
<div class="pagination-info flex items-center gap-3">
|
||||
<span>共 {{ platforms_table.pagination.total_count }} 个平台</span>
|
||||
<label class="flex items-center gap-1.5">每页显示:
|
||||
<select class="page-size-select px-2 py-1 rounded border border-slate-200 bg-white text-slate-700 text-xs focus:outline-none" onchange="handlePageSizeChange('platforms', this.value)">
|
||||
{% for size in platforms_table.pagination.page_sizes %}
|
||||
<option value="{{ size }}" {{ 'selected' if platforms_table.pagination.page_size == size }}>{{ size }} 条</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div class="pagination-pages flex items-center gap-2">
|
||||
<a href="javascript:void(0)" class="page-btn px-2.5 py-1 rounded border border-slate-200 bg-white text-slate-700 hover:bg-slate-50 transition {{ 'opacity-50 pointer-events-none' if not platforms_table.pagination.has_prev }}" onclick="handlePageChange('platforms', {{ platforms_table.pagination.page - 1 }})">上一页</a>
|
||||
<span class="px-1 text-slate-600 font-medium">第 {{ platforms_table.pagination.page }} / {{ platforms_table.pagination.total_pages }} 页</span>
|
||||
<a href="javascript:void(0)" class="page-btn px-2.5 py-1 rounded border border-slate-200 bg-white text-slate-700 hover:bg-slate-50 transition {{ 'opacity-50 pointer-events-none' if not platforms_table.pagination.has_next }}" onclick="handlePageChange('platforms', {{ platforms_table.pagination.page + 1 }})">下一页</a>
|
||||
</div>
|
||||
</div>
|
||||
{{ render_pagination(platforms_table, 'platforms', '个平台') }}
|
||||
|
||||
<!-- 底部悬浮胶囊批量工具栏 -->
|
||||
<div id="platforms-table-floating-toolbar" class="batch-floating-toolbar fixed bottom-6 left-1/2 -translate-x-1/2 bg-white/95 backdrop-blur-md text-slate-800 px-4 py-2.5 rounded-2xl shadow-xl border border-slate-200/90 flex items-center gap-2.5 z-40 text-xs font-semibold transition-all duration-200 opacity-0 pointer-events-none translate-y-4">
|
||||
|
||||
@@ -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 @@
|
||||
</div>
|
||||
|
||||
<!-- 分页控件与每页条数 Selector -->
|
||||
<div class="pagination-bar flex flex-col sm:flex-row items-center justify-between gap-4 mt-5 pt-4 border-t border-slate-100 text-xs text-slate-500">
|
||||
<div class="pagination-info flex items-center gap-3">
|
||||
<span>共 {{ users_table.pagination.total_count }} 条数据</span>
|
||||
<label class="flex items-center gap-1.5">每页显示:
|
||||
<select class="page-size-select px-2 py-1 rounded border border-slate-200 bg-white text-slate-700 text-xs focus:outline-none" onchange="handlePageSizeChange('users', this.value)">
|
||||
{% for size in users_table.pagination.page_sizes %}
|
||||
<option value="{{ size }}" {{ 'selected' if users_table.pagination.page_size == size }}>{{ size }} 条</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div class="pagination-pages flex items-center gap-2">
|
||||
<a href="javascript:void(0)" class="page-btn px-2.5 py-1 rounded border border-slate-200 bg-white text-slate-700 hover:bg-slate-50 transition {{ 'opacity-50 pointer-events-none' if not users_table.pagination.has_prev }}" onclick="handlePageChange('users', {{ users_table.pagination.page - 1 }})">上一页</a>
|
||||
<span class="px-1 text-slate-600 font-medium">第 {{ users_table.pagination.page }} / {{ users_table.pagination.total_pages }} 页</span>
|
||||
<a href="javascript:void(0)" class="page-btn px-2.5 py-1 rounded border border-slate-200 bg-white text-slate-700 hover:bg-slate-50 transition {{ 'opacity-50 pointer-events-none' if not users_table.pagination.has_next }}" onclick="handlePageChange('users', {{ users_table.pagination.page + 1 }})">下一页</a>
|
||||
</div>
|
||||
</div>
|
||||
{{ render_pagination(users_table, 'users', '个账号') }}
|
||||
|
||||
<!-- 底部悬浮胶囊批量工具栏 -->
|
||||
<div id="users-table-floating-toolbar" class="batch-floating-toolbar fixed bottom-6 left-1/2 -translate-x-1/2 bg-white/95 backdrop-blur-md text-slate-800 px-4 py-2.5 rounded-2xl shadow-xl border border-slate-200/90 flex items-center gap-2.5 z-40 text-xs font-semibold transition-all duration-200 opacity-0 pointer-events-none translate-y-4">
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
{% macro render_pagination(table_data, prefix='', unit='条数据') %}
|
||||
{% set p = table_data.pagination %}
|
||||
<div class="pagination-bar flex flex-col sm:flex-row items-center justify-between gap-4 mt-6 pt-4 border-t border-slate-100 text-xs text-slate-500 select-none">
|
||||
<!-- 左侧:总数与每页容量 (统一 32px 高度体系) -->
|
||||
<div class="pagination-info flex items-center gap-3">
|
||||
<span class="text-slate-500">共 <span class="font-semibold text-slate-800 tabular-nums">{{ p.total_count }}</span> {{ unit }}</span>
|
||||
<div class="h-3.5 w-px bg-slate-200"></div>
|
||||
<div class="flex items-center gap-1.5 text-slate-500">
|
||||
<span>每页</span>
|
||||
<select class="page-size-select h-8 pl-2.5 pr-6 rounded-lg border border-slate-200 bg-white text-slate-700 text-xs font-medium focus:outline-none focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 cursor-pointer hover:border-slate-300 transition shadow-2xs"
|
||||
onchange="handlePageSizeChange('{{ prefix }}', this.value)">
|
||||
{% for size in p.page_sizes %}
|
||||
<option value="{{ size }}" {{ 'selected' if p.page_size == size }}>{{ size }} 条</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 右侧:纯图标箭头 + 统一 32x32px 正方页码块 + 方案A浅底高亮 + 跳至指定页 -->
|
||||
<div class="pagination-pages flex items-center gap-1">
|
||||
<!-- 上一页图标按钮 (‹) -->
|
||||
<a href="javascript:void(0)"
|
||||
class="page-btn inline-flex items-center justify-center w-8 h-8 rounded-lg border text-xs font-medium transition-all duration-150 {{ 'bg-slate-50 text-slate-300 border-slate-200/70 cursor-not-allowed pointer-events-none' if not p.has_prev else 'bg-white text-slate-600 border-slate-200 hover:bg-slate-50 hover:text-slate-900 hover:border-slate-300 shadow-2xs cursor-pointer' }}"
|
||||
{% if not p.has_prev %}aria-disabled="true"{% endif %}
|
||||
onclick="handlePageChange('{{ prefix }}', {{ p.page - 1 }})"
|
||||
title="上一页"
|
||||
aria-label="上一页">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/></svg>
|
||||
</a>
|
||||
|
||||
<!-- 数字页码组 (激活态加粗 font-bold + 浅紫高亮底色) -->
|
||||
<div class="flex items-center gap-1 mx-0.5">
|
||||
{% if p.total_pages <= 7 %}
|
||||
{% for i in range(1, p.total_pages + 1) %}
|
||||
{% if i == p.page %}
|
||||
<span class="page-num-active inline-flex items-center justify-center w-8 h-8 rounded-lg bg-indigo-50 text-indigo-700 border border-indigo-200 font-bold text-xs tabular-nums">{{ i }}</span>
|
||||
{% else %}
|
||||
<a href="javascript:void(0)"
|
||||
class="page-num inline-flex items-center justify-center w-8 h-8 rounded-lg border border-transparent hover:border-slate-200 hover:bg-slate-100 text-slate-600 hover:text-slate-900 transition-all text-xs font-medium tabular-nums cursor-pointer"
|
||||
onclick="handlePageChange('{{ prefix }}', {{ i }})">{{ i }}</a>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
{% else %}
|
||||
{# 总页数大于 7 页 #}
|
||||
{% if p.page <= 4 %}
|
||||
{% for i in range(1, 6) %}
|
||||
{% if i == p.page %}
|
||||
<span class="page-num-active inline-flex items-center justify-center w-8 h-8 rounded-lg bg-indigo-50 text-indigo-700 border border-indigo-200 font-bold text-xs tabular-nums">{{ i }}</span>
|
||||
{% else %}
|
||||
<a href="javascript:void(0)"
|
||||
class="page-num inline-flex items-center justify-center w-8 h-8 rounded-lg border border-transparent hover:border-slate-200 hover:bg-slate-100 text-slate-600 hover:text-slate-900 transition-all text-xs font-medium tabular-nums cursor-pointer"
|
||||
onclick="handlePageChange('{{ prefix }}', {{ i }})">{{ i }}</a>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
<span class="inline-flex items-center justify-center w-8 h-8 text-slate-400 select-none text-xs">···</span>
|
||||
<a href="javascript:void(0)"
|
||||
class="page-num inline-flex items-center justify-center w-8 h-8 rounded-lg border border-transparent hover:border-slate-200 hover:bg-slate-100 text-slate-600 hover:text-slate-900 transition-all text-xs font-medium tabular-nums cursor-pointer"
|
||||
onclick="handlePageChange('{{ prefix }}', {{ p.total_pages }})">{{ p.total_pages }}</a>
|
||||
{% elif p.page >= p.total_pages - 3 %}
|
||||
<a href="javascript:void(0)"
|
||||
class="page-num inline-flex items-center justify-center w-8 h-8 rounded-lg border border-transparent hover:border-slate-200 hover:bg-slate-100 text-slate-600 hover:text-slate-900 transition-all text-xs font-medium tabular-nums cursor-pointer"
|
||||
onclick="handlePageChange('{{ prefix }}', 1)">1</a>
|
||||
<span class="inline-flex items-center justify-center w-8 h-8 text-slate-400 select-none text-xs">···</span>
|
||||
{% for i in range(p.total_pages - 4, p.total_pages + 1) %}
|
||||
{% if i == p.page %}
|
||||
<span class="page-num-active inline-flex items-center justify-center w-8 h-8 rounded-lg bg-indigo-50 text-indigo-700 border border-indigo-200 font-bold text-xs tabular-nums">{{ i }}</span>
|
||||
{% else %}
|
||||
<a href="javascript:void(0)"
|
||||
class="page-num inline-flex items-center justify-center w-8 h-8 rounded-lg border border-transparent hover:border-slate-200 hover:bg-slate-100 text-slate-600 hover:text-slate-900 transition-all text-xs font-medium tabular-nums cursor-pointer"
|
||||
onclick="handlePageChange('{{ prefix }}', {{ i }})">{{ i }}</a>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
{% else %}
|
||||
<a href="javascript:void(0)"
|
||||
class="page-num inline-flex items-center justify-center w-8 h-8 rounded-lg border border-transparent hover:border-slate-200 hover:bg-slate-100 text-slate-600 hover:text-slate-900 transition-all text-xs font-medium tabular-nums cursor-pointer"
|
||||
onclick="handlePageChange('{{ prefix }}', 1)">1</a>
|
||||
<span class="inline-flex items-center justify-center w-8 h-8 text-slate-400 select-none text-xs">···</span>
|
||||
{% for i in range(p.page - 1, p.page + 2) %}
|
||||
{% if i == p.page %}
|
||||
<span class="page-num-active inline-flex items-center justify-center w-8 h-8 rounded-lg bg-indigo-50 text-indigo-700 border border-indigo-200 font-bold text-xs tabular-nums">{{ i }}</span>
|
||||
{% else %}
|
||||
<a href="javascript:void(0)"
|
||||
class="page-num inline-flex items-center justify-center w-8 h-8 rounded-lg border border-transparent hover:border-slate-200 hover:bg-slate-100 text-slate-600 hover:text-slate-900 transition-all text-xs font-medium tabular-nums cursor-pointer"
|
||||
onclick="handlePageChange('{{ prefix }}', {{ i }})">{{ i }}</a>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
<span class="inline-flex items-center justify-center w-8 h-8 text-slate-400 select-none text-xs">···</span>
|
||||
<a href="javascript:void(0)"
|
||||
class="page-num inline-flex items-center justify-center w-8 h-8 rounded-lg border border-transparent hover:border-slate-200 hover:bg-slate-100 text-slate-600 hover:text-slate-900 transition-all text-xs font-medium tabular-nums cursor-pointer"
|
||||
onclick="handlePageChange('{{ prefix }}', {{ p.total_pages }})">{{ p.total_pages }}</a>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<!-- 下一页图标按钮 (›) -->
|
||||
<a href="javascript:void(0)"
|
||||
class="page-btn inline-flex items-center justify-center w-8 h-8 rounded-lg border text-xs font-medium transition-all duration-150 {{ 'bg-slate-50 text-slate-300 border-slate-200/70 cursor-not-allowed pointer-events-none' if not p.has_next else 'bg-white text-slate-600 border-slate-200 hover:bg-slate-50 hover:text-slate-900 hover:border-slate-300 shadow-2xs cursor-pointer' }}"
|
||||
{% if not p.has_next %}aria-disabled="true"{% endif %}
|
||||
onclick="handlePageChange('{{ prefix }}', {{ p.page + 1 }})"
|
||||
title="下一页"
|
||||
aria-label="下一页">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg>
|
||||
</a>
|
||||
|
||||
<!-- 前往指定页 (严格对齐 32px / h-8 高度、圆角与阴影) -->
|
||||
{% if p.total_pages > 1 %}
|
||||
<div class="h-3.5 w-px bg-slate-200 mx-1.5 hidden sm:block"></div>
|
||||
<div class="flex items-center gap-1.5 text-slate-500">
|
||||
<span>跳至</span>
|
||||
<input type="number"
|
||||
min="1"
|
||||
max="{{ p.total_pages }}"
|
||||
id="{{ prefix + '-' if prefix else '' }}jump-page-input"
|
||||
class="jump-page-input w-12 h-8 px-2 rounded-lg border border-slate-200 bg-white text-center text-xs font-medium text-slate-800 focus:outline-none focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none transition shadow-2xs hover:border-slate-300 tabular-nums"
|
||||
placeholder="{{ p.page }}"
|
||||
value="{{ p.page }}"
|
||||
onkeydown="if(event.key==='Enter'){ event.preventDefault(); handlePageJump('{{ prefix }}', {{ p.total_pages }}, this.value); }"
|
||||
onchange="handlePageJump('{{ prefix }}', {{ p.total_pages }}, this.value)">
|
||||
<span>页</span>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% endmacro %}
|
||||
@@ -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 @@
|
||||
</div>
|
||||
|
||||
<!-- 分页控件与每页条数 Selector -->
|
||||
<div class="pagination-bar flex flex-col sm:flex-row items-center justify-between gap-4 mt-5 pt-4 border-t border-slate-100 text-xs text-slate-500">
|
||||
<div class="pagination-info flex items-center gap-3">
|
||||
<span>共 {{ keys_table.pagination.total_count }} 条数据</span>
|
||||
<label class="flex items-center gap-1.5">每页显示:
|
||||
<select class="page-size-select px-2 py-1 rounded border border-slate-200 bg-white text-slate-700 text-xs focus:outline-none" onchange="handlePageSizeChange('keys', this.value)">
|
||||
{% for size in keys_table.pagination.page_sizes %}
|
||||
<option value="{{ size }}" {{ 'selected' if keys_table.pagination.page_size == size }}>{{ size }} 条</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div class="pagination-pages flex items-center gap-2">
|
||||
<a href="javascript:void(0)" class="page-btn px-2.5 py-1 rounded border border-slate-200 bg-white text-slate-700 hover:bg-slate-50 transition {{ 'opacity-50 pointer-events-none' if not keys_table.pagination.has_prev }}" onclick="handlePageChange('keys', {{ keys_table.pagination.page - 1 }})">上一页</a>
|
||||
<span class="px-1 text-slate-600 font-medium">第 {{ keys_table.pagination.page }} / {{ keys_table.pagination.total_pages }} 页</span>
|
||||
<a href="javascript:void(0)" class="page-btn px-2.5 py-1 rounded border border-slate-200 bg-white text-slate-700 hover:bg-slate-50 transition {{ 'opacity-50 pointer-events-none' if not keys_table.pagination.has_next }}" onclick="handlePageChange('keys', {{ keys_table.pagination.page + 1 }})">下一页</a>
|
||||
</div>
|
||||
</div>
|
||||
{{ render_pagination(keys_table, 'keys', '个密钥') }}
|
||||
|
||||
<!-- 底部悬浮胶囊批量工具栏 -->
|
||||
<div id="keys-table-floating-toolbar" class="batch-floating-toolbar fixed bottom-6 left-1/2 -translate-x-1/2 bg-white/95 backdrop-blur-md text-slate-800 px-4 py-2.5 rounded-2xl shadow-xl border border-slate-200/90 flex items-center gap-2.5 z-40 text-xs font-semibold transition-all duration-200 opacity-0 pointer-events-none translate-y-4">
|
||||
|
||||
@@ -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 @@
|
||||
</div>
|
||||
|
||||
<!-- 分页控件与每页条数 Selector -->
|
||||
<div class="pagination-bar flex flex-col sm:flex-row items-center justify-between gap-4 mt-5 pt-4 border-t border-slate-100 text-xs text-slate-500">
|
||||
<div class="pagination-info flex items-center gap-3">
|
||||
<span>共 {{ logs_table.pagination.total_count }} 条数据</span>
|
||||
<label class="flex items-center gap-1.5">每页显示:
|
||||
<select class="page-size-select px-2 py-1 rounded border border-slate-200 bg-white text-slate-700 text-xs focus:outline-none" onchange="handlePageSizeChange('logs', this.value)">
|
||||
{% for size in logs_table.pagination.page_sizes %}
|
||||
<option value="{{ size }}" {{ 'selected' if logs_table.pagination.page_size == size }}>{{ size }} 条</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div class="pagination-pages flex items-center gap-2">
|
||||
<a href="javascript:void(0)" class="page-btn px-2.5 py-1 rounded border border-slate-200 bg-white text-slate-700 hover:bg-slate-50 transition {{ 'opacity-50 pointer-events-none' if not logs_table.pagination.has_prev }}" onclick="handlePageChange('logs', {{ logs_table.pagination.page - 1 }})">上一页</a>
|
||||
<span class="px-1 text-slate-600 font-medium">第 {{ logs_table.pagination.page }} / {{ logs_table.pagination.total_pages }} 页</span>
|
||||
<a href="javascript:void(0)" class="page-btn px-2.5 py-1 rounded border border-slate-200 bg-white text-slate-700 hover:bg-slate-50 transition {{ 'opacity-50 pointer-events-none' if not logs_table.pagination.has_next }}" onclick="handlePageChange('logs', {{ logs_table.pagination.page + 1 }})">下一页</a>
|
||||
</div>
|
||||
</div>
|
||||
{{ render_pagination(logs_table, 'logs', '条数据') }}
|
||||
|
||||
<!-- 底部悬浮胶囊批量工具栏 -->
|
||||
<div id="logs-table-floating-toolbar" class="batch-floating-toolbar fixed bottom-6 left-1/2 -translate-x-1/2 bg-white/95 backdrop-blur-md text-slate-800 px-4 py-2.5 rounded-2xl shadow-xl border border-slate-200/90 flex items-center gap-2.5 z-40 text-xs font-semibold transition-all duration-200 opacity-0 pointer-events-none translate-y-4">
|
||||
|
||||
@@ -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 @@
|
||||
</div>
|
||||
|
||||
<!-- 分页控件与每页条数 Selector -->
|
||||
<div class="pagination-bar flex flex-col sm:flex-row items-center justify-between gap-4 mt-5 pt-4 border-t border-slate-100 text-xs text-slate-500">
|
||||
<div class="pagination-info flex items-center gap-3">
|
||||
<span>共 {{ platforms_table.pagination.total_count }} 个平台</span>
|
||||
<label class="flex items-center gap-1.5">每页显示:
|
||||
<select class="page-size-select px-2 py-1 rounded border border-slate-200 bg-white text-slate-700 text-xs focus:outline-none" onchange="handlePageSizeChange('platforms', this.value)">
|
||||
{% for size in platforms_table.pagination.page_sizes %}
|
||||
<option value="{{ size }}" {{ 'selected' if platforms_table.pagination.page_size == size }}>{{ size }} 条</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div class="pagination-pages flex items-center gap-2">
|
||||
<a href="javascript:void(0)" class="page-btn px-2.5 py-1 rounded border border-slate-200 bg-white text-slate-700 hover:bg-slate-50 transition {{ 'opacity-50 pointer-events-none' if not platforms_table.pagination.has_prev }}" onclick="handlePageChange('platforms', {{ platforms_table.pagination.page - 1 }})">上一页</a>
|
||||
<span class="px-1 text-slate-600 font-medium">第 {{ platforms_table.pagination.page }} / {{ platforms_table.pagination.total_pages }} 页</span>
|
||||
<a href="javascript:void(0)" class="page-btn px-2.5 py-1 rounded border border-slate-200 bg-white text-slate-700 hover:bg-slate-50 transition {{ 'opacity-50 pointer-events-none' if not platforms_table.pagination.has_next }}" onclick="handlePageChange('platforms', {{ platforms_table.pagination.page + 1 }})">下一页</a>
|
||||
</div>
|
||||
</div>
|
||||
{{ render_pagination(platforms_table, 'platforms', '个平台') }}
|
||||
</section>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user