Download app/statics/admin/account.html from LifeVta/Grok3API: direct link, hf CLI and curl.
- Browser
- Download file 106 kB
-
https://huggingface.co/spaces/LifeVta/Grok3API/resolve/main/app/statics/admin/account.html
- Command line
-
hf download hf://spaces/LifeVta/Grok3API/app/statics/admin/account.html
-
curl -L -o account.html https://huggingface.co/spaces/LifeVta/Grok3API/resolve/main/app/statics/admin/account.html
106 kB
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title data-i18n="account.pageTitle">Grok2API - 账户管理</title>
<link rel="icon" href="/favicon.ico?v={{APP_VERSION}}">
<link href="https://cdn.jsdelivr.net/npm/geist@1.0.0/dist/fonts/geist-sans/style.css" rel="stylesheet">
<link href="/static/css/app.css?v={{APP_VERSION}}" rel="stylesheet">
<style>
body { background: #141416; color: #f4f4f5; }
/* Page header */
.page-hd { display:flex; align-items:flex-start; justify-content:space-between; margin-bottom:20px }
.page-title{ font-size:22px; font-weight:700; line-height:1.2; color: #f4f4f5; }
.page-sub { font-size:13px; color:#a1a1aa; margin-top:5px }
.page-actions { display:flex; gap:8px; align-items:center; flex-shrink:0 }
.section-head {
display:flex;
align-items:baseline;
justify-content:space-between;
gap:12px;
margin:28px 0 14px;
}
.section-title {
font-size:13px;
font-weight:600;
color:#e4e4e7;
letter-spacing:.01em;
}
.section-title-row {
display:inline-flex;
align-items:center;
gap:8px;
}
.section-count-badge {
min-width:20px;
height:20px;
padding:0 7px;
border-radius:999px;
display:inline-flex;
align-items:center;
justify-content:center;
background:#2d2d34;
color:#a1a1aa;
font-size:11px;
font-weight:600;
font-variant-numeric:tabular-nums;
line-height:1;
}
.page-action-btn {
height:32px;
padding:0 14px;
border-radius:999px;
display:inline-flex;
align-items:center;
justify-content:center;
gap:6px;
font-size:13px;
font-weight:600;
border:1px solid #3f3f46;
background:#202024;
color:#e4e4e7;
}
.page-action-btn:hover {
background:#2d2d34;
border-color:#52525b;
}
.page-action-btn-primary {
background:#f4f4f5;
border-color:#f4f4f5;
color:#141416;
}
.page-action-btn-primary:hover {
background:#e4e4e7;
border-color:#e4e4e7;
}
/* Stats */
.stat-grid {
display:grid;
grid-template-columns:repeat(5, minmax(0, 1fr));
gap:12px;
margin-bottom:20px;
}
.stat-grid.mode-random {
grid-template-columns:repeat(4, minmax(0, 1fr));
}
.stat-grid-quota {
display:grid;
grid-template-columns:repeat(6, minmax(0, 1fr));
gap:12px;
margin-bottom:20px;
}
.stat-cell {
min-height:88px;
padding:14px 16px;
border-radius:12px;
background:#202024;
border:1px solid #2d2d34;
display:flex;
flex-direction:column;
gap:12px;
}
.stat-cell.clickable {
cursor:pointer;
transition:background-color .15s, transform .15s, box-shadow .15s;
}
.stat-cell.clickable:hover {
background-color:#2d2d34;
transform:translateY(-1px);
box-shadow:0 6px 16px rgba(0,0,0,0.2);
}
.stat-top {
display:flex;
align-items:center;
justify-content:space-between;
gap:10px;
}
.stat-label {
font-size:11px;
color:#a1a1aa;
letter-spacing:.01em;
white-space:nowrap;
}
.stat-icon {
width:24px;
height:24px;
display:inline-flex;
align-items:center;
justify-content:center;
color:#71717a;
flex:0 0 auto;
}
.stat-icon svg {
width:15px;
height:15px;
stroke:currentColor;
}
.stat-num {
font-size:22px;
font-weight:600;
line-height:1;
letter-spacing:-.02em;
margin-top:auto;
color: #f4f4f5;
}
.stat-muted { color:#52525b !important; }
[data-random-only] { display:none }
.stat-grid.mode-random [data-random-only] { display:flex }
.stat-grid.mode-random [data-stat-card="active"] { order:1 }
.stat-grid.mode-random [data-stat-card="cooling"] { order:2 }
.stat-grid.mode-random [data-stat-card="invalid"] { order:3 }
.stat-grid.mode-random [data-stat-card="disabled"] { order:4 }
.stat-grid.mode-random [data-stat-card="total"] { order:5 }
.stat-grid.mode-random [data-stat-card="calls"] { order:6 }
.stat-grid.mode-random [data-stat-card="success"] { order:7 }
.stat-grid.mode-random [data-stat-card="rate"] { order:8 }
/* Filters */
.filter-bar {
display:flex;
flex-direction:column;
align-items:flex-start;
gap:10px;
margin-bottom:16px;
width:100%;
}
.filter-group {
display:flex;
align-items:center;
gap:8px;
flex-wrap:wrap;
}
.filter-label {
width:52px;
flex:0 0 52px;
font-size:11px;
font-weight:600;
color:#71717a;
letter-spacing:.01em;
text-align:right;
white-space:nowrap;
}
.filter-chip {
height:30px;
min-width:84px;
padding:0 12px;
border-radius:999px;
font-size:12px;
font-weight:500;
color:#a1a1aa;
background:#202024;
border:1px solid #2d2d34;
display:flex;
align-items:center;
justify-content:space-between;
gap:6px;
transition:background .15s, color .15s;
white-space:nowrap;
flex:0 0 auto;
}
.filter-chip:hover { color:#e4e4e7; background:#2d2d34 }
.filter-chip.active {
background:#f4f4f5;
color:#141416;
border-color:#f4f4f5;
}
.filter-chip-count {
min-width:18px;
height:18px;
padding:0 5px;
border-radius:999px;
background:rgba(255,255,255,.1);
font-size:11px;
font-weight:600;
color:inherit;
display:inline-flex;
align-items:center;
justify-content:center;
font-variant-numeric:tabular-nums;
}
.filter-chip.active .filter-chip-count {
background:rgba(0,0,0,.1);
color:#141416;
}
.filter-chip-count.is-green,
.filter-chip-count.is-orange,
.filter-chip-count.is-red,
.filter-chip-count.is-purple { color:inherit }
/* Toolbar row above table */
.table-toolbar {
display:flex;
align-items:center;
gap:8px;
margin-bottom:8px;
flex-wrap:wrap;
color:#a1a1aa;
font-size:12px;
font-weight:500;
font-family:inherit;
}
.table-toolbar-left { flex:1 }
.table-toolbar-actions {
display:flex;
align-items:center;
gap:8px;
flex-wrap:wrap;
}
.toolbar-icon-btn {
width:28px;
height:28px;
display:inline-flex;
align-items:center;
justify-content:center;
color:inherit;
flex:0 0 auto;
font:inherit;
background:transparent;
border:none;
cursor:pointer;
}
.toolbar-icon-btn:hover {
color:#f4f4f5;
}
.toolbar-icon-btn-danger { color:inherit; }
.toolbar-icon-btn-danger:hover { color:#ef4444; }
.toolbar-icon-btn.is-active {
color:#141416;
background:#f4f4f5;
border-radius:999px;
}
.toolbar-page-size {
width:94px !important;
height:28px;
border-radius:999px;
font:inherit;
color:#e4e4e7 !important;
background:#202024 !important;
border:1px solid #3f3f46 !important;
}
.toolbar-dropdown {
position:relative;
display:inline-flex;
align-items:center;
}
.toolbar-dropdown-panel {
position:absolute;
top:calc(100% + 10px);
right:0;
width:min(416px, calc(100vw - 24px));
padding:12px;
border-radius:16px;
background:#1a1a1e;
border:1px solid #2d2d34;
box-shadow:0 12px 28px rgba(0,0,0,.4);
display:none;
z-index:30;
}
.toolbar-dropdown.open .toolbar-dropdown-panel {
display:block;
}
.toolbar-dropdown-panel .filter-bar {
gap:10px;
margin-bottom:0;
}
.toolbar-dropdown-panel .filter-group {
align-items:flex-start;
gap:8px;
width:100%;
flex-wrap:nowrap;
}
.filter-chip-list {
display:flex;
align-items:center;
gap:6px;
flex-wrap:nowrap;
min-width:0;
flex:1 1 auto;
overflow-x:auto;
overflow-y:hidden;
scrollbar-width:none;
-ms-overflow-style:none;
}
.filter-chip-list::-webkit-scrollbar {
display:none;
}
.toolbar-dropdown-panel .filter-label {
width:34px;
flex:0 0 34px;
padding-top:6px;
text-align:left;
}
.toolbar-dropdown-panel .filter-chip {
height:26px;
min-width:66px;
padding:0 10px;
font-size:11px;
gap:5px;
background:#202024;
}
.toolbar-dropdown-panel .filter-chip-count {
min-width:16px;
height:16px;
padding:0 4px;
font-size:10px;
}
@media (max-width: 720px) {
.toolbar-dropdown-panel {
right:-8px;
width:min(320px, calc(100vw - 20px));
}
.toolbar-dropdown-panel .filter-label {
width:32px;
flex:0 0 32px;
}
}
/* Table */
.table-card {
background:#202024;
border:1px solid #2d2d34;
border-radius:14px;
overflow-x:auto;
overflow-y:hidden;
-webkit-overflow-scrolling:touch;
}
.table-card > table { width:max-content; min-width:100%; border-collapse:collapse }
.table-freeze-last {
--table-sticky-bg:#202024;
--table-sticky-hover-bg:#2d2d34;
}
table { width:100%; border-collapse:collapse }
th {
background:#202024;
font-size:11px;
font-weight:500;
color:#a1a1aa;
padding:11px 16px;
text-align:left;
border-bottom:1px solid #2d2d34;
letter-spacing:.01em;
user-select:none;
}
th.sortable-th {
cursor:pointer;
transition:color .15s, background-color .15s;
}
th.sortable-th:hover {
color:#f4f4f5;
background-color:#2d2d34;
}
.sort-indicator {
font-size:10px;
display:inline-block;
margin-left:4px;
color:#f4f4f5;
font-weight:bold;
}
td {
font-size:13px;
padding:13px 16px;
border-bottom:1px solid #1a1a1e;
vertical-align:middle;
color:#e4e4e7;
}
tr:last-child td { border-bottom:none }
tr:hover td { background:#2d2d34 }
.table-card .badge {
display:inline-flex;
align-items:center;
height:20px;
padding:0 8px;
border-radius:999px;
font-size:11px;
font-weight:500;
border:none;
}
.table-card .badge-basic {
color:#a1a1aa;
background:#2d2d34;
}
.table-card .badge-super {
color:#60a5fa;
background:rgba(96, 165, 250, 0.15);
}
.table-card .badge-heavy {
color:#fb923c;
background:rgba(251, 146, 60, 0.15);
}
.table-card .badge-active {
color:#4ade80;
background:rgba(74, 222, 128, 0.15);
}
.table-card .badge-cooling {
color:#fbbf24;
background:rgba(251, 191, 36, 0.15);
}
.table-card .badge-expired,
.table-card .badge-invalid,
.table-card .badge-failed {
color:#f87171;
background:rgba(248, 113, 113, 0.15);
}
.table-card .badge-disabled {
color:#71717a;
background:#2d2d34;
}
.table-center { text-align:center }
.table-center .badge { margin:0 auto }
.token-stack {
display:flex;
align-items:center;
gap:8px;
min-width:0;
}
.row-actions {
display:flex;
align-items:center;
gap:10px;
flex-wrap:wrap;
}
.row-icon-btn {
width:22px;
height:22px;
display:inline-flex;
align-items:center;
justify-content:center;
color:#71717a;
background:transparent;
border:none;
cursor:pointer;
flex:0 0 auto;
}
.row-icon-btn svg {
width:13px;
height:13px;
stroke:currentColor;
stroke-linecap:round;
stroke-linejoin:round;
fill:none;
}
.row-icon-btn.row-icon-btn-state svg {
width:14.5px;
height:14.5px;
}
.row-icon-btn:hover { color:#e4e4e7 }
.row-icon-btn.is-loading {
color:#e4e4e7;
pointer-events:none;
}
.row-icon-btn.is-loading svg {
animation:spin .85s linear infinite;
}
.row-action {
color:#71717a;
font-size:11px;
font-weight:500;
display:inline-flex;
align-items:center;
justify-content:center;
}
.row-action:hover { color:#e4e4e7 }
.row-action:disabled {
opacity:1;
cursor:default;
}
.row-action-danger {
color:#f87171;
}
.row-action-danger:hover { color:#ef4444 }
.row-icon-danger { color:#f87171; }
.row-icon-danger:hover { color:#ef4444 }
.row-action-static {
color:#c084fc;
}
.admin-tooltip {
position:fixed;
left:0;
top:0;
z-index:500;
max-width:220px;
padding:6px 8px;
border-radius:8px;
background:rgba(32,32,36,.96);
border:1px solid #3f3f46;
color:#fff;
font-size:11px;
line-height:1.35;
white-space:normal;
pointer-events:none;
opacity:0;
transform:translate3d(0,0,0);
transition:opacity .08s ease;
}
.admin-tooltip.show { opacity:1 }
.row-nsfw-btn {
width:22px;
height:22px;
display:inline-flex;
align-items:center;
justify-content:center;
color:#71717a;
background:transparent;
border:none;
cursor:pointer;
flex:0 0 auto;
}
.row-nsfw-btn:hover { color:#e4e4e7 }
.row-nsfw-btn.is-on { color:#f87171 }
.row-nsfw-btn.is-on:hover { color:#ef4444 }
.row-nsfw-btn svg {
width:15px;
height:15px;
overflow:visible;
}
.row-nsfw-btn circle,
.row-nsfw-btn path {
stroke:currentColor;
stroke-width:1.7;
stroke-linecap:round;
stroke-linejoin:round;
fill:none;
}
.row-nsfw-btn text {
fill:currentColor;
font-family:var(--font-sans);
font-size:7.2px;
font-weight:700;
text-anchor:middle;
dominant-baseline:central;
}
.table-card .empty-state {
padding:48px 16px;
color:#71717a;
font-size:13px;
}
@keyframes spin {
from { transform:rotate(0deg) }
to { transform:rotate(360deg) }
}
/* Quota pills in table cell */
.quota-cell { display:flex; gap:8px; align-items:center }
.q-pill {
height:20px;
font-size:11px;
font-weight:500;
padding:0 7px;
border-radius:999px;
display:inline-flex;
align-items:center;
user-select:none;
}
.q-pill.sortable-pill {
cursor:pointer;
transition:opacity .15s, transform .15s;
}
.q-pill.sortable-pill:hover {
opacity:.85;
transform:scale(1.05);
}
.q-a { background:rgba(96, 165, 250, 0.15); color:#60a5fa }
.q-f { background:rgba(74, 222, 128, 0.15); color:#4ade80 }
.q-e { background:rgba(168, 85, 247, 0.15); color:#c084fc }
.q-h { background:rgba(251, 146, 60, 0.15); color:#fb923c }
.q-b { background:rgba(244, 63, 94, 0.15); color:#fb7185 }
.q-c { background:rgba(45, 212, 191, 0.15); color:#2dd4bf }
.q-z { background:#2d2d34; color:#71717a }
/* Token monospace */
.tok { font-family:ui-monospace,monospace; font-size:12px; color:#f4f4f5 }
/* Pagination */
.pagi-meta {
display:flex;
align-items:center;
gap:0;
color:inherit;
font:inherit;
margin:0 -2px;
}
.pagi-page {
min-width:0;
height:28px;
padding:0 4px;
font:inherit;
color:inherit;
display:inline-flex;
align-items:center;
justify-content:center;
font-variant-numeric:tabular-nums;
}
.pagi-btn {
width:28px;
height:28px;
border-radius:6px;
display:inline-flex;
align-items:center;
justify-content:center;
color:inherit;
background:transparent;
border:none;
cursor:pointer;
transition:background .1s, color .1s;
font:inherit;
}
.pagi-btn:hover { background:#2d2d34 }
.pagi-btn.on { background:#f4f4f5; color:#141416 }
.pagi-btn:disabled { opacity:.25; pointer-events:none }
/* Dialog框及输入控件大重构 */
.modal-overlay {
background: rgba(0,0,0,0.6) !important;
}
.modal {
background: #202024 !important;
border: 1px solid #3f3f46 !important;
color: #f4f4f5 !important;
box-shadow: 0 20px 25px -5px rgba(0,0,0,0.5) !important;
}
.modal-title {
color: #f4f4f5 !important;
}
.input, select, textarea {
background: #141416 !important;
border: 1px solid #3f3f46 !important;
color: #f4f4f5 !important;
}
.input:focus, select:focus, textarea:focus {
border-color: #71717a !important;
outline: none;
}
.dialog-help {
color: #a1a1aa !important;
}
.dialog-label {
color: #a1a1aa !important;
}
.dialog-btn {
height:32px;
padding:0 14px;
border-radius:999px;
background:#2d2d34;
border:1px solid #3f3f46;
color:#e4e4e7;
font-size:13px;
font-weight:600;
cursor:pointer;
}
.dialog-btn:hover {
background:#3f3f46;
}
.dialog-btn-primary {
background:#f4f4f5;
color:#141416;
border-color:#f4f4f5;
}
.dialog-btn-primary:hover {
background:#e4e4e7;
}
.dialog-btn-danger {
color:#f87171;
background:rgba(248,113,113,0.1);
border-color:rgba(248,113,113,0.2);
}
.dialog-btn-danger:hover {
background:rgba(248,113,113,0.2);
}
.export-option-btn {
width:100%;
min-height:34px;
height:auto;
padding:6px 12px;
display:flex;
align-items:center;
justify-content:center;
text-align:center;
white-space:normal;
line-height:1.35;
}
/* Import modal */
.import-file-shell {
height:34px;
display:flex;
align-items:center;
padding:0 10px;
border-radius:8px;
background:#141416;
border:1px solid #3f3f46;
cursor:pointer;
transition:background .15s;
flex:1;
min-width:0;
}
.import-file-shell:hover {
background:#2d2d34;
}
.import-file-name {
font-size:12px;
color:#e4e4e7;
white-space:nowrap;
overflow:hidden;
text-overflow:ellipsis;
min-width:0;
flex:1;
}
.import-file-name.empty { color:#71717a }
/* Audit log styles */
.audit-table-wrap {
width:100%;
overflow-x:auto;
border:1px solid #3f3f46;
border-radius:8px;
max-height:360px;
background:#141416;
}
.audit-table { width:100%; border-collapse:collapse; min-width:560px }
.audit-table th { background:#202024; padding:8px 12px; font-size:11px; color:#a1a1aa; border-bottom:1px solid #3f3f46 }
.audit-table td { padding:10px 12px; font-size:12px; border-bottom:1px solid #2d2d34; color:#e4e4e7 }
/* ── 新增内存审计多视图动态响应样式 ── */
.audit-summary-grid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 12px;
margin-bottom: 18px;
}
.audit-grid-box {
background: #141416;
padding: 12px;
border-radius: 8px;
text-align: center;
border: 1px solid #3f3f46;
}
.audit-grid-box h5 {
margin: 0 0 6px 0;
color: #a1a1aa;
font-size: 11px;
font-weight: 500;
}
.audit-grid-box p {
margin: 0;
font-size: 18px;
font-weight: 600;
color: #f4f4f5;
}
.audit-dist-section {
display: flex;
gap: 16px;
margin-top: 14px;
}
.audit-dist-col {
flex: 1;
background: #141416;
padding: 14px;
border-radius: 8px;
border: 1px solid #3f3f46;
min-width: 0;
}
.audit-dist-col h4 {
margin: 0 0 12px 0;
font-size: 12px;
color: #fbbf24;
font-weight: 600;
}
.audit-rank-list {
list-style: none;
padding: 0;
margin: 0;
}
.audit-rank-list li {
display: flex;
justify-content: space-between;
align-items: center;
padding: 7px 0;
border-bottom: 1px solid #2d2d34;
font-size: 12px;
}
.audit-rank-list li:last-child {
border-bottom: none;
}
.audit-rank-lbl {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 75%;
color: #e4e4e7;
}
.audit-rank-val {
color: #60a5fa;
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.audit-pagination-bar {
display: flex;
justify-content: center;
align-items: center;
gap: 14px;
margin-top: 14px;
}
.audit-badge-status {
padding: 2px 6px;
border-radius: 4px;
font-size: 11px;
font-weight: 500;
}
.audit-bg-success {
background: rgba(74, 222, 128, 0.15);
color: #4ade80;
}
.audit-bg-fail {
background: rgba(248, 113, 113, 0.15);
color: #f87171;
}
</style>
</head>
<body>
<!-- ── Header ─────────────────────────────────────────────────────────────── -->
<div id="admin-header" data-active="/admin/account"></div>
<!-- ── Main ───────────────────────────────────────────────────────────────── -->
<main class="admin-main">
<!-- Page heading -->
<div class="page-hd">
<div>
<div class="page-title" data-i18n="account.pageHeading">账户列表</div>
<div class="page-sub" data-i18n="account.pageSubtitle">管理 Grok2API 的 xAI 服务账户池。</div>
</div>
<div class="page-actions">
<button onclick="openImport()" class="page-action-btn">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
<span data-i18n="account.actionImportShort">导入</span>
</button>
<button onclick="openAdd()" class="page-action-btn page-action-btn-primary">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
<span data-i18n="account.actionAddShort">新增</span>
</button>
</div>
</div>
<div class="section-head">
<div class="section-title" data-i18n="account.sectionOverview">账户概览</div>
</div>
<!-- Stats -->
<div class="stat-grid" id="overview-stats">
<div class="stat-cell" data-stat-card="total">
<div class="stat-top">
<div class="stat-label" data-i18n="account.statTotal">账户总数</div>
<span class="stat-icon">
<svg viewBox="0 0 24 24" fill="none" stroke-width="1.8"><path d="M4 19a4 4 0 0 1 4-4h8a4 4 0 0 1 4 4"/><circle cx="12" cy="8" r="4"/></svg>
</span>
</div>
<div class="stat-num" id="s-total">0</div>
</div>
<div class="stat-cell" data-stat-card="active">
<div class="stat-top">
<div class="stat-label" data-i18n="account.statActive">正常账户</div>
<span class="stat-icon" style="color:#4ade80">
<svg viewBox="0 0 24 24" fill="none" stroke-width="1.9"><circle cx="12" cy="12" r="8"/><path d="m8.5 12 2.4 2.4 4.8-4.8"/></svg>
</span>
</div>
<div class="stat-num" id="s-active" style="color:#4ade80">0</div>
</div>
<div class="stat-cell" data-stat-card="cooling">
<div class="stat-top">
<div class="stat-label" data-i18n="account.statCooling">限流账户</div>
<span class="stat-icon" style="color:#fb923c">
<svg viewBox="0 0 24 24" fill="none" stroke-width="1.8"><path d="M12 6v6l4 2"/><circle cx="12" cy="12" r="8"/></svg>
</span>
</div>
<div class="stat-num" id="s-cooling" style="color:#fb923c">0</div>
</div>
<div class="stat-cell" data-stat-card="invalid">
<div class="stat-top">
<div class="stat-label" data-i18n="account.statInvalid">异常账户</div>
<span class="stat-icon" style="color:#f87171">
<svg viewBox="0 0 24 24" fill="none" stroke-width="1.8"><path d="m15 9-6 6m0-6 6 6"/><circle cx="12" cy="12" r="8"/></svg>
</span>
</div>
<div class="stat-num" id="s-invalid" style="color:#f87171">0</div>
</div>
<div class="stat-cell" data-stat-card="disabled">
<div class="stat-top">
<div class="stat-label" data-i18n="account.statDisabled">禁用账户</div>
<span class="stat-icon" style="color:#71717a">
<svg viewBox="0 0 24 24" fill="none" stroke-width="1.8"><circle cx="12" cy="12" r="8"/><path d="M8.5 8.5 15.5 15.5"/></svg>
</span>
</div>
<div class="stat-num" id="s-disabled" style="color:#71717a">0</div>
</div>
</div>
<!-- Quota stats (6 columns) -->
<div class="stat-grid-quota" id="overview-quota-stats">
<div class="stat-cell clickable" data-stat-card="calls" onclick="openAuditModal('calls')">
<div class="stat-top">
<div class="stat-label" data-i18n="account.statCalls">调用总数</div>
<span class="stat-icon" style="color:#f4f4f5">
<svg viewBox="0 0 24 24" fill="none" stroke-width="1.8"><path d="M5 19h14"/><path d="M8 16V10"/><path d="M12 16V6"/><path d="M16 16v-3"/></svg>
</span>
</div>
<div class="stat-num" id="s-calls" style="color:#f4f4f5">0</div>
</div>
<div class="stat-cell clickable" data-quota-only onclick="openAuditModal('auto')">
<div class="stat-top">
<div class="stat-label" data-i18n="account.statAuto">Auto 余额</div>
<span class="stat-icon" style="color:#60a5fa">
<svg viewBox="0 0 24 24" fill="none" stroke-width="1.8"><path d="M6 19h12"/><path d="M12 16V9"/></svg>
</span>
</div>
<div class="stat-num" id="s-qa" style="color:#60a5fa">0</div>
</div>
<div class="stat-cell clickable" data-quota-only onclick="openAuditModal('fast')">
<div class="stat-top">
<div class="stat-label" data-i18n="account.statFast">Fast 余额</div>
<span class="stat-icon" style="color:#4ade80">
<svg viewBox="0 0 24 24" fill="none" stroke-width="1.8"><path d="M6 19h12"/><path d="M10 16v-4"/><path d="M14 16V8"/></svg>
</span>
</div>
<div class="stat-num" id="s-qf" style="color:#4ade80">0</div>
</div>
<div class="stat-cell clickable" data-quota-only onclick="openAuditModal('expert')">
<div class="stat-top">
<div class="stat-label" data-i18n="account.statExpert">Expert 余额</div>
<span class="stat-icon" style="color:#c084fc">
<svg viewBox="0 0 24 24" fill="none" stroke-width="1.8"><path d="M6 19h12"/><path d="M8 16v-2"/><path d="M12 16v-6"/><path d="M16 16V6"/></svg>
</span>
</div>
<div class="stat-num" id="s-qe" style="color:#c084fc">0</div>
</div>
<div class="stat-cell clickable" data-quota-only onclick="openAuditModal('heavy')">
<div class="stat-top">
<div class="stat-label" data-i18n="account.statHeavy">Heavy 余额</div>
<span class="stat-icon" style="color:#fb923c">
<svg viewBox="0 0 24 24" fill="none" stroke-width="1.8"><path d="M5 19h14"/><path d="M7 16v-1"/><path d="M10 16v-4"/><path d="M14 16V8"/><path d="M17 16V5"/></svg>
</span>
</div>
<div class="stat-num" id="s-qh" style="color:#fb923c">0</div>
</div>
<div class="stat-cell clickable" data-quota-only onclick="openAuditModal('console')">
<div class="stat-top">
<div class="stat-label" data-i18n="account.statConsole">Console 余额</div>
<span class="stat-icon" style="color:#2dd4bf">
<svg viewBox="0 0 24 24" fill="none" stroke-width="1.8"><path d="M4 19h16"/><path d="M6 16v-1"/><path d="M9 16v-3"/><path d="M12 16v-6"/><path d="M15 16V8"/><path d="M18 16V5"/></svg>
</span>
</div>
<div class="stat-num" id="s-qc" style="color:#2dd4bf">0</div>
</div>
</div>
<div class="section-head" style="margin-top:40px">
<div class="section-title-row">
<div class="section-title" data-i18n="account.sectionTable">账户明细</div>
<span class="section-count-badge" id="section-table-count">0</span>
</div>
</div>
<!-- Toolbar -->
<div class="table-toolbar">
<div class="table-toolbar-left" style="display:flex;align-items:center;gap:6px">
<button onclick="prevPage()" class="pagi-btn" id="btn-prev">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="15 18 9 12 15 6"/></svg>
</button>
<div class="pagi-meta">
<span class="pagi-page" id="pagi-page">0 / 0</span>
</div>
<button onclick="nextPage()" class="pagi-btn" id="btn-next">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="9 18 15 12 9 6"/></svg>
</button>
</div>
<div class="table-toolbar-actions">
<div class="toolbar-dropdown" id="filter-menu">
<button type="button" id="btn-filter" class="toolbar-icon-btn" aria-haspopup="menu" aria-expanded="false">
<svg viewBox="0 0 24 24" stroke-width="1.8"><path d="M4 6h16"/><path d="M7 12h10"/><path d="M10 18h4"/></svg>
</button>
<div class="toolbar-dropdown-panel" id="filter-panel" role="menu" aria-labelledby="btn-filter">
<div class="filter-bar">
<div class="filter-group">
<span class="filter-label" data-i18n="account.filterStatusLabel">状态</span>
<div class="filter-chip-list">
<button type="button" class="filter-chip active" data-status="all" onclick="switchStatus('all')">
<span data-i18n="account.filterStatusAll">全部</span>
<span class="filter-chip-count" id="fc-status-all">0</span>
</button>
<button type="button" class="filter-chip" data-status="active" onclick="switchStatus('active')">
<span data-i18n="account.filterStatusActive">正常</span>
<span class="filter-chip-count is-green" id="fc-status-active">0</span>
</button>
<button type="button" class="filter-chip" data-status="cooling" onclick="switchStatus('cooling')">
<span data-i18n="account.filterStatusCooling">限流</span>
<span class="filter-chip-count is-orange" id="fc-status-cooling">0</span>
</button>
<button type="button" class="filter-chip" data-status="invalid" onclick="switchStatus('invalid')">
<span data-i18n="account.filterStatusInvalid">异常</span>
<span class="filter-chip-count is-red" id="fc-status-invalid">0</span>
</button>
<button type="button" class="filter-chip" data-status="disabled" onclick="switchStatus('disabled')">
<span data-i18n="account.filterStatusDisabled">禁用</span>
<span class="filter-chip-count" id="fc-status-disabled">0</span>
</button>
</div>
</div>
<div class="filter-group" id="pool-filter-group">
<span class="filter-label" data-i18n="account.filterTypeLabel">类型</span>
<div class="filter-chip-list" id="pool-filter-chips"></div>
</div>
<div class="filter-group">
<span class="filter-label" data-i18n="account.filterNsfwLabel">NSFW</span>
<div class="filter-chip-list">
<button type="button" class="filter-chip active" data-nsfw="all" onclick="switchNsfw('all')">
<span data-i18n="account.filterNsfwAll">全部</span>
<span class="filter-chip-count" id="fc-nsfw-all">0</span>
</button>
<button type="button" class="filter-chip" data-nsfw="enabled" onclick="switchNsfw('enabled')">
<span data-i18n="account.filterNsfwEnabled">开启</span>
<span class="filter-chip-count is-purple" id="fc-nsfw-enabled">0</span>
</button>
<button type="button" class="filter-chip" data-nsfw="disabled" onclick="switchNsfw('disabled')">
<span data-i18n="account.filterNsfwDisabled">关闭</span>
<span class="filter-chip-count" id="fc-nsfw-disabled">0</span>
</button>
</div>
</div>
</div>
</div>
</div>
<button type="button" onclick="doExport()" id="btn-export" class="toolbar-icon-btn">
<svg viewBox="0 0 24 24" stroke-width="1.8"><path d="M12 3v12"/><path d="m7 10 5 5 5-5"/><path d="M5 21h14"/></svg>
</button>
<button type="button" onclick="batchNSFWAll()" id="btn-nsfw-all" class="row-nsfw-btn">
<svg viewBox="0 0 20 20" aria-hidden="true">
<circle cx="10" cy="10" r="7.25"/>
<text x="10" y="10.4">18</text>
<path d="M4.5 10h11"/>
</svg>
</button>
<button type="button" onclick="batchRefreshAllManageable()" id="btn-refresh-all" class="toolbar-icon-btn">
<svg viewBox="0 0 24 24" stroke-width="1.8"><path d="M20 11a8 8 0 0 0-14.6-4.6"/><path d="M4 4v5h5"/><path d="M4 13a8 8 0 0 0 14.6 4.6"/><path d="M20 20v-5h-5"/><path d="M12 8v4l3 2"/></svg>
</button>
<button type="button" onclick="deleteAllInvalid()" id="btn-delete-invalid-all" class="toolbar-icon-btn toolbar-icon-btn-danger">
<svg viewBox="0 0 24 24" stroke-width="1.8"><path d="M5 7h14"/><path d="M9 7V4h6v3"/><path d="M8 10v7"/><path d="M12 10v7"/><path d="M16 10v7"/><path d="M7 7l1 13h8l1-13"/><path d="M12 2v2"/></svg>
</button>
<button type="button" onclick="batchNSFW()" id="btn-nsfw" class="row-nsfw-btn" style="display:none">
<svg viewBox="0 0 20 20" aria-hidden="true">
<circle cx="10" cy="10" r="7.25"/>
<text x="10" y="10.4">18</text>
</svg>
</button>
<button type="button" onclick="batchRefreshSel()" id="btn-refresh" class="toolbar-icon-btn" style="display:none">
<svg viewBox="0 0 24 24" stroke-width="1.8"><path d="M20 11a8 8 0 0 0-14.6-4.6"/><path d="M4 4v5h5"/><path d="M4 13a8 8 0 0 0 14.6 4.6"/><path d="M20 20v-5h-5"/></svg>
</button>
<button type="button" onclick="batchDisableSel()" id="btn-disable" class="toolbar-icon-btn" style="display:none">
<svg viewBox="0 0 24 24" stroke-width="1.8"><circle cx="12" cy="12" r="8"/><path d="M8.5 8.5 15.5 15.5"/></svg>
</button>
<button type="button" onclick="batchRestoreSel()" id="btn-restore" class="toolbar-icon-btn" style="display:none">
<svg viewBox="0 0 24 24" stroke-width="1.8"><path d="M3 12a9 9 0 1 0 3-6.708"/><path d="M3 4v5h5"/></svg>
</button>
<button type="button" onclick="batchDeleteSel()" id="btn-delete" class="toolbar-icon-btn toolbar-icon-btn-danger" style="display:none">
<svg viewBox="0 0 24 24" stroke-width="1.8"><path d="M5 7h14"/><path d="M9 7V4h6v3"/><path d="M8 10v7"/><path d="M12 10v7"/><path d="M16 10v7"/><path d="M7 7l1 13h8l1-13"/></svg>
</button>
<button type="button" onclick="batchDeleteInvalidSel()" id="btn-delete-invalid" class="toolbar-icon-btn toolbar-icon-btn-danger" style="display:none">
<svg viewBox="0 0 24 24" stroke-width="1.8"><path d="M5 7h14"/><path d="M9 7V4h6v3"/><path d="M8 10v7"/><path d="M12 10v7"/><path d="M16 10v7"/><path d="M7 7l1 13h8l1-13"/><path d="M12 2v2"/></svg>
</button>
<button type="button" onclick="cancelBatch()" id="btn-batch-cancel" class="toolbar-icon-btn toolbar-icon-btn-danger" style="display:none">
<svg viewBox="0 0 24 24" stroke-width="1.8"><path d="M6 6 18 18"/><path d="M18 6 6 18"/></svg>
</button>
<select class="input toolbar-page-size" id="page-size-sel" onchange="changePageSize(this.value)">
<option value="50">50 / 页</option>
<option value="100">100 / 页</option>
<option value="200">200 / 页</option>
<option value="500">500 / 页</option>
<option value="1000">1000 / 页</option>
<option value="2000">2000 / 页</option>
</select>
</div>
</div>
<!-- Table -->
<div class="table-card table-freeze-last">
<table>
<thead>
<tr>
<th style="width:36px"><input type="checkbox" class="cb" id="cb-all" onchange="toggleAll(this.checked)"></th>
<th style="width:200px" class="sortable-th" onclick="handleSort('token')"><span data-i18n="account.colToken">Token</span><span id="sort-token" class="sort-indicator"></span></th>
<th class="table-center sortable-th" style="width:70px" onclick="handleSort('pool')"><span data-i18n="account.colType">类型</span><span id="sort-pool" class="sort-indicator"></span></th>
<th class="table-center sortable-th" style="width:70px" onclick="handleSort('status')"><span data-i18n="account.colStatus">状态</span><span id="sort-status" class="sort-indicator"></span></th>
<th data-quota-only>
<span data-i18n="account.colQuota">额度</span>
<span style="margin-left:6px;display:inline-flex;align-items:center;gap:3px;vertical-align:middle">
<span class="q-pill q-a sortable-pill" onclick="handleSort('quota_auto')" title="按 Auto 排序">A<span id="sort-quota_auto" class="sort-indicator"></span></span>
<span class="q-pill q-f sortable-pill" onclick="handleSort('quota_fast')" title="按 Fast 排序">F<span id="sort-quota_fast" class="sort-indicator"></span></span>
<span class="q-pill q-e sortable-pill" onclick="handleSort('quota_expert')" title="按 Expert 排序">E<span id="sort-quota_expert" class="sort-indicator"></span></span>
<span class="q-pill q-h sortable-pill" onclick="handleSort('quota_heavy')" title="按 Heavy 排序">H<span id="sort-quota_heavy" class="sort-indicator"></span></span>
<span class="q-pill q-c sortable-pill" onclick="handleSort('quota_console')" title="按 Console 排序">C<span id="sort-quota_console" class="sort-indicator"></span></span>
</span>
</th>
<th class="table-center sortable-th" onclick="handleSort('success')"><span data-i18n="account.colSuccess">成功</span><span id="sort-success" class="sort-indicator"></span></th>
<th class="table-center sortable-th" onclick="handleSort('fail')"><span data-i18n="account.colFail">失败</span><span id="sort-fail" class="sort-indicator"></span></th>
<th class="table-center sortable-th" onclick="handleSort('rate')"><span data-i18n="account.colRate">成功率</span><span id="sort-rate" class="sort-indicator"></span></th>
<th class="sortable-th" onclick="handleSort('last_used')"><span data-i18n="account.colLastUsed">最近使用</span><span id="sort-last_used" class="sort-indicator"></span></th>
<th data-i18n="account.colActions">操作</th>
</tr>
</thead>
<tbody id="tbody"></tbody>
</table>
</div>
</main>
<!-- ── Add Modal ───────────────────────────────────────────────────────────── -->
<div class="modal-overlay" id="modal-import">
<div class="modal">
<div class="modal-title" data-i18n="account.addTitle">添加账户</div>
<div class="dialog-body">
<div>
<div class="dialog-help" data-i18n="account.addHint">每行一个 Token,已存在的会自动跳过</div>
<textarea class="input dialog-textarea" id="import-tokens" rows="8" placeholder="粘贴 Token,每行一个..." data-i18n-placeholder="account.addPlaceholder"></textarea>
</div>
<div class="dialog-field">
<span class="dialog-label" data-i18n="account.labelType">类型</span>
<select class="input" id="import-pool" style="flex:1"></select>
</div>
<div class="dialog-field" style="margin-top:12px">
<label style="display:flex;align-items:center;gap:8px;cursor:pointer">
<input type="checkbox" id="import-auto-nsfw" style="margin:0">
<span data-i18n="account.autoNsfwOnImport">导入后自动开启 NSFW</span>
</label>
<div style="font-size:12px;color:#a1a1aa;margin-top:4px" data-i18n="account.autoNsfwHint">需要额外时间检测账户状态</div>
</div>
</div>
<div class="dialog-actions">
<button onclick="closeModal('modal-import')" class="dialog-btn" data-i18n="account.cancel">取消</button>
<button onclick="doAdd()" class="dialog-btn dialog-btn-primary" data-i18n="account.actionAdd">添加</button>
</div>
</div>
</div>
<!-- ── Import Modal ────────────────────────────────────────────────────────── -->
<div class="modal-overlay" id="modal-import-file">
<div class="modal">
<div class="modal-title" data-i18n="account.importTitle">导入文件</div>
<div class="dialog-body">
<div class="dialog-help" id="import-file-hint" data-i18n="account.importHintDefault">支持 .txt(每行一个 Token)或 .json({pool:[tokens]} 格式)</div>
<div class="dialog-field">
<span class="dialog-label" data-i18n="account.labelFile">文件</span>
<input class="import-file-input" id="import-file" type="file" accept=".txt,.json,text/plain,application/json" onchange="updateImportFileState()">
<label for="import-file" class="import-file-shell">
<div class="import-file-name empty" id="import-file-name" data-i18n="account.noFile">未选择文件</div>
</label>
</div>
<div class="dialog-field" id="import-file-pool-row">
<span class="dialog-label" data-i18n="account.labelType">类型</span>
<select class="input" id="import-file-pool" style="flex:1"></select>
</div>
<div class="dialog-field" style="margin-top:12px">
<label style="display:flex;align-items:center;gap:8px;cursor:pointer">
<input type="checkbox" id="import-file-auto-nsfw" style="margin:0">
<span data-i18n="account.autoNsfwOnImport">导入后自动开启 NSFW</span>
</label>
<div style="font-size:12px;color:#a1a1aa;margin-top:4px" data-i18n="account.autoNsfwHint">需要额外时间检测账户状态</div>
</div>
</div>
<div class="dialog-actions">
<button onclick="closeModal('modal-import-file')" class="dialog-btn" data-i18n="account.cancel">取消</button>
<button onclick="doImport()" class="dialog-btn dialog-btn-primary" data-i18n="account.actionImport">导入</button>
</div>
</div>
</div>
<!-- ── Edit Modal ─────────────────────────────────────────────────────────── -->
<div class="modal-overlay" id="modal-edit">
<div class="modal">
<div class="modal-title" data-i18n="account.editTitle">编辑账户</div>
<div class="dialog-body">
<div class="dialog-field">
<span class="dialog-label" data-i18n="account.colToken">Token</span>
<input class="input" id="edit-token" placeholder="输入新的 Token" data-i18n-placeholder="account.editTokenPlaceholder">
</div>
<div class="dialog-field">
<span class="dialog-label" data-i18n="account.labelType">类型</span>
<select class="input" id="edit-pool" style="flex:1"></select>
</div>
</div>
<div class="dialog-actions">
<button onclick="closeModal('modal-edit')" class="dialog-btn" data-i18n="account.cancel">取消</button>
<button onclick="doEdit()" class="dialog-btn dialog-btn-primary" data-i18n="account.save">保存</button>
</div>
</div>
</div>
<!-- ── Export Modal ────────────────────────────────────────────────────────── -->
<div class="modal-overlay" id="modal-export">
<div class="modal" style="max-width:360px">
<div class="modal-title" data-i18n="account.exportTitle">导出格式</div>
<div class="dialog-help"><span data-i18n="account.exportCountPrefix">共 </span><b id="exp-count">0</b><span data-i18n="account.exportCountSuffix"> 个 Token</span></div>
<div class="dialog-body" style="gap:8px">
<button id="exp-json-btn" class="dialog-btn dialog-btn-primary export-option-btn" data-i18n="account.exportJson">JSON格式(完整导出)</button>
<button id="exp-txt-btn" class="dialog-btn export-option-btn" data-i18n="account.exportTxt">TXT格式(仅导出 Token)</button>
</div>
</div>
</div>
<!-- ── Confirm Modal ───────────────────────────────────────────────────────── -->
<div class="modal-overlay" id="modal-confirm">
<div class="modal" style="max-width:400px">
<div class="modal-title" id="confirm-title" data-i18n="account.confirmTitle">确认</div>
<div id="confirm-body" class="dialog-help"></div>
<div class="dialog-actions">
<button onclick="closeModal('modal-confirm')" class="dialog-btn" data-i18n="account.cancel">取消</button>
<button onclick="_cb&&_cb()" class="dialog-btn dialog-btn-danger" data-i18n="account.confirm">确认</button>
</div>
</div>
</div>
<!-- ── Audit Log Modal ─────────────────────────────────────────────────────── -->
<div class="modal-overlay" id="modal-audit">
<div class="modal" style="max-width:820px; width:92%;">
<div class="modal-title" id="audit-title">调用审计明细</div>
<div class="dialog-body" id="audit-modal-body-content" style="padding-top:8px;">
<!-- 动态视图多看板注入点 -->
</div>
<div class="dialog-actions">
<button onclick="closeModal('modal-audit')" class="dialog-btn dialog-btn-primary">关闭</button>
</div>
</div>
</div>
<script src="/static/js/i18n.js?v={{APP_VERSION}}"></script>
<script src="/static/js/auth.js?v={{APP_VERSION}}"></script>
<script src="/static/js/admin-header.js?v={{APP_VERSION}}"></script>
<script src="/static/js/toast.js?v={{APP_VERSION}}"></script>
<script src="/static/js/footer.js?v={{APP_VERSION}}"></script>
<script>
// ── State ──────────────────────────────────────────────────────────────────
const PAGE_SIZE_KEY = 'admin.account.page_size';
const PAGE_SIZE_OPTIONS = [50, 100, 200, 500, 1000, 2000];
let allTokens = [], curStatus = 'all', curNsfw = 'all', curPool = 'all', curPage = 1, pageSize = loadSavedPageSize();
let sortKey = '', sortOrder = 'desc';
const sel = new Set();
const refreshingTokens = new Set();
let _cb = null;
let _editingToken = '';
let _filterMenuBound = false;
let _tokenViewVersion = 0;
let _tokenViewCacheKey = '';
let _tokenViewCache = null;
function invalidateTokenView() {
_tokenViewVersion += 1;
_tokenViewCacheKey = '';
_tokenViewCache = null;
}
function tr(key, params, fallback) {
const value = t(key, params);
return value === key ? (fallback ?? key) : value;
}
function applyAccountI18n() {
document.title = tr('account.pageTitle', null, 'Grok2API - 账户管理');
document.querySelectorAll('#page-size-sel option').forEach(opt => {
opt.textContent = tr('account.pageSizeOption', { n: opt.value }, `${opt.value} / 页`);
});
const toolbarTips = [
['btn-filter', 'account.filter', '筛选'],
['btn-export', 'account.export', '导出数据'],
['btn-nsfw-all', 'account.batchNsfwAll', '全部开启 NSFW'],
['btn-refresh-all', 'account.refreshAllManageable', '重新测试全部正常账户'],
['btn-delete-invalid-all', 'account.deleteInvalidAll', '删除全部异常'],
['btn-nsfw', 'account.batchNsfw', '开启 NSFW'],
['btn-refresh', 'account.batchRefresh', '刷新选中'],
['btn-disable', 'account.batchDisable', '禁用选中'],
['btn-restore', 'account.batchRestore', '恢复选中'],
['btn-delete', 'account.batchDelete', '删除选中'],
['btn-delete-invalid', 'account.deleteInvalidSelected', '删除选中异常'],
['btn-batch-cancel', 'account.cancel', '取消'],
];
toolbarTips.forEach(([id, key, fallback]) => {
const el = document.getElementById(id);
if (!el) return;
const label = tr(key, null, fallback);
el.setAttribute('data-tip', label);
el.setAttribute('aria-label', label);
el.setAttribute('title', label);
});
const pageSizeSel = document.getElementById('page-size-sel');
if (pageSizeSel) pageSizeSel.value = String(pageSize);
updateImportFileState();
render();
}
function waitI18n() {
return new Promise((resolve) => I18n.onReady(resolve));
}
// ── Boot ───────────────────────────────────────────────────────────────────
(async () => {
await waitI18n();
applyAccountI18n();
await renderAdminHeader?.();
await renderSiteFooter?.();
initFilterMenu();
const key = await adminKey.get();
if (!key || !await verifyKey(ADMIN_API + '/verify', key).catch(() => false))
return location.href = '/admin/login';
load();
})();
// ── API ────────────────────────────────────────────────────────────────────
async function _api(method, path, body) {
const key = await adminKey.get();
const r = await fetch(ADMIN_API + path, {
method,
headers: { ...(body != null && { 'Content-Type': 'application/json' }), Authorization: `Bearer ${key}` },
...(body != null && { body: JSON.stringify(body) }),
});
if (!r.ok) { const d = await r.json().catch(() => ({})); throw new Error(d.detail || r.status); }
return r.json();
}
let selectionStrategy = 'quota';
// ── Load ───────────────────────────────────────────────────────────────────
async function load() {
try {
const [data, status] = await Promise.all([
_api('GET', '/tokens'),
_api('GET', '/status').catch(() => null),
]);
if (status && typeof status.selection_strategy === 'string') {
selectionStrategy = status.selection_strategy;
}
allTokens = Array.isArray(data.tokens)
? data.tokens
: Object.entries(data.tokens || {}).flatMap(([pool, items]) =>
Array.isArray(items) ? items.map(t => ({ ...t, pool: t.pool || pool })) : []);
applyStrategyUI();
invalidateTokenView();
render();
} catch (e) { showToast(`${tr('account.loadFailed', null, '加载失败')}: ${e.message}`, 'error'); }
}
function applyStrategyUI() {
const isRandom = selectionStrategy === 'random';
const statsGrid = document.getElementById('overview-stats');
if (statsGrid) statsGrid.classList.toggle('mode-random', isRandom);
const quotaGrid = document.getElementById('overview-quota-stats');
if (quotaGrid) quotaGrid.style.display = isRandom ? 'none' : '';
document.querySelectorAll('[data-quota-only]').forEach(el => {
el.style.display = isRandom ? 'none' : '';
});
}
// ── Sorting Logic ──────────────────────────────────────────────────────────
function handleSort(key) {
if (sortKey === key) {
sortOrder = sortOrder === 'asc' ? 'desc' : 'asc';
} else {
sortKey = key;
sortOrder = 'desc';
}
invalidateTokenView();
render();
}
function updateSortIndicators() {
const keys = ['token', 'pool', 'status', 'quota_auto', 'quota_fast', 'quota_expert', 'quota_heavy', 'quota_console', 'success', 'fail', 'rate', 'last_used'];
keys.forEach(k => {
const el = document.getElementById(`sort-${k}`);
if (el) {
if (sortKey === k) {
el.textContent = sortOrder === 'asc' ? ' 🔼' : ' 🔽';
} else {
el.textContent = '';
}
}
});
}
// ── Audit Drill-down ───────────────────────────────────────────────────────
async function openAuditModal(type, page = 1) {
const titleMap = {
calls: '调用总数审计明细',
auto: 'Auto 额度调用分布审计',
fast: 'Fast 额度调用分布审计',
expert: 'Expert 额度调用分布审计',
heavy: 'Heavy 额度调用分布审计',
console: 'Console 额度调用分布审计'
};
document.getElementById('audit-title').textContent = titleMap[type] || '调用审计明细';
const container = document.getElementById('audit-modal-body-content');
container.innerHTML = `<div style="text-align:center;padding:32px;color:#a1a1aa;">正在从内存同步链读取审计快照...</div>`;
openModal('modal-audit');
const key = await adminKey.get();
const headers = { 'Authorization': `Bearer ${key}` };
// 视图 A: 渲染调用总数高并发明细列表(支持无损内存分页)
if (type === 'calls') {
try {
const response = await fetch(`${ADMIN_API}/audit/logs?page=${page}&size=50`, { headers });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
const logs = data.logs || [];
if (!logs.length) {
container.innerHTML = `<div style="text-align:center;color:#71717a;padding:40px 16px;">当前通道近期没有上游日志产生 (直连/历史日志为空)</div>`;
return;
}
let html = `
<div class="audit-table-wrap">
<table class="audit-table">
<thead>
<tr>
<th>请求时间</th>
<th>设备 IP</th>
<th>客户端 (User-Agent)</th>
<th>渠道额度</th>
<th>流状态</th>
</tr>
</thead>
<tbody>
`;
logs.forEach(log => {
const dateStr = new Date(log.request_time).toLocaleString('zh-CN', { hour12: false });
const statusBadge = log.status === 'SUCCESS'
? '<span class="audit-badge-status audit-bg-success">成功</span>'
: '<span class="audit-badge-status audit-bg-fail">阻断</span>';
html += `
<tr>
<td style="font-variant-numeric:tabular-nums; white-space:nowrap;">${dateStr}</td>
<td style="font-family:ui-monospace,monospace;color:#f4f4f5;">${log.device_ip || '—'}</td>
<td style="max-width:240px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#a1a1aa;" title="${xe(log.user_agent || '')}">${log.user_agent || '—'}</td>
<td><span class="q-pill q-f" style="text-transform:capitalize; font-size:10px;">${log.quota_type}</span></td>
<td>${statusBadge}</td>
</tr>
`;
});
html += `</tbody></table></div>`;
html += `
<div class="audit-pagination-bar">
<button class="dialog-btn" ${page <= 1 ? 'disabled style="opacity:0.3;cursor:not-allowed;"' : ''} onclick="openAuditModal('calls', ${page - 1})">上一页</button>
<span style="font-size:12px;color:#a1a1aa;">第 ${page} 页</span>
<button class="dialog-btn" ${logs.length < 50 ? 'disabled style="opacity:0.3;cursor:not-allowed;"' : ''} onclick="openAuditModal('calls', ${page + 1})">下一页</button>
</div>
`;
container.innerHTML = html;
} catch (e) {
container.innerHTML = `<div style="text-align:center;color:#f87171;padding:32px;">读取审计明细失败: ${e.message}</div>`;
}
}
// 视图 B: 针对各类 Quota 卡片,离散计算并渲染 Top5 分布拓扑
else {
try {
const response = await fetch(`${ADMIN_API}/audit/distribution?type=${type}`, { headers });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
const successRate = data.total_calls > 0
? ((data.success_calls / data.total_calls) * 100).toFixed(1)
: '0.0';
let html = `
<div class="audit-summary-grid">
<div class="audit-grid-box"><h5>总计调用</h5><p>${data.total_calls}</p></div>
<div class="audit-grid-box"><h5 style="color:#4ade80">成功频次</h5><p style="color:#4ade80">${data.success_calls}</p></div>
<div class="audit-grid-box"><h5 style="color:#f87171">失败阻断</h5><p style="color:#f87171">${data.fail_calls}</p></div>
<div class="audit-grid-box"><h5>健康合规率</h5><p>${successRate}%</p></div>
</div>
<div class="audit-dist-section">
<div class="audit-dist-col">
<h4>Top 5 活跃调用设备 IP 排名</h4>
`;
const ipEntries = Object.entries(data.top_ips || {});
if (!ipEntries.length) {
html += `<div style="text-align:center;color:#71717a;font-size:12px;padding:24px 0;">暂无任何 IP 请求分布捕获</div>`;
} else {
html += `<ul class="audit-rank-list">`;
ipEntries.forEach(([ip, count]) => {
html += `<li><span class="audit-rank-lbl" style="font-family:ui-monospace,monospace;">${ip}</span><span class="audit-rank-val">${count} 次</span></li>`;
});
html += `</ul>`;
}
html += `
</div>
<div class="audit-dist-col">
<h4>Top 5 客户端 (User-Agent) 负载源</h4>
`;
const uaEntries = Object.entries(data.top_user_agents || {});
if (!uaEntries.length) {
html += `<div style="text-align:center;color:#71717a;font-size:12px;padding:24px 0;">暂无任何 User-Agent 分布捕获</div>`;
} else {
html += `<ul class="audit-rank-list">`;
uaEntries.forEach(([ua, count]) => {
html += `<li><span class="audit-rank-lbl" title="${xe(ua)}">${ua}</span><span class="audit-rank-val">${count} 次</span></li>`;
});
html += `</ul>`;
}
html += `</div></div>`;
container.innerHTML = html;
} catch (e) {
container.innerHTML = `<div style="text-align:center;color:#f87171;padding:32px;">分析额度调用分布失败: ${e.message}</div>`;
}
}
}
// ── Render ─────────────────────────────────────────────────────────────────
function render() {
const view = getTokenView();
renderStats(view);
renderFilters(view);
renderTable(view);
applyStrategyUI();
updateSortIndicators();
}
function getTokenView() {
const cacheKey = `${_tokenViewVersion}|${curStatus}|${curNsfw}|${curPool}|${sortKey}|${sortOrder}`;
if (_tokenViewCache && _tokenViewCacheKey === cacheKey) return _tokenViewCache;
const stats = {
active: 0,
cooling: 0,
invalid: 0,
disabled: 0,
calls: 0,
success: 0,
fail: 0,
qa: 0,
qf: 0,
qe: 0,
qh: 0,
qc: 0,
};
const statusCounts = { all: 0, active: 0, cooling: 0, invalid: 0, disabled: 0 };
const nsfwCounts = { all: 0, enabled: 0, disabled: 0 };
const poolCounts = new Map([['all', 0]]);
const poolsSet = new Set(['basic', 'super', 'heavy']);
let filteredItems = [];
for (const token of allTokens) {
const pool = token.pool || 'basic';
const quota = token.quota || {};
const nsfwEnabled = (token.tags || []).includes('nsfw');
const invalid = isInvalidStatus(token.status);
const disabled = isDisabledStatus(token.status);
const matchesPool = curPool === 'all' || pool === curPool;
const matchesStatus = curStatus === 'all'
|| (curStatus === 'invalid' ? invalid : curStatus === 'disabled' ? disabled : token.status === curStatus);
const matchesNsfw = curNsfw === 'all' || (curNsfw === 'enabled' ? nsfwEnabled : !nsfwEnabled);
poolsSet.add(pool);
const successCount = token.use_count || 0;
const failCount = token.fail_count || 0;
stats.success += successCount;
stats.fail += failCount;
stats.calls += successCount + failCount;
stats.qa += quota.auto?.remaining || 0;
stats.qf += quota.fast?.remaining || 0;
stats.qe += quota.expert?.remaining || 0;
stats.qh += quota.heavy?.remaining || 0;
stats.qc += quota.console?.remaining || 0;
if (token.status === 'active') stats.active += 1;
if (token.status === 'cooling') stats.cooling += 1;
if (invalid) stats.invalid += 1;
if (disabled) stats.disabled += 1;
if (matchesPool && matchesNsfw) {
statusCounts.all += 1;
if (token.status === 'active') statusCounts.active += 1;
if (token.status === 'cooling') statusCounts.cooling += 1;
if (invalid) statusCounts.invalid += 1;
if (disabled) statusCounts.disabled += 1;
}
if (matchesPool && matchesStatus) {
nsfwCounts.all += 1;
if (nsfwEnabled) nsfwCounts.enabled += 1;
else nsfwCounts.disabled += 1;
}
if (matchesStatus && matchesNsfw) {
poolCounts.set('all', poolCounts.get('all') + 1);
poolCounts.set(pool, (poolCounts.get(pool) || 0) + 1);
}
if (matchesPool && matchesStatus && matchesNsfw) filteredItems.push(token);
}
if (sortKey) {
filteredItems.sort((a, b) => {
let vA, vB;
if (sortKey === 'token') { vA = a.token || ''; vB = b.token || ''; }
else if (sortKey === 'pool') { vA = a.pool || 'basic'; vB = b.pool || 'basic'; }
else if (sortKey === 'status') { vA = a.status || ''; vB = b.status || ''; }
else if (sortKey === 'quota_auto') { vA = a.quota?.auto?.remaining || 0; vB = b.quota?.auto?.remaining || 0; }
else if (sortKey === 'quota_fast') { vA = a.quota?.fast?.remaining || 0; vB = b.quota?.fast?.remaining || 0; }
else if (sortKey === 'quota_expert') { vA = a.quota?.expert?.remaining || 0; vB = b.quota?.expert?.remaining || 0; }
else if (sortKey === 'quota_heavy') { vA = a.quota?.heavy?.remaining || 0; vB = b.quota?.heavy?.remaining || 0; }
else if (sortKey === 'quota_console') { vA = a.quota?.console?.remaining || 0; vB = b.quota?.console?.remaining || 0; }
else if (sortKey === 'success') { vA = a.use_count || 0; vB = b.use_count || 0; }
else if (sortKey === 'fail') { vA = a.fail_count || 0; vB = b.fail_count || 0; }
else if (sortKey === 'rate') {
const totalA = (a.use_count || 0) + (a.fail_count || 0);
const totalB = (b.use_count || 0) + (b.fail_count || 0);
vA = totalA ? (a.use_count || 0) / totalA : 0;
vB = totalB ? (b.use_count || 0) / totalB : 0;
}
else if (sortKey === 'last_used') { vA = a.last_used_at || 0; vB = b.last_used_at || 0; }
if (vA < vB) return sortOrder === 'asc' ? -1 : 1;
if (vA > vB) return sortOrder === 'asc' ? 1 : -1;
return 0;
});
}
if (curPool !== 'all' && !poolsSet.has(curPool)) {
curPool = 'all';
return getTokenView();
}
_tokenViewCacheKey = cacheKey;
_tokenViewCache = {
stats,
statusCounts,
nsfwCounts,
poolCounts,
pools: Array.from(poolsSet),
filteredItems,
};
return _tokenViewCache;
}
function poolLabel(pool) {
return tr(`account.pool.${pool}`, null, pool);
}
function isDisabledStatus(status) {
return status === 'disabled';
}
// ── Anti-corruption checking indicators ──
function isInvalidStatus(status) {
return !['active', 'cooling', 'disabled'].includes(status);
}
function isManageableStatus(status) {
return status === 'active' || status === 'cooling';
}
function renderStats(view = getTokenView()) {
const { stats } = view;
$('s-total', allTokens.length);
$('s-active', stats.active);
$('s-cooling', stats.cooling);
$('s-invalid', stats.invalid);
$('s-disabled', stats.disabled);
$('s-calls', fmt(stats.calls));
$('s-success', fmt(stats.success));
$('s-rate', fmtRate(stats.success, stats.fail));
$('s-qa', fmt(stats.qa)); $('s-qf', fmt(stats.qf)); $('s-qe', fmt(stats.qe)); $('s-qh', fmt(stats.qh)); $('s-qc', fmt(stats.qc));
}
function renderFilters(view = getTokenView()) {
renderStatusFilters(view);
renderNsfwFilters(view);
renderPoolFilters(view);
syncFilterTrigger();
}
function initFilterMenu() {
if (_filterMenuBound) return;
const menu = document.getElementById('filter-menu');
const trigger = document.getElementById('btn-filter');
const panel = document.getElementById('filter-panel');
if (!menu || !trigger || !panel) return;
_filterMenuBound = true;
const close = () => {
menu.classList.remove('open');
trigger.setAttribute('aria-expanded', 'false');
syncFilterTrigger();
};
trigger.addEventListener('click', (event) => {
event.stopPropagation();
const open = !menu.classList.contains('open');
menu.classList.toggle('open', open);
trigger.setAttribute('aria-expanded', open ? 'true' : 'false');
syncFilterTrigger();
});
panel.addEventListener('click', (event) => event.stopPropagation());
document.addEventListener('click', (event) => {
const target = event.target;
if (!(target instanceof Node) || !menu.contains(target)) close();
});
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') close();
});
}
function syncFilterTrigger() {
const menu = document.getElementById('filter-menu');
const trigger = document.getElementById('btn-filter');
if (!menu || !trigger) return;
const active = curStatus !== 'all' || curPool !== 'all' || curNsfw !== 'all' || menu.classList.contains('open');
trigger.classList.toggle('is-active', active);
}
function renderStatusFilters(view = getTokenView()) {
setFilterCount('fc-status-all', view.statusCounts.all);
setFilterCount('fc-status-active', view.statusCounts.active);
setFilterCount('fc-status-cooling', view.statusCounts.cooling);
setFilterCount('fc-status-invalid', view.statusCounts.invalid);
setFilterCount('fc-status-disabled', view.statusCounts.disabled);
document.querySelectorAll('[data-status]').forEach(el => el.classList.toggle('active', el.dataset.status === curStatus));
}
function renderNsfwFilters(view = getTokenView()) {
setFilterCount('fc-nsfw-all', view.nsfwCounts.all);
setFilterCount('fc-nsfw-enabled', view.nsfwCounts.enabled);
setFilterCount('fc-nsfw-disabled', view.nsfwCounts.disabled);
document.querySelectorAll('[data-nsfw]').forEach(el => el.classList.toggle('active', el.dataset.nsfw === curNsfw));
}
function renderPoolFilters(view = getTokenView()) {
const wrap = document.getElementById('pool-filter-chips');
if (!wrap) return;
const pools = view.pools;
wrap.innerHTML = [
`<button type="button" class="filter-chip${curPool === 'all' ? ' active' : ''}" data-pool="all" onclick="switchPool('all')"><span>${tr('account.filterTypeAll', null, '全部')}</span><span class="filter-chip-count">${view.poolCounts.get('all') || 0}</span></button>`,
...pools.map(pool => {
const count = view.poolCounts.get(pool) || 0;
return `<button type="button" class="filter-chip${curPool === pool ? ' active' : ''}" data-pool="${xe(pool)}" onclick="switchPool('${xe(pool)}')"><span>${xe(poolLabel(pool))}</span><span class="filter-chip-count">${count}</span></button>`;
}),
].join('');
}
function setFilterCount(id, value) {
const el = document.getElementById(id);
if (el) el.textContent = value;
}
function applyPoolFilter(items, pool = curPool) {
if (pool === 'all') return items;
return items.filter(t => (t.pool || 'basic') === pool);
}
function applyStatusFilter(items, status = curStatus) {
if (status === 'all') return items;
if (status === 'invalid') return items.filter(t => isInvalidStatus(t.status));
if (status === 'disabled') return items.filter(t => isDisabledStatus(t.status));
return items.filter(t => t.status === status);
}
function applyNsfwFilter(items, mode = curNsfw) {
if (mode === 'all') return items;
if (mode === 'enabled') return items.filter(t => (t.tags || []).includes('nsfw'));
return items.filter(t => !(t.tags || []).includes('nsfw'));
}
function filtered() {
return getTokenView().filteredItems;
}
function preserveScroll(fn) {
const y = window.scrollY;
fn();
requestAnimationFrame(() => window.scrollTo({ top: y, behavior: 'auto' }));
}
function renderTable(view = getTokenView()) {
const items = view.filteredItems;
const total = items.length;
const pages = Math.max(1, Math.ceil(total / pageSize));
if (curPage > pages) curPage = pages;
const slice = items.slice((curPage - 1) * pageSize, curPage * pageSize);
document.getElementById('tbody').innerHTML = slice.length
? slice.map(rowHtml).join('')
: `<tr><td colspan="10" class="empty-state">${tr('account.empty', null, '暂无 Token,请点击右上角导入或添加。')}</td></tr>`;
$('pagi-page', tr('account.pageIndicator', { current: total ? curPage : 0, total: pages }, `第 ${total ? curPage : 0} / ${pages} 页`));
$('section-table-count', total);
const prev = document.getElementById('btn-prev'), next = document.getElementById('btn-next');
prev.disabled = curPage <= 1; next.disabled = curPage >= pages;
updateBatchBtns();
}
function rowHtml(t) {
const q = t.quota || {};
const isNsfw = (t.tags || []).includes('nsfw');
const isDisabled = t.status === 'disabled';
const canManageNsfw = isManageableStatus(t.status);
const isRefreshing = refreshingTokens.has(t.token);
const success = t.use_count || 0;
const fail = t.fail_count || 0;
const nsfwBtn = isNsfw
? `<button type="button" class="row-nsfw-btn is-on" ${canManageNsfw ? `data-nsfw-token="${xe(t.token)}" data-nsfw-enabled="false"` : 'disabled'} data-tip="${xe(canManageNsfw ? tr('account.batchNsfwDisable', null, '关闭 NSFW') : tr('account.rowActionNotSupported', null, '当前状态不支持此操作'))}" aria-label="${xe(canManageNsfw ? tr('account.batchNsfwDisable', null, '关闭 NSFW') : tr('account.rowActionNotSupported', null, '当前状态不支持此操作'))}">
<svg viewBox="0 0 20 20" aria-hidden="true">
<circle cx="10" cy="10" r="7.25"/>
<text x="10" y="10.4">18</text>
</svg>
</button>`
: `<button type="button" class="row-nsfw-btn" ${canManageNsfw ? `data-nsfw-token="${xe(t.token)}" data-nsfw-enabled="true"` : 'disabled'} data-tip="${xe(canManageNsfw ? tr('account.batchNsfw', null, '开启 NSFW') : tr('account.rowActionNotSupported', null, '当前状态不支持此操作'))}" aria-label="${xe(canManageNsfw ? tr('account.batchNsfw', null, '开启 NSFW') : tr('account.rowActionNotSupported', null, '当前状态不支持此操作'))}">
<svg viewBox="0 0 20 20" aria-hidden="true">
<circle cx="10" cy="10" r="7.25"/>
<text x="10" y="10.4">18</text>
<path d="M14.8 5.2 5.2 14.8"/>
</svg>
</button>`;
return `<tr>
<td><input type="checkbox" class="cb row-cb" data-token="${xe(t.token)}" ${sel.has(t.token)?'checked':''} onchange="toggleRow(this)"></td>
<td><div class="token-stack">
<span class="tok">${mask(t.token)}</span>
<button onclick="copy('${xe(t.token)}')" class="row-icon-btn" data-tip="${xe(tr('account.actionCopy', null, '复制'))}" aria-label="${xe(tr('account.actionCopy', null, '复制'))}">
<svg viewBox="0 0 24 24" stroke-width="1.8"><rect x="9" y="9" width="10" height="10" rx="2"/><path d="M7 15H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h7a2 2 0 0 1 2 2v1"/></svg>
</button>
</div></td>
<td class="table-center"><span class="badge badge-${t.pool||'basic'}">${xe(poolLabel(t.pool || 'basic'))}</span></td>
<td class="table-center">${statusBadge(t.status)}</td>
<td data-quota-only><div class="quota-cell">${qpills(q)}</div></td>
<td class="table-center" style="font-variant-numeric:tabular-nums;color:#a1a1aa">${success}</td>
<td class="table-center" style="font-variant-numeric:tabular-nums;color:#71717a">${fail}</td>
<td class="table-center" style="font-variant-numeric:tabular-nums;color:#71717a">${fmtRate(success, fail)}</td>
<td style="font-size:12px;color:#71717a">${fmtDate(t.last_used_at)}</td>
<td><div class="row-actions">
${nsfwBtn}
<button onclick="${isDisabled ? `restoreOne('${xe(t.token)}')` : `disableOne('${xe(t.token)}')`}" class="row-icon-btn row-icon-btn-state" data-tip="${xe(isDisabled ? tr('account.actionRestore', null, '恢复账号') : tr('account.actionDisable', null, '禁用账号'))}" aria-label="${xe(isDisabled ? tr('account.actionRestore', null, '恢复账号') : tr('account.actionDisable', null, '禁用账号'))}">
${isDisabled
? '<svg viewBox="0 0 24 24" stroke-width="1.8"><path d="M3 12a9 9 0 1 0 3-6.708"/><path d="M3 4v5h5"/></svg>'
: '<svg viewBox="0 0 24 24" stroke-width="1.8"><circle cx="12" cy="12" r="8"/><path d="M8.5 8.5 15.5 15.5"/></svg>'}
</button>
<button onclick="refreshOne('${xe(t.token)}')" class="row-icon-btn${isRefreshing ? ' is-loading' : ''}" data-tip="${xe(isRefreshing ? tr('account.refreshing', { n: 1 }, '正在刷新 1 个账户…') : tr('account.actionRefresh', null, '刷新 Usage'))}" aria-label="${xe(tr('account.actionRefresh', null, '刷新 Usage'))}">
<svg viewBox="0 0 24 24" stroke-width="1.8"><path d="M20 11a8 8 0 0 0-14.6-4.6"/><path d="M4 4v5h5"/><path d="M4 13a8 8 0 0 0 14.6 4.6"/><path d="M20 20v-5h-5"/></svg>
</button>
<button onclick="openEdit('${xe(t.token)}')" class="row-icon-btn" data-tip="${xe(tr('account.actionEdit', null, '编辑'))}" aria-label="${xe(tr('account.actionEdit', null, '编辑'))}">
<svg viewBox="0 0 24 24" stroke-width="1.8"><path d="m4 20 4.5-1 9.5-9.5-3.5-3.5L5 15.5z"/><path d="m13.5 5.5 3.5 3.5"/></svg>
</button>
<button onclick="doDelete(['${xe(t.token)}'])" class="row-icon-btn row-icon-danger" data-tip="${xe(tr('account.actionDelete', null, '删除'))}" aria-label="${xe(tr('account.actionDelete', null, '删除'))}">
<svg viewBox="0 0 24 24" stroke-width="1.8"><path d="M5 7h14"/><path d="M9 7V4h6v3"/><path d="M8 10v7"/><path d="M12 10v7"/><path d="M16 10v7"/><path d="M7 7l1 13h8l1-13"/></svg>
</button>
</div></td>
</tr>`;
}
function qpills(q) {
const modes = [
['auto', 'A', 'q-a', true],
['fast', 'F', 'q-f', true],
['expert', 'E', 'q-e', true],
['heavy', 'H', 'q-h', true],
['grok_4_3', 'B', 'q-b', false],
['console', 'C', 'q-c', false],
];
return modes.map(([m,l,c,showEmpty]) => {
const win = q[m];
if (win == null) {
if (!showEmpty) return '';
return `<span class="q-pill q-z" data-tip="${xe(tr(`account.mode.${m}`, null, m))}: 0">${l}:0</span>`;
}
const r = win.remaining ?? null;
return `<span class="q-pill ${r ? c : 'q-z'}" data-tip="${xe(`${tr(`account.mode.${m}`, null, m)}: ${r ?? tr('account.unknown', null, '未知')}/${win.total ?? '?'}`)}">${l}:${r ?? '?'}</span>`;
}).join('');
}
// ── Nav & Pagination ────────────────────────────────────────────────────────
function switchStatus(status) {
preserveScroll(() => {
curStatus = status || 'all';
curPage = 1;
sel.clear();
renderFilters();
renderTable();
});
}
function switchNsfw(mode) {
preserveScroll(() => {
curNsfw = mode || 'all';
curPage = 1;
sel.clear();
renderFilters();
renderTable();
});
}
function switchPool(pool) {
preserveScroll(() => {
curPool = pool || 'all';
curPage = 1;
sel.clear();
renderFilters();
renderTable();
});
}
function prevPage() { if (curPage > 1) { curPage--; renderTable(); } }
function nextPage() {
const pages = Math.max(1, Math.ceil(getTokenView().filteredItems.length / pageSize));
if (curPage < pages) { curPage++; renderTable(); }
}
function changePageSize(v) {
const next = Number(v);
pageSize = PAGE_SIZE_OPTIONS.includes(next) ? next : 50;
localStorage.setItem(PAGE_SIZE_KEY, String(pageSize));
curPage = 1;
renderTable();
}
function toggleAll(checked) {
getTokenView().filteredItems.slice((curPage-1)*pageSize, curPage*pageSize).forEach(t => checked ? sel.add(t.token) : sel.delete(t.token));
document.querySelectorAll('.row-cb').forEach(el => el.checked = checked);
updateBatchBtns();
}
function toggleRow(el) {
el.checked ? sel.add(el.dataset.token) : sel.delete(el.dataset.token);
const page = getTokenView().filteredItems.slice((curPage-1)*pageSize, curPage*pageSize);
const cbAll = document.getElementById('cb-all');
cbAll.checked = page.every(t => sel.has(t.token));
cbAll.indeterminate = !cbAll.checked && sel.size > 0;
updateBatchBtns();
}
function updateBatchBtns() {
const show = sel.size > 0;
const globalBtns = ['btn-nsfw-all','btn-refresh-all','btn-delete-invalid-all'];
const selectionBtns = ['btn-nsfw','btn-refresh','btn-disable','btn-restore','btn-delete','btn-delete-invalid'];
globalBtns.forEach(id => document.getElementById(id).style.display = show ? 'none' : '');
selectionBtns.forEach(id => document.getElementById(id).style.display = show ? '' : 'none');
}
// ── Helpers ────────────────────────────────────────────────────────────────
function $(id, v) { const el = document.getElementById(id); if (el) el.textContent = v; }
function fmt(n) { return n >= 10000 ? (n/1000).toFixed(1)+'k' : n; }
function loadSavedPageSize() {
const raw = Number(localStorage.getItem(PAGE_SIZE_KEY) || 0);
return PAGE_SIZE_OPTIONS.includes(raw) ? raw : 50;
}
function fmtRate(success, fail) {
const total = success + fail;
if (!total) return tr('account.na', null, '—');
return `${Math.round(success / total * 100)}%`;
}
function mask(t) { return t.length > 20 ? t.slice(0,8) + '…' + t.slice(-8) : t; }
function xe(s) { return s.replace(/\\/g,'\\\\').replace(/'/g,"\\'").replace(/"/g,'"'); }
function fmtDate(d) {
if (!d) return tr('account.na', null, '—');
const dt = new Date(typeof d === 'number' ? d : d);
return isNaN(dt)
? tr('account.na', null, '—')
: dt.toLocaleDateString(I18n.getLang() === 'en' ? 'en-US' : 'zh-CN', {month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit'});
}
function statusBadge(s) {
const m = {
active:['badge-active', tr('account.status.active', null, '正常')],
cooling:['badge-cooling', tr('account.status.cooling', null, '限流')],
expired:['badge-expired', tr('account.status.expired', null, '过期')],
disabled:['badge-disabled', tr('account.status.disabled', null, '禁用')],
invalid:['badge-invalid', tr('account.status.invalid', null, '异常')],
};
const [cls, label] = m[s] || ['badge-invalid', s || tr('account.unknown', null, '未知')];
return `<span class="badge ${cls}">${label}</span>`;
}
async function copy(t) {
try { await navigator.clipboard.writeText(t); showToast(tr('account.copied', null, '已复制'), 'success'); }
catch { showToast(tr('account.copyFailed', null, '复制失败'), 'error'); }
}
// ── Add / Import ───────────────────────────────────────────────────────────
function fillImportPoolOptions(id) {
const known = [...new Set(['basic', 'super', 'heavy', ...allTokens.map(t => t.pool || 'basic')])];
const opts = [
`<option value="auto">${xe(tr('account.pool.autoRecommended', null, '自动检测(推荐)'))}</option>`,
...known.map(p => `<option value="${p}">${xe(poolLabel(p))}</option>`),
];
document.getElementById(id).innerHTML = opts.join('');
}
function fillPoolOptions(id) {
const pools = [...new Set(['basic', 'super', 'heavy', ...allTokens.map(t => t.pool || 'basic')])];
document.getElementById(id).innerHTML = pools.map(p => `<option value="${p}">${xe(poolLabel(p))}</option>`).join('');
}
function openAdd() {
document.getElementById('import-tokens').value = '';
fillImportPoolOptions('import-pool');
openModal('modal-import');
}
function openImport() {
document.getElementById('import-file').value = '';
updateImportFileState();
fillImportPoolOptions('import-file-pool');
openModal('modal-import-file');
}
function openEdit(token) {
const item = allTokens.find(t => t.token === token);
if (!item) return showToast(tr('account.notFound', null, '账户不存在'), 'error');
_editingToken = item.token;
document.getElementById('edit-token').value = item.token;
fillPoolOptions('edit-pool');
document.getElementById('edit-pool').value = item.pool || 'basic';
openModal('modal-edit');
}
async function doAdd() {
const raw = document.getElementById('import-tokens').value;
const pool = document.getElementById('import-pool').value;
const autoNsfw = document.getElementById('import-auto-nsfw').checked;
const newToks = raw.split('\n').map(s => s.trim()).filter(Boolean);
if (!newToks.length) return showToast(tr('account.enterToken', null, '请输入 Token'), 'error');
return saveTokens(
pool,
newToks,
autoNsfw,
'modal-import',
tr('account.adding', { n: newToks.length }, `正在添加 ${newToks.length} 个账户…`),
tr('account.addDone', null, '添加完成'),
tr('account.addFailed', null, '添加失败'),
);
}
async function doImport() {
const file = document.getElementById('import-file').files?.[0];
if (!file) return showToast(tr('account.selectFile', null, '请选择文件'), 'error');
const isJson = file.name.toLowerCase().endsWith('.json');
const autoNsfw = document.getElementById('import-file-auto-nsfw').checked;
let raw = '';
try { raw = await file.text(); } catch { return showToast(tr('account.readFileFailed', null, '读取文件失败'), 'error'); }
if (isJson) {
let parsed;
try { parsed = JSON.parse(raw); } catch { return showToast(tr('account.jsonInvalid', null, 'JSON 格式错误'), 'error'); }
if (typeof parsed !== 'object' || Array.isArray(parsed)) return showToast(tr('account.jsonShapeInvalid', null, 'JSON 格式不正确,应为 {pool:[tokens]} 结构'), 'error');
let total = 0;
Object.values(parsed).forEach(arr => { if (Array.isArray(arr)) total += arr.length; });
if (!total) return showToast(tr('account.jsonEmpty', null, 'JSON 文件中没有可导入的 Token'), 'error');
try {
showToast(tr('account.importing', { n: total }, `正在导入 ${total} 个账户…`), 'info');
await _api('POST', `/tokens?auto_nsfw=${autoNsfw}`, parsed);
closeModal('modal-import-file');
showToast(tr('account.importJsonDone', { n: total }, `导入完成,共 ${total} 个`), 'success');
load();
} catch (e) { showToast(`${tr('account.importFailed', null, '导入失败')}: ${e.message}`, 'error'); }
} else {
const pool = document.getElementById('import-file-pool').value;
const newToks = raw.split(/\r?\n/).map(s => s.trim()).filter(Boolean);
if (!newToks.length) return showToast(tr('account.fileEmpty', null, '文件中没有可导入的 Token'), 'error');
return saveTokens(
pool,
newToks,
autoNsfw,
'modal-import-file',
tr('account.importing', { n: newToks.length }, `正在导入 ${newToks.length} 个账户…`),
tr('account.importDone', null, '导入完成'),
tr('account.importFailed', null, '导入失败'),
);
}
}
async function doEdit() {
const token = document.getElementById('edit-token').value.trim();
const pool = document.getElementById('edit-pool').value;
if (!_editingToken) return;
if (!token) return showToast(tr('account.enterToken', null, '请输入 Token'), 'error');
try {
showToast(tr('account.saving', null, '正在保存修改…'), 'info');
await _api('PUT', '/tokens/edit', { old_token: _editingToken, token, pool });
closeModal('modal-edit');
_editingToken = '';
showToast(tr('account.editDone', null, '编辑完成'), 'success');
load();
} catch (e) { showToast(`${tr('account.editFailed', null, '编辑失败')}: ${e.message}`, 'error'); }
}
function updateImportFileState() {
const file = document.getElementById('import-file').files?.[0];
const el = document.getElementById('import-file-name');
if (!el) return;
el.textContent = file ? file.name : tr('account.noFile', null, '未选择文件');
el.classList.toggle('empty', !file);
const isJson = file && file.name.toLowerCase().endsWith('.json');
const poolRow = document.getElementById('import-file-pool-row');
const hint = document.getElementById('import-file-hint');
if (poolRow) poolRow.style.display = isJson ? 'none' : '';
if (hint) hint.textContent = isJson
? tr('account.importHintJson', null, 'JSON 文件已包含 pool 信息,无需选择类型')
: tr('account.importHintTxt', null, '每行一个 Token,将添加到所选类型');
}
async function saveTokens(pool, newToks, autoNsfw, modalId, pendingMessage, successPrefix, errorPrefix) {
const unique = [...new Set(newToks)];
try {
showToast(pendingMessage, 'info');
const d = await _api('POST', `/tokens/add?auto_nsfw=${autoNsfw}`, { pool, tokens: unique });
closeModal(modalId);
const msg = d.skipped
? tr('account.saveResultSkipped', { prefix: successPrefix, count: d.count, skipped: d.skipped }, `${successPrefix},新增 ${d.count},已存在跳过 ${d.skipped}`)
: tr('account.saveResult', { prefix: successPrefix, count: d.count }, `${successPrefix},新增 ${d.count} 个`);
showToast(msg, 'success');
load();
} catch (e) { showToast(`${errorPrefix}: ${e.message}`, 'error'); }
}
// ── Export ─────────────────────────────────────────────────────────────────
function doExport() {
const tokens = filtered();
if (!tokens.length) return showToast(tr('account.exportEmpty', null, '当前没有可导出的 Token'), 'error');
openModal('modal-export');
document.getElementById('exp-count').textContent = tokens.length;
document.getElementById('exp-json-btn').onclick = () => {
closeModal('modal-export');
const out = {};
tokens.forEach(t => (out[t.pool||'basic'] = out[t.pool||'basic']||[]).push({token:t.token,tags:t.tags||[]}));
_download(JSON.stringify(out,null,2), `tokens-${currentFilterSuffix()}.json`, 'application/json');
};
document.getElementById('exp-txt-btn').onclick = () => {
closeModal('modal-export');
_download(tokens.map(t => t.token).join('\n'), `tokens-${currentFilterSuffix()}.txt`, 'text/plain');
};
}
function currentFilterSuffix() {
return [curStatus, curNsfw, curPool].filter(Boolean).join('-');
}
function _download(content, filename, mime) {
const a = document.createElement('a');
a.href = URL.createObjectURL(new Blob([content], {type: mime}));
a.download = filename; a.click();
}
// ── Delete ─────────────────────────────────────────────────────────────────
function doDelete(tokens) {
const n = tokens.length;
openConfirm(tr('account.deleteConfirmTitle', null, '确认删除'),
n === 1
? tr('account.deleteConfirmOne', { token: `<code>${mask(tokens[0])}</code>` }, `确认删除 <code>${mask(tokens[0])}</code>?<br><small style="color:#f87171">此操作不可撤销。</small>`)
: tr('account.deleteConfirmMany', { n }, `确认删除 <b>${n}</b> 个账户?<br><small style="color:#f87171">此操作不可撤销。</small>`),
async () => {
try {
showToast(tr('account.deleting', { n }, `正在删除 ${n} 个账户…`), 'info');
await _api('DELETE', '/tokens', tokens);
tokens.forEach(t => sel.delete(t));
showToast(tr('account.deleteDone', { n }, `已删除 ${n} 个`), 'success');
load();
} catch (e) { showToast(`${tr('account.deleteFailed', null, '删除失败')}: ${e.message}`, 'error'); }
});
}
function batchDeleteSel() { if (sel.size) doDelete([...sel]); }
function selectedInvalidTokens() {
return allTokens
.filter(t => sel.has(t.token) && isInvalidStatus(t.status))
.map(t => t.token);
}
function invalidTokenCount() {
return allTokens.filter(t => isInvalidStatus(t.status)).length;
}
function batchDeleteInvalidSel() {
const tokens = selectedInvalidTokens();
if (!tokens.length) return showToast(tr('account.noInvalidSelected', null, '选中项中没有异常账户'), 'error');
doDelete(tokens);
}
function deleteAllInvalid() {
const total = invalidTokenCount();
if (!total) return showToast(tr('account.noInvalidAccounts', null, '没有可删除的异常账户'), 'error');
openConfirm(
tr('account.deleteInvalidAllTitle', null, '删除全部异常账户'),
tr('account.deleteInvalidAllBody', { n: total }, `确认删除全部 <b>${total}</b> 个异常账户?<br><small style="color:#f87171">此操作不可撤销。确认后还需要输入 DELETE。</small>`),
async () => {
const typed = window.prompt(tr('account.deleteInvalidTypeConfirm', null, '输入 DELETE 确认删除全部异常账户'));
if (typed !== 'DELETE') return showToast(tr('account.cancelled', null, '已取消'), 'error');
try {
showToast(tr('account.deleting', { n: total }, `正在删除 ${total} 个账户…`), 'info');
const d = await _api('DELETE', '/tokens/invalid');
showToast(tr('account.deleteDone', { n: d.deleted || 0 }, `已删除 ${d.deleted || 0} 个`), 'success');
sel.clear();
load();
} catch (e) {
showToast(`${tr('account.deleteFailed', null, '删除失败')}: ${e.message}`, 'error');
}
}
);
}
// ── Batch SSE runner ───────────────────────────────────────────────────────
let _batchTaskId = null;
let _batchEs = null;
let _batchStarting = false;
async function _runBatch(endpoint, tokens, label, onDone) {
if (_batchStarting || _batchEs) {
showToast(tr('account.batchRunning', null, '已有批量任务正在运行'), 'error');
return;
}
_batchStarting = true;
const btnCancel = document.getElementById('btn-batch-cancel');
const globalActionIds = ['btn-nsfw-all','btn-refresh-all','btn-delete-invalid-all'];
globalActionIds.forEach(id => document.getElementById(id).style.display = 'none');
['btn-nsfw','btn-refresh','btn-disable','btn-restore','btn-delete','btn-delete-invalid'].forEach(id =>
document.getElementById(id).style.display = 'none');
btnCancel.style.display = '';
const progress = showProgressToast(label);
let _finalReceived = false;
function _cleanup() {
_batchStarting = false;
globalActionIds.forEach(id => document.getElementById(id).style.display = '');
btnCancel.style.display = 'none';
updateBatchBtns();
}
function _done(es) {
_finalReceived = true;
es.close(); _batchEs = null; _batchTaskId = null;
_cleanup();
}
try {
const join = endpoint.includes('?') ? '&' : '?';
const d = await _api('POST', `${endpoint}${join}async=true`, { tokens });
_batchTaskId = d.task_id;
const total = d.total || tokens.length;
const key = await adminKey.get();
const es = new EventSource(`${ADMIN_API}/batch/${_batchTaskId}/stream?app_key=${encodeURIComponent(key)}`);
_batchEs = es;
_batchStarting = false;
es.onmessage = (e) => {
const ev = JSON.parse(e.data);
if (ev.type === 'snapshot' || ev.type === 'progress') {
progress.update(ev.processed || 0, total);
}
if (['done', 'error', 'cancelled'].includes(ev.type)) {
_done(es);
if (ev.type === 'done') {
const s = ev.result?.summary || {};
const ok = s.ok ?? 0, fail = s.fail ?? 0;
const expired = s.expired ?? 0, transient = s.transient ?? (fail - expired);
let finishMsg = `${label.replace('…','').replace('正在','')} 完成:成功 ${ok}`;
if (expired > 0) finishMsg += `,异常 ${expired}`;
if (transient > 0) finishMsg += `,临时失败 ${transient}`;
progress.finish(finishMsg, fail > 0 ? 'error' : 'success');
onDone(ok, fail, s);
load();
} else if (ev.type === 'cancelled') {
progress.finish('已取消', 'error');
} else {
progress.finish(ev.error || '操作失败', 'error');
}
}
};
es.onerror = function() {
if (_finalReceived) { _batchEs = null; return; }
if (this.readyState === EventSource.CLOSED) {
_batchEs = null;
_batchTaskId = null;
_cleanup();
progress.finish('连接中断', 'error');
}
};
} catch (e) {
_cleanup();
progress.finish(`启动失败: ${e.message}`, 'error');
}
}
async function cancelBatch() {
if (!_batchTaskId) return;
showToast('已暂停,请耐心等待本批次完成…', 'info');
try { await _api('POST', `/batch/${_batchTaskId}/cancel`); } catch {}
}
// ── Refresh ────────────────────────────────────────────────────────────────
async function refreshOne(token) {
if (refreshingTokens.has(token)) return;
refreshingTokens.add(token);
renderTable();
try {
showToast(tr('account.refreshing', { n: 1 }, '正在刷新 1 个账户…'), 'info');
const d = await _api('POST', '/batch/refresh', { tokens:[token] });
showToast(tr('account.refreshDone', { ok: d.summary?.ok ?? 0, fail: d.summary?.fail ?? 0 }, `刷新完成:成功 ${d.summary?.ok??0},失败 ${d.summary?.fail??0}`), 'success');
await load();
} catch (e) { showToast(`${tr('account.refreshFailed', null, '刷新失败')}: ${e.message}`, 'error'); }
finally {
refreshingTokens.delete(token);
renderTable();
}
}
async function setDisabled(token, disabled) {
const masked = mask(token);
const title = disabled
? tr('account.disableConfirmTitle', null, '禁用账号')
: tr('account.restoreConfirmTitle', null, '恢复账号');
const body = disabled
? tr('account.disableConfirmBody', { token: `<code>${masked}</code>` }, `确认禁用 <code>${masked}</code>?<br><small style="color:#a1a1aa">禁用后该账号不会参与请求分配。</small>`)
: tr('account.restoreConfirmBody', { token: `<code>${masked}</code>` }, `确认恢复 <code>${masked}</code>?<br><small style="color:#a1a1aa">恢复后该账号将重新参与请求分配。</small>`);
openConfirm(title, body, async () => {
try {
showToast(
disabled
? tr('account.disablingOne', null, '正在禁用账号…')
: tr('account.restoringOne', null, '正在恢复账号…'),
'info',
);
await _api('POST', '/tokens/disabled', { token, disabled });
showToast(
disabled
? tr('account.disableDone', null, '账号已禁用')
: tr('account.restoreDone', null, '账号已恢复'),
'success',
);
await load();
} catch (e) {
showToast(`${tr('account.operationFailed', null, '操作失败')}: ${e.message}`, 'error');
}
});
}
function disableOne(token) { setDisabled(token, true); }
function restoreOne(token) { setDisabled(token, false); }
function batchSetDisabled(disabled) {
if (!sel.size) return;
const tokens = [...sel];
const n = tokens.length;
const title = disabled
? tr('account.batchDisableConfirmTitle', null, '批量禁用账号')
: tr('account.batchRestoreConfirmTitle', null, '批量恢复账号');
const body = disabled
? tr('account.batchDisableConfirmBody', { n }, `确认禁用选中的 <b>${n}</b> 个账户?<br><small style="color:#a1a1aa">禁用后这些账号不会参与请求分配,但可随时恢复。</small>`)
: tr('account.batchRestoreConfirmBody', { n }, `确认恢复选中的 <b>${n}</b> 个账户?<br><small style="color:#a1a1aa">恢复后这些账号将重新参与请求分配。</small>`);
openConfirm(title, body, async () => {
try {
showToast(
disabled
? tr('account.disablingMany', { n }, `正在禁用 ${n} 个账户…`)
: tr('account.restoringMany', { n }, `正在恢复 ${n} 个账户…`),
'info',
);
const d = await _api('POST', '/tokens/disabled/batch', { tokens, disabled });
const ok = d.summary?.ok ?? 0;
const fail = d.summary?.fail ?? 0;
showToast(
disabled
? tr('account.disableManyDone', { ok, fail }, `禁用完成:成功 ${ok} 个,失败 ${fail} 个`)
: tr('account.restoreManyDone', { ok, fail }, `恢复完成:成功 ${ok} 个,失败 ${fail} 个`),
fail > 0 ? 'error' : 'success',
);
sel.clear();
await load();
} catch (e) {
showToast(`${tr('account.operationFailed', null, '操作失败')}: ${e.message}`, 'error');
}
});
}
function batchDisableSel() { batchSetDisabled(true); }
function batchRestoreSel() { batchSetDisabled(false); }
async function batchRefreshSel() {
if (!sel.size) return;
await _runBatch('/batch/refresh', [...sel],
tr('account.refreshing', { n: sel.size }, `正在刷新 ${sel.size} 个账户…`),
(ok, fail, s) => {
const expired = s?.expired ?? 0, transient = s?.transient ?? (fail - expired);
let msg = `刷新完成:成功 ${ok}`;
if (expired > 0) msg += `,异常 ${expired}`;
if (transient > 0) msg += `,临时失败 ${transient}`;
showToast(msg, fail > 0 ? 'warning' : 'success');
}
);
}
function manageableTokens() {
return allTokens
.filter(t => isManageableStatus(t.status))
.map(t => t.token);
}
function selectedManageableTokens() {
return allTokens
.filter(t => sel.has(t.token) && isManageableStatus(t.status))
.map(t => t.token);
}
function batchRefreshAllManageable() {
const n = manageableTokens().length;
if (!n) return showToast(tr('account.noManageableAccounts', null, '没有可操作的可用账户'), 'error');
openConfirm(
tr('account.refreshAllConfirmTitle', null, '重新测试全部正常账户'),
tr('account.refreshAllConfirmBody', { n }, `重新测试全部 <b>${n}</b> 个正常/限流账户的运行状态?<br><small style="color:#a1a1aa">该操作会调用上游接口,并按后端并发上限 50 分批执行。</small>`),
async () => _runBatch('/batch/refresh?all_manageable=true', [],
tr('account.refreshAllRunning', { n }, `正在重新测试 ${n} 个账户…`),
(ok, fail, s) => {
const expired = s?.expired ?? 0, transient = s?.transient ?? (fail - expired);
let msg = `刷新完成:成功 ${ok}`;
if (expired > 0) msg += `,异常 ${expired}`;
if (transient > 0) msg += `,临时失败 ${transient}`;
showToast(msg, fail > 0 ? 'warning' : 'success');
}
)
);
}
// ── NSFW ───────────────────────────────────────────────────────────────────
async function nsfwOne(token, enabled = true) {
try {
showToast(enabled
? tr('account.nsfwEnablingOne', null, '正在开启 NSFW…')
: tr('account.nsfwDisablingOne', null, '正在关闭 NSFW…'), 'info');
const d = await _api('POST', `/batch/nsfw?enabled=${enabled ? 'true' : 'false'}`, { tokens: [token] });
showToast(enabled
? tr('account.nsfwDone', { ok: d.summary?.ok ?? 0, fail: d.summary?.fail ?? 0 }, `NSFW 已开启:成功 ${d.summary?.ok??0},失败 ${d.summary?.fail??0}`)
: tr('account.nsfwDisableDone', { ok: d.summary?.ok ?? 0, fail: d.summary?.fail ?? 0 }, `NSFW 已关闭:成功 ${d.summary?.ok??0},失败 ${d.summary?.fail??0}`),
'success');
load();
} catch (e) { showToast(`${tr('account.operationFailed', null, '操作失败')}: ${e.message}`, 'error'); }
}
function batchNSFW() {
if (!sel.size) return;
const tokens = selectedManageableTokens();
if (!tokens.length) return showToast(tr('account.noManageableAccounts', null, '没有可操作的可用账户'), 'error');
openConfirm(
tr('account.nsfwConfirmTitle', null, '开启 NSFW'),
tr('account.nsfwConfirmBody', { n: tokens.length }, `为选中的 <b>${tokens.length}</b> 个正常/限流账户开启 NSFW?`),
async () => _runBatch('/batch/nsfw', tokens,
tr('account.nsfwEnabling', { n: tokens.length }, `正在为 ${tokens.length} 个账户开启 NSFW…`),
(ok, fail) => showToast(tr('account.nsfwDone', { ok, fail }, `NSFW 完成:成功 ${ok},失败 ${fail}`), 'success')
)
);
}
function batchNSFWAll() {
const n = manageableTokens().length;
if (!n) return showToast(tr('account.noManageableAccounts', null, '没有可操作的可用账户'), 'error');
openConfirm(
tr('account.nsfwAllConfirmTitle', null, '全部开启 NSFW'),
tr('account.nsfwAllConfirmBody', { n }, `为全部 <b>${n}</b> 个正常/限流账户开启 NSFW?<br><small style="color:#a1a1aa">该操作会按后端并发上限 50 分批执行。</small>`),
async () => _runBatch('/batch/nsfw?all_manageable=true', [],
tr('account.nsfwAllEnabling', { n }, `正在为 ${n} 个账户开启 NSFW…`),
(ok, fail) => showToast(tr('account.nsfwDone', { ok, fail }, `NSFW 完成:成功 ${ok},失败 ${fail}`), fail > 0 ? 'error' : 'success')
)
);
}
// ── Modal ──────────────────────────────────────────────────────────────────
function openModal(id) { document.getElementById(id).classList.add('open'); }
function closeModal(id) { document.getElementById(id).classList.remove('open'); }
function openConfirm(title, body, cb) {
_cb = async () => { closeModal('modal-confirm'); await cb(); };
document.getElementById('confirm-title').textContent = title;
document.getElementById('confirm-body').innerHTML = body;
openModal('modal-confirm');
}
document.querySelectorAll('.modal-overlay').forEach(el =>
el.addEventListener('click', e => { if (e.target === el) el.classList.remove('open'); }));
const _tooltipEl = document.createElement('div');
_tooltipEl.className = 'admin-tooltip';
document.body.appendChild(_tooltipEl);
let _tooltipTarget = null;
function _placeTooltip(x, y) {
const pad = 12;
const rect = _tooltipEl.getBoundingClientRect();
const maxX = window.innerWidth - rect.width - pad;
const maxY = window.innerHeight - rect.height - pad;
const left = Math.max(pad, Math.min(x + 14, maxX));
const top = Math.max(pad, Math.min(y + 16, maxY));
_tooltipEl.style.left = `${left}px`;
_tooltipEl.style.top = `${top}px`;
}
function _showTooltip(target, x, y) {
const text = target?.getAttribute('data-tip');
if (!text) return;
_tooltipTarget = target;
_tooltipEl.textContent = text;
_tooltipEl.classList.add('show');
_placeTooltip(x, y);
}
function _hideTooltip() {
_tooltipTarget = null;
_tooltipEl.classList.remove('show');
}
document.addEventListener('mouseover', (e) => {
const target = e.target.closest('[data-tip]');
if (!target) return _hideTooltip();
_showTooltip(target, e.clientX, e.clientY);
});
document.addEventListener('mousemove', (e) => {
if (_tooltipTarget) _placeTooltip(e.clientX, e.clientY);
});
document.addEventListener('mouseout', (e) => {
if (!_tooltipTarget) return;
const next = e.relatedTarget;
if (next && _tooltipTarget.contains(next)) return;
if (e.target.closest('[data-tip]') === _tooltipTarget) _hideTooltip();
});
document.addEventListener('focusin', (e) => {
const target = e.target.closest('[data-tip]');
if (!target) return;
const rect = target.getBoundingClientRect();
_showTooltip(target, rect.left + rect.width / 2, rect.top);
});
document.addEventListener('focusout', (e) => {
if (e.target.closest('[data-tip]')) _hideTooltip();
});
document.addEventListener('click', (e) => {
const btn = e.target.closest('[data-nsfw-token]');
if (!btn) return;
e.preventDefault();
const token = btn.getAttribute('data-nsfw-token');
const enabled = btn.getAttribute('data-nsfw-enabled') === 'true';
if (token) nsfwOne(token, enabled);
});
</script>
</body>
</html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title data-i18n="account.pageTitle">Grok2API - 账户管理</title>
<link rel="icon" href="/favicon.ico?v={{APP_VERSION}}">
<link href="https://cdn.jsdelivr.net/npm/geist@1.0.0/dist/fonts/geist-sans/style.css" rel="stylesheet">
<link href="/static/css/app.css?v={{APP_VERSION}}" rel="stylesheet">
<style>
body { background: #141416; color: #f4f4f5; }
/* Page header */
.page-hd { display:flex; align-items:flex-start; justify-content:space-between; margin-bottom:20px }
.page-title{ font-size:22px; font-weight:700; line-height:1.2; color: #f4f4f5; }
.page-sub { font-size:13px; color:#a1a1aa; margin-top:5px }
.page-actions { display:flex; gap:8px; align-items:center; flex-shrink:0 }
.section-head {
display:flex;
align-items:baseline;
justify-content:space-between;
gap:12px;
margin:28px 0 14px;
}
.section-title {
font-size:13px;
font-weight:600;
color:#e4e4e7;
letter-spacing:.01em;
}
.section-title-row {
display:inline-flex;
align-items:center;
gap:8px;
}
.section-count-badge {
min-width:20px;
height:20px;
padding:0 7px;
border-radius:999px;
display:inline-flex;
align-items:center;
justify-content:center;
background:#2d2d34;
color:#a1a1aa;
font-size:11px;
font-weight:600;
font-variant-numeric:tabular-nums;
line-height:1;
}
.page-action-btn {
height:32px;
padding:0 14px;
border-radius:999px;
display:inline-flex;
align-items:center;
justify-content:center;
gap:6px;
font-size:13px;
font-weight:600;
border:1px solid #3f3f46;
background:#202024;
color:#e4e4e7;
}
.page-action-btn:hover {
background:#2d2d34;
border-color:#52525b;
}
.page-action-btn-primary {
background:#f4f4f5;
border-color:#f4f4f5;
color:#141416;
}
.page-action-btn-primary:hover {
background:#e4e4e7;
border-color:#e4e4e7;
}
/* Stats */
.stat-grid {
display:grid;
grid-template-columns:repeat(5, minmax(0, 1fr));
gap:12px;
margin-bottom:20px;
}
.stat-grid.mode-random {
grid-template-columns:repeat(4, minmax(0, 1fr));
}
.stat-grid-quota {
display:grid;
grid-template-columns:repeat(6, minmax(0, 1fr));
gap:12px;
margin-bottom:20px;
}
.stat-cell {
min-height:88px;
padding:14px 16px;
border-radius:12px;
background:#202024;
border:1px solid #2d2d34;
display:flex;