feat: refine account management UI

Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
Zyy
2026-06-26 18:40:20 +08:00
co-authored by Codex
parent 4775cb6fc7
commit a7244c4eb2
18 changed files with 1146 additions and 195 deletions
+52 -45
View File
@@ -18,7 +18,7 @@ use crate::{
admin::auth::session::require_admin_session,
admin::response::{AdminEnvelope, AdminError, AdminPageEnvelope, AdminResponse},
admin::{
accounts::service::{AdminAccountError, AdminAccountMetadata},
accounts::service::{AdminAccountError, AdminAccountMetadata, AdminAccountMetadataUpdate},
monitoring::{
billing,
event_store::AdminLogFilter,
@@ -806,28 +806,13 @@ pub(crate) async fn update_account(
require_admin_session(&state, &headers, &request_id).await?;
match parse_account_update(payload, &request_id)? {
ParsedAccountUpdate::Single { id, label, status } => {
if let Some(label) = label {
match state.services.admin_accounts.update_label(&id, label).await {
Ok(true) => {}
Ok(false) => return Err(account_not_found(request_id)),
Err(error) => return Err(account_error(error, request_id)),
}
}
if let Some(status) = status {
match state
.services
.admin_accounts
.update_status(&id, &status)
.await
{
Ok(Some(_)) => {}
Ok(None) => return Err(account_not_found(request_id)),
Err(error) => return Err(account_error(error, request_id)),
}
}
match state.services.admin_accounts.get(&id).await {
ParsedAccountUpdate::Single { id, update } => {
match state
.services
.admin_accounts
.update_metadata(&id, update)
.await
{
Ok(Some(account)) => Ok(AdminResponse::new(
StatusCode::OK,
AdminEnvelope::ok(
@@ -1395,8 +1380,7 @@ fn format_cost(value: f64) -> String {
enum ParsedAccountUpdate {
Single {
id: String,
label: Option<Option<String>>,
status: Option<String>,
update: AdminAccountMetadataUpdate,
},
BatchStatus {
ids: Vec<String>,
@@ -1425,7 +1409,10 @@ fn parse_account_update(
request_id,
));
}
if object.contains_key("label") {
if ["label", "email", "accountId", "userId", "planType"]
.iter()
.any(|field| object.contains_key(*field))
{
return Err(AdminError::new(
StatusCode::BAD_REQUEST,
40001,
@@ -1438,23 +1425,32 @@ fn parse_account_update(
return Ok(ParsedAccountUpdate::BatchStatus { ids, status });
}
let id = required_string_field(object, "id", request_id)?;
let label = object
.get("label")
.map(|value| optional_string_field(value, "label", request_id))
.transpose()?;
let label = optional_string_update_field(object, "label", request_id)?;
let email = optional_string_update_field(object, "email", request_id)?;
let account_id = optional_string_update_field(object, "accountId", request_id)?;
let user_id = optional_string_update_field(object, "userId", request_id)?;
let plan_type = optional_string_update_field(object, "planType", request_id)?;
let status = object
.get("status")
.map(|value| required_string_value(value, "status", request_id))
.transpose()?;
if label.is_none() && status.is_none() {
let update = AdminAccountMetadataUpdate {
email,
account_id,
user_id,
label,
plan_type,
status,
};
if !update.any() {
return Err(AdminError::new(
StatusCode::BAD_REQUEST,
40001,
"Account update request must include label or status",
"Account update request must include editable fields",
request_id,
));
}
Ok(ParsedAccountUpdate::Single { id, label, status })
Ok(ParsedAccountUpdate::Single { id, update })
}
fn required_string_field(
@@ -1536,18 +1532,29 @@ fn optional_string_field(
if value.is_null() {
return Ok(None);
}
value
.as_str()
.map(ToString::to_string)
.map(Some)
.ok_or_else(|| {
AdminError::new(
StatusCode::BAD_REQUEST,
40001,
format!("{field} must be a string or null"),
request_id,
)
})
match value.as_str() {
Some(value) => {
let value = value.trim();
Ok((!value.is_empty()).then(|| value.to_string()))
}
None => Err(AdminError::new(
StatusCode::BAD_REQUEST,
40001,
format!("{field} must be a string or null"),
request_id,
)),
}
}
fn optional_string_update_field(
object: &serde_json::Map<String, Value>,
field: &'static str,
request_id: &str,
) -> Result<Option<Option<String>>, AdminError> {
object
.get(field)
.map(|value| optional_string_field(value, field, request_id))
.transpose()
}
fn account_error(error: AdminAccountError, request_id: String) -> AdminError {
+49
View File
@@ -211,6 +211,55 @@ impl AdminAccountService {
Err(_) => Err(AdminAccountError::UpdateStatus),
}
}
pub async fn update_metadata(
&self,
account_id: &str,
update: AdminAccountMetadataUpdate,
) -> Result<Option<AdminAccountMetadata>, AdminAccountError> {
if !update.any() {
return self.get(account_id).await;
}
if update
.label
.as_ref()
.and_then(|label| label.as_ref())
.is_some_and(|label| label.chars().count() > 64)
{
return Err(AdminAccountError::LabelTooLong);
}
let status = update
.status
.as_deref()
.map(parse_account_status)
.transpose()?;
let should_evict = status.is_some();
let updated = self
.store
.update_metadata(
account_id,
crate::upstream::accounts::store::AccountMetadataUpdate {
email: update.email,
account_id: update.account_id,
user_id: update.user_id,
label: update.label,
plan_type: update.plan_type,
status,
},
)
.await
.map_err(|_| AdminAccountError::UpdateMetadata)?;
if !updated {
return Ok(None);
}
self.sync_account_pool_best_effort(account_id, "account metadata update")
.await;
if should_evict {
self.evict_account_websocket_pool(account_id).await;
}
self.get(account_id).await
}
pub async fn batch_delete(
&self,
ids: Vec<String>,
+2 -2
View File
@@ -20,8 +20,8 @@ use crate::{
};
pub use types::{
AdminAccountError, AdminAccountMetadata, BatchDeleteAccounts, BatchUpdateAccountStatus,
ImportedAccounts, UpdatedAccountStatus,
AdminAccountError, AdminAccountMetadata, AdminAccountMetadataUpdate, BatchDeleteAccounts,
BatchUpdateAccountStatus, ImportedAccounts, UpdatedAccountStatus,
};
#[derive(Clone)]
+23
View File
@@ -64,6 +64,8 @@ pub enum AdminAccountError {
NotFound,
#[error("failed to update label")]
UpdateLabel,
#[error("failed to update account metadata")]
UpdateMetadata,
#[error("failed to update status")]
UpdateStatus,
#[error("failed to delete account")]
@@ -116,6 +118,27 @@ pub struct UpdatedAccountStatus {
pub status: AcctStatus,
}
#[derive(Debug, Clone, Default)]
pub struct AdminAccountMetadataUpdate {
pub email: Option<Option<String>>,
pub account_id: Option<Option<String>>,
pub user_id: Option<Option<String>>,
pub label: Option<Option<String>>,
pub plan_type: Option<Option<String>>,
pub status: Option<String>,
}
impl AdminAccountMetadataUpdate {
pub fn any(&self) -> bool {
self.email.is_some()
|| self.account_id.is_some()
|| self.user_id.is_some()
|| self.label.is_some()
|| self.plan_type.is_some()
|| self.status.is_some()
}
}
#[derive(Debug, Clone)]
pub struct BatchDeleteAccounts {
pub deleted: u32,
+68
View File
@@ -165,6 +165,18 @@ select
from accounts
where id = ?";
const UPDATE_ACCOUNT_METADATA_SQL: &str = r"
update accounts
set
email = case when ? then ? else email end,
chatgpt_account_id = case when ? then ? else chatgpt_account_id end,
chatgpt_user_id = case when ? then ? else chatgpt_user_id end,
label = case when ? then ? else label end,
plan_type = case when ? then ? else plan_type end,
status = case when ? then ? else status end,
updated_at = ?
where id = ?";
const LIST_STORED_ACCOUNTS_AFTER_CURSOR_SQL: &str = r"
select
id,
@@ -694,6 +706,27 @@ pub struct StoredAccountMetadata {
pub updated_at: String,
}
#[derive(Debug, Clone, Default)]
pub struct AccountMetadataUpdate {
pub email: Option<Option<String>>,
pub account_id: Option<Option<String>>,
pub user_id: Option<Option<String>>,
pub label: Option<Option<String>>,
pub plan_type: Option<Option<String>>,
pub status: Option<AccountStatus>,
}
impl AccountMetadataUpdate {
pub fn any(&self) -> bool {
self.email.is_some()
|| self.account_id.is_some()
|| self.user_id.is_some()
|| self.label.is_some()
|| self.plan_type.is_some()
|| self.status.is_some()
}
}
/// 账号用量记录。
#[derive(Debug, Clone)]
pub struct AccountUsageRecord {
@@ -1066,6 +1099,37 @@ impl SqliteAccountStore {
row.as_ref().map(metadata_from_row).transpose()
}
/// 更新单账号元数据(不含 token)。
pub async fn update_metadata(
&self,
account_id: &str,
update: AccountMetadataUpdate,
) -> SqliteAccountStoreResult<bool> {
if !update.any() {
return Ok(false);
}
let now = Utc::now().to_rfc3339();
let status = update.status.map(status_to_db);
let result = sqlx::query(UPDATE_ACCOUNT_METADATA_SQL)
.bind(update.email.is_some())
.bind(optional_update_value(&update.email))
.bind(update.account_id.is_some())
.bind(optional_update_value(&update.account_id))
.bind(update.user_id.is_some())
.bind(optional_update_value(&update.user_id))
.bind(update.label.is_some())
.bind(optional_update_value(&update.label))
.bind(update.plan_type.is_some())
.bind(optional_update_value(&update.plan_type))
.bind(update.status.is_some())
.bind(status)
.bind(&now)
.bind(account_id)
.execute(&self.pool)
.await?;
Ok(result.rows_affected() > 0)
}
/// 更新账号 claims(含 refresh token)。
pub async fn update_from_claims(
&self,
@@ -1873,6 +1937,10 @@ fn status_to_db(status: AccountStatus) -> &'static str {
}
}
fn optional_update_value(value: &Option<Option<String>>) -> Option<&str> {
value.as_ref().and_then(|value| value.as_deref())
}
fn status_from_db(value: &str) -> SqliteAccountStoreResult<AccountStatus> {
match value {
"active" => Ok(AccountStatus::Active),
+33
View File
@@ -67,6 +67,39 @@ async fn admin_accounts_lifecycle_should_update_and_delete_accounts() {
assert_eq!(status.status(), StatusCode::OK);
assert_eq!(response_json(status).await["data"]["status"], "disabled");
let metadata = app
.clone()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/admin/accounts/update")
.header("content-type", "application/json")
.header("cookie", "cpr_admin_session=session_1")
.body(Body::from(
json!({
"id": "acct_lifecycle",
"label": null,
"email": "updated-life@example.com",
"accountId": "chatgpt-updated-life",
"userId": "user-updated-life",
"planType": "team",
"status": "active"
})
.to_string(),
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(metadata.status(), StatusCode::OK);
let metadata_body = response_json(metadata).await;
assert_eq!(metadata_body["data"]["label"], Value::Null);
assert_eq!(metadata_body["data"]["email"], "updated-life@example.com");
assert_eq!(metadata_body["data"]["accountId"], "chatgpt-updated-life");
assert_eq!(metadata_body["data"]["userId"], "user-updated-life");
assert_eq!(metadata_body["data"]["planType"], "team");
assert_eq!(metadata_body["data"]["status"], "active");
let deleted = app
.oneshot(
Request::builder()
+43 -6
View File
@@ -136,18 +136,28 @@ export function refreshAccount(accountId: string) {
})
}
export function updateAccountLabel(accountId: string, label: string | null) {
export interface UpdateAccountPayload {
label?: string | null
email?: string | null
accountId?: string | null
userId?: string | null
planType?: string | null
status?: Account['status']
}
export function updateAccount(accountId: string, payload: UpdateAccountPayload) {
return requestJson<Account>('/api/admin/accounts/update', {
method: 'POST',
data: { id: accountId, label },
data: { id: accountId, ...payload },
})
}
export function updateAccountLabel(accountId: string, label: string | null) {
return updateAccount(accountId, { label })
}
export function updateAccountStatus(accountId: string, status: Account['status']) {
return requestJson<Account>('/api/admin/accounts/update', {
method: 'POST',
data: { id: accountId, status },
})
return updateAccount(accountId, { status })
}
export function batchDeleteAccounts(accountIds: string[]) {
@@ -167,3 +177,30 @@ export function getAccountQuota(accountId: string) {
const params = new URLSearchParams({ id: accountId })
return requestJson<QuotaInfo>(`/api/admin/accounts/quota?${params}`)
}
export interface AccountHealthCheckSummary {
total: number
alive: number
dead: number
skipped: number
}
export interface AccountHealthCheckResult {
id: string
email?: string | null
result: 'alive' | 'dead' | string
error?: string
durationMs?: number
}
export interface AccountHealthCheckData {
summary: AccountHealthCheckSummary
results: AccountHealthCheckResult[]
}
export function testAccountConnection(accountId: string) {
return requestJson<AccountHealthCheckData>('/api/admin/accounts/health-check', {
method: 'POST',
data: { ids: [accountId] },
})
}
+28 -2
View File
@@ -5,12 +5,16 @@ const props = withDefaults(
padded?: boolean
radiusClass?: string
shadowClass?: string
headerClass?: string
bodyClass?: string
}>(),
{
as: 'section',
padded: true,
radiusClass: 'rounded-(--cp-card-radius)',
shadowClass: 'shadow-(--cp-shadow-card)',
headerClass: 'px-6 pt-6 pb-3 md:px-7',
bodyClass: '',
},
)
</script>
@@ -19,8 +23,30 @@ const props = withDefaults(
<component
:is="props.as"
class="[--cp-input-current-bg:var(--cp-input-soft-bg)] [--cp-input-current-bg-hover:var(--cp-input-soft-bg-hover)] overflow-hidden bg-(--cp-bg-surface)"
:class="[props.radiusClass, props.shadowClass, props.padded ? 'p-6 md:px-7' : undefined]"
:class="[
props.radiusClass,
props.shadowClass,
!$slots.header && !$slots.body && props.padded ? 'p-6 md:px-7' : undefined,
]"
>
<slot />
<template v-if="$slots.header || $slots.body">
<header v-if="$slots.header" class="shrink-0" :class="props.headerClass">
<slot name="header" />
</header>
<div
v-if="$slots.body || $slots.default"
:class="[
props.padded ? ($slots.header ? 'px-6 pb-6 md:px-7' : 'p-6 md:px-7') : undefined,
props.bodyClass,
]"
>
<slot name="body">
<slot />
</slot>
</div>
</template>
<slot v-else />
</component>
</template>
+175
View File
@@ -0,0 +1,175 @@
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, useAttrs, watch } from 'vue'
import type { CSSProperties } from 'vue'
type PopoverPlacement = 'bottom-start' | 'bottom-end' | 'top-start' | 'top-end'
defineOptions({
inheritAttrs: false,
})
const props = withDefaults(
defineProps<{
placement?: PopoverPlacement
offset?: number
width?: number | string
disabled?: boolean
panelClass?: string
}>(),
{
placement: 'bottom-end',
offset: 6,
disabled: false,
panelClass: '',
},
)
const open = defineModel<boolean>({ default: false })
const attrs = useAttrs()
const rootRef = ref<HTMLElement | null>(null)
const triggerRef = ref<HTMLElement | null>(null)
const popoverRef = ref<HTMLElement | null>(null)
const popoverStyle = ref<CSSProperties>({})
const popoverClasses = computed(() => [
'fixed z-50 overflow-visible rounded-(--cp-popover-radius) border-0 bg-(--cp-bg-surface) p-1.5 text-left shadow-(--cp-shadow-popover)',
props.panelClass,
])
const sizeStyle = computed<CSSProperties>(() => {
const width = toCssLength(props.width)
return width ? { width } : {}
})
function toCssLength(value?: number | string) {
if (typeof value === 'number') {
return `${value}px`
}
const trimmed = value?.trim()
return trimmed || undefined
}
function clamp(value: number, min: number, max: number) {
return Math.max(min, Math.min(value, max))
}
function updatePopoverPosition() {
if (!open.value || !triggerRef.value) return
const viewportPadding = 8
const triggerRect = triggerRef.value.getBoundingClientRect()
const panelRect = popoverRef.value?.getBoundingClientRect()
const panelWidth = Math.max(panelRect?.width ?? 0, toCssLength(props.width) ? 0 : triggerRect.width)
const panelHeight = panelRect?.height ?? 0
const belowSpace = window.innerHeight - triggerRect.bottom - props.offset
const aboveSpace = triggerRect.top - props.offset
const prefersTop = props.placement.startsWith('top')
const placeAbove = prefersTop
? !(aboveSpace < panelHeight && belowSpace > aboveSpace)
: belowSpace < panelHeight && aboveSpace > belowSpace
const rawTop = placeAbove
? triggerRect.top - panelHeight - props.offset
: triggerRect.bottom + props.offset
const maxTop = Math.max(viewportPadding, window.innerHeight - panelHeight - viewportPadding)
const top = panelHeight > 0 ? clamp(rawTop, viewportPadding, maxTop) : rawTop
const rawLeft = props.placement.endsWith('end')
? triggerRect.right - panelWidth
: triggerRect.left
const maxLeft = Math.max(viewportPadding, window.innerWidth - panelWidth - viewportPadding)
const left = clamp(rawLeft, viewportPadding, maxLeft)
popoverStyle.value = {
left: `${left}px`,
top: `${top}px`,
maxWidth: `calc(100vw - ${viewportPadding * 2}px)`,
...(toCssLength(props.width) ? {} : { minWidth: `${triggerRect.width}px` }),
}
}
async function openPopover() {
if (props.disabled || open.value) return
open.value = true
await nextTick()
updatePopoverPosition()
}
function closePopover() {
open.value = false
}
function togglePopover() {
if (open.value) {
closePopover()
return
}
void openPopover()
}
function handleTriggerKeydown(event: KeyboardEvent) {
if (event.key === 'Escape') {
closePopover()
}
}
function handleDocumentKeydown(event: KeyboardEvent) {
if (!open.value || event.key !== 'Escape') return
closePopover()
}
function handlePointerDown(event: PointerEvent) {
const target = event.target as Node | null
if (!target) return
if (rootRef.value?.contains(target) || popoverRef.value?.contains(target)) return
closePopover()
}
watch(open, async (isOpen) => {
if (!isOpen) return
await nextTick()
updatePopoverPosition()
})
onMounted(() => {
document.addEventListener('pointerdown', handlePointerDown)
document.addEventListener('keydown', handleDocumentKeydown)
window.addEventListener('resize', updatePopoverPosition)
window.addEventListener('scroll', updatePopoverPosition, true)
})
onBeforeUnmount(() => {
document.removeEventListener('pointerdown', handlePointerDown)
document.removeEventListener('keydown', handleDocumentKeydown)
window.removeEventListener('resize', updatePopoverPosition)
window.removeEventListener('scroll', updatePopoverPosition, true)
})
</script>
<template>
<div ref="rootRef" class="relative inline-block overflow-visible" v-bind="attrs">
<div
ref="triggerRef"
class="inline-flex"
@click.stop="togglePopover"
@keydown="handleTriggerKeydown"
>
<slot name="trigger" :open="open" :close="closePopover" :toggle="togglePopover" />
</div>
<Teleport to="body">
<div
v-if="open"
ref="popoverRef"
:class="popoverClasses"
:style="[sizeStyle, popoverStyle]"
>
<slot :open="open" :close="closePopover" :toggle="togglePopover" />
</div>
</Teleport>
</div>
</template>
+14
View File
@@ -73,6 +73,7 @@ function update() {
if (scrollRange <= 0 || availableTrackHeight <= 0) {
thumbHeight.value = 0
thumbTop.value = 0
visible.value = false
return
}
@@ -81,6 +82,18 @@ function update() {
thumbTop.value = (wrap.scrollTop / scrollRange) * maxThumbTop(wrap)
}
async function scrollToTop() {
const wrap = wrapRef.value
if (wrap) {
wrap.scrollTop = 0
wrap.scrollLeft = 0
}
dragging.value = false
visible.value = false
await nextTick()
update()
}
function handleScroll() {
const wrap = wrapRef.value
if (!wrap) {
@@ -170,6 +183,7 @@ onBeforeUnmount(() => {
defineExpose({
update,
scrollToTop,
wrapRef,
})
</script>
+2 -2
View File
@@ -206,12 +206,12 @@ watch(
>
<div
class="mt-5 grid h-12 grid-cols-[44px_minmax(0,1fr)] items-center"
:class="collapsed ? 'w-12 justify-start' : 'w-full gap-3'"
:class="collapsed ? 'w-11 justify-start' : 'w-full gap-3'"
>
<span
class="inline-flex size-11 items-center justify-center rounded-xl bg-slate-100 text-slate-700"
>
<Cat :size="27" stroke-width="2.05" />
<Cat :size="27" stroke-width="2" />
</span>
<span
v-show="brandLabelVisible"
+14 -2
View File
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { RouterView } from 'vue-router'
import { nextTick, ref, watch } from 'vue'
import { RouterView, useRoute } from 'vue-router'
import BaseScrollbar from '@/components/base/BaseScrollbar.vue'
import { useUiStore } from '@/stores/modules/ui'
@@ -10,13 +11,24 @@ import AppSidebar from './components/AppSidebar.vue'
const uiStore = useUiStore()
const { sidebarCollapsed } = storeToRefs(uiStore)
const { toggleSidebar } = uiStore
const route = useRoute()
const pageScrollbarRef = ref<InstanceType<typeof BaseScrollbar> | null>(null)
watch(
() => route.fullPath,
async () => {
await nextTick()
await pageScrollbarRef.value?.scrollToTop()
},
{ flush: 'post' },
)
</script>
<template>
<div class="flex h-screen overflow-hidden bg-(--cp-bg-page)">
<AppSidebar :collapsed="sidebarCollapsed" @toggle="toggleSidebar" />
<main class="h-screen min-w-0 flex-1 overflow-hidden">
<BaseScrollbar view-class="flex h-full min-w-0 flex-col p-6">
<BaseScrollbar ref="pageScrollbarRef" view-class="flex h-full min-w-0 flex-col p-6">
<RouterView />
</BaseScrollbar>
</main>
+612 -116
View File
@@ -1,6 +1,20 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { ChevronDown, Plus, RefreshCw, Trash2, Download, Upload, Search } from '@lucide/vue'
import { computed, onBeforeUnmount, onMounted, ref, watch, type Component } from 'vue'
import {
AlertTriangle,
ChevronDown,
Gauge,
MoreHorizontal,
Pencil,
Plus,
Power,
RefreshCw,
Search,
ShieldCheck,
Trash2,
Users,
Wifi,
} from '@lucide/vue'
import BaseButton from '@/components/base/BaseButton.vue'
import BaseCard from '@/components/base/BaseCard.vue'
@@ -9,7 +23,9 @@ import BaseConfirmModal from '@/components/base/BaseConfirmModal.vue'
import BaseIconButton from '@/components/base/BaseIconButton.vue'
import BaseInput from '@/components/base/BaseInput.vue'
import BaseModal from '@/components/base/BaseModal.vue'
import BasePopover from '@/components/base/BasePopover.vue'
import BaseTable from '@/components/base/BaseTable.vue'
import { toast } from '@/components/base/BaseToast'
import { withMinimumDuration } from '@/utils/async'
import type { Account, AccountQuotaWindow } from '@/api'
@@ -20,6 +36,9 @@ import {
getAccountQuota,
getAccounts,
refreshAccount,
testAccountConnection,
updateAccount,
updateAccountStatus,
} from '@/api'
const loading = ref(true)
@@ -33,11 +52,14 @@ const expandedAccountIds = ref<Set<string>>(new Set())
const showCreateModal = ref(false)
const showDeleteModal = ref(false)
const showSingleDeleteModal = ref(false)
const editingAccount = ref<Account | null>(null)
const pendingDeleteAccount = ref<Account | null>(null)
const refreshingList = ref(false)
const refreshingAccountIds = ref<Set<string>>(new Set())
const refreshingQuotaAccountIds = ref<Set<string>>(new Set())
const updatingStatusAccountIds = ref<Set<string>>(new Set())
const testingConnectionIds = ref<Set<string>>(new Set())
const deletingAccount = ref(false)
const savingAccount = ref(false)
const batchDeleting = ref(false)
let searchTimer: number | undefined
@@ -45,6 +67,40 @@ const createForm = ref({
refreshToken: '',
})
const editForm = ref<{
label: string
email: string
accountId: string
userId: string
planType: string
status: Account['status']
}>({
label: '',
email: '',
accountId: '',
userId: '',
planType: '',
status: 'active',
})
type OverviewTone = 'info' | 'success' | 'warning' | 'danger'
interface OverviewItem {
label: string
value: string
caption: string
tone: OverviewTone
icon: Component
}
const attentionStatuses = new Set<Account['status']>([
'expired',
'disabled',
'banned',
'quota_exhausted',
])
const relaxedCellClass = 'py-3 align-middle'
const accountColumns = [
{
key: 'expander',
@@ -52,7 +108,7 @@ const accountColumns = [
width: '40px',
align: 'center' as const,
headerClass: '!px-2',
cellClass: '!px-2',
cellClass: `!px-2 ${relaxedCellClass}`,
},
{
key: 'selection',
@@ -60,16 +116,27 @@ const accountColumns = [
width: '40px',
align: 'center' as const,
headerClass: '!px-2',
cellClass: '!px-2',
cellClass: `!px-2 ${relaxedCellClass}`,
},
{ key: 'identity', label: '邮箱', flex: 2.6, minWidth: '260px', cellClass: relaxedCellClass },
{ key: 'status', label: '状态', flex: 0.8, cellClass: relaxedCellClass },
{ key: 'planType', label: '套餐', flex: 0.8, cellClass: relaxedCellClass },
{ key: 'usage', label: '用量', flex: 1.5, minWidth: '220px', cellClass: relaxedCellClass },
{ key: 'updatedAt', label: '最后使用', flex: 1.2, cellClass: relaxedCellClass },
{
key: 'accessTokenExpiresAt',
label: '过期时间',
flex: 1.2,
cellClass: relaxedCellClass,
},
{
key: 'actions',
label: '操作',
width: '116px',
align: 'right' as const,
headerClass: '!pr-3',
cellClass: `!px-2 ${relaxedCellClass}`,
},
{ key: 'identity', label: '邮箱', flex: 2.6, minWidth: '260px' },
{ key: 'status', label: '状态', flex: 0.8 },
{ key: 'planType', label: '套餐', flex: 0.8 },
{ key: 'requests', label: '请求数', flex: 0.9 },
{ key: 'tokens', label: '总 Tokens', flex: 1 },
{ key: 'updatedAt', label: '最后使用', flex: 1.2 },
{ key: 'accessTokenExpiresAt', label: '过期时间', flex: 1.2 },
{ key: 'actions', label: '操作', width: '104px', align: 'left' as const },
]
const statusLabels: Record<Account['status'], string> = {
@@ -81,6 +148,15 @@ const statusLabels: Record<Account['status'], string> = {
refreshing: '刷新中',
}
const editableStatusOptions: Array<{ value: Account['status']; label: string }> = [
{ value: 'active', label: statusLabels.active },
{ value: 'disabled', label: statusLabels.disabled },
{ value: 'expired', label: statusLabels.expired },
{ value: 'quota_exhausted', label: statusLabels.quota_exhausted },
{ value: 'refreshing', label: statusLabels.refreshing },
{ value: 'banned', label: statusLabels.banned },
]
const statusTones: Record<Account['status'], 'success' | 'danger' | 'warning' | 'info' | 'normal'> =
{
active: 'success',
@@ -110,6 +186,50 @@ const accountPagination = computed(() => ({
total: totalAccounts.value,
pageSizes: [10, 20, 50, 100],
}))
const showEditModal = computed({
get: () => editingAccount.value !== null,
set: (value: boolean) => {
if (!value) {
editingAccount.value = null
}
},
})
const loadedAccountsCount = computed(() => accounts.value.length)
const activeAccountsCount = computed(
() => accounts.value.filter((account) => account.status === 'active').length,
)
const highUsageAccountsCount = computed(() => accounts.value.filter(accountHasHighUsage).length)
const attentionAccountsCount = computed(() => accounts.value.filter(accountNeedsAttention).length)
const overviewItems = computed<OverviewItem[]>(() => [
{
label: '总账号',
value: formatCount(totalAccounts.value),
caption: searchQuery.value.trim() ? '匹配筛选结果' : '账号池规模',
tone: 'info',
icon: Users,
},
{
label: '当前页正常',
value: formatCount(activeAccountsCount.value),
caption: `${formatCount(loadedAccountsCount.value)} 个已加载账号`,
tone: 'success',
icon: ShieldCheck,
},
{
label: '额度预警',
value: formatCount(highUsageAccountsCount.value),
caption: '任一窗口 >= 80%',
tone: 'warning',
icon: Gauge,
},
{
label: '需处理',
value: formatCount(attentionAccountsCount.value),
caption: '过期 / 禁用 / 封禁 / 耗尽',
tone: 'danger',
icon: AlertTriangle,
},
])
async function loadAccounts() {
try {
@@ -133,16 +253,6 @@ async function loadAccounts() {
}
}
async function refreshAccounts() {
if (refreshingList.value || loading.value) return
refreshingList.value = true
try {
await withMinimumDuration(loadAccounts)
} finally {
refreshingList.value = false
}
}
async function handleCreate() {
if (!createForm.value.refreshToken.trim()) return
@@ -158,6 +268,47 @@ async function handleCreate() {
}
}
function openEditAccount(account: Account) {
editingAccount.value = account
editForm.value = {
label: account.label || '',
email: account.email || '',
accountId: account.accountId || '',
userId: account.userId || '',
planType: account.planType || '',
status: account.status,
}
}
async function handleSaveAccount() {
const account = editingAccount.value
if (!account) return
try {
savingAccount.value = true
await updateAccount(account.id, {
label: nullableTrimmedValue(editForm.value.label),
email: nullableTrimmedValue(editForm.value.email),
accountId: nullableTrimmedValue(editForm.value.accountId),
userId: nullableTrimmedValue(editForm.value.userId),
planType: nullableTrimmedValue(editForm.value.planType),
status: editForm.value.status,
})
editingAccount.value = null
await loadAccounts()
toast.success('账号已更新')
} catch (error: any) {
toast.error(error.message || '保存失败')
} finally {
savingAccount.value = false
}
}
function nullableTrimmedValue(value: string) {
const trimmed = value.trim()
return trimmed || null
}
function requestDeleteAccount(account: Account) {
pendingDeleteAccount.value = account
showSingleDeleteModal.value = true
@@ -173,8 +324,9 @@ async function handleDelete() {
showSingleDeleteModal.value = false
pendingDeleteAccount.value = null
await loadAccounts()
} catch (error) {
console.error('Failed to delete account:', error)
toast.success('账号已删除')
} catch (error: any) {
toast.error(error.message || '删除失败')
} finally {
deletingAccount.value = false
}
@@ -204,8 +356,9 @@ async function handleRefresh(accountId: string) {
await refreshAccount(accountId)
await loadAccounts()
})
} catch (error) {
console.error('Failed to refresh account:', error)
toast.success('Token 已刷新')
} catch (error: any) {
toast.error(error.message || '刷新失败')
} finally {
const next = new Set(refreshingAccountIds.value)
next.delete(accountId)
@@ -213,6 +366,26 @@ async function handleRefresh(accountId: string) {
}
}
async function handleTestConnection(account: Account) {
if (testingConnectionIds.value.has(account.id)) return
testingConnectionIds.value = new Set(testingConnectionIds.value).add(account.id)
try {
const result = await withMinimumDuration(async () => testAccountConnection(account.id))
const check = result.results.find((item) => item.id === account.id) || result.results[0]
if (check?.result === 'alive') {
toast.success(`连接正常${check.durationMs !== undefined ? ` · ${check.durationMs}ms` : ''}`)
} else {
toast.error(check?.error || '测试连接失败')
}
} catch (error: any) {
toast.error(error.message || '测试连接失败')
} finally {
const next = new Set(testingConnectionIds.value)
next.delete(account.id)
testingConnectionIds.value = next
}
}
async function handleRefreshQuota(accountId: string) {
if (refreshingQuotaAccountIds.value.has(accountId)) return
refreshingQuotaAccountIds.value = new Set(refreshingQuotaAccountIds.value).add(accountId)
@@ -230,6 +403,27 @@ async function handleRefreshQuota(accountId: string) {
}
}
async function handleToggleSchedule(account: Account) {
if (updatingStatusAccountIds.value.has(account.id)) return
const nextStatus: Account['status'] = account.status === 'disabled' ? 'active' : 'disabled'
updatingStatusAccountIds.value = new Set(updatingStatusAccountIds.value).add(account.id)
try {
await updateAccountStatus(account.id, nextStatus)
await loadAccounts()
toast.success(nextStatus === 'disabled' ? '已禁用调度' : '已启用调度')
} catch (error: any) {
toast.error(error.message || '状态更新失败')
} finally {
const next = new Set(updatingStatusAccountIds.value)
next.delete(account.id)
updatingStatusAccountIds.value = next
}
}
function scheduleActionLabel(account: Account) {
return account.status === 'disabled' ? '启用调度' : '禁用调度'
}
function statusTone(status: Account['status']) {
return statusTones[status]
}
@@ -238,6 +432,98 @@ function statusLabel(status: Account['status']) {
return statusLabels[status]
}
function statusTextClass(status: Account['status']) {
const tone = statusTone(status)
if (tone === 'success') {
return 'text-emerald-700'
}
if (tone === 'danger') {
return 'text-red-700'
}
if (tone === 'warning') {
return 'text-amber-700'
}
if (tone === 'info') {
return 'text-blue-700'
}
return 'text-slate-600'
}
function statusDotClass(status: Account['status']) {
const tone = statusTone(status)
if (tone === 'success') {
return 'bg-emerald-500'
}
if (tone === 'danger') {
return 'bg-red-500'
}
if (tone === 'warning') {
return 'bg-amber-500'
}
if (tone === 'info') {
return 'bg-blue-500'
}
return 'bg-gray-400'
}
function planTypeLabel(planType?: string) {
return planType?.trim() || 'Free'
}
function planTypeClass(planType?: string) {
const normalized = planTypeLabel(planType).toLowerCase()
if (normalized.includes('enterprise') || normalized.includes('team')) {
return 'bg-slate-900 text-white'
}
if (normalized.includes('pro')) {
return 'bg-indigo-50 text-indigo-700'
}
if (normalized.includes('plus') || normalized.includes('basic')) {
return 'bg-blue-50 text-blue-700'
}
return 'bg-gray-50 text-gray-700'
}
function accountDisplayTitle(account: Account) {
return account.label?.trim() || account.email || account.accountId || account.id
}
function accountSecondaryText(account: Account) {
const title = accountDisplayTitle(account)
const secondary = [account.email, account.accountId, account.userId, account.id].find(
(value) => value && value !== title,
)
return secondary || account.id
}
function accountInitial(account: Account) {
return accountDisplayTitle(account).slice(0, 1).toUpperCase()
}
function accountAvatarClass(account: Account) {
const palettes = [
'bg-cyan-50 text-cyan-700 shadow-[inset_0_0_0_1px_#bae6fd]',
'bg-emerald-50 text-emerald-700 shadow-[inset_0_0_0_1px_#bbf7d0]',
'bg-violet-50 text-violet-700 shadow-[inset_0_0_0_1px_#ddd6fe]',
'bg-amber-50 text-amber-700 shadow-[inset_0_0_0_1px_#fde68a]',
]
const key = account.id || account.email || accountDisplayTitle(account)
const hash = [...key].reduce((sum, char) => sum + char.charCodeAt(0), 0)
return palettes[hash % palettes.length]
}
function formatCount(value: number) {
return value.toLocaleString('zh-CN')
}
function accountNeedsAttention(account: Account) {
return attentionStatuses.has(account.status)
}
function accountHasHighUsage(account: Account) {
return quotaWindows(account).some((window) => quotaWindowPercent(window) >= 80)
}
function toggleSelection(accountId: string) {
if (selectedIds.value.has(accountId)) {
selectedIds.value.delete(accountId)
@@ -283,8 +569,46 @@ function quotaWindowsByGroup(account: Account, group: AccountQuotaWindow['group'
return quotaWindows(account).filter((window) => window.group === group)
}
function quotaWindowBarWidth(window: AccountQuotaWindow) {
return `${Math.max(0, Math.min(window.usedPercent ?? 0, 100))}%`
function quotaWindowPercent(window?: AccountQuotaWindow) {
return Math.max(0, Math.min(window?.usedPercent ?? 0, 100))
}
function quotaWindowBarWidth(window?: AccountQuotaWindow) {
return `${quotaWindowPercent(window)}%`
}
function quotaWindowBarStyle(window?: AccountQuotaWindow) {
const percent = quotaWindowPercent(window)
return {
width: `${percent}%`,
minWidth: percent > 0 ? '6px' : '0',
}
}
function quotaWindowBarClass(window?: AccountQuotaWindow) {
if (window?.usedPercent === null || window?.usedPercent === undefined) {
return 'bg-(--cp-border-strong)'
}
if (window.usedPercent >= 95) {
return 'bg-red-400'
}
if (window.usedPercent >= 80) {
return 'bg-amber-400'
}
return 'bg-emerald-400'
}
function overviewIconClass(tone: OverviewTone) {
if (tone === 'success') {
return 'bg-emerald-50 text-emerald-700'
}
if (tone === 'warning') {
return 'bg-amber-50 text-amber-700'
}
if (tone === 'danger') {
return 'bg-red-50 text-red-700'
}
return 'bg-cyan-50 text-cyan-700'
}
onMounted(() => {
@@ -321,63 +645,88 @@ onBeforeUnmount(() => {
</div>
</header>
<div class="mt-6 flex shrink-0 items-center justify-between gap-4">
<div class="flex items-center gap-3">
<BaseInput v-model="searchQuery" placeholder="搜索邮箱或 ID..." class="w-80">
<template #prefix>
<Search class="size-4.5 text-(--cp-text-tertiary)" />
</template>
</BaseInput>
<BaseButton
v-if="selectedIds.size > 0"
variant="danger"
:disabled="batchDeleting"
@click="showDeleteModal = true"
>
<Trash2 class="size-4" />
删除选中 ({{ selectedIds.size }})
</BaseButton>
</div>
<div class="flex items-center gap-2">
<BaseIconButton variant="ghost" size="md" title="导出账号">
<Download class="size-4.5" />
</BaseIconButton>
<BaseIconButton variant="ghost" size="md" title="导入账号">
<Upload class="size-4.5" />
</BaseIconButton>
<BaseIconButton
variant="ghost"
size="md"
title="刷新列表"
:loading="refreshingList"
:disabled="loading"
@click="refreshAccounts"
>
<RefreshCw class="size-4.5" />
</BaseIconButton>
<BaseButton variant="primary" @click="showCreateModal = true">
<Plus class="size-4" />
添加账号
</BaseButton>
</div>
<div class="mt-5 grid shrink-0 grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-4">
<section
v-for="item in overviewItems"
:key="item.label"
class="min-h-24 rounded-lg bg-(--cp-bg-surface) px-4 py-3.5 shadow-(--cp-shadow-control)"
>
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<p class="m-0 text-[12px] leading-none font-[760] text-(--cp-text-secondary)">
{{ item.label }}
</p>
<strong
class="mt-2 block font-mono text-[26px] leading-none font-[820] text-(--cp-text-primary)"
>
{{ item.value }}
</strong>
<p class="m-0 mt-2 truncate text-[12px] leading-none font-[650] text-(--cp-text-muted)">
{{ item.caption }}
</p>
</div>
<span
class="inline-flex size-9 shrink-0 items-center justify-center rounded-lg"
:class="overviewIconClass(item.tone)"
>
<component :is="item.icon" class="size-4.5" />
</span>
</div>
</section>
</div>
<BaseCard v-loading="loading" class="mt-5 flex min-h-0 flex-1 p-0">
<BaseTable
:columns="accountColumns"
:rows="filteredAccounts"
:selected-row-keys="selectedRowKeys"
:expanded-row-keys="[...expandedAccountIds]"
:pagination="accountPagination"
empty-text="暂无账号数据"
@page-change="handlePageChange"
@page-size-change="handlePageSizeChange"
>
<BaseCard
v-loading="loading"
:padded="false"
class="mt-4 flex min-h-0 flex-1 flex-col"
header-class="px-4 pt-4 pb-2 md:px-5"
body-class="flex min-h-0 flex-1 px-4 pb-3 md:px-5"
>
<template #header>
<div class="flex flex-wrap items-center justify-between gap-3">
<div class="flex min-w-0 flex-1 flex-wrap items-center gap-3">
<BaseInput
v-model="searchQuery"
placeholder="搜索邮箱或 ID..."
class="w-80 max-w-full [--cp-input-current-bg:var(--cp-input-soft-bg)] [--cp-input-current-bg-hover:var(--cp-input-soft-bg-hover)]"
>
<template #prefix>
<Search class="size-4.5 text-(--cp-text-tertiary)" />
</template>
</BaseInput>
<BaseButton
v-if="selectedIds.size > 0"
variant="danger"
:disabled="batchDeleting"
@click="showDeleteModal = true"
>
<Trash2 class="size-4" />
删除选中 ({{ selectedIds.size }})
</BaseButton>
</div>
<div class="flex shrink-0 items-center gap-2">
<BaseButton variant="primary" @click="showCreateModal = true">
<Plus class="size-4" />
添加账号
</BaseButton>
</div>
</div>
</template>
<template #body>
<BaseTable
class="min-h-0 flex-1"
:columns="accountColumns"
:rows="filteredAccounts"
:selected-row-keys="selectedRowKeys"
:expanded-row-keys="[...expandedAccountIds]"
:pagination="accountPagination"
empty-text="暂无账号数据"
@page-change="handlePageChange"
@page-size-change="handlePageSizeChange"
>
<template #expander="{ row }">
<button
type="button"
@@ -410,42 +759,73 @@ onBeforeUnmount(() => {
</template>
<template #identity="{ row }">
<span class="text-[14px] font-medium text-(--cp-text-primary)">
{{ row.email || row.accountId || row.id }}
</span>
<div class="flex min-w-0 items-center gap-3">
<span
class="inline-flex size-9 shrink-0 items-center justify-center rounded-lg text-[13px] font-[820]"
:class="accountAvatarClass(row)"
>
{{ accountInitial(row) }}
</span>
<div class="min-w-0">
<div class="truncate text-[14px] font-[760] text-(--cp-text-primary)">
{{ accountDisplayTitle(row) }}
</div>
<div class="mt-0.5 truncate font-mono text-[11px] text-(--cp-text-muted)">
{{ accountSecondaryText(row) }}
</div>
</div>
</div>
</template>
<template #status="{ row }">
<span
class="inline-flex items-center rounded-full px-2 py-0.5 text-[12px] font-medium"
:class="{
'bg-green-50 text-green-700': statusTone(row.status) === 'success',
'bg-red-50 text-red-700': statusTone(row.status) === 'danger',
'bg-yellow-50 text-yellow-700': statusTone(row.status) === 'warning',
'bg-blue-50 text-blue-700': statusTone(row.status) === 'info',
'bg-gray-50 text-gray-700': statusTone(row.status) === 'normal',
}"
class="inline-flex min-w-16 items-center gap-1.5 text-[12px] leading-none font-[650]"
:class="statusTextClass(row.status)"
>
{{ statusLabel(row.status) }}
<span class="size-1.5 rounded-full" :class="statusDotClass(row.status)" />
<span>{{ statusLabel(row.status) }}</span>
</span>
</template>
<template #planType="{ row }">
<span class="capitalize text-(--cp-text-secondary)">
{{ row.planType || '—' }}
<span
class="inline-flex items-center rounded-full px-2.5 py-1 text-[12px] font-[760] capitalize"
:class="planTypeClass(row.planType)"
>
{{ planTypeLabel(row.planType) }}
</span>
</template>
<template #requests="{ row }">
<span class="font-mono text-[14px] text-(--cp-text-primary)">
{{ row.usage.requestCountDisplay }}
</span>
</template>
<template #tokens="{ row }">
<span class="font-mono text-[14px] text-(--cp-text-primary)">
{{ row.usage.totalTokensDisplay }}
</span>
<template #usage="{ row }">
<div
v-if="quotaWindows(row).length > 0"
class="flex w-full max-w-[124px] min-w-0 flex-col gap-2 whitespace-normal py-1.5"
>
<div
v-for="window in quotaWindows(row)"
:key="window.key"
class="min-w-0 border-b border-slate-200/70 pb-2 last:border-b-0 last:pb-0"
>
<div
class="mb-1.5 flex items-center justify-between gap-2 text-[11px] leading-none font-[760]"
>
<span class="truncate text-(--cp-text-secondary)">
{{ window.labelDisplay }}
</span>
<span class="shrink-0 font-mono text-(--cp-text-primary)">
{{ window.usedPercentDisplay }}
</span>
</div>
<div class="h-1 w-full overflow-hidden rounded-full bg-(--cp-default-border)">
<div
class="h-full rounded-full transition-[width,background-color] duration-200"
:class="quotaWindowBarClass(window)"
:style="quotaWindowBarStyle(window)"
/>
</div>
</div>
</div>
<span v-else class="text-(--cp-text-muted)">-</span>
</template>
<template #updatedAt="{ row }">
@@ -461,25 +841,63 @@ onBeforeUnmount(() => {
</template>
<template #actions="{ row }">
<div class="flex items-center justify-start gap-1">
<div class="relative flex items-center justify-end gap-1">
<BaseIconButton
variant="ghost"
size="sm"
title="刷新令牌"
:loading="refreshingAccountIds.has(row.id)"
@click="handleRefresh(row.id)"
title="编辑账号"
@click.stop="openEditAccount(row)"
>
<RefreshCw class="size-3.5" />
<Pencil class="size-3.5" />
</BaseIconButton>
<BaseIconButton
variant="ghost"
size="sm"
title="删除账号"
:disabled="deletingAccount"
@click="requestDeleteAccount(row)"
@click.stop="requestDeleteAccount(row)"
>
<Trash2 class="size-3.5" />
<Trash2 class="size-3.5 text-red-500" />
</BaseIconButton>
<BasePopover placement="bottom-end" width="160px">
<template #trigger="{ open }">
<BaseIconButton variant="ghost" size="sm" title="更多操作" :active="open">
<MoreHorizontal class="size-4" />
</BaseIconButton>
</template>
<template #default="{ close }">
<button
type="button"
class="flex h-8.5 w-full items-center gap-2 rounded-(--cp-input-radius-small) border-0 bg-transparent px-3 text-left text-[13px] leading-none font-[650] text-(--cp-text-primary) transition-colors hover:bg-(--cp-default-bg-hover) disabled:cursor-not-allowed disabled:text-(--cp-disabled-text)"
:disabled="testingConnectionIds.has(row.id)"
@click.stop="close(); handleTestConnection(row)"
>
<Wifi class="size-3.5 text-(--cp-text-muted)" />
测试连接
</button>
<button
type="button"
class="flex h-8.5 w-full items-center gap-2 rounded-(--cp-input-radius-small) border-0 bg-transparent px-3 text-left text-[13px] leading-none font-[650] text-(--cp-text-primary) transition-colors hover:bg-(--cp-default-bg-hover) disabled:cursor-not-allowed disabled:text-(--cp-disabled-text)"
:disabled="refreshingAccountIds.has(row.id)"
@click.stop="close(); handleRefresh(row.id)"
>
<RefreshCw class="size-3.5 text-(--cp-text-muted)" />
刷新 token
</button>
<button
type="button"
class="flex h-8.5 w-full items-center gap-2 rounded-(--cp-input-radius-small) border-0 bg-transparent px-3 text-left text-[13px] leading-none font-[650] text-(--cp-text-primary) transition-colors hover:bg-(--cp-default-bg-hover) disabled:cursor-not-allowed disabled:text-(--cp-disabled-text)"
:disabled="updatingStatusAccountIds.has(row.id)"
@click.stop="close(); handleToggleSchedule(row)"
>
<Power class="size-3.5 text-(--cp-text-muted)" />
{{ scheduleActionLabel(row) }}
</button>
</template>
</BasePopover>
</div>
</template>
@@ -668,7 +1086,8 @@ onBeforeUnmount(() => {
</section>
</div>
</template>
</BaseTable>
</BaseTable>
</template>
</BaseCard>
<!-- 创建账号模态框 -->
@@ -704,6 +1123,83 @@ onBeforeUnmount(() => {
</template>
</BaseModal>
<BaseModal
v-model="showEditModal"
title="编辑账号"
description="更新账号元信息、套餐和调度状态。"
variant="info"
width="680px"
>
<div class="grid gap-4 sm:grid-cols-2">
<div class="sm:col-span-2">
<label class="mb-2 block text-[13px] font-medium text-(--cp-text-secondary)">
内部 ID
</label>
<div
class="flex h-10 items-center truncate rounded-lg bg-(--cp-bg-secondary) px-3 font-mono text-[12px] font-[650] text-(--cp-text-muted)"
>
{{ editingAccount?.id || '-' }}
</div>
</div>
<div>
<label class="mb-2 block text-[13px] font-medium text-(--cp-text-secondary)">
备注标签
</label>
<BaseInput v-model="editForm.label" placeholder="例如:主账号 / 备用账号" />
</div>
<div>
<label class="mb-2 block text-[13px] font-medium text-(--cp-text-secondary)">
邮箱
</label>
<BaseInput v-model="editForm.email" placeholder="account@example.com" />
</div>
<div>
<label class="mb-2 block text-[13px] font-medium text-(--cp-text-secondary)">
ChatGPT 账号 ID
</label>
<BaseInput v-model="editForm.accountId" placeholder="chatgpt account id" />
</div>
<div>
<label class="mb-2 block text-[13px] font-medium text-(--cp-text-secondary)">
用户 ID
</label>
<BaseInput v-model="editForm.userId" placeholder="user id" />
</div>
<div>
<label class="mb-2 block text-[13px] font-medium text-(--cp-text-secondary)">
套餐
</label>
<BaseInput v-model="editForm.planType" placeholder="free / plus / pro / team" />
</div>
<div>
<label class="mb-2 block text-[13px] font-medium text-(--cp-text-secondary)">
状态
</label>
<select
v-model="editForm.status"
class="h-10 w-full rounded-lg border border-(--cp-border) bg-(--cp-bg-surface) px-3 text-[13px] font-[650] text-(--cp-text-primary) outline-none transition focus:border-(--cp-primary) focus:ring-2 focus:ring-(--cp-primary)/15"
>
<option v-for="option in editableStatusOptions" :key="option.value" :value="option.value">
{{ option.label }}
</option>
</select>
</div>
</div>
<template #footer>
<BaseButton variant="ghost" @click="showEditModal = false"> 取消 </BaseButton>
<BaseButton variant="primary" :loading="savingAccount" @click="handleSaveAccount">
保存
</BaseButton>
</template>
</BaseModal>
<BaseConfirmModal
v-model="showDeleteModal"
title="确认删除"
+10 -8
View File
@@ -1,6 +1,8 @@
<script setup lang="ts">
import { RefreshCw } from '@lucide/vue'
import BaseIconButton from '@/components/base/BaseIconButton.vue'
import AccountOverviewCard from './components/AccountOverviewCard.vue'
import EventLogCard from './components/EventLogCard.vue'
import MetricCard from './components/MetricCard.vue'
@@ -11,6 +13,7 @@ import { useDashboard } from './composables/useDashboard'
const {
loading,
refreshing,
trendLoading,
metrics,
trendPoints,
@@ -39,16 +42,15 @@ const {
</p>
</div>
<button
class="mt-0.5 inline-flex size-11 shrink-0 items-center justify-center rounded-xl border-0 bg-white text-(--cp-normal) shadow-(--cp-shadow-control) disabled:cursor-not-allowed disabled:opacity-50"
type="button"
aria-label="刷新概览"
:aria-busy="loading"
:disabled="loading"
<BaseIconButton
class="mt-0.5 text-(--cp-normal)"
size="md"
label="刷新概览"
:loading="loading || refreshing"
@click="refresh"
>
<RefreshCw :size="19" :class="loading ? 'animate-spin' : ''" />
</button>
<RefreshCw :size="19" />
</BaseIconButton>
</header>
<section
@@ -13,7 +13,6 @@ const props = defineProps<{
const activeFilter = ref('all')
const filters = [
{ label: '全部', value: 'all' },
{ label: '警告', value: 'warn' },
{ label: '错误', value: 'error' },
]
const eventLogColumns = [
@@ -63,7 +62,7 @@ const filteredRows = computed(() => {
</p>
</div>
<BaseSegmented v-model="activeFilter" :options="filters" class="w-51.5" />
<BaseSegmented v-model="activeFilter" :options="filters" class="w-38" />
</header>
<div class="mt-4.25 flex h-60 w-full justify-between overflow-hidden">
@@ -41,10 +41,10 @@ function cellClass(point: string) {
class="flex items-center gap-2 text-[11px] leading-none font-[650] text-(--cp-text-muted)"
>
<span>{{ timeline.oldestLabel }}</span>
<i class="size-2 rounded-[2px] bg-[#CBD2DC]" />
<i class="size-2 rounded-[2px] bg-[#D86A62]" />
<i class="size-2 rounded-[2px] bg-[#D9A13B]" />
<i class="size-2 rounded-[2px] bg-[#4FAD7A]" />
<i class="size-2 rounded-xs bg-[#CBD2DC]" />
<i class="size-2 rounded-xs bg-[#D86A62]" />
<i class="size-2 rounded-xs bg-[#D9A13B]" />
<i class="size-2 rounded-xs bg-[#4FAD7A]" />
<span>{{ timeline.newestLabel }}</span>
</div>
</div>
@@ -215,10 +215,7 @@ function formatLatency(ms: number): string {
<div
class="mt-4.75 grid grid-cols-1 gap-5 lg:grid-cols-[minmax(0,1fr)_minmax(150px,180px)] lg:gap-7.5"
>
<div
v-loading="props.loading"
class="relative h-67 w-full overflow-hidden rounded-[10px] bg-white"
>
<div class="relative h-67 w-full overflow-hidden rounded-[10px] bg-white">
<BaseChart v-if="hasSamples" :option="chartOption" :height="268" />
<BaseEmpty
v-if="!hasSamples"
@@ -36,6 +36,7 @@ import { withMinimumDuration } from '@/utils/async'
export function useDashboard(): {
loading: Ref<boolean>
refreshing: Ref<boolean>
trendLoading: Ref<boolean>
metrics: Ref<MetricCardItem[]>
trendPoints: Ref<TrendPoint[]>
@@ -61,6 +62,7 @@ export function useDashboard(): {
const capacityInfo = ref<AccountCapacityInfo | null>(null)
const rotationStrategy = ref<string | null>(null)
const loading = ref(false)
const refreshing = ref(false)
const trendLoading = ref(false)
const autoRefreshTimer = ref<ReturnType<typeof setInterval> | null>(null)
@@ -77,8 +79,18 @@ export function useDashboard(): {
}
async function refreshDashboardData() {
if (loading.value) return
await withMinimumDuration(loadDashboardData)
if (loading.value || refreshing.value) return
refreshing.value = true
try {
await withMinimumDuration(async () => {
const summary = await getDashboardSummary()
applySummary(summary)
})
} catch (error) {
console.error('Failed to refresh dashboard data:', error)
} finally {
refreshing.value = false
}
}
async function loadTrend(tab: string) {
@@ -440,6 +452,7 @@ export function useDashboard(): {
return {
loading,
refreshing,
trendLoading,
metrics,
trendPoints,