From 0ac0d5fa11b87111eeefdb5b4593f418f8d6c1e9 Mon Sep 17 00:00:00 2001 From: ucmao <294323976@qq.com> Date: Wed, 9 Sep 2026 19:11:58 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E5=96=84=E5=AA=92=E4=BD=93=E8=A7=A3?= =?UTF-8?q?=E6=9E=90=E6=B5=81=E7=A8=8B=E5=B9=B6=E4=BC=98=E5=8C=96=E7=9B=B8?= =?UTF-8?q?=E5=85=B3=E5=A4=84=E7=90=86=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/web/admin.py | 59 ++-- src/web/portal.py | 113 ++++--- static/css/console.css | 470 ++++++++++++++++++++++++++--- static/js/table_manager.js | 214 ++++++++++++- templates/admin/keys.html | 4 +- templates/admin/logs.html | 15 +- templates/admin/overview.html | 2 +- templates/admin/settings.html | 12 +- templates/admin/users.html | 2 +- templates/components/api_docs.html | 162 +++++++--- templates/portal/keys.html | 2 +- templates/portal/logs.html | 4 +- tests/test_management.py | 11 + 13 files changed, 876 insertions(+), 194 deletions(-) diff --git a/src/web/admin.py b/src/web/admin.py index a428797..1315320 100644 --- a/src/web/admin.py +++ b/src/web/admin.py @@ -1,8 +1,9 @@ import csv from datetime import datetime, time, timedelta, timezone +import io from zoneinfo import ZoneInfo -from flask import Blueprint, Response, flash, g, redirect, render_template, request, session, stream_with_context, url_for +from flask import Blueprint, Response, flash, g, redirect, render_template, request, session, url_for from werkzeug.security import generate_password_hash @@ -781,11 +782,6 @@ def _safe_csv_cell(value): return text -class _CsvRowBuffer: - def write(self, value): - return value - - @bp.get("/logs/export.csv") @admin_required def export_logs(): @@ -828,30 +824,41 @@ def export_logs(): where_sql = (" WHERE " + " AND ".join(where_clauses)) if where_clauses else "" - def generate(): - writer = csv.writer(_CsvRowBuffer()) - yield "\ufeff" - yield writer.writerow(("时间", "客户", "Key", "平台", "请求路径", "请求 URL", "状态码", "耗时(毫秒)", "错误码")) - cursor = db.execute( - f"SELECT l.*, u.username, k.key_prefix FROM request_logs l " - f"LEFT JOIN users u ON u.id=l.user_id LEFT JOIN api_keys k ON k.id=l.api_key_id " - f"{where_sql} ORDER BY l.id DESC", - params, - ) - while rows := cursor.fetchmany(1000): - for row in rows: - yield writer.writerow(tuple(_safe_csv_cell(value) for value in ( - format_log_time(row["created_at"]), row["username"] or "在线体验", - f"{row['key_prefix']}••••••••••••" if row["key_prefix"] else "", row["platform"] or "", row["path"], - row["input_url"] or "", row["status_code"], row["duration_ms"], - row["error_code"] or "", - ))) + output = io.StringIO() + output.write("\ufeff") + writer = csv.writer(output, lineterminator="\r\n") + writer.writerow(("时间", "客户", "Key", "平台", "请求路径", "请求 URL", "状态码", "耗时(毫秒)", "错误码")) + cursor = db.execute( + f"SELECT l.*, u.username, k.key_prefix FROM request_logs l " + f"LEFT JOIN users u ON u.id=l.user_id LEFT JOIN api_keys k ON k.id=l.api_key_id " + f"{where_sql} ORDER BY l.id DESC", + params, + ) + while rows := cursor.fetchmany(1000): + for row in rows: + writer.writerow(( + _safe_csv_cell(format_log_time(row["created_at"])), + _safe_csv_cell(row["username"] or "在线体验"), + _safe_csv_cell(f"{row['key_prefix']}••••••••••••" if row["key_prefix"] else ""), + _safe_csv_cell(row["platform"] or ""), + _safe_csv_cell(row["path"]), + _safe_csv_cell(row["input_url"] or ""), + _safe_csv_cell(row["status_code"]), + _safe_csv_cell(row["duration_ms"]), + _safe_csv_cell(row["error_code"] or ""), + )) + + csv_bytes = output.getvalue().encode("utf-8") filename = datetime.now(ZoneInfo("Asia/Shanghai")).strftime("request-logs-%Y%m%d-%H%M%S.csv") return Response( - stream_with_context(generate()), + csv_bytes, content_type="text/csv; charset=utf-8", - headers={"Content-Disposition": f'attachment; filename="{filename}"'}, + headers={ + "Content-Disposition": f'attachment; filename="{filename}"', + "Content-Length": str(len(csv_bytes)), + "Cache-Control": "no-cache, no-store, must-revalidate", + }, ) diff --git a/src/web/portal.py b/src/web/portal.py index 668eada..eedb06f 100644 --- a/src/web/portal.py +++ b/src/web/portal.py @@ -1,8 +1,9 @@ import csv from datetime import datetime, time, timezone +import io from zoneinfo import ZoneInfo -from flask import Blueprint, Response, flash, g, redirect, render_template, request, session, stream_with_context, url_for +from flask import Blueprint, Response, flash, g, redirect, render_template, request, session, url_for from configs.general_constants import DOMAIN_TO_NAME from src.auth import csrf_protected, format_log_time, generate_api_key, hash_api_key, login_required, user_is_expired @@ -417,53 +418,81 @@ def _safe_csv_cell(value): return text -class _CsvRowBuffer: - def write(self, value): - return value - - @bp.get("/logs/export.csv") @login_required def export_logs(): + db = get_db() + export_type = request.args.get("export_type", "all") ids_param = request.args.get("ids", "").strip() - selected_ids = [] - if ids_param: - try: - selected_ids = [int(i.strip()) for i in ids_param.split(",") if i.strip().isdigit()] - except ValueError: - selected_ids = [] - def generate(): - writer = csv.writer(_CsvRowBuffer()) - yield "\ufeff" - yield writer.writerow(("时间", "调用 Key", "平台", "请求路径", "请求 URL", "状态码", "耗时(毫秒)", "错误码")) - db = get_db() - if selected_ids: - placeholders = ",".join(["?"] * len(selected_ids)) - sql = f"""SELECT l.*, k.key_prefix, k.name as key_name - FROM request_logs l - LEFT JOIN api_keys k ON l.api_key_id = k.id - WHERE l.user_id=? AND l.id IN ({placeholders}) - ORDER BY l.id DESC""" - cursor = db.execute(sql, [g.user["id"]] + selected_ids) - else: - sql = """SELECT l.*, k.key_prefix, k.name as key_name - FROM request_logs l - LEFT JOIN api_keys k ON l.api_key_id = k.id - WHERE l.user_id=? - ORDER BY l.id DESC""" - cursor = db.execute(sql, (g.user["id"],)) - while rows := cursor.fetchmany(1000): - for row in rows: - key_display = f"{row['key_name']} ({row['key_prefix']}...)" if row["key_prefix"] else "Web 免鉴权" - yield writer.writerow(tuple(_safe_csv_cell(value) for value in ( - format_log_time(row["created_at"]), key_display, row["platform"] or "", row["path"], - row["input_url"] or "", row["status_code"], row["duration_ms"], - row["error_code"] or "", - ))) + where_clauses, params = ["l.user_id = ?"], [g.user["id"]] + + if export_type == "selected" and ids_param: + try: + id_list = [int(i.strip()) for i in ids_param.split(",") if i.strip().isdigit()] + if id_list: + placeholders = ",".join(["?"] * len(id_list)) + where_clauses.append(f"l.id IN ({placeholders})") + params.extend(id_list) + except ValueError: + pass + else: + if l_q := request.args.get("logs_q", request.args.get("q", "")).strip(): + where_clauses.append("(l.input_url LIKE ? OR l.error_code LIKE ? OR k.name LIKE ?)") + params.extend([f"%{l_q}%", f"%{l_q}%", f"%{l_q}%"]) + if l_status := request.args.get("logs_status", request.args.get("status_code", "")).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.args.get("logs_platform", request.args.get("platform", "")).strip(): + where_clauses.append("l.platform = ?") + params.append(l_platform) + if utc_start := _parse_shanghai_to_utc_iso(request.args.get("logs_start_date", request.args.get("start_date", "")), is_end=False): + where_clauses.append("l.created_at >= ?") + params.append(utc_start) + if utc_end := _parse_shanghai_to_utc_iso(request.args.get("logs_end_date", request.args.get("end_date", "")), is_end=True): + where_clauses.append("l.created_at <= ?") + params.append(utc_end) + + where_sql = " WHERE " + " AND ".join(where_clauses) + + output = io.StringIO() + output.write("\ufeff") + writer = csv.writer(output, lineterminator="\r\n") + writer.writerow(("时间", "调用 Key", "平台", "请求路径", "请求 URL", "状态码", "耗时(毫秒)", "错误码")) + + sql = f"""SELECT l.*, k.key_prefix, k.name as key_name + FROM request_logs l + LEFT JOIN api_keys k ON l.api_key_id = k.id + {where_sql} + ORDER BY l.id DESC""" + cursor = db.execute(sql, params) + while rows := cursor.fetchmany(1000): + for row in rows: + key_display = f"{row['key_name']} ({row['key_prefix']}...)" if row["key_prefix"] else "Web 免鉴权" + writer.writerow(( + _safe_csv_cell(format_log_time(row["created_at"])), + _safe_csv_cell(key_display), + _safe_csv_cell(row["platform"] or ""), + _safe_csv_cell(row["path"]), + _safe_csv_cell(row["input_url"] or ""), + _safe_csv_cell(row["status_code"]), + _safe_csv_cell(row["duration_ms"]), + _safe_csv_cell(row["error_code"] or ""), + )) + + csv_bytes = output.getvalue().encode("utf-8") filename = datetime.now(ZoneInfo("Asia/Shanghai")).strftime("my-request-logs-%Y%m%d-%H%M%S.csv") return Response( - stream_with_context(generate()), + csv_bytes, content_type="text/csv; charset=utf-8", - headers={"Content-Disposition": f'attachment; filename="{filename}"'}, + headers={ + "Content-Disposition": f'attachment; filename="{filename}"', + "Content-Length": str(len(csv_bytes)), + "Cache-Control": "no-cache, no-store, must-revalidate", + }, ) diff --git a/static/css/console.css b/static/css/console.css index 6a9ba9a..360ea8b 100644 --- a/static/css/console.css +++ b/static/css/console.css @@ -648,6 +648,16 @@ input:not([type="checkbox"]):not([type="radio"]), select, textarea { transition: all 0.15s ease; } +select { + appearance: none; + -webkit-appearance: none; + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%2364748b' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E"); + background-repeat: no-repeat; + background-position: right 12px center; + padding-right: 32px !important; + cursor: pointer; +} + input:not([type="checkbox"]):not([type="radio"]):focus, select:focus, textarea:focus { outline: none; border-color: var(--brand); @@ -1651,6 +1661,17 @@ table input[type="number"] { align-items: center; justify-content: space-between; margin-bottom: 8px; + list-style: none; + cursor: pointer; + user-select: none; +} + +.api-tip-preview-header::-webkit-details-marker { + display: none; +} + +details.api-tip-preview-box:not([open]) .api-tip-preview-header { + margin-bottom: 0; } .api-tip-preview-title { @@ -2081,6 +2102,8 @@ table input[type="number"] { .table-filter-form select { min-width: 110px !important; + background-position: right 8px center !important; + padding-right: 26px !important; } .th-sortable { @@ -2107,6 +2130,19 @@ table input[type="number"] { font-weight: bold; } +.error-code-badge { + display: inline-block; + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; + font-size: 11.5px; + font-weight: 500; + color: var(--ink-secondary); + background: var(--bg-subtle); + border: 1px solid var(--line); + padding: 1.5px 6px; + border-radius: var(--radius-xs); + letter-spacing: -0.2px; +} + .table-selection-banner { display: none; align-items: center; @@ -2160,12 +2196,13 @@ table input[type="number"] { .page-size-select { width: auto !important; height: 30px !important; - min-width: 76px !important; - padding: 0 8px !important; + min-width: 86px !important; + padding: 0 24px 0 8px !important; + background-position: right 6px center !important; font-size: 12px !important; border-radius: var(--radius-sm) !important; border: 1px solid #cbd5e1 !important; - background: var(--bg-card) !important; + background-color: var(--bg-card) !important; color: var(--ink) !important; cursor: pointer; } @@ -2348,27 +2385,28 @@ table input[type="number"] { .api-docs-container { display: flex; flex-direction: column; - max-width: 1160px; - margin: 0 auto; - padding: 8px 36px 80px; width: 100%; + margin: 0; + padding: 0; } -/* 纯净无卡片无边界文档画布 (Seamless Canvas) */ +/* 统一独立纯白技术文档大画布卡片 (Whitepaper Document Card Canvas) - 与全站 .card 间距完全一致 */ .api-docs-canvas { - background: transparent; - border: none; - border-radius: 0; - box-shadow: none; + background: var(--bg-card); + border: 1px solid var(--line); + border-radius: var(--radius-xl); + padding: 22px 24px; + box-shadow: var(--shadow-xs); + transition: box-shadow 0.2s ease, border-color 0.2s ease; overflow: visible; } /* 顶部强化 Endpoint Hero Header */ .api-endpoint-hero { - padding: 12px 0 24px; + padding: 0 0 20px; background: transparent; border-bottom: 1px solid var(--line); - margin-bottom: 28px; + margin-bottom: 24px; } .api-hero-main-row { @@ -2437,7 +2475,7 @@ table input[type="number"] { display: flex; align-items: flex-start; justify-content: space-between; - gap: 56px; + gap: 36px; position: relative; } @@ -2445,10 +2483,9 @@ table input[type="number"] { .api-doc-article { flex: 1; min-width: 0; - max-width: 860px; display: flex; flex-direction: column; - gap: 44px; + gap: 36px; } .api-doc-section { @@ -2457,7 +2494,7 @@ table input[type="number"] { /* 右侧粘性固定目录 (On this page) */ .api-doc-toc-wrap { - width: 200px; + width: 190px; flex-shrink: 0; position: sticky; top: calc(var(--topbar-height) + 24px); @@ -2504,25 +2541,10 @@ table input[type="number"] { border-left-color: var(--brand); } -@media (max-width: 1200px) { - .api-docs-container { - padding: 8px 24px 60px; - } -} - @media (max-width: 1080px) { .api-doc-toc-wrap { display: none !important; } - .api-doc-article { - max-width: 100%; - } -} - -@media (max-width: 768px) { - .api-docs-container { - padding: 4px 10px 40px; - } } .doc-section-title { @@ -2550,37 +2572,43 @@ table input[type="number"] { margin: 0 0 14px; } -/* 扁平化数据表格 */ +/* 纯净文档排版数据表格 (Technical Documentation Table) */ .doc-flat-table-wrap { overflow-x: auto; - margin: 12px 0 18px; + margin: 14px 0 20px; + border-top: 1px solid var(--line); + border-bottom: 1px solid var(--line); } .doc-flat-table { width: 100%; border-collapse: collapse; - font-size: 13px; + font-size: 13.5px; text-align: left; } .doc-flat-table th { - background: transparent; - color: var(--ink-muted); - font-weight: 600; + background: #f8fafc; + color: var(--ink-secondary); + font-weight: 650; font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; - padding: 8px 12px 10px; - border-bottom: 2px solid var(--line); + padding: 10px 14px; + border-bottom: 1px solid var(--line); white-space: nowrap; } .doc-flat-table td { - padding: 11px 12px; + padding: 12px 14px; border-bottom: 1px solid var(--line-subtle); color: var(--ink); vertical-align: top; - line-height: 1.5; + line-height: 1.6; +} + +.doc-flat-table tr:last-child td { + border-bottom: none; } .doc-flat-table td:nth-child(1), @@ -2588,8 +2616,26 @@ table input[type="number"] { white-space: nowrap; } +/* 纯净文档排版:彻底移除表格行悬浮变色(强制覆盖全局 tbody tr:hover) */ +.doc-flat-table tbody tr, +.doc-flat-table tbody tr:hover, +.doc-flat-table tr, +.doc-flat-table tr:hover, +.doc-flat-table td, .doc-flat-table tr:hover td { - background: #f8fafc; + background: transparent !important; + background-color: transparent !important; + transition: none !important; +} + +.api-doc-article :not(pre) > code { + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; + font-size: 12.5px; + background: var(--bg-subtle); + color: var(--ink); + padding: 1.5px 5.5px; + border-radius: var(--radius-xs); + border: 1px solid var(--line); } .param-req { @@ -2992,20 +3038,155 @@ textarea.pg-input { border: none !important; } -.pg-key-dropdown { +/* Playground Key Selector Custom Dropdown */ +.pg-key-dropdown-wrap { position: absolute; right: 6px; top: 50%; transform: translateY(-50%); - height: 26px; + z-index: 25; +} + +.pg-key-dropdown-trigger { + display: inline-flex; + align-items: center; + gap: 5px; + height: 28px; + padding: 0 9px; font-size: 11.5px; - border-radius: var(--radius-sm); - border: 1px solid var(--line); - background: var(--bg-subtle); + font-weight: 500; color: var(--ink-secondary); - padding: 0 6px; + background: var(--bg-subtle); + border: 1px solid var(--line); + border-radius: var(--radius-sm); cursor: pointer; - max-width: 155px; + transition: all 0.15s ease; + user-select: none; + max-width: 160px; +} + +.pg-key-dropdown-trigger:hover, +.pg-key-dropdown-wrap.open .pg-key-dropdown-trigger { + border-color: var(--brand-border); + color: var(--brand); + background: var(--brand-light); +} + +.pg-key-dropdown-chevron { + flex-shrink: 0; + color: var(--ink-muted); + transition: transform 0.2s cubic-bezier(0.16, 1, 0.3, 1), color 0.15s ease; +} + +.pg-key-dropdown-wrap.open .pg-key-dropdown-chevron { + transform: rotate(180deg); + color: var(--brand); +} + +.pg-key-dropdown-menu { + position: absolute; + top: calc(100% + 5px); + right: 0; + min-width: 175px; + width: max-content; + max-width: 240px; + max-height: 280px; + background: var(--bg-card); + border: 1px solid var(--line); + border-radius: var(--radius-md); + box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.12), 0 8px 10px -6px rgba(0, 0, 0, 0.08); + padding: 4px; + z-index: 1000; + display: none; + overflow-y: auto; + box-sizing: border-box; +} + +.pg-key-dropdown-wrap.open .pg-key-dropdown-menu { + display: block; + animation: pgKeyMenuFadeIn 0.15s cubic-bezier(0.16, 1, 0.3, 1); +} + +@keyframes pgKeyMenuFadeIn { + from { + opacity: 0; + transform: translateY(-4px) scale(0.98); + } + to { + opacity: 1; + transform: translateY(0) scale(1); + } +} + +.pg-key-menu-divider { + height: 1px; + background: var(--line); + margin: 4px 0; +} + +.pg-key-menu-item { + width: 100%; + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + padding: 6px 9px; + border-radius: var(--radius-sm); + background: transparent; + border: none; + text-align: left; + cursor: pointer; + transition: background 0.12s ease; + box-sizing: border-box; + font-size: 12.5px; + color: var(--ink); +} + +.pg-key-menu-item:hover { + background: var(--bg-subtle); +} + +.pg-key-menu-item.active { + background: var(--brand-light); + color: var(--brand); +} + +.pg-key-menu-item .pg-key-item-title { + font-size: 12.5px; + font-weight: 400; + color: inherit; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + flex: 1; +} + +.pg-key-menu-item.active .pg-key-item-title { + font-weight: 600; + color: var(--brand); +} + +.pg-key-item-check { + color: var(--brand); + flex-shrink: 0; + opacity: 0; +} + +.pg-key-menu-item.active .pg-key-item-check { + opacity: 1; +} + +.pg-key-menu-item.action-create { + display: flex; + align-items: center; + color: var(--brand); + font-size: 12px; + font-weight: 500; + padding: 6px 9px; +} + +.pg-key-menu-item.action-create:hover { + background: var(--brand-light); } .pg-mode-toggle { @@ -3119,6 +3300,195 @@ textarea.pg-input { border-radius: 4px; } +/* ========================================================================== + Clean Minimalist Custom Select Dropdown (Universal Web Dropdown) + ========================================================================== */ +.custom-select-wrap { + position: relative; + display: inline-flex; + align-items: center; + vertical-align: middle; + box-sizing: border-box; +} + +.custom-select-btn { + display: inline-flex; + align-items: center; + justify-content: space-between; + gap: 6px; + height: 34px; + padding: 0 10px; + background: var(--bg-card); + border: 1px solid #cbd5e1; + border-radius: var(--radius-md); + color: var(--ink); + font-size: 13px; + font-weight: 400; + cursor: pointer; + user-select: none; + transition: all 0.15s ease; + white-space: nowrap; + box-sizing: border-box; + text-align: left; +} + +.custom-select-btn:hover { + border-color: var(--brand-border); + background: var(--bg-subtle); +} + +.custom-select-wrap.open .custom-select-btn { + border-color: var(--brand); + box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.12); + background: var(--bg-card); +} + +.custom-select-btn-text { + flex: 1; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.custom-select-chevron { + color: #94a3b8; + flex-shrink: 0; + transition: transform 0.2s cubic-bezier(0.16, 1, 0.3, 1), color 0.15s ease; +} + +.custom-select-wrap.open .custom-select-chevron { + transform: rotate(180deg); + color: var(--brand); +} + +.custom-select-popover { + position: absolute; + top: calc(100% + 4px); + left: 0; + min-width: 100%; + width: max-content; + max-width: 320px; + max-height: 240px; + background: var(--bg-card); + border: 1px solid var(--line); + border-radius: var(--radius-md); + box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.12), 0 8px 10px -6px rgba(0, 0, 0, 0.08); + padding: 4px; + z-index: 1000; + display: none; + overflow-y: auto; + box-sizing: border-box; +} + +.custom-select-wrap.open .custom-select-popover { + display: block; + animation: csFadeIn 0.15s cubic-bezier(0.16, 1, 0.3, 1); +} + +.custom-select-wrap.drop-up .custom-select-popover { + top: auto; + bottom: calc(100% + 4px); +} + +@keyframes csFadeIn { + from { + opacity: 0; + transform: translateY(-3px) scale(0.98); + } + to { + opacity: 1; + transform: translateY(0) scale(1); + } +} + +.custom-select-group-header { + padding: 6px 10px 2px; + font-size: 11px; + font-weight: 700; + color: var(--ink-muted); + user-select: none; +} + +.custom-select-item { + width: 100%; + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + padding: 6px 10px; + border-radius: var(--radius-sm); + background: transparent; + border: none; + text-align: left; + cursor: pointer; + transition: background 0.12s ease; + box-sizing: border-box; + font-size: 13px; + color: var(--ink); + white-space: nowrap; +} + +.custom-select-item:hover { + background: var(--bg-subtle); +} + +.custom-select-item.active { + background: var(--brand-light); + color: var(--brand); + font-weight: 500; +} + +.custom-select-item-text { + flex: 1; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.custom-select-item-check { + color: var(--brand); + flex-shrink: 0; + opacity: 0; +} + +.custom-select-item.active .custom-select-item-check { + opacity: 1; +} + +/* Modifiers for pagination and form sizes */ +.pagination-info .custom-select-btn, +.page-size-selector .custom-select-btn { + height: 28px !important; + padding: 0 8px !important; + font-size: 12px !important; + border-radius: var(--radius-sm) !important; + background: var(--bg-card); +} + +.pagination-info .custom-select-item, +.page-size-selector .custom-select-item { + padding: 5px 8px !important; + font-size: 12px !important; +} + +.table-filter-form .custom-select-wrap { + min-width: 105px; +} + +.field .custom-select-wrap { + width: 100%; +} + +.field .custom-select-btn { + width: 100%; + height: 38px; +} + +.modal-card .custom-select-popover { + z-index: 1200; +} + + diff --git a/static/js/table_manager.js b/static/js/table_manager.js index c8b9bbd..0def9d3 100644 --- a/static/js/table_manager.js +++ b/static/js/table_manager.js @@ -3,6 +3,9 @@ * 通用后台数据表格交互核心逻辑:排序、动态筛选、批量勾选/跨页全选、分页及条数切换、导出。 */ function initAll() { + // 初始化页面自定义下拉组件 + initCustomSelects(); + // 监听全选框与单选框联动 initTableSelection(); @@ -301,7 +304,7 @@ function setSelectAllFilteredMode(tableId, totalCount) { /** * 核心批量操作提交接口 */ -function executeBatchAction(tableId, targetUrl, action, extraPayload = {}, confirmPrompt = '') { +async function executeBatchAction(tableId, targetUrl, action, extraPayload = {}, confirmPrompt = '', confirmTitle = '操作确认', confirmType = 'danger') { const table = document.getElementById(tableId); if (!table) return; @@ -310,12 +313,24 @@ function executeBatchAction(tableId, targetUrl, action, extraPayload = {}, confi const values = Array.from(checkedBoxes).map(cb => cb.value); if (!isAllMode && values.length === 0) { - alert('请先勾选需要批量操作的行!'); + if (window.showToast) { + window.showToast('请先勾选需要批量操作的行!', 'warning'); + } return; } - if (confirmPrompt && !confirm(confirmPrompt)) { - return; + if (confirmPrompt) { + if (window.confirmModal) { + const ok = await window.confirmModal({ + title: confirmTitle, + message: confirmPrompt, + confirmText: '确定', + type: confirmType + }); + if (!ok) return; + } else if (typeof confirm === 'function' && !confirm(confirmPrompt)) { + return; + } } const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content || @@ -381,7 +396,9 @@ function triggerLogExport(exportType = 'auto') { if (exportType === 'selected') { if (ids.length === 0) { - alert('请先勾选需要导出的日志条目!'); + if (window.showToast) { + window.showToast('请先勾选需要导出的日志条目!', 'warning'); + } return; } urlParams.set('ids', ids.join(',')); @@ -402,7 +419,9 @@ function openBatchModal(modalId, tableId) { if (!m) return; const checked = document.querySelectorAll(`#${tableId} .row-checkbox:checked`); if (checked.length === 0) { - alert('请先勾选需要批量操作的项!'); + if (window.showToast) { + window.showToast('请先勾选需要批量操作的项!', 'warning'); + } return; } m.style.display = 'flex'; @@ -430,7 +449,9 @@ function submitBatchUserCredits() { function submitBatchUserExpires() { const expires = document.getElementById('batch-expires-date')?.value || ''; if (!expires) { - alert('请选择到期日期!'); + if (window.showToast) { + window.showToast('请选择到期日期!', 'warning'); + } return; } executeBatchAction('users-table', '/admin/users/batch', 'set_expires', { expires_at: expires }); @@ -451,3 +472,182 @@ function submitBatchPlatformQps() { executeBatchAction('platforms-table', '/admin/platforms/batch', 'set_qps', { qps_limit: qps }); } +/** + * ========================================================================== + * 轻量级网页自定义下拉菜单组件 (替代系统原生 - - - {% else %} - 暂无符合条件的日志记录 + 暂无符合条件的日志记录 {% endfor %} @@ -154,7 +147,7 @@
- +
diff --git a/templates/admin/overview.html b/templates/admin/overview.html index c6c86a3..f3a95ff 100644 --- a/templates/admin/overview.html +++ b/templates/admin/overview.html @@ -9,7 +9,7 @@

系统管理概览

控制服务全局开放状态、配置客户到期时间与各平台 QPS 限制。
- 超级管理员 + 超级管理员
diff --git a/templates/admin/settings.html b/templates/admin/settings.html index 567d512..9b7f245 100644 --- a/templates/admin/settings.html +++ b/templates/admin/settings.html @@ -174,18 +174,18 @@ onchange="triggerSettingsSubmit(this)">
-
-
+
+ 响应 JSON 效果预览 - 实时联动 -
-
-
+ 点击展开/收起 ▾ + +
+
diff --git a/templates/admin/users.html b/templates/admin/users.html index 7546df1..a7a83d0 100644 --- a/templates/admin/users.html +++ b/templates/admin/users.html @@ -85,7 +85,7 @@ #{{ user['id'] }} {{ user['username'] }} - {{ '管理员' if user['role']=='admin' else '客户' }} + {{ '管理员' if user['role']=='admin' else '客户' }} {{ '正常' if user['active'] else '停用' }} diff --git a/templates/components/api_docs.html b/templates/components/api_docs.html index 038ee14..33bebd2 100644 --- a/templates/components/api_docs.html +++ b/templates/components/api_docs.html @@ -345,7 +345,7 @@
待解析链接 / 分享文案 *
- @@ -377,17 +377,39 @@ onkeydown="handleKeyInputKeydown(event)"> - + +
+ +
+ + {% if available_keys and available_keys|length > 0 %} + {% for k in available_keys %} + {% set is_selected = (new_api_key and k['key_prefix'] in new_api_key) or (not new_api_key and loop.first) %} + + {% endfor %} +
+ + {% else %} +
+ + {% endif %} +
+
@@ -601,30 +623,44 @@ if (input && input.style.display !== 'none') input.focus(); }; - window.handleApiKeyDropdownChange = function(sel) { - const val = typeof sel === 'string' ? sel : (sel ? sel.value : ''); - if (val === '__GO_CREATE_KEY__') { - const dropdown = document.getElementById('pg-key-selector'); - if (dropdown) dropdown.value = ''; - goToKeyManagement(); - return; + window.togglePgKeyDropdown = function(e) { + if (e) { + e.preventDefault(); + e.stopPropagation(); } + const wrap = document.getElementById('pg-key-dropdown-wrap'); + if (wrap) { + wrap.classList.toggle('open'); + } + }; + + window.closePgKeyDropdown = function() { + const wrap = document.getElementById('pg-key-dropdown-wrap'); + if (wrap) { + wrap.classList.remove('open'); + } + }; + + window.handlePgKeyItemSelect = function(val, name) { + closePgKeyDropdown(); if (!val) { clearSelectedKey(); return; } - const dropdown = document.getElementById('pg-key-selector'); - const opt = dropdown ? dropdown.options[dropdown.selectedIndex] : null; - const name = opt ? (opt.dataset.name || opt.text) : '密钥'; applySelectedKey(val, name); }; + window.handlePgKeyActionCreate = function() { + closePgKeyDropdown(); + goToKeyManagement(); + }; + window.applySelectedKey = function(prefixVal, name) { const chip = document.getElementById('pg-selected-key-chip'); const chipName = document.getElementById('pg-key-chip-name'); const chipPrefix = document.getElementById('pg-key-chip-prefix'); const input = document.getElementById('pg-api-key'); - const dropdown = document.getElementById('pg-key-selector'); + const label = document.getElementById('pg-key-dropdown-label'); if (chipName) chipName.textContent = name || '密钥'; if (chipPrefix) chipPrefix.textContent = '(' + prefixVal + ')'; @@ -638,10 +674,18 @@ input.style.display = 'none'; } - if (dropdown && dropdown.value !== prefixVal) { - dropdown.value = prefixVal; + if (label) { + label.textContent = name || '密钥'; } + document.querySelectorAll('#pg-key-dropdown-menu .pg-key-menu-item').forEach(item => { + if (item.dataset.val === prefixVal) { + item.classList.add('active'); + } else { + item.classList.remove('active'); + } + }); + syncCodeSnippets(); }; @@ -649,7 +693,7 @@ if (e) e.stopPropagation(); const chip = document.getElementById('pg-selected-key-chip'); const input = document.getElementById('pg-api-key'); - const dropdown = document.getElementById('pg-key-selector'); + const label = document.getElementById('pg-key-dropdown-label'); if (chip) { chip.style.display = 'none'; @@ -661,24 +705,39 @@ input.placeholder = '请输入或选择 API Key'; input.focus(); } - if (dropdown) { - dropdown.value = ''; + if (label) { + label.textContent = '选择 Key'; } + + document.querySelectorAll('#pg-key-dropdown-menu .pg-key-menu-item').forEach(item => { + if (!item.dataset.val) { + item.classList.add('active'); + } else { + item.classList.remove('active'); + } + }); + syncCodeSnippets(); }; window.handleManualKeyInput = function() { const chip = document.getElementById('pg-selected-key-chip'); - const input = document.getElementById('pg-api-key'); - const dropdown = document.getElementById('pg-key-selector'); + const label = document.getElementById('pg-key-dropdown-label'); if (chip && chip.style.display !== 'none') { chip.style.display = 'none'; chip.dataset.val = ''; } - if (dropdown) { - dropdown.value = ''; + if (label) { + label.textContent = '选择 Key'; } + document.querySelectorAll('#pg-key-dropdown-menu .pg-key-menu-item').forEach(item => { + if (!item.dataset.val) { + item.classList.add('active'); + } else { + item.classList.remove('active'); + } + }); syncCodeSnippets(); }; @@ -691,23 +750,36 @@ }; window.selectApiKey = function(keyVal) { - const dropdown = document.getElementById('pg-key-selector'); - if (dropdown) { - for (let i = 0; i < dropdown.options.length; i++) { - if (dropdown.options[i].value === keyVal) { - dropdown.selectedIndex = i; - applySelectedKey(keyVal, dropdown.options[i].dataset.name || dropdown.options[i].text); - return; - } + let matched = false; + document.querySelectorAll('#pg-key-dropdown-menu .pg-key-menu-item[data-val]').forEach(item => { + if (item.dataset.val === keyVal || item.dataset.val === (keyVal + '...')) { + applySelectedKey(item.dataset.val, item.dataset.name || '密钥'); + matched = true; + } + }); + if (!matched) { + const input = document.getElementById('pg-api-key'); + if (input) { + input.value = keyVal; + syncCodeSnippets(); } } - const input = document.getElementById('pg-api-key'); - if (input) { - input.value = keyVal; - syncCodeSnippets(); - } }; + document.addEventListener('click', function(e) { + const wrap = document.getElementById('pg-key-dropdown-wrap'); + if (wrap && wrap.classList.contains('open') && !wrap.contains(e.target)) { + wrap.classList.remove('open'); + } + }); + + document.addEventListener('keydown', function(e) { + if (e.key === 'Escape') { + const wrap = document.getElementById('pg-key-dropdown-wrap'); + if (wrap) wrap.classList.remove('open'); + } + }); + window.resetPlayground = function() { const urlInput = document.getElementById('pg-target-url'); if (urlInput) urlInput.value = ''; diff --git a/templates/portal/keys.html b/templates/portal/keys.html index 99ab131..9099919 100644 --- a/templates/portal/keys.html +++ b/templates/portal/keys.html @@ -188,7 +188,7 @@
- +
diff --git a/templates/portal/logs.html b/templates/portal/logs.html index 72e98d7..089257d 100644 --- a/templates/portal/logs.html +++ b/templates/portal/logs.html @@ -94,8 +94,8 @@ {{ log['status_code'] }} {% if log['error_code'] %} - {{ log['error_code'] }} - {% else %}-{% endif %} + {{ log['error_code'] }} + {% else %}-{% endif %} {{ log['duration_ms'] }} ms diff --git a/tests/test_management.py b/tests/test_management.py index e13f0a2..7516764 100644 --- a/tests/test_management.py +++ b/tests/test_management.py @@ -376,11 +376,22 @@ class ManagementTest(unittest.TestCase): response = self.client.get("/admin/logs/export.csv") self.assertEqual(response.status_code, 200) self.assertIn("text/csv", response.content_type) + self.assertIn("Content-Length", response.headers) body = response.get_data(as_text=True) self.assertIn("请求 URL", body) self.assertIn("https://example.com/video/1", body) self.assertIn("MEDIA_NOT_FOUND", body) + # Test with error status filter and all mode + filtered_resp = self.client.get("/admin/logs/export.csv?logs_status=error&export_type=all") + self.assertEqual(filtered_resp.status_code, 200) + self.assertIn("https://example.com/video/1", filtered_resp.get_data(as_text=True)) + + # Test with 200 status filter (should exclude error log) + ok_resp = self.client.get("/admin/logs/export.csv?logs_status=200&export_type=all") + self.assertEqual(ok_resp.status_code, 200) + self.assertNotIn("https://example.com/video/1", ok_resp.get_data(as_text=True)) + def test_user_can_export_only_own_logs_as_csv(self): self.client.post( "/auth/register",