mirror of
https://gitee.com/wanwujie/sub2api
synced 2026-04-21 23:24:46 +08:00
Merge tag 'v0.1.90' into merge/upstream-v0.1.90
注册邮箱域名白名单策略上线,后台大数据场景性能大幅优化。 - 注册邮箱域名白名单:支持管理员配置允许注册的邮箱域名策略 - Keys 页面表单筛选:用户 /keys 页面支持按条件筛选 API Key - Settings 页面分 Tab 拆分:管理后台设置页面按功能模块分 Tab 展示 - 后台大数据场景加载性能优化:仪表盘/用户/账号/Ops 页面大数据集加载显著提速 - Usage 大表分页优化:默认避免全量 COUNT(*),大幅降低分页查询耗时 - 消除重复的 normalizeAccountIDList,补充新增组件的单元测试 - 清理无用文件和过时文档,精简项目结构 - EmailVerifyView 硬编码英文字符串替换为 i18n 调用 - 修复 Anthropic 平台无限流重置时间的 429 误标记账号限流问题 - 修复自定义菜单页面管理员视角菜单不生效问题 - 修复 Ops 错误详情弹窗未展示真实上游 payload 的问题 - 修复充值/订阅菜单 icon 显示问题 # Conflicts: # .gitignore # backend/cmd/server/VERSION # backend/ent/group.go # backend/ent/runtime/runtime.go # backend/ent/schema/group.go # backend/go.sum # backend/internal/handler/admin/account_handler.go # backend/internal/handler/admin/dashboard_handler.go # backend/internal/pkg/usagestats/usage_log_types.go # backend/internal/repository/group_repo.go # backend/internal/repository/usage_log_repo.go # backend/internal/server/middleware/security_headers.go # backend/internal/server/router.go # backend/internal/service/account_usage_service.go # backend/internal/service/admin_service_bulk_update_test.go # backend/internal/service/dashboard_service.go # backend/internal/service/gateway_service.go # frontend/src/api/admin/dashboard.ts # frontend/src/components/account/BulkEditAccountModal.vue # frontend/src/components/charts/GroupDistributionChart.vue # frontend/src/components/layout/AppSidebar.vue # frontend/src/i18n/locales/en.ts # frontend/src/i18n/locales/zh.ts # frontend/src/views/admin/GroupsView.vue # frontend/src/views/admin/SettingsView.vue # frontend/src/views/admin/UsageView.vue # frontend/src/views/user/PurchaseSubscriptionView.vue
This commit is contained in:
@@ -184,7 +184,11 @@
|
||||
</button>
|
||||
</template>
|
||||
<template #cell-today_stats="{ row }">
|
||||
<AccountTodayStatsCell :account="row" />
|
||||
<AccountTodayStatsCell
|
||||
:stats="todayStatsByAccountId[String(row.id)] ?? null"
|
||||
:loading="todayStatsLoading"
|
||||
:error="todayStatsError"
|
||||
/>
|
||||
</template>
|
||||
<template #cell-groups="{ row }">
|
||||
<AccountGroupsCell :groups="row.groups" :max-display="4" />
|
||||
@@ -259,7 +263,7 @@
|
||||
<AccountActionMenu :show="menu.show" :account="menu.acc" :position="menu.pos" @close="menu.show = false" @test="handleTest" @stats="handleViewStats" @reauth="handleReAuth" @refresh-token="handleRefresh" @reset-status="handleResetStatus" @clear-rate-limit="handleClearRateLimit" />
|
||||
<SyncFromCrsModal :show="showSync" @close="showSync = false" @synced="reload" />
|
||||
<ImportDataModal :show="showImportData" @close="showImportData = false" @imported="handleDataImported" />
|
||||
<BulkEditAccountModal :show="showBulkEdit" :account-ids="selIds" :selected-platforms="selPlatforms" :proxies="proxies" :groups="groups" @close="showBulkEdit = false" @updated="handleBulkUpdated" />
|
||||
<BulkEditAccountModal :show="showBulkEdit" :account-ids="selIds" :selected-platforms="selPlatforms" :selected-types="selTypes" :proxies="proxies" :groups="groups" @close="showBulkEdit = false" @updated="handleBulkUpdated" />
|
||||
<TempUnschedStatusModal :show="showTempUnsched" :account="tempUnschedAcc" @close="showTempUnsched = false" @reset="handleTempUnschedReset" />
|
||||
<ConfirmDialog :show="showDeleteDialog" :title="t('admin.accounts.deleteAccount')" :message="t('admin.accounts.deleteConfirm', { name: deletingAcc?.name })" :confirm-text="t('common.delete')" :cancel-text="t('common.cancel')" :danger="true" @confirm="confirmDelete" @cancel="showDeleteDialog = false" />
|
||||
<ConfirmDialog :show="showExportDataDialog" :title="t('admin.accounts.dataExport')" :message="t('admin.accounts.dataExportConfirmMessage')" :confirm-text="t('admin.accounts.dataExportConfirm')" :cancel-text="t('common.cancel')" @confirm="handleExportData" @cancel="showExportDataDialog = false">
|
||||
@@ -273,7 +277,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, reactive, computed, onMounted, onUnmounted, toRaw } from 'vue'
|
||||
import { ref, reactive, computed, onMounted, onUnmounted, toRaw, watch } from 'vue'
|
||||
import { useIntervalFn } from '@vueuse/core'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useAppStore } from '@/stores/app'
|
||||
@@ -303,7 +307,7 @@ import PlatformTypeBadge from '@/components/common/PlatformTypeBadge.vue'
|
||||
import Icon from '@/components/icons/Icon.vue'
|
||||
import ErrorPassthroughRulesModal from '@/components/admin/ErrorPassthroughRulesModal.vue'
|
||||
import { formatDateTime, formatRelativeTime } from '@/utils/format'
|
||||
import type { Account, AccountPlatform, Proxy, AdminGroup } from '@/types'
|
||||
import type { Account, AccountPlatform, AccountType, Proxy, AdminGroup, WindowStats } from '@/types'
|
||||
|
||||
const { t } = useI18n()
|
||||
const appStore = useAppStore()
|
||||
@@ -320,6 +324,14 @@ const selPlatforms = computed<AccountPlatform[]>(() => {
|
||||
)
|
||||
return [...platforms]
|
||||
})
|
||||
const selTypes = computed<AccountType[]>(() => {
|
||||
const types = new Set(
|
||||
accounts.value
|
||||
.filter(a => selIds.value.includes(a.id))
|
||||
.map(a => a.type)
|
||||
)
|
||||
return [...types]
|
||||
})
|
||||
const showCreate = ref(false)
|
||||
const showEdit = ref(false)
|
||||
const showSync = ref(false)
|
||||
@@ -347,7 +359,7 @@ const exportingData = ref(false)
|
||||
const showColumnDropdown = ref(false)
|
||||
const columnDropdownRef = ref<HTMLElement | null>(null)
|
||||
const hiddenColumns = reactive<Set<string>>(new Set())
|
||||
const DEFAULT_HIDDEN_COLUMNS = ['proxy', 'notes', 'priority', 'rate_multiplier']
|
||||
const DEFAULT_HIDDEN_COLUMNS = ['today_stats', 'proxy', 'notes', 'priority', 'rate_multiplier']
|
||||
const HIDDEN_COLUMNS_KEY = 'account-hidden-columns'
|
||||
|
||||
// Sorting settings
|
||||
@@ -366,6 +378,59 @@ const autoRefreshFetching = ref(false)
|
||||
const AUTO_REFRESH_SILENT_WINDOW_MS = 15000
|
||||
const autoRefreshSilentUntil = ref(0)
|
||||
const hasPendingListSync = ref(false)
|
||||
const todayStatsByAccountId = ref<Record<string, WindowStats>>({})
|
||||
const todayStatsLoading = ref(false)
|
||||
const todayStatsError = ref<string | null>(null)
|
||||
const todayStatsReqSeq = ref(0)
|
||||
const pendingTodayStatsRefresh = ref(false)
|
||||
|
||||
const buildDefaultTodayStats = (): WindowStats => ({
|
||||
requests: 0,
|
||||
tokens: 0,
|
||||
cost: 0,
|
||||
standard_cost: 0,
|
||||
user_cost: 0
|
||||
})
|
||||
|
||||
const refreshTodayStatsBatch = async () => {
|
||||
if (hiddenColumns.has('today_stats')) {
|
||||
todayStatsLoading.value = false
|
||||
todayStatsError.value = null
|
||||
return
|
||||
}
|
||||
|
||||
const accountIDs = accounts.value.map(account => account.id)
|
||||
const reqSeq = ++todayStatsReqSeq.value
|
||||
if (accountIDs.length === 0) {
|
||||
todayStatsByAccountId.value = {}
|
||||
todayStatsError.value = null
|
||||
todayStatsLoading.value = false
|
||||
return
|
||||
}
|
||||
|
||||
todayStatsLoading.value = true
|
||||
todayStatsError.value = null
|
||||
|
||||
try {
|
||||
const result = await adminAPI.accounts.getBatchTodayStats(accountIDs)
|
||||
if (reqSeq !== todayStatsReqSeq.value) return
|
||||
const serverStats = result.stats ?? {}
|
||||
const nextStats: Record<string, WindowStats> = {}
|
||||
for (const accountID of accountIDs) {
|
||||
const key = String(accountID)
|
||||
nextStats[key] = serverStats[key] ?? buildDefaultTodayStats()
|
||||
}
|
||||
todayStatsByAccountId.value = nextStats
|
||||
} catch (error) {
|
||||
if (reqSeq !== todayStatsReqSeq.value) return
|
||||
todayStatsError.value = 'Failed'
|
||||
console.error('Failed to load account today stats:', error)
|
||||
} finally {
|
||||
if (reqSeq === todayStatsReqSeq.value) {
|
||||
todayStatsLoading.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const autoRefreshIntervalLabel = (sec: number) => {
|
||||
if (sec === 5) return t('admin.accounts.refreshInterval5s')
|
||||
@@ -453,12 +518,18 @@ const setAutoRefreshInterval = (seconds: (typeof autoRefreshIntervals)[number])
|
||||
}
|
||||
|
||||
const toggleColumn = (key: string) => {
|
||||
const wasHidden = hiddenColumns.has(key)
|
||||
if (hiddenColumns.has(key)) {
|
||||
hiddenColumns.delete(key)
|
||||
} else {
|
||||
hiddenColumns.add(key)
|
||||
}
|
||||
saveColumnsToStorage()
|
||||
if (key === 'today_stats' && wasHidden) {
|
||||
refreshTodayStatsBatch().catch((error) => {
|
||||
console.error('Failed to load account today stats after showing column:', error)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const isColumnVisible = (key: string) => !hiddenColumns.has(key)
|
||||
@@ -475,7 +546,7 @@ const {
|
||||
handlePageSizeChange: baseHandlePageSizeChange
|
||||
} = useTableLoader<Account, any>({
|
||||
fetchFn: adminAPI.accounts.list,
|
||||
initialParams: { platform: '', type: '', status: '', group: '', search: '' }
|
||||
initialParams: { platform: '', type: '', status: '', group: '', search: '', lite: '1' }
|
||||
})
|
||||
|
||||
const resetAutoRefreshCache = () => {
|
||||
@@ -485,33 +556,49 @@ const resetAutoRefreshCache = () => {
|
||||
const load = async () => {
|
||||
hasPendingListSync.value = false
|
||||
resetAutoRefreshCache()
|
||||
pendingTodayStatsRefresh.value = false
|
||||
await baseLoad()
|
||||
await refreshTodayStatsBatch()
|
||||
}
|
||||
|
||||
const reload = async () => {
|
||||
hasPendingListSync.value = false
|
||||
resetAutoRefreshCache()
|
||||
pendingTodayStatsRefresh.value = false
|
||||
await baseReload()
|
||||
await refreshTodayStatsBatch()
|
||||
}
|
||||
|
||||
const debouncedReload = () => {
|
||||
hasPendingListSync.value = false
|
||||
resetAutoRefreshCache()
|
||||
pendingTodayStatsRefresh.value = true
|
||||
baseDebouncedReload()
|
||||
}
|
||||
|
||||
const handlePageChange = (page: number) => {
|
||||
hasPendingListSync.value = false
|
||||
resetAutoRefreshCache()
|
||||
pendingTodayStatsRefresh.value = true
|
||||
baseHandlePageChange(page)
|
||||
}
|
||||
|
||||
const handlePageSizeChange = (size: number) => {
|
||||
hasPendingListSync.value = false
|
||||
resetAutoRefreshCache()
|
||||
pendingTodayStatsRefresh.value = true
|
||||
baseHandlePageSizeChange(size)
|
||||
}
|
||||
|
||||
watch(loading, (isLoading, wasLoading) => {
|
||||
if (wasLoading && !isLoading && pendingTodayStatsRefresh.value) {
|
||||
pendingTodayStatsRefresh.value = false
|
||||
refreshTodayStatsBatch().catch((error) => {
|
||||
console.error('Failed to refresh account today stats after table load:', error)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
const isAnyModalOpen = computed(() => {
|
||||
return (
|
||||
showCreate.value ||
|
||||
@@ -602,6 +689,7 @@ const refreshAccountsIncrementally = async () => {
|
||||
type?: string
|
||||
status?: string
|
||||
search?: string
|
||||
lite?: string
|
||||
},
|
||||
{ etag: autoRefreshETag.value }
|
||||
)
|
||||
@@ -609,14 +697,14 @@ const refreshAccountsIncrementally = async () => {
|
||||
if (result.etag) {
|
||||
autoRefreshETag.value = result.etag
|
||||
}
|
||||
if (result.notModified || !result.data) {
|
||||
return
|
||||
if (!result.notModified && result.data) {
|
||||
pagination.total = result.data.total || 0
|
||||
pagination.pages = result.data.pages || 0
|
||||
mergeAccountsIncrementally(result.data.items || [])
|
||||
hasPendingListSync.value = false
|
||||
}
|
||||
|
||||
pagination.total = result.data.total || 0
|
||||
pagination.pages = result.data.pages || 0
|
||||
mergeAccountsIncrementally(result.data.items || [])
|
||||
hasPendingListSync.value = false
|
||||
await refreshTodayStatsBatch()
|
||||
} catch (error) {
|
||||
console.error('Auto refresh failed:', error)
|
||||
} finally {
|
||||
|
||||
@@ -246,7 +246,10 @@
|
||||
{{ t('admin.dashboard.recentUsage') }} (Top 12)
|
||||
</h3>
|
||||
<div class="h-64">
|
||||
<Line v-if="userTrendChartData" :data="userTrendChartData" :options="lineOptions" />
|
||||
<div v-if="userTrendLoading" class="flex h-full items-center justify-center">
|
||||
<LoadingSpinner size="md" />
|
||||
</div>
|
||||
<Line v-else-if="userTrendChartData" :data="userTrendChartData" :options="lineOptions" />
|
||||
<div
|
||||
v-else
|
||||
class="flex h-full items-center justify-center text-sm text-gray-500 dark:text-gray-400"
|
||||
@@ -306,11 +309,14 @@ const appStore = useAppStore()
|
||||
const stats = ref<DashboardStats | null>(null)
|
||||
const loading = ref(false)
|
||||
const chartsLoading = ref(false)
|
||||
const userTrendLoading = ref(false)
|
||||
|
||||
// Chart data
|
||||
const trendData = ref<TrendDataPoint[]>([])
|
||||
const modelStats = ref<ModelStat[]>([])
|
||||
const userTrend = ref<UserUsageTrendPoint[]>([])
|
||||
let chartLoadSeq = 0
|
||||
let usersTrendLoadSeq = 0
|
||||
|
||||
// Helper function to format date in local timezone
|
||||
const formatLocalDate = (date: Date): string => {
|
||||
@@ -366,6 +372,11 @@ const lineOptions = computed(() => ({
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
itemSort: (a: any, b: any) => {
|
||||
const aValue = typeof a?.raw === 'number' ? a.raw : Number(a?.parsed?.y ?? 0)
|
||||
const bValue = typeof b?.raw === 'number' ? b.raw : Number(b?.parsed?.y ?? 0)
|
||||
return bValue - aValue
|
||||
},
|
||||
callbacks: {
|
||||
label: (context: any) => {
|
||||
return `${context.dataset.label}: ${formatTokens(context.raw)}`
|
||||
@@ -513,46 +524,74 @@ const onDateRangeChange = (range: {
|
||||
}
|
||||
|
||||
// Load data
|
||||
const loadDashboardStats = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
stats.value = await adminAPI.dashboard.getStats()
|
||||
} catch (error) {
|
||||
appStore.showError(t('admin.dashboard.failedToLoad'))
|
||||
console.error('Error loading dashboard stats:', error)
|
||||
} finally {
|
||||
loading.value = false
|
||||
const loadDashboardSnapshot = async (includeStats: boolean) => {
|
||||
const currentSeq = ++chartLoadSeq
|
||||
if (includeStats && !stats.value) {
|
||||
loading.value = true
|
||||
}
|
||||
}
|
||||
|
||||
const loadChartData = async () => {
|
||||
chartsLoading.value = true
|
||||
try {
|
||||
const params = {
|
||||
const response = await adminAPI.dashboard.getSnapshotV2({
|
||||
start_date: startDate.value,
|
||||
end_date: endDate.value,
|
||||
granularity: granularity.value
|
||||
granularity: granularity.value,
|
||||
include_stats: includeStats,
|
||||
include_trend: true,
|
||||
include_model_stats: true,
|
||||
include_group_stats: false,
|
||||
include_users_trend: false
|
||||
})
|
||||
if (currentSeq !== chartLoadSeq) return
|
||||
if (includeStats && response.stats) {
|
||||
stats.value = response.stats
|
||||
}
|
||||
|
||||
const [trendResponse, modelResponse, userResponse] = await Promise.all([
|
||||
adminAPI.dashboard.getUsageTrend(params),
|
||||
adminAPI.dashboard.getModelStats({ start_date: startDate.value, end_date: endDate.value }),
|
||||
adminAPI.dashboard.getUserUsageTrend({ ...params, limit: 12 })
|
||||
])
|
||||
|
||||
trendData.value = trendResponse.trend || []
|
||||
modelStats.value = modelResponse.models || []
|
||||
userTrend.value = userResponse.trend || []
|
||||
trendData.value = response.trend || []
|
||||
modelStats.value = response.models || []
|
||||
} catch (error) {
|
||||
console.error('Error loading chart data:', error)
|
||||
if (currentSeq !== chartLoadSeq) return
|
||||
appStore.showError(t('admin.dashboard.failedToLoad'))
|
||||
console.error('Error loading dashboard snapshot:', error)
|
||||
} finally {
|
||||
if (currentSeq !== chartLoadSeq) return
|
||||
loading.value = false
|
||||
chartsLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const loadUsersTrend = async () => {
|
||||
const currentSeq = ++usersTrendLoadSeq
|
||||
userTrendLoading.value = true
|
||||
try {
|
||||
const response = await adminAPI.dashboard.getUserUsageTrend({
|
||||
start_date: startDate.value,
|
||||
end_date: endDate.value,
|
||||
granularity: granularity.value,
|
||||
limit: 12
|
||||
})
|
||||
if (currentSeq !== usersTrendLoadSeq) return
|
||||
userTrend.value = response.trend || []
|
||||
} catch (error) {
|
||||
if (currentSeq !== usersTrendLoadSeq) return
|
||||
console.error('Error loading users trend:', error)
|
||||
userTrend.value = []
|
||||
} finally {
|
||||
if (currentSeq !== usersTrendLoadSeq) return
|
||||
userTrendLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const loadDashboardStats = async () => {
|
||||
await loadDashboardSnapshot(true)
|
||||
void loadUsersTrend()
|
||||
}
|
||||
|
||||
const loadChartData = async () => {
|
||||
await loadDashboardSnapshot(false)
|
||||
void loadUsersTrend()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadDashboardStats()
|
||||
loadChartData()
|
||||
})
|
||||
</script>
|
||||
|
||||
|
||||
514
frontend/src/views/admin/DataManagementView.vue
Normal file
514
frontend/src/views/admin/DataManagementView.vue
Normal file
@@ -0,0 +1,514 @@
|
||||
<template>
|
||||
<AppLayout>
|
||||
<div class="space-y-6">
|
||||
<div class="card p-6">
|
||||
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h3 class="text-base font-semibold text-gray-900 dark:text-white">
|
||||
{{ t('admin.settings.soraS3.title') }}
|
||||
</h3>
|
||||
<p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
|
||||
{{ t('admin.settings.soraS3.description') }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button type="button" class="btn btn-secondary btn-sm" @click="startCreateSoraProfile">
|
||||
{{ t('admin.settings.soraS3.newProfile') }}
|
||||
</button>
|
||||
<button type="button" class="btn btn-secondary btn-sm" :disabled="loadingSoraProfiles" @click="loadSoraS3Profiles">
|
||||
{{ loadingSoraProfiles ? t('common.loading') : t('admin.settings.soraS3.reloadProfiles') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full min-w-[1000px] text-sm">
|
||||
<thead>
|
||||
<tr class="border-b border-gray-200 text-left text-xs uppercase tracking-wide text-gray-500 dark:border-dark-700 dark:text-gray-400">
|
||||
<th class="py-2 pr-4">{{ t('admin.settings.soraS3.columns.profile') }}</th>
|
||||
<th class="py-2 pr-4">{{ t('admin.settings.soraS3.columns.active') }}</th>
|
||||
<th class="py-2 pr-4">{{ t('admin.settings.soraS3.columns.endpoint') }}</th>
|
||||
<th class="py-2 pr-4">{{ t('admin.settings.soraS3.columns.bucket') }}</th>
|
||||
<th class="py-2 pr-4">{{ t('admin.settings.soraS3.columns.quota') }}</th>
|
||||
<th class="py-2 pr-4">{{ t('admin.settings.soraS3.columns.updatedAt') }}</th>
|
||||
<th class="py-2">{{ t('admin.settings.soraS3.columns.actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="profile in soraS3Profiles" :key="profile.profile_id" class="border-b border-gray-100 align-top dark:border-dark-800">
|
||||
<td class="py-3 pr-4">
|
||||
<div class="font-mono text-xs">{{ profile.profile_id }}</div>
|
||||
<div class="mt-1 text-xs text-gray-600 dark:text-gray-400">{{ profile.name }}</div>
|
||||
</td>
|
||||
<td class="py-3 pr-4">
|
||||
<span
|
||||
class="rounded px-2 py-0.5 text-xs"
|
||||
:class="profile.is_active ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300' : 'bg-gray-100 text-gray-700 dark:bg-dark-800 dark:text-gray-300'"
|
||||
>
|
||||
{{ profile.is_active ? t('common.enabled') : t('common.disabled') }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="py-3 pr-4 text-xs">
|
||||
<div>{{ profile.endpoint || '-' }}</div>
|
||||
<div class="mt-1 text-gray-500 dark:text-gray-400">{{ profile.region || '-' }}</div>
|
||||
</td>
|
||||
<td class="py-3 pr-4 text-xs">{{ profile.bucket || '-' }}</td>
|
||||
<td class="py-3 pr-4 text-xs">{{ formatStorageQuotaGB(profile.default_storage_quota_bytes) }}</td>
|
||||
<td class="py-3 pr-4 text-xs">{{ formatDate(profile.updated_at) }}</td>
|
||||
<td class="py-3 text-xs">
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button type="button" class="btn btn-secondary btn-xs" @click="editSoraProfile(profile.profile_id)">
|
||||
{{ t('common.edit') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="!profile.is_active"
|
||||
type="button"
|
||||
class="btn btn-secondary btn-xs"
|
||||
:disabled="activatingSoraProfile"
|
||||
@click="activateSoraProfile(profile.profile_id)"
|
||||
>
|
||||
{{ t('admin.settings.soraS3.activateProfile') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-danger btn-xs"
|
||||
:disabled="deletingSoraProfile"
|
||||
@click="removeSoraProfile(profile.profile_id)"
|
||||
>
|
||||
{{ t('common.delete') }}
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-if="soraS3Profiles.length === 0">
|
||||
<td colspan="7" class="py-6 text-center text-sm text-gray-500 dark:text-gray-400">
|
||||
{{ t('admin.settings.soraS3.empty') }}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Teleport to="body">
|
||||
<Transition name="dm-drawer-mask">
|
||||
<div
|
||||
v-if="soraProfileDrawerOpen"
|
||||
class="fixed inset-0 z-[54] bg-black/40 backdrop-blur-sm"
|
||||
@click="closeSoraProfileDrawer"
|
||||
></div>
|
||||
</Transition>
|
||||
|
||||
<Transition name="dm-drawer-panel">
|
||||
<div
|
||||
v-if="soraProfileDrawerOpen"
|
||||
class="fixed inset-y-0 right-0 z-[55] flex h-full w-full max-w-2xl flex-col border-l border-gray-200 bg-white shadow-2xl dark:border-dark-700 dark:bg-dark-900"
|
||||
>
|
||||
<div class="flex items-center justify-between border-b border-gray-200 px-4 py-3 dark:border-dark-700">
|
||||
<h4 class="text-sm font-semibold text-gray-900 dark:text-white">
|
||||
{{ creatingSoraProfile ? t('admin.settings.soraS3.createTitle') : t('admin.settings.soraS3.editTitle') }}
|
||||
</h4>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded p-1 text-gray-500 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:bg-dark-800 dark:hover:text-gray-200"
|
||||
@click="closeSoraProfileDrawer"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="flex-1 overflow-y-auto p-4">
|
||||
<div class="grid grid-cols-1 gap-3 md:grid-cols-2">
|
||||
<input
|
||||
v-model="soraProfileForm.profile_id"
|
||||
class="input w-full"
|
||||
:placeholder="t('admin.settings.soraS3.profileID')"
|
||||
:disabled="!creatingSoraProfile"
|
||||
/>
|
||||
<input
|
||||
v-model="soraProfileForm.name"
|
||||
class="input w-full"
|
||||
:placeholder="t('admin.settings.soraS3.profileName')"
|
||||
/>
|
||||
<label class="inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300 md:col-span-2">
|
||||
<input v-model="soraProfileForm.enabled" type="checkbox" />
|
||||
<span>{{ t('admin.settings.soraS3.enabled') }}</span>
|
||||
</label>
|
||||
<input v-model="soraProfileForm.endpoint" class="input w-full" :placeholder="t('admin.settings.soraS3.endpoint')" />
|
||||
<input v-model="soraProfileForm.region" class="input w-full" :placeholder="t('admin.settings.soraS3.region')" />
|
||||
<input v-model="soraProfileForm.bucket" class="input w-full" :placeholder="t('admin.settings.soraS3.bucket')" />
|
||||
<input v-model="soraProfileForm.prefix" class="input w-full" :placeholder="t('admin.settings.soraS3.prefix')" />
|
||||
<input v-model="soraProfileForm.access_key_id" class="input w-full" :placeholder="t('admin.settings.soraS3.accessKeyId')" />
|
||||
<input
|
||||
v-model="soraProfileForm.secret_access_key"
|
||||
type="password"
|
||||
class="input w-full"
|
||||
:placeholder="soraProfileForm.secret_access_key_configured ? t('admin.settings.soraS3.secretConfigured') : t('admin.settings.soraS3.secretAccessKey')"
|
||||
/>
|
||||
<input v-model="soraProfileForm.cdn_url" class="input w-full" :placeholder="t('admin.settings.soraS3.cdnUrl')" />
|
||||
<div>
|
||||
<input
|
||||
v-model.number="soraProfileForm.default_storage_quota_gb"
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.1"
|
||||
class="input w-full"
|
||||
:placeholder="t('admin.settings.soraS3.defaultQuota')"
|
||||
/>
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">{{ t('admin.settings.soraS3.defaultQuotaHint') }}</p>
|
||||
</div>
|
||||
<label class="inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
|
||||
<input v-model="soraProfileForm.force_path_style" type="checkbox" />
|
||||
<span>{{ t('admin.settings.soraS3.forcePathStyle') }}</span>
|
||||
</label>
|
||||
<label v-if="creatingSoraProfile" class="inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300 md:col-span-2">
|
||||
<input v-model="soraProfileForm.set_active" type="checkbox" />
|
||||
<span>{{ t('admin.settings.soraS3.setActive') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap justify-end gap-2 border-t border-gray-200 p-4 dark:border-dark-700">
|
||||
<button type="button" class="btn btn-secondary btn-sm" @click="closeSoraProfileDrawer">
|
||||
{{ t('common.cancel') }}
|
||||
</button>
|
||||
<button type="button" class="btn btn-secondary btn-sm" :disabled="testingSoraProfile || !soraProfileForm.enabled" @click="testSoraProfileConnection">
|
||||
{{ testingSoraProfile ? t('common.loading') : t('admin.settings.soraS3.testConnection') }}
|
||||
</button>
|
||||
<button type="button" class="btn btn-primary btn-sm" :disabled="savingSoraProfile" @click="saveSoraProfile">
|
||||
{{ savingSoraProfile ? t('common.loading') : t('admin.settings.soraS3.saveProfile') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Transition>
|
||||
</Teleport>
|
||||
</AppLayout>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import AppLayout from '@/components/layout/AppLayout.vue'
|
||||
import type { SoraS3Profile } from '@/api/admin/settings'
|
||||
import { adminAPI } from '@/api'
|
||||
import { useAppStore } from '@/stores'
|
||||
|
||||
const { t } = useI18n()
|
||||
const appStore = useAppStore()
|
||||
|
||||
const loadingSoraProfiles = ref(false)
|
||||
const savingSoraProfile = ref(false)
|
||||
const testingSoraProfile = ref(false)
|
||||
const activatingSoraProfile = ref(false)
|
||||
const deletingSoraProfile = ref(false)
|
||||
const creatingSoraProfile = ref(false)
|
||||
const soraProfileDrawerOpen = ref(false)
|
||||
|
||||
const soraS3Profiles = ref<SoraS3Profile[]>([])
|
||||
const selectedSoraProfileID = ref('')
|
||||
|
||||
type SoraS3ProfileForm = {
|
||||
profile_id: string
|
||||
name: string
|
||||
set_active: boolean
|
||||
enabled: boolean
|
||||
endpoint: string
|
||||
region: string
|
||||
bucket: string
|
||||
access_key_id: string
|
||||
secret_access_key: string
|
||||
secret_access_key_configured: boolean
|
||||
prefix: string
|
||||
force_path_style: boolean
|
||||
cdn_url: string
|
||||
default_storage_quota_gb: number
|
||||
}
|
||||
|
||||
const soraProfileForm = ref<SoraS3ProfileForm>(newDefaultSoraS3ProfileForm())
|
||||
|
||||
async function loadSoraS3Profiles() {
|
||||
loadingSoraProfiles.value = true
|
||||
try {
|
||||
const result = await adminAPI.settings.listSoraS3Profiles()
|
||||
soraS3Profiles.value = result.items || []
|
||||
if (!creatingSoraProfile.value) {
|
||||
const stillExists = selectedSoraProfileID.value
|
||||
? soraS3Profiles.value.some((item) => item.profile_id === selectedSoraProfileID.value)
|
||||
: false
|
||||
if (!stillExists) {
|
||||
selectedSoraProfileID.value = pickPreferredSoraProfileID()
|
||||
}
|
||||
syncSoraProfileFormWithSelection()
|
||||
}
|
||||
} catch (error) {
|
||||
appStore.showError((error as { message?: string })?.message || t('errors.networkError'))
|
||||
} finally {
|
||||
loadingSoraProfiles.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function startCreateSoraProfile() {
|
||||
creatingSoraProfile.value = true
|
||||
selectedSoraProfileID.value = ''
|
||||
soraProfileForm.value = newDefaultSoraS3ProfileForm()
|
||||
soraProfileDrawerOpen.value = true
|
||||
}
|
||||
|
||||
function editSoraProfile(profileID: string) {
|
||||
selectedSoraProfileID.value = profileID
|
||||
creatingSoraProfile.value = false
|
||||
syncSoraProfileFormWithSelection()
|
||||
soraProfileDrawerOpen.value = true
|
||||
}
|
||||
|
||||
function closeSoraProfileDrawer() {
|
||||
soraProfileDrawerOpen.value = false
|
||||
if (creatingSoraProfile.value) {
|
||||
creatingSoraProfile.value = false
|
||||
selectedSoraProfileID.value = pickPreferredSoraProfileID()
|
||||
syncSoraProfileFormWithSelection()
|
||||
}
|
||||
}
|
||||
|
||||
async function saveSoraProfile() {
|
||||
if (!soraProfileForm.value.name.trim()) {
|
||||
appStore.showError(t('admin.settings.soraS3.profileNameRequired'))
|
||||
return
|
||||
}
|
||||
if (creatingSoraProfile.value && !soraProfileForm.value.profile_id.trim()) {
|
||||
appStore.showError(t('admin.settings.soraS3.profileIDRequired'))
|
||||
return
|
||||
}
|
||||
if (!creatingSoraProfile.value && !selectedSoraProfileID.value) {
|
||||
appStore.showError(t('admin.settings.soraS3.profileSelectRequired'))
|
||||
return
|
||||
}
|
||||
if (soraProfileForm.value.enabled) {
|
||||
if (!soraProfileForm.value.endpoint.trim()) {
|
||||
appStore.showError(t('admin.settings.soraS3.endpointRequired'))
|
||||
return
|
||||
}
|
||||
if (!soraProfileForm.value.bucket.trim()) {
|
||||
appStore.showError(t('admin.settings.soraS3.bucketRequired'))
|
||||
return
|
||||
}
|
||||
if (!soraProfileForm.value.access_key_id.trim()) {
|
||||
appStore.showError(t('admin.settings.soraS3.accessKeyRequired'))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
savingSoraProfile.value = true
|
||||
try {
|
||||
if (creatingSoraProfile.value) {
|
||||
const created = await adminAPI.settings.createSoraS3Profile({
|
||||
profile_id: soraProfileForm.value.profile_id.trim(),
|
||||
name: soraProfileForm.value.name.trim(),
|
||||
set_active: soraProfileForm.value.set_active,
|
||||
enabled: soraProfileForm.value.enabled,
|
||||
endpoint: soraProfileForm.value.endpoint,
|
||||
region: soraProfileForm.value.region,
|
||||
bucket: soraProfileForm.value.bucket,
|
||||
access_key_id: soraProfileForm.value.access_key_id,
|
||||
secret_access_key: soraProfileForm.value.secret_access_key || undefined,
|
||||
prefix: soraProfileForm.value.prefix,
|
||||
force_path_style: soraProfileForm.value.force_path_style,
|
||||
cdn_url: soraProfileForm.value.cdn_url,
|
||||
default_storage_quota_bytes: Math.round((soraProfileForm.value.default_storage_quota_gb || 0) * 1024 * 1024 * 1024)
|
||||
})
|
||||
selectedSoraProfileID.value = created.profile_id
|
||||
creatingSoraProfile.value = false
|
||||
soraProfileDrawerOpen.value = false
|
||||
appStore.showSuccess(t('admin.settings.soraS3.profileCreated'))
|
||||
} else {
|
||||
await adminAPI.settings.updateSoraS3Profile(selectedSoraProfileID.value, {
|
||||
name: soraProfileForm.value.name.trim(),
|
||||
enabled: soraProfileForm.value.enabled,
|
||||
endpoint: soraProfileForm.value.endpoint,
|
||||
region: soraProfileForm.value.region,
|
||||
bucket: soraProfileForm.value.bucket,
|
||||
access_key_id: soraProfileForm.value.access_key_id,
|
||||
secret_access_key: soraProfileForm.value.secret_access_key || undefined,
|
||||
prefix: soraProfileForm.value.prefix,
|
||||
force_path_style: soraProfileForm.value.force_path_style,
|
||||
cdn_url: soraProfileForm.value.cdn_url,
|
||||
default_storage_quota_bytes: Math.round((soraProfileForm.value.default_storage_quota_gb || 0) * 1024 * 1024 * 1024)
|
||||
})
|
||||
soraProfileDrawerOpen.value = false
|
||||
appStore.showSuccess(t('admin.settings.soraS3.profileSaved'))
|
||||
}
|
||||
await loadSoraS3Profiles()
|
||||
} catch (error) {
|
||||
appStore.showError((error as { message?: string })?.message || t('errors.networkError'))
|
||||
} finally {
|
||||
savingSoraProfile.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function testSoraProfileConnection() {
|
||||
testingSoraProfile.value = true
|
||||
try {
|
||||
const result = await adminAPI.settings.testSoraS3Connection({
|
||||
profile_id: creatingSoraProfile.value ? undefined : selectedSoraProfileID.value,
|
||||
enabled: soraProfileForm.value.enabled,
|
||||
endpoint: soraProfileForm.value.endpoint,
|
||||
region: soraProfileForm.value.region,
|
||||
bucket: soraProfileForm.value.bucket,
|
||||
access_key_id: soraProfileForm.value.access_key_id,
|
||||
secret_access_key: soraProfileForm.value.secret_access_key || undefined,
|
||||
prefix: soraProfileForm.value.prefix,
|
||||
force_path_style: soraProfileForm.value.force_path_style,
|
||||
cdn_url: soraProfileForm.value.cdn_url,
|
||||
default_storage_quota_bytes: Math.round((soraProfileForm.value.default_storage_quota_gb || 0) * 1024 * 1024 * 1024)
|
||||
})
|
||||
appStore.showSuccess(result.message || t('admin.settings.soraS3.testSuccess'))
|
||||
} catch (error) {
|
||||
appStore.showError((error as { message?: string })?.message || t('errors.networkError'))
|
||||
} finally {
|
||||
testingSoraProfile.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function activateSoraProfile(profileID: string) {
|
||||
activatingSoraProfile.value = true
|
||||
try {
|
||||
await adminAPI.settings.setActiveSoraS3Profile(profileID)
|
||||
appStore.showSuccess(t('admin.settings.soraS3.profileActivated'))
|
||||
await loadSoraS3Profiles()
|
||||
} catch (error) {
|
||||
appStore.showError((error as { message?: string })?.message || t('errors.networkError'))
|
||||
} finally {
|
||||
activatingSoraProfile.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function removeSoraProfile(profileID: string) {
|
||||
if (!window.confirm(t('admin.settings.soraS3.deleteConfirm', { profileID }))) {
|
||||
return
|
||||
}
|
||||
deletingSoraProfile.value = true
|
||||
try {
|
||||
await adminAPI.settings.deleteSoraS3Profile(profileID)
|
||||
if (selectedSoraProfileID.value === profileID) {
|
||||
selectedSoraProfileID.value = ''
|
||||
}
|
||||
appStore.showSuccess(t('admin.settings.soraS3.profileDeleted'))
|
||||
await loadSoraS3Profiles()
|
||||
} catch (error) {
|
||||
appStore.showError((error as { message?: string })?.message || t('errors.networkError'))
|
||||
} finally {
|
||||
deletingSoraProfile.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function formatDate(value?: string): string {
|
||||
if (!value) {
|
||||
return '-'
|
||||
}
|
||||
const date = new Date(value)
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return value
|
||||
}
|
||||
return date.toLocaleString()
|
||||
}
|
||||
|
||||
function formatStorageQuotaGB(bytes: number): string {
|
||||
if (!bytes || bytes <= 0) {
|
||||
return '0 GB'
|
||||
}
|
||||
const gb = bytes / (1024 * 1024 * 1024)
|
||||
return `${gb.toFixed(gb >= 10 ? 0 : 1)} GB`
|
||||
}
|
||||
|
||||
function pickPreferredSoraProfileID(): string {
|
||||
const active = soraS3Profiles.value.find((item) => item.is_active)
|
||||
if (active) {
|
||||
return active.profile_id
|
||||
}
|
||||
return soraS3Profiles.value[0]?.profile_id || ''
|
||||
}
|
||||
|
||||
function syncSoraProfileFormWithSelection() {
|
||||
const profile = soraS3Profiles.value.find((item) => item.profile_id === selectedSoraProfileID.value)
|
||||
soraProfileForm.value = newDefaultSoraS3ProfileForm(profile)
|
||||
}
|
||||
|
||||
function newDefaultSoraS3ProfileForm(profile?: SoraS3Profile): SoraS3ProfileForm {
|
||||
if (!profile) {
|
||||
return {
|
||||
profile_id: '',
|
||||
name: '',
|
||||
set_active: false,
|
||||
enabled: false,
|
||||
endpoint: '',
|
||||
region: '',
|
||||
bucket: '',
|
||||
access_key_id: '',
|
||||
secret_access_key: '',
|
||||
secret_access_key_configured: false,
|
||||
prefix: 'sora/',
|
||||
force_path_style: false,
|
||||
cdn_url: '',
|
||||
default_storage_quota_gb: 0
|
||||
}
|
||||
}
|
||||
|
||||
const quotaBytes = profile.default_storage_quota_bytes || 0
|
||||
|
||||
return {
|
||||
profile_id: profile.profile_id,
|
||||
name: profile.name,
|
||||
set_active: false,
|
||||
enabled: profile.enabled,
|
||||
endpoint: profile.endpoint || '',
|
||||
region: profile.region || '',
|
||||
bucket: profile.bucket || '',
|
||||
access_key_id: profile.access_key_id || '',
|
||||
secret_access_key: '',
|
||||
secret_access_key_configured: Boolean(profile.secret_access_key_configured),
|
||||
prefix: profile.prefix || '',
|
||||
force_path_style: Boolean(profile.force_path_style),
|
||||
cdn_url: profile.cdn_url || '',
|
||||
default_storage_quota_gb: Number((quotaBytes / (1024 * 1024 * 1024)).toFixed(2))
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await loadSoraS3Profiles()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.dm-drawer-mask-enter-active,
|
||||
.dm-drawer-mask-leave-active {
|
||||
transition: opacity 0.2s ease;
|
||||
}
|
||||
|
||||
.dm-drawer-mask-enter-from,
|
||||
.dm-drawer-mask-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.dm-drawer-panel-enter-active,
|
||||
.dm-drawer-panel-leave-active {
|
||||
transition:
|
||||
transform 0.24s cubic-bezier(0.22, 1, 0.36, 1),
|
||||
opacity 0.2s ease;
|
||||
}
|
||||
|
||||
.dm-drawer-panel-enter-from,
|
||||
.dm-drawer-panel-leave-to {
|
||||
opacity: 0.96;
|
||||
transform: translateX(100%);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.dm-drawer-mask-enter-active,
|
||||
.dm-drawer-mask-leave-active,
|
||||
.dm-drawer-panel-enter-active,
|
||||
.dm-drawer-panel-leave-active {
|
||||
transition-duration: 0s;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -532,6 +532,23 @@
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-3">
|
||||
<label class="input-label">{{ t('admin.groups.soraPricing.storageQuota') }}</label>
|
||||
<div class="flex items-center gap-2">
|
||||
<input
|
||||
v-model.number="createForm.sora_storage_quota_gb"
|
||||
type="number"
|
||||
step="0.1"
|
||||
min="0"
|
||||
class="input"
|
||||
placeholder="10"
|
||||
/>
|
||||
<span class="shrink-0 text-sm text-gray-500">GB</span>
|
||||
</div>
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
{{ t('admin.groups.soraPricing.storageQuotaHint') }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 支持的模型系列(仅 antigravity 平台) -->
|
||||
@@ -1264,6 +1281,23 @@
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-3">
|
||||
<label class="input-label">{{ t('admin.groups.soraPricing.storageQuota') }}</label>
|
||||
<div class="flex items-center gap-2">
|
||||
<input
|
||||
v-model.number="editForm.sora_storage_quota_gb"
|
||||
type="number"
|
||||
step="0.1"
|
||||
min="0"
|
||||
class="input"
|
||||
placeholder="10"
|
||||
/>
|
||||
<span class="shrink-0 text-sm text-gray-500">GB</span>
|
||||
</div>
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
{{ t('admin.groups.soraPricing.storageQuotaHint') }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 支持的模型系列(仅 antigravity 平台) -->
|
||||
@@ -1985,6 +2019,7 @@ const createForm = reactive({
|
||||
sora_image_price_540: null as number | null,
|
||||
sora_video_price_per_request: null as number | null,
|
||||
sora_video_price_per_request_hd: null as number | null,
|
||||
sora_storage_quota_gb: null as number | null,
|
||||
// Claude Code 客户端限制(仅 anthropic 平台使用)
|
||||
claude_code_only: false,
|
||||
// Claude Max usage 模拟开关(仅 anthropic 平台)
|
||||
@@ -2227,6 +2262,7 @@ const editForm = reactive({
|
||||
sora_image_price_540: null as number | null,
|
||||
sora_video_price_per_request: null as number | null,
|
||||
sora_video_price_per_request_hd: null as number | null,
|
||||
sora_storage_quota_gb: null as number | null,
|
||||
// Claude Code 客户端限制(仅 anthropic 平台使用)
|
||||
claude_code_only: false,
|
||||
// Claude Max usage 模拟开关(仅 anthropic 平台)
|
||||
@@ -2328,6 +2364,7 @@ const closeCreateModal = () => {
|
||||
createForm.sora_image_price_540 = null
|
||||
createForm.sora_video_price_per_request = null
|
||||
createForm.sora_video_price_per_request_hd = null
|
||||
createForm.sora_storage_quota_gb = null
|
||||
createForm.claude_code_only = false
|
||||
createForm.simulate_claude_max_enabled = false
|
||||
createForm.fallback_group_id = null
|
||||
@@ -2346,8 +2383,10 @@ const handleCreateGroup = async () => {
|
||||
submitting.value = true
|
||||
try {
|
||||
// 构建请求数据,包含模型路由配置
|
||||
const { sora_storage_quota_gb: createQuotaGb, ...createRest } = createForm
|
||||
const requestData = {
|
||||
...createForm,
|
||||
...createRest,
|
||||
sora_storage_quota_bytes: createQuotaGb ? Math.round(createQuotaGb * 1024 * 1024 * 1024) : 0,
|
||||
simulate_claude_max_enabled:
|
||||
createForm.platform === 'anthropic' ? createForm.simulate_claude_max_enabled : false,
|
||||
model_routing: convertRoutingRulesToApiFormat(createModelRoutingRules.value)
|
||||
@@ -2388,6 +2427,7 @@ const handleEdit = async (group: AdminGroup) => {
|
||||
editForm.sora_image_price_540 = group.sora_image_price_540
|
||||
editForm.sora_video_price_per_request = group.sora_video_price_per_request
|
||||
editForm.sora_video_price_per_request_hd = group.sora_video_price_per_request_hd
|
||||
editForm.sora_storage_quota_gb = group.sora_storage_quota_bytes ? Number((group.sora_storage_quota_bytes / (1024 * 1024 * 1024)).toFixed(2)) : null
|
||||
editForm.claude_code_only = group.claude_code_only || false
|
||||
editForm.simulate_claude_max_enabled = group.simulate_claude_max_enabled || false
|
||||
editForm.fallback_group_id = group.fallback_group_id
|
||||
@@ -2423,8 +2463,10 @@ const handleUpdateGroup = async () => {
|
||||
submitting.value = true
|
||||
try {
|
||||
// 转换 fallback_group_id: null -> 0 (后端使用 0 表示清除)
|
||||
const { sora_storage_quota_gb: editQuotaGb, ...editRest } = editForm
|
||||
const payload = {
|
||||
...editForm,
|
||||
...editRest,
|
||||
sora_storage_quota_bytes: editQuotaGb ? Math.round(editQuotaGb * 1024 * 1024 * 1024) : 0,
|
||||
simulate_claude_max_enabled:
|
||||
editForm.platform === 'anthropic' ? editForm.simulate_claude_max_enabled : false,
|
||||
fallback_group_id: editForm.fallback_group_id === null ? 0 : editForm.fallback_group_id,
|
||||
|
||||
@@ -124,7 +124,54 @@
|
||||
</template>
|
||||
|
||||
<template #cell-address="{ row }">
|
||||
<code class="code text-xs">{{ row.host }}:{{ row.port }}</code>
|
||||
<div class="flex items-center gap-1.5">
|
||||
<code class="code text-xs">{{ row.host }}:{{ row.port }}</code>
|
||||
<div class="relative">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded p-0.5 text-gray-400 hover:text-primary-600 dark:hover:text-primary-400"
|
||||
:title="t('admin.proxies.copyProxyUrl')"
|
||||
@click.stop="copyProxyUrl(row)"
|
||||
@contextmenu.prevent="toggleCopyMenu(row.id)"
|
||||
>
|
||||
<Icon name="copy" size="sm" />
|
||||
</button>
|
||||
<!-- 右键展开格式选择菜单 -->
|
||||
<div
|
||||
v-if="copyMenuProxyId === row.id"
|
||||
class="absolute left-0 top-full z-50 mt-1 w-auto min-w-[180px] rounded-lg border border-gray-200 bg-white py-1 shadow-lg dark:border-dark-500 dark:bg-dark-700"
|
||||
>
|
||||
<button
|
||||
v-for="fmt in getCopyFormats(row)"
|
||||
:key="fmt.label"
|
||||
class="flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs hover:bg-gray-100 dark:hover:bg-dark-600"
|
||||
@click.stop="copyFormat(fmt.value)"
|
||||
>
|
||||
<span class="truncate font-mono text-gray-600 dark:text-gray-300">{{ fmt.label }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #cell-auth="{ row }">
|
||||
<div v-if="row.username || row.password" class="flex items-center gap-1.5">
|
||||
<div class="flex flex-col text-xs">
|
||||
<span v-if="row.username" class="text-gray-700 dark:text-gray-200">{{ row.username }}</span>
|
||||
<span v-if="row.password" class="font-mono text-gray-500 dark:text-gray-400">
|
||||
{{ visiblePasswordIds.has(row.id) ? row.password : '••••••' }}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
v-if="row.password"
|
||||
type="button"
|
||||
class="ml-1 rounded p-0.5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
|
||||
@click.stop="visiblePasswordIds.has(row.id) ? visiblePasswordIds.delete(row.id) : visiblePasswordIds.add(row.id)"
|
||||
>
|
||||
<Icon :name="visiblePasswordIds.has(row.id) ? 'eyeOff' : 'eye'" size="sm" />
|
||||
</button>
|
||||
</div>
|
||||
<span v-else class="text-sm text-gray-400">-</span>
|
||||
</template>
|
||||
|
||||
<template #cell-location="{ row }">
|
||||
@@ -397,12 +444,21 @@
|
||||
</div>
|
||||
<div>
|
||||
<label class="input-label">{{ t('admin.proxies.password') }}</label>
|
||||
<input
|
||||
v-model="createForm.password"
|
||||
type="password"
|
||||
class="input"
|
||||
:placeholder="t('admin.proxies.optionalAuth')"
|
||||
/>
|
||||
<div class="relative">
|
||||
<input
|
||||
v-model="createForm.password"
|
||||
:type="createPasswordVisible ? 'text' : 'password'"
|
||||
class="input pr-10"
|
||||
:placeholder="t('admin.proxies.optionalAuth')"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
|
||||
@click="createPasswordVisible = !createPasswordVisible"
|
||||
>
|
||||
<Icon :name="createPasswordVisible ? 'eyeOff' : 'eye'" size="md" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</form>
|
||||
@@ -581,12 +637,22 @@
|
||||
</div>
|
||||
<div>
|
||||
<label class="input-label">{{ t('admin.proxies.password') }}</label>
|
||||
<input
|
||||
v-model="editForm.password"
|
||||
type="password"
|
||||
:placeholder="t('admin.proxies.leaveEmptyToKeep')"
|
||||
class="input"
|
||||
/>
|
||||
<div class="relative">
|
||||
<input
|
||||
v-model="editForm.password"
|
||||
:type="editPasswordVisible ? 'text' : 'password'"
|
||||
:placeholder="t('admin.proxies.leaveEmptyToKeep')"
|
||||
class="input pr-10"
|
||||
@input="editPasswordDirty = true"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
|
||||
@click="editPasswordVisible = !editPasswordVisible"
|
||||
>
|
||||
<Icon :name="editPasswordVisible ? 'eyeOff' : 'eye'" size="md" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="input-label">{{ t('admin.proxies.status') }}</label>
|
||||
@@ -813,15 +879,18 @@ import ImportDataModal from '@/components/admin/proxy/ImportDataModal.vue'
|
||||
import Select from '@/components/common/Select.vue'
|
||||
import Icon from '@/components/icons/Icon.vue'
|
||||
import PlatformTypeBadge from '@/components/common/PlatformTypeBadge.vue'
|
||||
import { useClipboard } from '@/composables/useClipboard'
|
||||
|
||||
const { t } = useI18n()
|
||||
const appStore = useAppStore()
|
||||
const { copyToClipboard } = useClipboard()
|
||||
|
||||
const columns = computed<Column[]>(() => [
|
||||
{ key: 'select', label: '', sortable: false },
|
||||
{ key: 'name', label: t('admin.proxies.columns.name'), sortable: true },
|
||||
{ key: 'protocol', label: t('admin.proxies.columns.protocol'), sortable: true },
|
||||
{ key: 'address', label: t('admin.proxies.columns.address'), sortable: false },
|
||||
{ key: 'auth', label: t('admin.proxies.columns.auth'), sortable: false },
|
||||
{ key: 'location', label: t('admin.proxies.columns.location'), sortable: false },
|
||||
{ key: 'account_count', label: t('admin.proxies.columns.accounts'), sortable: true },
|
||||
{ key: 'latency', label: t('admin.proxies.columns.latency'), sortable: false },
|
||||
@@ -858,6 +927,8 @@ const editStatusOptions = computed(() => [
|
||||
])
|
||||
|
||||
const proxies = ref<Proxy[]>([])
|
||||
const visiblePasswordIds = reactive(new Set<number>())
|
||||
const copyMenuProxyId = ref<number | null>(null)
|
||||
const loading = ref(false)
|
||||
const searchQuery = ref('')
|
||||
const filters = reactive({
|
||||
@@ -872,7 +943,10 @@ const pagination = reactive({
|
||||
})
|
||||
|
||||
const showCreateModal = ref(false)
|
||||
const createPasswordVisible = ref(false)
|
||||
const showEditModal = ref(false)
|
||||
const editPasswordVisible = ref(false)
|
||||
const editPasswordDirty = ref(false)
|
||||
const showImportData = ref(false)
|
||||
const showDeleteDialog = ref(false)
|
||||
const showBatchDeleteDialog = ref(false)
|
||||
@@ -1030,6 +1104,7 @@ const closeCreateModal = () => {
|
||||
createForm.port = 8080
|
||||
createForm.username = ''
|
||||
createForm.password = ''
|
||||
createPasswordVisible.value = false
|
||||
batchInput.value = ''
|
||||
batchParseResult.total = 0
|
||||
batchParseResult.valid = 0
|
||||
@@ -1173,14 +1248,18 @@ const handleEdit = (proxy: Proxy) => {
|
||||
editForm.host = proxy.host
|
||||
editForm.port = proxy.port
|
||||
editForm.username = proxy.username || ''
|
||||
editForm.password = ''
|
||||
editForm.password = proxy.password || ''
|
||||
editForm.status = proxy.status
|
||||
editPasswordVisible.value = false
|
||||
editPasswordDirty.value = false
|
||||
showEditModal.value = true
|
||||
}
|
||||
|
||||
const closeEditModal = () => {
|
||||
showEditModal.value = false
|
||||
editingProxy.value = null
|
||||
editPasswordVisible.value = false
|
||||
editPasswordDirty.value = false
|
||||
}
|
||||
|
||||
const handleUpdateProxy = async () => {
|
||||
@@ -1209,10 +1288,9 @@ const handleUpdateProxy = async () => {
|
||||
status: editForm.status
|
||||
}
|
||||
|
||||
// Only include password if it was changed
|
||||
const trimmedPassword = editForm.password.trim()
|
||||
if (trimmedPassword) {
|
||||
updateData.password = trimmedPassword
|
||||
// Only include password if user actually modified the field
|
||||
if (editPasswordDirty.value) {
|
||||
updateData.password = editForm.password.trim() || null
|
||||
}
|
||||
|
||||
await adminAPI.proxies.update(editingProxy.value.id, updateData)
|
||||
@@ -1715,12 +1793,60 @@ const closeAccountsModal = () => {
|
||||
proxyAccounts.value = []
|
||||
}
|
||||
|
||||
// ── Proxy URL copy ──
|
||||
function buildAuthPart(row: any): string {
|
||||
const user = row.username ? encodeURIComponent(row.username) : ''
|
||||
const pass = row.password ? encodeURIComponent(row.password) : ''
|
||||
if (user && pass) return `${user}:${pass}@`
|
||||
if (user) return `${user}@`
|
||||
if (pass) return `:${pass}@`
|
||||
return ''
|
||||
}
|
||||
|
||||
function buildProxyUrl(row: any): string {
|
||||
return `${row.protocol}://${buildAuthPart(row)}${row.host}:${row.port}`
|
||||
}
|
||||
|
||||
function getCopyFormats(row: any) {
|
||||
const hasAuth = row.username || row.password
|
||||
const fullUrl = buildProxyUrl(row)
|
||||
const formats = [
|
||||
{ label: fullUrl, value: fullUrl },
|
||||
]
|
||||
if (hasAuth) {
|
||||
const withoutProtocol = fullUrl.replace(/^[^:]+:\/\//, '')
|
||||
formats.push({ label: withoutProtocol, value: withoutProtocol })
|
||||
}
|
||||
formats.push({ label: `${row.host}:${row.port}`, value: `${row.host}:${row.port}` })
|
||||
return formats
|
||||
}
|
||||
|
||||
function copyProxyUrl(row: any) {
|
||||
copyToClipboard(buildProxyUrl(row), t('admin.proxies.urlCopied'))
|
||||
copyMenuProxyId.value = null
|
||||
}
|
||||
|
||||
function toggleCopyMenu(id: number) {
|
||||
copyMenuProxyId.value = copyMenuProxyId.value === id ? null : id
|
||||
}
|
||||
|
||||
function copyFormat(value: string) {
|
||||
copyToClipboard(value, t('admin.proxies.urlCopied'))
|
||||
copyMenuProxyId.value = null
|
||||
}
|
||||
|
||||
function closeCopyMenu() {
|
||||
copyMenuProxyId.value = null
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadProxies()
|
||||
document.addEventListener('click', closeCopyMenu)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
clearTimeout(searchTimeout)
|
||||
abortController?.abort()
|
||||
document.removeEventListener('click', closeCopyMenu)
|
||||
})
|
||||
</script>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -74,11 +74,12 @@ import { useI18n } from 'vue-i18n'
|
||||
import { saveAs } from 'file-saver'
|
||||
import { useAppStore } from '@/stores/app'; import { adminAPI } from '@/api/admin'; import { adminUsageAPI } from '@/api/admin/usage'
|
||||
import { formatReasoningEffort } from '@/utils/format'
|
||||
import { resolveUsageRequestType, requestTypeToLegacyStream } from '@/utils/usageRequestType'
|
||||
import AppLayout from '@/components/layout/AppLayout.vue'; import Pagination from '@/components/common/Pagination.vue'; import Select from '@/components/common/Select.vue'
|
||||
import UsageStatsCards from '@/components/admin/usage/UsageStatsCards.vue'; import UsageFilters from '@/components/admin/usage/UsageFilters.vue'
|
||||
import UsageTable from '@/components/admin/usage/UsageTable.vue'; import UsageExportProgress from '@/components/admin/usage/UsageExportProgress.vue'
|
||||
import UsageCleanupDialog from '@/components/admin/usage/UsageCleanupDialog.vue'
|
||||
import ModelDistributionChart from '@/components/charts/ModelDistributionChart.vue'; import TokenUsageTrend from '@/components/charts/TokenUsageTrend.vue'; import GroupDistributionChart from '@/components/charts/GroupDistributionChart.vue'
|
||||
import ModelDistributionChart from '@/components/charts/ModelDistributionChart.vue'; import GroupDistributionChart from '@/components/charts/GroupDistributionChart.vue'; import TokenUsageTrend from '@/components/charts/TokenUsageTrend.vue'
|
||||
import Icon from '@/components/icons/Icon.vue'
|
||||
import type { AdminUsageLog, TrendDataPoint, ModelStat, GroupStat } from '@/types'; import type { AdminUsageStatsResponse, AdminUsageQueryParams } from '@/api/admin/usage'
|
||||
|
||||
@@ -87,6 +88,7 @@ const appStore = useAppStore()
|
||||
const usageStats = ref<AdminUsageStatsResponse | null>(null); const usageLogs = ref<AdminUsageLog[]>([]); const loading = ref(false); const exporting = ref(false)
|
||||
const trendData = ref<TrendDataPoint[]>([]); const modelStats = ref<ModelStat[]>([]); const groupStats = ref<GroupStat[]>([]); const chartsLoading = ref(false); const granularity = ref<'day' | 'hour'>('day')
|
||||
let abortController: AbortController | null = null; let exportAbortController: AbortController | null = null
|
||||
let chartReqSeq = 0
|
||||
const exportProgress = reactive({ show: false, progress: 0, current: 0, total: 0, estimatedTime: '' })
|
||||
const cleanupDialogVisible = ref(false)
|
||||
|
||||
@@ -100,33 +102,72 @@ const formatLD = (d: Date) => {
|
||||
}
|
||||
const now = new Date(); const weekAgo = new Date(); weekAgo.setDate(weekAgo.getDate() - 6)
|
||||
const startDate = ref(formatLD(weekAgo)); const endDate = ref(formatLD(now))
|
||||
const filters = ref<AdminUsageQueryParams>({ user_id: undefined, model: undefined, group_id: undefined, billing_type: null, start_date: startDate.value, end_date: endDate.value })
|
||||
const filters = ref<AdminUsageQueryParams>({ user_id: undefined, model: undefined, group_id: undefined, request_type: undefined, billing_type: null, start_date: startDate.value, end_date: endDate.value })
|
||||
const pagination = reactive({ page: 1, page_size: 20, total: 0 })
|
||||
|
||||
const loadLogs = async () => {
|
||||
abortController?.abort(); const c = new AbortController(); abortController = c; loading.value = true
|
||||
try {
|
||||
const res = await adminAPI.usage.list({ page: pagination.page, page_size: pagination.page_size, ...filters.value }, { signal: c.signal })
|
||||
const requestType = filters.value.request_type
|
||||
const legacyStream = requestType ? requestTypeToLegacyStream(requestType) : filters.value.stream
|
||||
const res = await adminAPI.usage.list({ page: pagination.page, page_size: pagination.page_size, exact_total: false, ...filters.value, stream: legacyStream === null ? undefined : legacyStream }, { signal: c.signal })
|
||||
if(!c.signal.aborted) { usageLogs.value = res.items; pagination.total = res.total }
|
||||
} catch (error: any) { if(error?.name !== 'AbortError') console.error('Failed to load usage logs:', error) } finally { if(abortController === c) loading.value = false }
|
||||
}
|
||||
const loadStats = async () => { try { const s = await adminAPI.usage.getStats(filters.value); usageStats.value = s } catch (error) { console.error('Failed to load usage stats:', error) } }
|
||||
const loadStats = async () => {
|
||||
try {
|
||||
const requestType = filters.value.request_type
|
||||
const legacyStream = requestType ? requestTypeToLegacyStream(requestType) : filters.value.stream
|
||||
const s = await adminAPI.usage.getStats({ ...filters.value, stream: legacyStream === null ? undefined : legacyStream })
|
||||
usageStats.value = s
|
||||
} catch (error) {
|
||||
console.error('Failed to load usage stats:', error)
|
||||
}
|
||||
}
|
||||
const loadChartData = async () => {
|
||||
const seq = ++chartReqSeq
|
||||
chartsLoading.value = true
|
||||
try {
|
||||
const params = { start_date: filters.value.start_date || startDate.value, end_date: filters.value.end_date || endDate.value, granularity: granularity.value, user_id: filters.value.user_id, model: filters.value.model, api_key_id: filters.value.api_key_id, account_id: filters.value.account_id, group_id: filters.value.group_id, stream: filters.value.stream, billing_type: filters.value.billing_type }
|
||||
const statsParams = { start_date: params.start_date, end_date: params.end_date, user_id: params.user_id, model: params.model, api_key_id: params.api_key_id, account_id: params.account_id, group_id: params.group_id, stream: params.stream, billing_type: params.billing_type }
|
||||
const [trendRes, modelRes, groupRes] = await Promise.all([adminAPI.dashboard.getUsageTrend(params), adminAPI.dashboard.getModelStats(statsParams), adminAPI.dashboard.getGroupStats(statsParams)])
|
||||
trendData.value = trendRes.trend || []; modelStats.value = modelRes.models || []; groupStats.value = groupRes.groups || []
|
||||
} catch (error) { console.error('Failed to load chart data:', error) } finally { chartsLoading.value = false }
|
||||
const requestType = filters.value.request_type
|
||||
const legacyStream = requestType ? requestTypeToLegacyStream(requestType) : filters.value.stream
|
||||
const snapshot = await adminAPI.dashboard.getSnapshotV2({
|
||||
start_date: filters.value.start_date || startDate.value,
|
||||
end_date: filters.value.end_date || endDate.value,
|
||||
granularity: granularity.value,
|
||||
user_id: filters.value.user_id,
|
||||
model: filters.value.model,
|
||||
api_key_id: filters.value.api_key_id,
|
||||
account_id: filters.value.account_id,
|
||||
group_id: filters.value.group_id,
|
||||
request_type: requestType,
|
||||
stream: legacyStream === null ? undefined : legacyStream,
|
||||
billing_type: filters.value.billing_type,
|
||||
include_stats: false,
|
||||
include_trend: true,
|
||||
include_model_stats: true,
|
||||
include_group_stats: true,
|
||||
include_users_trend: false
|
||||
})
|
||||
if (seq !== chartReqSeq) return
|
||||
trendData.value = snapshot.trend || []
|
||||
modelStats.value = snapshot.models || []
|
||||
groupStats.value = snapshot.groups || []
|
||||
} catch (error) { console.error('Failed to load chart data:', error) } finally { if (seq === chartReqSeq) chartsLoading.value = false }
|
||||
}
|
||||
const applyFilters = () => { pagination.page = 1; loadLogs(); loadStats(); loadChartData() }
|
||||
const refreshData = () => { loadLogs(); loadStats(); loadChartData() }
|
||||
const resetFilters = () => { startDate.value = formatLD(weekAgo); endDate.value = formatLD(now); filters.value = { start_date: startDate.value, end_date: endDate.value, billing_type: null }; granularity.value = 'day'; applyFilters() }
|
||||
const resetFilters = () => { startDate.value = formatLD(weekAgo); endDate.value = formatLD(now); filters.value = { start_date: startDate.value, end_date: endDate.value, request_type: undefined, billing_type: null }; granularity.value = 'day'; applyFilters() }
|
||||
const handlePageChange = (p: number) => { pagination.page = p; loadLogs() }
|
||||
const handlePageSizeChange = (s: number) => { pagination.page_size = s; pagination.page = 1; loadLogs() }
|
||||
const cancelExport = () => exportAbortController?.abort()
|
||||
const openCleanupDialog = () => { cleanupDialogVisible.value = true }
|
||||
const getRequestTypeLabel = (log: AdminUsageLog): string => {
|
||||
const requestType = resolveUsageRequestType(log)
|
||||
if (requestType === 'ws_v2') return t('usage.ws')
|
||||
if (requestType === 'stream') return t('usage.stream')
|
||||
if (requestType === 'sync') return t('usage.sync')
|
||||
return t('usage.unknown')
|
||||
}
|
||||
|
||||
const exportToExcel = async () => {
|
||||
if (exporting.value) return; exporting.value = true; exportProgress.show = true
|
||||
@@ -148,11 +189,13 @@ const exportToExcel = async () => {
|
||||
]
|
||||
const ws = XLSX.utils.aoa_to_sheet([headers])
|
||||
while (true) {
|
||||
const res = await adminUsageAPI.list({ page: p, page_size: 100, ...filters.value }, { signal: c.signal })
|
||||
const requestType = filters.value.request_type
|
||||
const legacyStream = requestType ? requestTypeToLegacyStream(requestType) : filters.value.stream
|
||||
const res = await adminUsageAPI.list({ page: p, page_size: 100, exact_total: true, ...filters.value, stream: legacyStream === null ? undefined : legacyStream }, { signal: c.signal })
|
||||
if (c.signal.aborted) break; if (p === 1) { total = res.total; exportProgress.total = total }
|
||||
const rows = (res.items || []).map((log: AdminUsageLog) => [
|
||||
log.created_at, log.user?.email || '', log.api_key?.name || '', log.account?.name || '', log.model,
|
||||
formatReasoningEffort(log.reasoning_effort), log.group?.name || '', log.stream ? t('usage.stream') : t('usage.sync'),
|
||||
formatReasoningEffort(log.reasoning_effort), log.group?.name || '', getRequestTypeLabel(log),
|
||||
log.input_tokens, log.output_tokens, log.cache_read_tokens, log.cache_creation_tokens,
|
||||
log.input_cost?.toFixed(6) || '0.000000', log.output_cost?.toFixed(6) || '0.000000',
|
||||
log.cache_read_cost?.toFixed(6) || '0.000000', log.cache_creation_cost?.toFixed(6) || '0.000000',
|
||||
@@ -250,6 +293,14 @@ const handleColumnClickOutside = (event: MouseEvent) => {
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => { loadLogs(); loadStats(); loadChartData(); loadSavedColumns(); document.addEventListener('click', handleColumnClickOutside) })
|
||||
onMounted(() => {
|
||||
loadLogs()
|
||||
loadStats()
|
||||
window.setTimeout(() => {
|
||||
void loadChartData()
|
||||
}, 120)
|
||||
loadSavedColumns()
|
||||
document.addEventListener('click', handleColumnClickOutside)
|
||||
})
|
||||
onUnmounted(() => { abortController?.abort(); exportAbortController?.abort(); document.removeEventListener('click', handleColumnClickOutside) })
|
||||
</script>
|
||||
|
||||
@@ -655,16 +655,28 @@ const saveColumnsToStorage = () => {
|
||||
|
||||
// Toggle column visibility
|
||||
const toggleColumn = (key: string) => {
|
||||
const wasHidden = hiddenColumns.has(key)
|
||||
if (hiddenColumns.has(key)) {
|
||||
hiddenColumns.delete(key)
|
||||
} else {
|
||||
hiddenColumns.add(key)
|
||||
}
|
||||
saveColumnsToStorage()
|
||||
if (wasHidden && (key === 'usage' || key.startsWith('attr_'))) {
|
||||
refreshCurrentPageSecondaryData()
|
||||
}
|
||||
if (key === 'subscriptions') {
|
||||
loadUsers()
|
||||
}
|
||||
}
|
||||
|
||||
// Check if column is visible (not in hidden set)
|
||||
const isColumnVisible = (key: string) => !hiddenColumns.has(key)
|
||||
const hasVisibleUsageColumn = computed(() => !hiddenColumns.has('usage'))
|
||||
const hasVisibleSubscriptionsColumn = computed(() => !hiddenColumns.has('subscriptions'))
|
||||
const hasVisibleAttributeColumns = computed(() =>
|
||||
attributeDefinitions.value.some((def) => def.enabled && !hiddenColumns.has(`attr_${def.id}`))
|
||||
)
|
||||
|
||||
// Filtered columns based on visibility
|
||||
const columns = computed<Column[]>(() =>
|
||||
@@ -776,6 +788,60 @@ const editingUser = ref<AdminUser | null>(null)
|
||||
const deletingUser = ref<AdminUser | null>(null)
|
||||
const viewingUser = ref<AdminUser | null>(null)
|
||||
let abortController: AbortController | null = null
|
||||
let secondaryDataSeq = 0
|
||||
|
||||
const loadUsersSecondaryData = async (
|
||||
userIds: number[],
|
||||
signal?: AbortSignal,
|
||||
expectedSeq?: number
|
||||
) => {
|
||||
if (userIds.length === 0) return
|
||||
|
||||
const tasks: Promise<void>[] = []
|
||||
|
||||
if (hasVisibleUsageColumn.value) {
|
||||
tasks.push(
|
||||
(async () => {
|
||||
try {
|
||||
const usageResponse = await adminAPI.dashboard.getBatchUsersUsage(userIds)
|
||||
if (signal?.aborted) return
|
||||
if (typeof expectedSeq === 'number' && expectedSeq !== secondaryDataSeq) return
|
||||
usageStats.value = usageResponse.stats
|
||||
} catch (e) {
|
||||
if (signal?.aborted) return
|
||||
console.error('Failed to load usage stats:', e)
|
||||
}
|
||||
})()
|
||||
)
|
||||
}
|
||||
|
||||
if (attributeDefinitions.value.length > 0 && hasVisibleAttributeColumns.value) {
|
||||
tasks.push(
|
||||
(async () => {
|
||||
try {
|
||||
const attrResponse = await adminAPI.userAttributes.getBatchUserAttributes(userIds)
|
||||
if (signal?.aborted) return
|
||||
if (typeof expectedSeq === 'number' && expectedSeq !== secondaryDataSeq) return
|
||||
userAttributeValues.value = attrResponse.attributes
|
||||
} catch (e) {
|
||||
if (signal?.aborted) return
|
||||
console.error('Failed to load user attribute values:', e)
|
||||
}
|
||||
})()
|
||||
)
|
||||
}
|
||||
|
||||
if (tasks.length > 0) {
|
||||
await Promise.allSettled(tasks)
|
||||
}
|
||||
}
|
||||
|
||||
const refreshCurrentPageSecondaryData = () => {
|
||||
const userIds = users.value.map((u) => u.id)
|
||||
if (userIds.length === 0) return
|
||||
const seq = ++secondaryDataSeq
|
||||
void loadUsersSecondaryData(userIds, undefined, seq)
|
||||
}
|
||||
|
||||
// Action Menu State
|
||||
const activeMenuId = ref<number | null>(null)
|
||||
@@ -913,7 +979,8 @@ const loadUsers = async () => {
|
||||
role: filters.role as any,
|
||||
status: filters.status as any,
|
||||
search: searchQuery.value || undefined,
|
||||
attributes: Object.keys(attrFilters).length > 0 ? attrFilters : undefined
|
||||
attributes: Object.keys(attrFilters).length > 0 ? attrFilters : undefined,
|
||||
include_subscriptions: hasVisibleSubscriptionsColumn.value
|
||||
},
|
||||
{ signal }
|
||||
)
|
||||
@@ -923,38 +990,17 @@ const loadUsers = async () => {
|
||||
users.value = response.items
|
||||
pagination.total = response.total
|
||||
pagination.pages = response.pages
|
||||
usageStats.value = {}
|
||||
userAttributeValues.value = {}
|
||||
|
||||
// Load usage stats and attribute values for all users in the list
|
||||
// Defer heavy secondary data so table can render first.
|
||||
if (response.items.length > 0) {
|
||||
const userIds = response.items.map((u) => u.id)
|
||||
// Load usage stats
|
||||
try {
|
||||
const usageResponse = await adminAPI.dashboard.getBatchUsersUsage(userIds)
|
||||
if (signal.aborted) {
|
||||
return
|
||||
}
|
||||
usageStats.value = usageResponse.stats
|
||||
} catch (e) {
|
||||
if (signal.aborted) {
|
||||
return
|
||||
}
|
||||
console.error('Failed to load usage stats:', e)
|
||||
}
|
||||
// Load attribute values
|
||||
if (attributeDefinitions.value.length > 0) {
|
||||
try {
|
||||
const attrResponse = await adminAPI.userAttributes.getBatchUserAttributes(userIds)
|
||||
if (signal.aborted) {
|
||||
return
|
||||
}
|
||||
userAttributeValues.value = attrResponse.attributes
|
||||
} catch (e) {
|
||||
if (signal.aborted) {
|
||||
return
|
||||
}
|
||||
console.error('Failed to load user attribute values:', e)
|
||||
}
|
||||
}
|
||||
const seq = ++secondaryDataSeq
|
||||
window.setTimeout(() => {
|
||||
if (signal.aborted || seq !== secondaryDataSeq) return
|
||||
void loadUsersSecondaryData(userIds, signal, seq)
|
||||
}, 50)
|
||||
}
|
||||
} catch (error: any) {
|
||||
const errorInfo = error as { name?: string; code?: string }
|
||||
|
||||
@@ -586,6 +586,32 @@ async function refreshThroughputTrendWithCancel(fetchSeq: number, signal: AbortS
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshCoreSnapshotWithCancel(fetchSeq: number, signal: AbortSignal) {
|
||||
if (!opsEnabled.value) return
|
||||
loadingTrend.value = true
|
||||
loadingErrorTrend.value = true
|
||||
try {
|
||||
const data = await opsAPI.getDashboardSnapshotV2(buildApiParams(), { signal })
|
||||
if (fetchSeq !== dashboardFetchSeq) return
|
||||
overview.value = data.overview
|
||||
throughputTrend.value = data.throughput_trend
|
||||
errorTrend.value = data.error_trend
|
||||
} catch (err: any) {
|
||||
if (fetchSeq !== dashboardFetchSeq || isCanceledRequest(err)) return
|
||||
// Fallback to legacy split endpoints when snapshot endpoint is unavailable.
|
||||
await Promise.all([
|
||||
refreshOverviewWithCancel(fetchSeq, signal),
|
||||
refreshThroughputTrendWithCancel(fetchSeq, signal),
|
||||
refreshErrorTrendWithCancel(fetchSeq, signal)
|
||||
])
|
||||
} finally {
|
||||
if (fetchSeq === dashboardFetchSeq) {
|
||||
loadingTrend.value = false
|
||||
loadingErrorTrend.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshLatencyHistogramWithCancel(fetchSeq: number, signal: AbortSignal) {
|
||||
if (!opsEnabled.value) return
|
||||
loadingLatency.value = true
|
||||
@@ -640,6 +666,14 @@ async function refreshErrorDistributionWithCancel(fetchSeq: number, signal: Abor
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshDeferredPanels(fetchSeq: number, signal: AbortSignal) {
|
||||
if (!opsEnabled.value) return
|
||||
await Promise.all([
|
||||
refreshLatencyHistogramWithCancel(fetchSeq, signal),
|
||||
refreshErrorDistributionWithCancel(fetchSeq, signal)
|
||||
])
|
||||
}
|
||||
|
||||
function isOpsDisabledError(err: unknown): boolean {
|
||||
return (
|
||||
!!err &&
|
||||
@@ -662,12 +696,8 @@ async function fetchData() {
|
||||
errorMessage.value = ''
|
||||
try {
|
||||
await Promise.all([
|
||||
refreshOverviewWithCancel(fetchSeq, dashboardFetchController.signal),
|
||||
refreshThroughputTrendWithCancel(fetchSeq, dashboardFetchController.signal),
|
||||
refreshCoreSnapshotWithCancel(fetchSeq, dashboardFetchController.signal),
|
||||
refreshSwitchTrendWithCancel(fetchSeq, dashboardFetchController.signal),
|
||||
refreshLatencyHistogramWithCancel(fetchSeq, dashboardFetchController.signal),
|
||||
refreshErrorTrendWithCancel(fetchSeq, dashboardFetchController.signal),
|
||||
refreshErrorDistributionWithCancel(fetchSeq, dashboardFetchController.signal)
|
||||
])
|
||||
if (fetchSeq !== dashboardFetchSeq) return
|
||||
|
||||
@@ -680,6 +710,9 @@ async function fetchData() {
|
||||
if (autoRefreshEnabled.value) {
|
||||
autoRefreshCountdown.value = Math.floor(autoRefreshIntervalMs.value / 1000)
|
||||
}
|
||||
|
||||
// Defer non-core visual panels to reduce initial blocking.
|
||||
void refreshDeferredPanels(fetchSeq, dashboardFetchController.signal)
|
||||
} catch (err) {
|
||||
if (!isOpsDisabledError(err)) {
|
||||
console.error('[ops] failed to fetch dashboard data', err)
|
||||
|
||||
@@ -167,6 +167,7 @@ import Icon from '@/components/icons/Icon.vue'
|
||||
import { useAppStore } from '@/stores'
|
||||
import { opsAPI, type OpsErrorDetail } from '@/api/admin/ops'
|
||||
import { formatDateTime } from '@/utils/format'
|
||||
import { resolvePrimaryResponseBody, resolveUpstreamPayload } from '../utils/errorDetailResponse'
|
||||
|
||||
interface Props {
|
||||
show: boolean
|
||||
@@ -192,11 +193,7 @@ const showUpstreamList = computed(() => props.errorType === 'request')
|
||||
const requestId = computed(() => detail.value?.request_id || detail.value?.client_request_id || '')
|
||||
|
||||
const primaryResponseBody = computed(() => {
|
||||
if (!detail.value) return ''
|
||||
if (props.errorType === 'upstream') {
|
||||
return detail.value.upstream_error_detail || detail.value.upstream_errors || detail.value.upstream_error_message || detail.value.error_body || ''
|
||||
}
|
||||
return detail.value.error_body || ''
|
||||
return resolvePrimaryResponseBody(detail.value, props.errorType)
|
||||
})
|
||||
|
||||
|
||||
@@ -224,7 +221,9 @@ const correlatedUpstreamErrors = computed<OpsErrorDetail[]>(() => correlatedUpst
|
||||
const expandedUpstreamDetailIds = ref(new Set<number>())
|
||||
|
||||
function getUpstreamResponsePreview(ev: OpsErrorDetail): string {
|
||||
return String(ev.upstream_error_detail || ev.error_body || ev.upstream_error_message || '').trim()
|
||||
const upstreamPayload = resolveUpstreamPayload(ev)
|
||||
if (upstreamPayload) return upstreamPayload
|
||||
return String(ev.error_body || '').trim()
|
||||
}
|
||||
|
||||
function toggleUpstreamDetail(id: number) {
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { OpsErrorDetail } from '@/api/admin/ops'
|
||||
import { resolvePrimaryResponseBody, resolveUpstreamPayload } from '../errorDetailResponse'
|
||||
|
||||
function makeDetail(overrides: Partial<OpsErrorDetail>): OpsErrorDetail {
|
||||
return {
|
||||
id: 1,
|
||||
created_at: '2026-01-01T00:00:00Z',
|
||||
phase: 'request',
|
||||
type: 'api_error',
|
||||
error_owner: 'platform',
|
||||
error_source: 'gateway',
|
||||
severity: 'P2',
|
||||
status_code: 502,
|
||||
platform: 'openai',
|
||||
model: 'gpt-4o-mini',
|
||||
is_retryable: true,
|
||||
retry_count: 0,
|
||||
resolved: false,
|
||||
client_request_id: 'crid-1',
|
||||
request_id: 'rid-1',
|
||||
message: 'Upstream request failed',
|
||||
user_email: 'user@example.com',
|
||||
account_name: 'acc',
|
||||
group_name: 'group',
|
||||
error_body: '',
|
||||
user_agent: '',
|
||||
request_body: '',
|
||||
request_body_truncated: false,
|
||||
is_business_limited: false,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
describe('errorDetailResponse', () => {
|
||||
it('prefers upstream payload for request modal when error_body is generic gateway wrapper', () => {
|
||||
const detail = makeDetail({
|
||||
error_body: JSON.stringify({
|
||||
type: 'error',
|
||||
error: {
|
||||
type: 'upstream_error',
|
||||
message: 'Upstream request failed'
|
||||
}
|
||||
}),
|
||||
upstream_error_detail: '{"provider_message":"real upstream detail"}'
|
||||
})
|
||||
|
||||
expect(resolvePrimaryResponseBody(detail, 'request')).toBe('{"provider_message":"real upstream detail"}')
|
||||
})
|
||||
|
||||
it('keeps error_body for request modal when body is not generic wrapper', () => {
|
||||
const detail = makeDetail({
|
||||
error_body: JSON.stringify({
|
||||
type: 'error',
|
||||
error: {
|
||||
type: 'upstream_error',
|
||||
message: 'Upstream authentication failed, please contact administrator'
|
||||
}
|
||||
}),
|
||||
upstream_error_detail: '{"provider_message":"real upstream detail"}'
|
||||
})
|
||||
|
||||
expect(resolvePrimaryResponseBody(detail, 'request')).toBe(detail.error_body)
|
||||
})
|
||||
|
||||
it('uses upstream payload first in upstream modal', () => {
|
||||
const detail = makeDetail({
|
||||
phase: 'upstream',
|
||||
upstream_error_message: 'provider 503 overloaded',
|
||||
error_body: '{"type":"error","error":{"type":"upstream_error","message":"Upstream request failed"}}'
|
||||
})
|
||||
|
||||
expect(resolvePrimaryResponseBody(detail, 'upstream')).toBe('provider 503 overloaded')
|
||||
})
|
||||
|
||||
it('falls back to upstream payload when request error_body is empty', () => {
|
||||
const detail = makeDetail({
|
||||
error_body: '',
|
||||
upstream_error_message: 'dial tcp timeout'
|
||||
})
|
||||
|
||||
expect(resolvePrimaryResponseBody(detail, 'request')).toBe('dial tcp timeout')
|
||||
})
|
||||
|
||||
it('resolves upstream payload by detail -> events -> message priority', () => {
|
||||
expect(resolveUpstreamPayload(makeDetail({
|
||||
upstream_error_detail: 'detail payload',
|
||||
upstream_errors: '[{"message":"event payload"}]',
|
||||
upstream_error_message: 'message payload'
|
||||
}))).toBe('detail payload')
|
||||
|
||||
expect(resolveUpstreamPayload(makeDetail({
|
||||
upstream_error_detail: '',
|
||||
upstream_errors: '[{"message":"event payload"}]',
|
||||
upstream_error_message: 'message payload'
|
||||
}))).toBe('[{"message":"event payload"}]')
|
||||
|
||||
expect(resolveUpstreamPayload(makeDetail({
|
||||
upstream_error_detail: '',
|
||||
upstream_errors: '',
|
||||
upstream_error_message: 'message payload'
|
||||
}))).toBe('message payload')
|
||||
})
|
||||
|
||||
it('treats empty JSON placeholders in upstream payload as empty', () => {
|
||||
expect(resolveUpstreamPayload(makeDetail({
|
||||
upstream_error_detail: '',
|
||||
upstream_errors: '[]',
|
||||
upstream_error_message: ''
|
||||
}))).toBe('')
|
||||
|
||||
expect(resolveUpstreamPayload(makeDetail({
|
||||
upstream_error_detail: '',
|
||||
upstream_errors: '{}',
|
||||
upstream_error_message: ''
|
||||
}))).toBe('')
|
||||
|
||||
expect(resolveUpstreamPayload(makeDetail({
|
||||
upstream_error_detail: '',
|
||||
upstream_errors: 'null',
|
||||
upstream_error_message: ''
|
||||
}))).toBe('')
|
||||
})
|
||||
|
||||
it('skips placeholder candidates and falls back to the next upstream field', () => {
|
||||
expect(resolveUpstreamPayload(makeDetail({
|
||||
upstream_error_detail: '',
|
||||
upstream_errors: '[]',
|
||||
upstream_error_message: 'fallback message'
|
||||
}))).toBe('fallback message')
|
||||
|
||||
expect(resolveUpstreamPayload(makeDetail({
|
||||
upstream_error_detail: 'null',
|
||||
upstream_errors: '',
|
||||
upstream_error_message: 'fallback message'
|
||||
}))).toBe('fallback message')
|
||||
})
|
||||
})
|
||||
91
frontend/src/views/admin/ops/utils/errorDetailResponse.ts
Normal file
91
frontend/src/views/admin/ops/utils/errorDetailResponse.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import type { OpsErrorDetail } from '@/api/admin/ops'
|
||||
|
||||
const GENERIC_UPSTREAM_MESSAGES = new Set([
|
||||
'upstream request failed',
|
||||
'upstream request failed after retries',
|
||||
'upstream gateway error',
|
||||
'upstream service temporarily unavailable'
|
||||
])
|
||||
|
||||
type ParsedGatewayError = {
|
||||
type: string
|
||||
message: string
|
||||
}
|
||||
|
||||
function parseGatewayErrorBody(raw: string): ParsedGatewayError | null {
|
||||
const text = String(raw || '').trim()
|
||||
if (!text) return null
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(text) as Record<string, any>
|
||||
const err = parsed?.error as Record<string, any> | undefined
|
||||
if (!err || typeof err !== 'object') return null
|
||||
|
||||
const type = typeof err.type === 'string' ? err.type.trim() : ''
|
||||
const message = typeof err.message === 'string' ? err.message.trim() : ''
|
||||
if (!type && !message) return null
|
||||
|
||||
return { type, message }
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function isGenericGatewayUpstreamError(raw: string): boolean {
|
||||
const parsed = parseGatewayErrorBody(raw)
|
||||
if (!parsed) return false
|
||||
if (parsed.type !== 'upstream_error') return false
|
||||
return GENERIC_UPSTREAM_MESSAGES.has(parsed.message.toLowerCase())
|
||||
}
|
||||
|
||||
export function resolveUpstreamPayload(
|
||||
detail: Pick<OpsErrorDetail, 'upstream_error_detail' | 'upstream_errors' | 'upstream_error_message'> | null | undefined
|
||||
): string {
|
||||
if (!detail) return ''
|
||||
|
||||
const candidates = [
|
||||
detail.upstream_error_detail,
|
||||
detail.upstream_errors,
|
||||
detail.upstream_error_message
|
||||
]
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const payload = String(candidate || '').trim()
|
||||
if (!payload) continue
|
||||
|
||||
// Normalize common "empty but present" JSON placeholders.
|
||||
if (payload === '[]' || payload === '{}' || payload.toLowerCase() === 'null') {
|
||||
continue
|
||||
}
|
||||
|
||||
return payload
|
||||
}
|
||||
|
||||
return ''
|
||||
}
|
||||
|
||||
export function resolvePrimaryResponseBody(
|
||||
detail: OpsErrorDetail | null,
|
||||
errorType?: 'request' | 'upstream'
|
||||
): string {
|
||||
if (!detail) return ''
|
||||
|
||||
const upstreamPayload = resolveUpstreamPayload(detail)
|
||||
const errorBody = String(detail.error_body || '').trim()
|
||||
|
||||
if (errorType === 'upstream') {
|
||||
return upstreamPayload || errorBody
|
||||
}
|
||||
|
||||
if (!errorBody) {
|
||||
return upstreamPayload
|
||||
}
|
||||
|
||||
// For request detail modal, keep client-visible body by default.
|
||||
// But if that body is a generic gateway wrapper, show upstream payload first.
|
||||
if (upstreamPayload && isGenericGatewayUpstreamError(errorBody)) {
|
||||
return upstreamPayload
|
||||
}
|
||||
|
||||
return errorBody
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
{{ t('auth.verifyYourEmail') }}
|
||||
</h2>
|
||||
<p class="mt-2 text-sm text-gray-500 dark:text-dark-400">
|
||||
We'll send a verification code to
|
||||
{{ t('auth.sendCodeDesc') }}
|
||||
<span class="font-medium text-gray-700 dark:text-gray-300">{{ email }}</span>
|
||||
</p>
|
||||
</div>
|
||||
@@ -64,7 +64,7 @@
|
||||
<Icon name="checkCircle" size="md" class="text-green-500" />
|
||||
</div>
|
||||
<p class="text-sm text-green-700 dark:text-green-400">
|
||||
Verification code sent! Please check your inbox.
|
||||
{{ t('auth.codeSentSuccess') }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -123,7 +123,7 @@
|
||||
></path>
|
||||
</svg>
|
||||
<Icon v-else name="checkCircle" size="md" class="mr-2" />
|
||||
{{ isLoading ? 'Verifying...' : 'Verify & Create Account' }}
|
||||
{{ isLoading ? t('auth.verifying') : t('auth.verifyAndCreate') }}
|
||||
</button>
|
||||
|
||||
<!-- Resend Code -->
|
||||
@@ -134,7 +134,7 @@
|
||||
disabled
|
||||
class="cursor-not-allowed text-sm text-gray-400 dark:text-dark-500"
|
||||
>
|
||||
Resend code in {{ countdown }}s
|
||||
{{ t('auth.resendCountdown', { countdown }) }}
|
||||
</button>
|
||||
<button
|
||||
v-else
|
||||
@@ -162,7 +162,7 @@
|
||||
class="flex items-center gap-2 text-gray-500 transition-colors hover:text-gray-700 dark:text-dark-400 dark:hover:text-gray-300"
|
||||
>
|
||||
<Icon name="arrowLeft" size="sm" />
|
||||
Back to registration
|
||||
{{ t('auth.backToRegistration') }}
|
||||
</button>
|
||||
</template>
|
||||
</AuthLayout>
|
||||
@@ -177,8 +177,13 @@ import Icon from '@/components/icons/Icon.vue'
|
||||
import TurnstileWidget from '@/components/TurnstileWidget.vue'
|
||||
import { useAuthStore, useAppStore } from '@/stores'
|
||||
import { getPublicSettings, sendVerifyCode } from '@/api/auth'
|
||||
import { buildAuthErrorMessage } from '@/utils/authError'
|
||||
import {
|
||||
isRegistrationEmailSuffixAllowed,
|
||||
normalizeRegistrationEmailSuffixWhitelist
|
||||
} from '@/utils/registrationEmailPolicy'
|
||||
|
||||
const { t } = useI18n()
|
||||
const { t, locale } = useI18n()
|
||||
|
||||
// ==================== Router & Stores ====================
|
||||
|
||||
@@ -208,6 +213,7 @@ const hasRegisterData = ref<boolean>(false)
|
||||
const turnstileEnabled = ref<boolean>(false)
|
||||
const turnstileSiteKey = ref<string>('')
|
||||
const siteName = ref<string>('Sub2API')
|
||||
const registrationEmailSuffixWhitelist = ref<string[]>([])
|
||||
|
||||
// Turnstile for resend
|
||||
const turnstileRef = ref<InstanceType<typeof TurnstileWidget> | null>(null)
|
||||
@@ -244,6 +250,9 @@ onMounted(async () => {
|
||||
turnstileEnabled.value = settings.turnstile_enabled
|
||||
turnstileSiteKey.value = settings.turnstile_site_key || ''
|
||||
siteName.value = settings.site_name || 'Sub2API'
|
||||
registrationEmailSuffixWhitelist.value = normalizeRegistrationEmailSuffixWhitelist(
|
||||
settings.registration_email_suffix_whitelist || []
|
||||
)
|
||||
} catch (error) {
|
||||
console.error('Failed to load public settings:', error)
|
||||
}
|
||||
@@ -291,12 +300,12 @@ function onTurnstileVerify(token: string): void {
|
||||
|
||||
function onTurnstileExpire(): void {
|
||||
resendTurnstileToken.value = ''
|
||||
errors.value.turnstile = 'Verification expired, please try again'
|
||||
errors.value.turnstile = t('auth.turnstileExpired')
|
||||
}
|
||||
|
||||
function onTurnstileError(): void {
|
||||
resendTurnstileToken.value = ''
|
||||
errors.value.turnstile = 'Verification failed, please try again'
|
||||
errors.value.turnstile = t('auth.turnstileFailed')
|
||||
}
|
||||
|
||||
// ==================== Send Code ====================
|
||||
@@ -306,6 +315,12 @@ async function sendCode(): Promise<void> {
|
||||
errorMessage.value = ''
|
||||
|
||||
try {
|
||||
if (!isRegistrationEmailSuffixAllowed(email.value, registrationEmailSuffixWhitelist.value)) {
|
||||
errorMessage.value = buildEmailSuffixNotAllowedMessage()
|
||||
appStore.showError(errorMessage.value)
|
||||
return
|
||||
}
|
||||
|
||||
const response = await sendVerifyCode({
|
||||
email: email.value,
|
||||
// 优先使用重发时新获取的 token(因为初始 token 可能已被使用)
|
||||
@@ -320,15 +335,9 @@ async function sendCode(): Promise<void> {
|
||||
showResendTurnstile.value = false
|
||||
resendTurnstileToken.value = ''
|
||||
} catch (error: unknown) {
|
||||
const err = error as { message?: string; response?: { data?: { detail?: string } } }
|
||||
|
||||
if (err.response?.data?.detail) {
|
||||
errorMessage.value = err.response.data.detail
|
||||
} else if (err.message) {
|
||||
errorMessage.value = err.message
|
||||
} else {
|
||||
errorMessage.value = 'Failed to send verification code. Please try again.'
|
||||
}
|
||||
errorMessage.value = buildAuthErrorMessage(error, {
|
||||
fallback: t('auth.sendCodeFailed')
|
||||
})
|
||||
|
||||
appStore.showError(errorMessage.value)
|
||||
} finally {
|
||||
@@ -347,7 +356,7 @@ async function handleResendCode(): Promise<void> {
|
||||
|
||||
// If turnstile is enabled but no token yet, wait
|
||||
if (turnstileEnabled.value && !resendTurnstileToken.value) {
|
||||
errors.value.turnstile = 'Please complete the verification'
|
||||
errors.value.turnstile = t('auth.completeVerification')
|
||||
return
|
||||
}
|
||||
|
||||
@@ -358,12 +367,12 @@ function validateForm(): boolean {
|
||||
errors.value.code = ''
|
||||
|
||||
if (!verifyCode.value.trim()) {
|
||||
errors.value.code = 'Verification code is required'
|
||||
errors.value.code = t('auth.codeRequired')
|
||||
return false
|
||||
}
|
||||
|
||||
if (!/^\d{6}$/.test(verifyCode.value.trim())) {
|
||||
errors.value.code = 'Please enter a valid 6-digit code'
|
||||
errors.value.code = t('auth.invalidCode')
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -380,6 +389,12 @@ async function handleVerify(): Promise<void> {
|
||||
isLoading.value = true
|
||||
|
||||
try {
|
||||
if (!isRegistrationEmailSuffixAllowed(email.value, registrationEmailSuffixWhitelist.value)) {
|
||||
errorMessage.value = buildEmailSuffixNotAllowedMessage()
|
||||
appStore.showError(errorMessage.value)
|
||||
return
|
||||
}
|
||||
|
||||
// Register with verification code
|
||||
await authStore.register({
|
||||
email: email.value,
|
||||
@@ -394,20 +409,14 @@ async function handleVerify(): Promise<void> {
|
||||
sessionStorage.removeItem('register_data')
|
||||
|
||||
// Show success toast
|
||||
appStore.showSuccess('Account created successfully! Welcome to ' + siteName.value + '.')
|
||||
appStore.showSuccess(t('auth.accountCreatedSuccess', { siteName: siteName.value }))
|
||||
|
||||
// Redirect to dashboard
|
||||
await router.push('/dashboard')
|
||||
} catch (error: unknown) {
|
||||
const err = error as { message?: string; response?: { data?: { detail?: string } } }
|
||||
|
||||
if (err.response?.data?.detail) {
|
||||
errorMessage.value = err.response.data.detail
|
||||
} else if (err.message) {
|
||||
errorMessage.value = err.message
|
||||
} else {
|
||||
errorMessage.value = 'Verification failed. Please try again.'
|
||||
}
|
||||
errorMessage.value = buildAuthErrorMessage(error, {
|
||||
fallback: t('auth.verifyFailed')
|
||||
})
|
||||
|
||||
appStore.showError(errorMessage.value)
|
||||
} finally {
|
||||
@@ -422,6 +431,19 @@ function handleBack(): void {
|
||||
// Go back to registration
|
||||
router.push('/register')
|
||||
}
|
||||
|
||||
function buildEmailSuffixNotAllowedMessage(): string {
|
||||
const normalizedWhitelist = normalizeRegistrationEmailSuffixWhitelist(
|
||||
registrationEmailSuffixWhitelist.value
|
||||
)
|
||||
if (normalizedWhitelist.length === 0) {
|
||||
return t('auth.emailSuffixNotAllowed')
|
||||
}
|
||||
const separator = String(locale.value || '').toLowerCase().startsWith('zh') ? '、' : ', '
|
||||
return t('auth.emailSuffixNotAllowedWithAllowed', {
|
||||
suffixes: normalizedWhitelist.join(separator)
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
@@ -293,8 +293,13 @@ import Icon from '@/components/icons/Icon.vue'
|
||||
import TurnstileWidget from '@/components/TurnstileWidget.vue'
|
||||
import { useAuthStore, useAppStore } from '@/stores'
|
||||
import { getPublicSettings, validatePromoCode, validateInvitationCode } from '@/api/auth'
|
||||
import { buildAuthErrorMessage } from '@/utils/authError'
|
||||
import {
|
||||
isRegistrationEmailSuffixAllowed,
|
||||
normalizeRegistrationEmailSuffixWhitelist
|
||||
} from '@/utils/registrationEmailPolicy'
|
||||
|
||||
const { t } = useI18n()
|
||||
const { t, locale } = useI18n()
|
||||
|
||||
// ==================== Router & Stores ====================
|
||||
|
||||
@@ -319,6 +324,7 @@ const turnstileEnabled = ref<boolean>(false)
|
||||
const turnstileSiteKey = ref<string>('')
|
||||
const siteName = ref<string>('Sub2API')
|
||||
const linuxdoOAuthEnabled = ref<boolean>(false)
|
||||
const registrationEmailSuffixWhitelist = ref<string[]>([])
|
||||
|
||||
// Turnstile
|
||||
const turnstileRef = ref<InstanceType<typeof TurnstileWidget> | null>(null)
|
||||
@@ -370,6 +376,9 @@ onMounted(async () => {
|
||||
turnstileSiteKey.value = settings.turnstile_site_key || ''
|
||||
siteName.value = settings.site_name || 'Sub2API'
|
||||
linuxdoOAuthEnabled.value = settings.linuxdo_oauth_enabled
|
||||
registrationEmailSuffixWhitelist.value = normalizeRegistrationEmailSuffixWhitelist(
|
||||
settings.registration_email_suffix_whitelist || []
|
||||
)
|
||||
|
||||
// Read promo code from URL parameter only if promo code is enabled
|
||||
if (promoCodeEnabled.value) {
|
||||
@@ -557,6 +566,19 @@ function validateEmail(email: string): boolean {
|
||||
return emailRegex.test(email)
|
||||
}
|
||||
|
||||
function buildEmailSuffixNotAllowedMessage(): string {
|
||||
const normalizedWhitelist = normalizeRegistrationEmailSuffixWhitelist(
|
||||
registrationEmailSuffixWhitelist.value
|
||||
)
|
||||
if (normalizedWhitelist.length === 0) {
|
||||
return t('auth.emailSuffixNotAllowed')
|
||||
}
|
||||
const separator = String(locale.value || '').toLowerCase().startsWith('zh') ? '、' : ', '
|
||||
return t('auth.emailSuffixNotAllowedWithAllowed', {
|
||||
suffixes: normalizedWhitelist.join(separator)
|
||||
})
|
||||
}
|
||||
|
||||
function validateForm(): boolean {
|
||||
// Reset errors
|
||||
errors.email = ''
|
||||
@@ -573,6 +595,11 @@ function validateForm(): boolean {
|
||||
} else if (!validateEmail(formData.email)) {
|
||||
errors.email = t('auth.invalidEmail')
|
||||
isValid = false
|
||||
} else if (
|
||||
!isRegistrationEmailSuffixAllowed(formData.email, registrationEmailSuffixWhitelist.value)
|
||||
) {
|
||||
errors.email = buildEmailSuffixNotAllowedMessage()
|
||||
isValid = false
|
||||
}
|
||||
|
||||
// Password validation
|
||||
@@ -694,15 +721,9 @@ async function handleRegister(): Promise<void> {
|
||||
}
|
||||
|
||||
// Handle registration error
|
||||
const err = error as { message?: string; response?: { data?: { detail?: string } } }
|
||||
|
||||
if (err.response?.data?.detail) {
|
||||
errorMessage.value = err.response.data.detail
|
||||
} else if (err.message) {
|
||||
errorMessage.value = err.message
|
||||
} else {
|
||||
errorMessage.value = t('auth.registrationFailed')
|
||||
}
|
||||
errorMessage.value = buildAuthErrorMessage(error, {
|
||||
fallback: t('auth.registrationFailed')
|
||||
})
|
||||
|
||||
// Also show error toast
|
||||
appStore.showError(errorMessage.value)
|
||||
|
||||
176
frontend/src/views/user/CustomPageView.vue
Normal file
176
frontend/src/views/user/CustomPageView.vue
Normal file
@@ -0,0 +1,176 @@
|
||||
<template>
|
||||
<AppLayout>
|
||||
<div class="custom-page-layout">
|
||||
<div class="card flex-1 min-h-0 overflow-hidden">
|
||||
<div v-if="loading" class="flex h-full items-center justify-center py-12">
|
||||
<div
|
||||
class="h-8 w-8 animate-spin rounded-full border-2 border-primary-500 border-t-transparent"
|
||||
></div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else-if="!menuItem"
|
||||
class="flex h-full items-center justify-center p-10 text-center"
|
||||
>
|
||||
<div class="max-w-md">
|
||||
<div
|
||||
class="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-gray-100 dark:bg-dark-700"
|
||||
>
|
||||
<Icon name="link" size="lg" class="text-gray-400" />
|
||||
</div>
|
||||
<h3 class="text-lg font-semibold text-gray-900 dark:text-white">
|
||||
{{ t('customPage.notFoundTitle') }}
|
||||
</h3>
|
||||
<p class="mt-2 text-sm text-gray-500 dark:text-dark-400">
|
||||
{{ t('customPage.notFoundDesc') }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="!isValidUrl" class="flex h-full items-center justify-center p-10 text-center">
|
||||
<div class="max-w-md">
|
||||
<div
|
||||
class="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-gray-100 dark:bg-dark-700"
|
||||
>
|
||||
<Icon name="link" size="lg" class="text-gray-400" />
|
||||
</div>
|
||||
<h3 class="text-lg font-semibold text-gray-900 dark:text-white">
|
||||
{{ t('customPage.notConfiguredTitle') }}
|
||||
</h3>
|
||||
<p class="mt-2 text-sm text-gray-500 dark:text-dark-400">
|
||||
{{ t('customPage.notConfiguredDesc') }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="custom-embed-shell">
|
||||
<a
|
||||
:href="embeddedUrl"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="btn btn-secondary btn-sm custom-open-fab"
|
||||
>
|
||||
<Icon name="externalLink" size="sm" class="mr-1.5" :stroke-width="2" />
|
||||
{{ t('customPage.openInNewTab') }}
|
||||
</a>
|
||||
<iframe
|
||||
:src="embeddedUrl"
|
||||
class="custom-embed-frame"
|
||||
allowfullscreen
|
||||
></iframe>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</AppLayout>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useAppStore } from '@/stores'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useAdminSettingsStore } from '@/stores/adminSettings'
|
||||
import AppLayout from '@/components/layout/AppLayout.vue'
|
||||
import Icon from '@/components/icons/Icon.vue'
|
||||
import { buildEmbeddedUrl, detectTheme } from '@/utils/embedded-url'
|
||||
|
||||
const { t } = useI18n()
|
||||
const route = useRoute()
|
||||
const appStore = useAppStore()
|
||||
const authStore = useAuthStore()
|
||||
const adminSettingsStore = useAdminSettingsStore()
|
||||
|
||||
const loading = ref(false)
|
||||
const pageTheme = ref<'light' | 'dark'>('light')
|
||||
let themeObserver: MutationObserver | null = null
|
||||
|
||||
const menuItemId = computed(() => route.params.id as string)
|
||||
|
||||
const menuItem = computed(() => {
|
||||
const id = menuItemId.value
|
||||
// Try public settings first (contains user-visible items)
|
||||
const publicItems = appStore.cachedPublicSettings?.custom_menu_items ?? []
|
||||
const found = publicItems.find((item) => item.id === id) ?? null
|
||||
if (found) return found
|
||||
// For admin users, also check admin settings (contains admin-only items)
|
||||
if (authStore.isAdmin) {
|
||||
return adminSettingsStore.customMenuItems.find((item) => item.id === id) ?? null
|
||||
}
|
||||
return null
|
||||
})
|
||||
|
||||
const embeddedUrl = computed(() => {
|
||||
if (!menuItem.value) return ''
|
||||
return buildEmbeddedUrl(
|
||||
menuItem.value.url,
|
||||
authStore.user?.id,
|
||||
authStore.token,
|
||||
pageTheme.value,
|
||||
)
|
||||
})
|
||||
|
||||
const isValidUrl = computed(() => {
|
||||
const url = embeddedUrl.value
|
||||
return url.startsWith('http://') || url.startsWith('https://')
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
pageTheme.value = detectTheme()
|
||||
|
||||
if (typeof document !== 'undefined') {
|
||||
themeObserver = new MutationObserver(() => {
|
||||
pageTheme.value = detectTheme()
|
||||
})
|
||||
themeObserver.observe(document.documentElement, {
|
||||
attributes: true,
|
||||
attributeFilter: ['class'],
|
||||
})
|
||||
}
|
||||
|
||||
if (appStore.publicSettingsLoaded) return
|
||||
loading.value = true
|
||||
try {
|
||||
await appStore.fetchPublicSettings()
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
if (themeObserver) {
|
||||
themeObserver.disconnect()
|
||||
themeObserver = null
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.custom-page-layout {
|
||||
@apply flex flex-col;
|
||||
height: calc(100vh - 64px - 4rem);
|
||||
}
|
||||
|
||||
.custom-embed-shell {
|
||||
@apply relative;
|
||||
@apply h-full w-full overflow-hidden rounded-2xl;
|
||||
@apply bg-gradient-to-b from-gray-50 to-white dark:from-dark-900 dark:to-dark-950;
|
||||
@apply p-0;
|
||||
}
|
||||
|
||||
.custom-open-fab {
|
||||
@apply absolute right-3 top-3 z-10;
|
||||
@apply shadow-sm backdrop-blur supports-[backdrop-filter]:bg-white/80;
|
||||
}
|
||||
|
||||
.custom-embed-frame {
|
||||
display: block;
|
||||
margin: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
box-shadow: none;
|
||||
background: transparent;
|
||||
}
|
||||
</style>
|
||||
@@ -1,6 +1,29 @@
|
||||
<template>
|
||||
<AppLayout>
|
||||
<TablePageLayout>
|
||||
<template #filters>
|
||||
<div class="flex flex-wrap items-center gap-3">
|
||||
<SearchInput
|
||||
v-model="filterSearch"
|
||||
:placeholder="t('keys.searchPlaceholder')"
|
||||
class="w-full sm:w-64"
|
||||
@search="onFilterChange"
|
||||
/>
|
||||
<Select
|
||||
:model-value="filterGroupId"
|
||||
class="w-40"
|
||||
:options="groupFilterOptions"
|
||||
@update:model-value="onGroupFilterChange"
|
||||
/>
|
||||
<Select
|
||||
:model-value="filterStatus"
|
||||
class="w-40"
|
||||
:options="statusFilterOptions"
|
||||
@update:model-value="onStatusFilterChange"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #actions>
|
||||
<div class="flex justify-end gap-3">
|
||||
<button
|
||||
@@ -137,6 +160,97 @@
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #cell-rate_limit="{ row }">
|
||||
<div v-if="row.rate_limit_5h > 0 || row.rate_limit_1d > 0 || row.rate_limit_7d > 0" class="space-y-1.5 min-w-[140px]">
|
||||
<!-- 5h window -->
|
||||
<div v-if="row.rate_limit_5h > 0">
|
||||
<div class="flex items-center justify-between text-xs">
|
||||
<span class="text-gray-500 dark:text-gray-400">5h</span>
|
||||
<span :class="[
|
||||
'font-medium tabular-nums',
|
||||
row.usage_5h >= row.rate_limit_5h ? 'text-red-500' :
|
||||
row.usage_5h >= row.rate_limit_5h * 0.8 ? 'text-yellow-500' :
|
||||
'text-gray-700 dark:text-gray-300'
|
||||
]">
|
||||
${{ row.usage_5h?.toFixed(2) || '0.00' }}/${{ row.rate_limit_5h?.toFixed(2) }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="h-1 w-full overflow-hidden rounded-full bg-gray-200 dark:bg-dark-600">
|
||||
<div
|
||||
:class="[
|
||||
'h-full rounded-full transition-all',
|
||||
row.usage_5h >= row.rate_limit_5h ? 'bg-red-500' :
|
||||
row.usage_5h >= row.rate_limit_5h * 0.8 ? 'bg-yellow-500' :
|
||||
'bg-emerald-500'
|
||||
]"
|
||||
:style="{ width: Math.min((row.usage_5h / row.rate_limit_5h) * 100, 100) + '%' }"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 1d window -->
|
||||
<div v-if="row.rate_limit_1d > 0">
|
||||
<div class="flex items-center justify-between text-xs">
|
||||
<span class="text-gray-500 dark:text-gray-400">1d</span>
|
||||
<span :class="[
|
||||
'font-medium tabular-nums',
|
||||
row.usage_1d >= row.rate_limit_1d ? 'text-red-500' :
|
||||
row.usage_1d >= row.rate_limit_1d * 0.8 ? 'text-yellow-500' :
|
||||
'text-gray-700 dark:text-gray-300'
|
||||
]">
|
||||
${{ row.usage_1d?.toFixed(2) || '0.00' }}/${{ row.rate_limit_1d?.toFixed(2) }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="h-1 w-full overflow-hidden rounded-full bg-gray-200 dark:bg-dark-600">
|
||||
<div
|
||||
:class="[
|
||||
'h-full rounded-full transition-all',
|
||||
row.usage_1d >= row.rate_limit_1d ? 'bg-red-500' :
|
||||
row.usage_1d >= row.rate_limit_1d * 0.8 ? 'bg-yellow-500' :
|
||||
'bg-emerald-500'
|
||||
]"
|
||||
:style="{ width: Math.min((row.usage_1d / row.rate_limit_1d) * 100, 100) + '%' }"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 7d window -->
|
||||
<div v-if="row.rate_limit_7d > 0">
|
||||
<div class="flex items-center justify-between text-xs">
|
||||
<span class="text-gray-500 dark:text-gray-400">7d</span>
|
||||
<span :class="[
|
||||
'font-medium tabular-nums',
|
||||
row.usage_7d >= row.rate_limit_7d ? 'text-red-500' :
|
||||
row.usage_7d >= row.rate_limit_7d * 0.8 ? 'text-yellow-500' :
|
||||
'text-gray-700 dark:text-gray-300'
|
||||
]">
|
||||
${{ row.usage_7d?.toFixed(2) || '0.00' }}/${{ row.rate_limit_7d?.toFixed(2) }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="h-1 w-full overflow-hidden rounded-full bg-gray-200 dark:bg-dark-600">
|
||||
<div
|
||||
:class="[
|
||||
'h-full rounded-full transition-all',
|
||||
row.usage_7d >= row.rate_limit_7d ? 'bg-red-500' :
|
||||
row.usage_7d >= row.rate_limit_7d * 0.8 ? 'bg-yellow-500' :
|
||||
'bg-emerald-500'
|
||||
]"
|
||||
:style="{ width: Math.min((row.usage_7d / row.rate_limit_7d) * 100, 100) + '%' }"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Reset button -->
|
||||
<button
|
||||
v-if="row.usage_5h > 0 || row.usage_1d > 0 || row.usage_7d > 0"
|
||||
@click.stop="confirmResetRateLimitFromTable(row)"
|
||||
class="mt-0.5 inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-xs text-gray-500 transition-colors hover:bg-gray-100 hover:text-primary-600 dark:hover:bg-dark-700 dark:hover:text-primary-400"
|
||||
:title="t('keys.resetRateLimitUsage')"
|
||||
>
|
||||
<Icon name="refresh" size="xs" />
|
||||
{{ t('keys.resetUsage') }}
|
||||
</button>
|
||||
</div>
|
||||
<span v-else class="text-sm text-gray-400 dark:text-dark-500">-</span>
|
||||
</template>
|
||||
|
||||
<template #cell-expires_at="{ value }">
|
||||
<span v-if="value" :class="[
|
||||
'text-sm',
|
||||
@@ -452,6 +566,180 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Rate Limit Section -->
|
||||
<div class="space-y-3">
|
||||
<div class="flex items-center justify-between">
|
||||
<label class="input-label mb-0">{{ t('keys.rateLimitSection') }}</label>
|
||||
<button
|
||||
type="button"
|
||||
@click="formData.enable_rate_limit = !formData.enable_rate_limit"
|
||||
:class="[
|
||||
'relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none',
|
||||
formData.enable_rate_limit ? 'bg-primary-600' : 'bg-gray-200 dark:bg-dark-600'
|
||||
]"
|
||||
>
|
||||
<span
|
||||
:class="[
|
||||
'pointer-events-none inline-block h-4 w-4 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out',
|
||||
formData.enable_rate_limit ? 'translate-x-4' : 'translate-x-0'
|
||||
]"
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="formData.enable_rate_limit" class="space-y-4 pt-2">
|
||||
<p class="input-hint -mt-2">{{ t('keys.rateLimitHint') }}</p>
|
||||
<!-- 5-Hour Limit -->
|
||||
<div>
|
||||
<label class="input-label">{{ t('keys.rateLimit5h') }}</label>
|
||||
<div class="relative">
|
||||
<span class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500">$</span>
|
||||
<input
|
||||
v-model.number="formData.rate_limit_5h"
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
class="input pl-7"
|
||||
:placeholder="'0'"
|
||||
/>
|
||||
</div>
|
||||
<!-- Usage info (edit mode only) -->
|
||||
<div v-if="showEditModal && selectedKey && selectedKey.rate_limit_5h > 0" class="mt-2">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="flex-1 rounded-lg bg-gray-100 px-3 py-2 dark:bg-dark-700 text-sm">
|
||||
<span :class="[
|
||||
'font-medium',
|
||||
selectedKey.usage_5h >= selectedKey.rate_limit_5h ? 'text-red-500' :
|
||||
selectedKey.usage_5h >= selectedKey.rate_limit_5h * 0.8 ? 'text-yellow-500' :
|
||||
'text-gray-900 dark:text-white'
|
||||
]">
|
||||
${{ selectedKey.usage_5h?.toFixed(4) || '0.0000' }}
|
||||
</span>
|
||||
<span class="mx-2 text-gray-400">/</span>
|
||||
<span class="text-gray-500 dark:text-gray-400">
|
||||
${{ selectedKey.rate_limit_5h?.toFixed(2) || '0.00' }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-1 h-1.5 w-full overflow-hidden rounded-full bg-gray-200 dark:bg-dark-600">
|
||||
<div
|
||||
:class="[
|
||||
'h-full rounded-full transition-all',
|
||||
selectedKey.usage_5h >= selectedKey.rate_limit_5h ? 'bg-red-500' :
|
||||
selectedKey.usage_5h >= selectedKey.rate_limit_5h * 0.8 ? 'bg-yellow-500' :
|
||||
'bg-green-500'
|
||||
]"
|
||||
:style="{ width: Math.min((selectedKey.usage_5h / selectedKey.rate_limit_5h) * 100, 100) + '%' }"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Daily Limit -->
|
||||
<div>
|
||||
<label class="input-label">{{ t('keys.rateLimit1d') }}</label>
|
||||
<div class="relative">
|
||||
<span class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500">$</span>
|
||||
<input
|
||||
v-model.number="formData.rate_limit_1d"
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
class="input pl-7"
|
||||
:placeholder="'0'"
|
||||
/>
|
||||
</div>
|
||||
<!-- Usage info (edit mode only) -->
|
||||
<div v-if="showEditModal && selectedKey && selectedKey.rate_limit_1d > 0" class="mt-2">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="flex-1 rounded-lg bg-gray-100 px-3 py-2 dark:bg-dark-700 text-sm">
|
||||
<span :class="[
|
||||
'font-medium',
|
||||
selectedKey.usage_1d >= selectedKey.rate_limit_1d ? 'text-red-500' :
|
||||
selectedKey.usage_1d >= selectedKey.rate_limit_1d * 0.8 ? 'text-yellow-500' :
|
||||
'text-gray-900 dark:text-white'
|
||||
]">
|
||||
${{ selectedKey.usage_1d?.toFixed(4) || '0.0000' }}
|
||||
</span>
|
||||
<span class="mx-2 text-gray-400">/</span>
|
||||
<span class="text-gray-500 dark:text-gray-400">
|
||||
${{ selectedKey.rate_limit_1d?.toFixed(2) || '0.00' }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-1 h-1.5 w-full overflow-hidden rounded-full bg-gray-200 dark:bg-dark-600">
|
||||
<div
|
||||
:class="[
|
||||
'h-full rounded-full transition-all',
|
||||
selectedKey.usage_1d >= selectedKey.rate_limit_1d ? 'bg-red-500' :
|
||||
selectedKey.usage_1d >= selectedKey.rate_limit_1d * 0.8 ? 'bg-yellow-500' :
|
||||
'bg-green-500'
|
||||
]"
|
||||
:style="{ width: Math.min((selectedKey.usage_1d / selectedKey.rate_limit_1d) * 100, 100) + '%' }"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 7-Day Limit -->
|
||||
<div>
|
||||
<label class="input-label">{{ t('keys.rateLimit7d') }}</label>
|
||||
<div class="relative">
|
||||
<span class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500">$</span>
|
||||
<input
|
||||
v-model.number="formData.rate_limit_7d"
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
class="input pl-7"
|
||||
:placeholder="'0'"
|
||||
/>
|
||||
</div>
|
||||
<!-- Usage info (edit mode only) -->
|
||||
<div v-if="showEditModal && selectedKey && selectedKey.rate_limit_7d > 0" class="mt-2">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="flex-1 rounded-lg bg-gray-100 px-3 py-2 dark:bg-dark-700 text-sm">
|
||||
<span :class="[
|
||||
'font-medium',
|
||||
selectedKey.usage_7d >= selectedKey.rate_limit_7d ? 'text-red-500' :
|
||||
selectedKey.usage_7d >= selectedKey.rate_limit_7d * 0.8 ? 'text-yellow-500' :
|
||||
'text-gray-900 dark:text-white'
|
||||
]">
|
||||
${{ selectedKey.usage_7d?.toFixed(4) || '0.0000' }}
|
||||
</span>
|
||||
<span class="mx-2 text-gray-400">/</span>
|
||||
<span class="text-gray-500 dark:text-gray-400">
|
||||
${{ selectedKey.rate_limit_7d?.toFixed(2) || '0.00' }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-1 h-1.5 w-full overflow-hidden rounded-full bg-gray-200 dark:bg-dark-600">
|
||||
<div
|
||||
:class="[
|
||||
'h-full rounded-full transition-all',
|
||||
selectedKey.usage_7d >= selectedKey.rate_limit_7d ? 'bg-red-500' :
|
||||
selectedKey.usage_7d >= selectedKey.rate_limit_7d * 0.8 ? 'bg-yellow-500' :
|
||||
'bg-green-500'
|
||||
]"
|
||||
:style="{ width: Math.min((selectedKey.usage_7d / selectedKey.rate_limit_7d) * 100, 100) + '%' }"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Reset Rate Limit button (edit mode only) -->
|
||||
<div v-if="showEditModal && selectedKey && (selectedKey.rate_limit_5h > 0 || selectedKey.rate_limit_1d > 0 || selectedKey.rate_limit_7d > 0)">
|
||||
<button
|
||||
type="button"
|
||||
@click="confirmResetRateLimit"
|
||||
class="btn btn-secondary text-sm"
|
||||
>
|
||||
{{ t('keys.resetRateLimitUsage') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Expiration Section -->
|
||||
<div class="space-y-3">
|
||||
<div class="flex items-center justify-between">
|
||||
@@ -593,6 +881,18 @@
|
||||
@cancel="showResetQuotaDialog = false"
|
||||
/>
|
||||
|
||||
<!-- Reset Rate Limit Confirmation Dialog -->
|
||||
<ConfirmDialog
|
||||
:show="showResetRateLimitDialog"
|
||||
:title="t('keys.resetRateLimitTitle')"
|
||||
:message="t('keys.resetRateLimitConfirmMessage', { name: selectedKey?.name })"
|
||||
:confirm-text="t('keys.reset')"
|
||||
:cancel-text="t('common.cancel')"
|
||||
:danger="true"
|
||||
@confirm="resetRateLimitUsage"
|
||||
@cancel="showResetRateLimitDialog = false"
|
||||
/>
|
||||
|
||||
<!-- Use Key Modal -->
|
||||
<UseKeyModal
|
||||
:show="showUseKeyModal"
|
||||
@@ -708,6 +1008,7 @@ import TablePageLayout from '@/components/layout/TablePageLayout.vue'
|
||||
import ConfirmDialog from '@/components/common/ConfirmDialog.vue'
|
||||
import EmptyState from '@/components/common/EmptyState.vue'
|
||||
import Select from '@/components/common/Select.vue'
|
||||
import SearchInput from '@/components/common/SearchInput.vue'
|
||||
import Icon from '@/components/icons/Icon.vue'
|
||||
import UseKeyModal from '@/components/keys/UseKeyModal.vue'
|
||||
import GroupBadge from '@/components/common/GroupBadge.vue'
|
||||
@@ -743,6 +1044,7 @@ const columns = computed<Column[]>(() => [
|
||||
{ key: 'key', label: t('keys.apiKey'), sortable: false },
|
||||
{ key: 'group', label: t('keys.group'), sortable: false },
|
||||
{ key: 'usage', label: t('keys.usage'), sortable: false },
|
||||
{ key: 'rate_limit', label: t('keys.rateLimitColumn'), sortable: false },
|
||||
{ key: 'expires_at', label: t('keys.expiresAt'), sortable: true },
|
||||
{ key: 'status', label: t('common.status'), sortable: true },
|
||||
{ key: 'last_used_at', label: t('keys.lastUsedAt'), sortable: true },
|
||||
@@ -764,10 +1066,16 @@ const pagination = ref({
|
||||
pages: 0
|
||||
})
|
||||
|
||||
// Filter state
|
||||
const filterSearch = ref('')
|
||||
const filterStatus = ref('')
|
||||
const filterGroupId = ref<string | number>('')
|
||||
|
||||
const showCreateModal = ref(false)
|
||||
const showEditModal = ref(false)
|
||||
const showDeleteDialog = ref(false)
|
||||
const showResetQuotaDialog = ref(false)
|
||||
const showResetRateLimitDialog = ref(false)
|
||||
const showUseKeyModal = ref(false)
|
||||
const showCcsClientSelect = ref(false)
|
||||
const pendingCcsRow = ref<ApiKey | null>(null)
|
||||
@@ -806,6 +1114,11 @@ const formData = ref({
|
||||
// Quota settings (empty = unlimited)
|
||||
enable_quota: false,
|
||||
quota: null as number | null,
|
||||
// Rate limit settings
|
||||
enable_rate_limit: false,
|
||||
rate_limit_5h: null as number | null,
|
||||
rate_limit_1d: null as number | null,
|
||||
rate_limit_7d: null as number | null,
|
||||
enable_expiration: false,
|
||||
expiration_preset: '30' as '7' | '30' | '90' | 'custom',
|
||||
expiration_date: ''
|
||||
@@ -832,6 +1145,36 @@ const statusOptions = computed(() => [
|
||||
{ value: 'inactive', label: t('common.inactive') }
|
||||
])
|
||||
|
||||
// Filter dropdown options
|
||||
const groupFilterOptions = computed(() => [
|
||||
{ value: '', label: t('keys.allGroups') },
|
||||
{ value: 0, label: t('keys.noGroup') },
|
||||
...groups.value.map((g) => ({ value: g.id, label: g.name }))
|
||||
])
|
||||
|
||||
const statusFilterOptions = computed(() => [
|
||||
{ value: '', label: t('keys.allStatus') },
|
||||
{ value: 'active', label: t('keys.status.active') },
|
||||
{ value: 'inactive', label: t('keys.status.inactive') },
|
||||
{ value: 'quota_exhausted', label: t('keys.status.quota_exhausted') },
|
||||
{ value: 'expired', label: t('keys.status.expired') }
|
||||
])
|
||||
|
||||
const onFilterChange = () => {
|
||||
pagination.value.page = 1
|
||||
loadApiKeys()
|
||||
}
|
||||
|
||||
const onGroupFilterChange = (value: string | number | boolean | null) => {
|
||||
filterGroupId.value = value as string | number
|
||||
onFilterChange()
|
||||
}
|
||||
|
||||
const onStatusFilterChange = (value: string | number | boolean | null) => {
|
||||
filterStatus.value = value as string
|
||||
onFilterChange()
|
||||
}
|
||||
|
||||
// Convert groups to Select options format with rate multiplier and subscription type
|
||||
const groupOptions = computed(() =>
|
||||
groups.value.map((group) => ({
|
||||
@@ -873,7 +1216,13 @@ const loadApiKeys = async () => {
|
||||
const { signal } = controller
|
||||
loading.value = true
|
||||
try {
|
||||
const response = await keysAPI.list(pagination.value.page, pagination.value.page_size, {
|
||||
// Build filters
|
||||
const filters: { search?: string; status?: string; group_id?: number | string } = {}
|
||||
if (filterSearch.value) filters.search = filterSearch.value
|
||||
if (filterStatus.value) filters.status = filterStatus.value
|
||||
if (filterGroupId.value !== '') filters.group_id = filterGroupId.value
|
||||
|
||||
const response = await keysAPI.list(pagination.value.page, pagination.value.page_size, filters, {
|
||||
signal
|
||||
})
|
||||
if (signal.aborted) return
|
||||
@@ -966,6 +1315,10 @@ const editKey = (key: ApiKey) => {
|
||||
ip_blacklist: (key.ip_blacklist || []).join('\n'),
|
||||
enable_quota: key.quota > 0,
|
||||
quota: key.quota > 0 ? key.quota : null,
|
||||
enable_rate_limit: (key.rate_limit_5h > 0) || (key.rate_limit_1d > 0) || (key.rate_limit_7d > 0),
|
||||
rate_limit_5h: key.rate_limit_5h || null,
|
||||
rate_limit_1d: key.rate_limit_1d || null,
|
||||
rate_limit_7d: key.rate_limit_7d || null,
|
||||
enable_expiration: hasExpiration,
|
||||
expiration_preset: 'custom',
|
||||
expiration_date: key.expires_at ? formatDateTimeLocal(key.expires_at) : ''
|
||||
@@ -1078,6 +1431,13 @@ const handleSubmit = async () => {
|
||||
expiresAt = ''
|
||||
}
|
||||
|
||||
// Calculate rate limit values (send 0 when toggle is off)
|
||||
const rateLimitData = formData.value.enable_rate_limit ? {
|
||||
rate_limit_5h: formData.value.rate_limit_5h && formData.value.rate_limit_5h > 0 ? formData.value.rate_limit_5h : 0,
|
||||
rate_limit_1d: formData.value.rate_limit_1d && formData.value.rate_limit_1d > 0 ? formData.value.rate_limit_1d : 0,
|
||||
rate_limit_7d: formData.value.rate_limit_7d && formData.value.rate_limit_7d > 0 ? formData.value.rate_limit_7d : 0,
|
||||
} : { rate_limit_5h: 0, rate_limit_1d: 0, rate_limit_7d: 0 }
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
if (showEditModal.value && selectedKey.value) {
|
||||
@@ -1088,7 +1448,10 @@ const handleSubmit = async () => {
|
||||
ip_whitelist: ipWhitelist,
|
||||
ip_blacklist: ipBlacklist,
|
||||
quota: quota,
|
||||
expires_at: expiresAt
|
||||
expires_at: expiresAt,
|
||||
rate_limit_5h: rateLimitData.rate_limit_5h,
|
||||
rate_limit_1d: rateLimitData.rate_limit_1d,
|
||||
rate_limit_7d: rateLimitData.rate_limit_7d,
|
||||
})
|
||||
appStore.showSuccess(t('keys.keyUpdatedSuccess'))
|
||||
} else {
|
||||
@@ -1100,7 +1463,8 @@ const handleSubmit = async () => {
|
||||
ipWhitelist,
|
||||
ipBlacklist,
|
||||
quota,
|
||||
expiresInDays
|
||||
expiresInDays,
|
||||
rateLimitData
|
||||
)
|
||||
appStore.showSuccess(t('keys.keyCreatedSuccess'))
|
||||
// Only advance tour if active, on submit step, and creation succeeded
|
||||
@@ -1154,6 +1518,10 @@ const closeModals = () => {
|
||||
ip_blacklist: '',
|
||||
enable_quota: false,
|
||||
quota: null,
|
||||
enable_rate_limit: false,
|
||||
rate_limit_5h: null,
|
||||
rate_limit_1d: null,
|
||||
rate_limit_7d: null,
|
||||
enable_expiration: false,
|
||||
expiration_preset: '30',
|
||||
expiration_date: ''
|
||||
@@ -1190,6 +1558,37 @@ const resetQuotaUsed = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
// Show reset rate limit confirmation dialog (from edit modal)
|
||||
const confirmResetRateLimit = () => {
|
||||
showResetRateLimitDialog.value = true
|
||||
}
|
||||
|
||||
// Show reset rate limit confirmation dialog (from table row)
|
||||
const confirmResetRateLimitFromTable = (row: ApiKey) => {
|
||||
selectedKey.value = row
|
||||
showResetRateLimitDialog.value = true
|
||||
}
|
||||
|
||||
// Reset rate limit usage for an API key
|
||||
const resetRateLimitUsage = async () => {
|
||||
if (!selectedKey.value) return
|
||||
showResetRateLimitDialog.value = false
|
||||
try {
|
||||
await keysAPI.update(selectedKey.value.id, { reset_rate_limit_usage: true })
|
||||
appStore.showSuccess(t('keys.rateLimitResetSuccess'))
|
||||
// Refresh key data
|
||||
await loadApiKeys()
|
||||
// Update the editing key with fresh data
|
||||
const refreshedKey = apiKeys.value.find(k => k.id === selectedKey.value!.id)
|
||||
if (refreshedKey) {
|
||||
selectedKey.value = refreshedKey
|
||||
}
|
||||
} catch (error: any) {
|
||||
const errorMsg = error.response?.data?.detail || t('keys.failedToResetRateLimit')
|
||||
appStore.showError(errorMsg)
|
||||
}
|
||||
}
|
||||
|
||||
const importToCcswitch = (row: ApiKey) => {
|
||||
const platform = row.group?.platform || 'anthropic'
|
||||
|
||||
|
||||
@@ -74,17 +74,12 @@ import { useAppStore } from '@/stores'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import AppLayout from '@/components/layout/AppLayout.vue'
|
||||
import Icon from '@/components/icons/Icon.vue'
|
||||
import { buildEmbeddedUrl, detectTheme } from '@/utils/embedded-url'
|
||||
|
||||
const { t } = useI18n()
|
||||
const appStore = useAppStore()
|
||||
const authStore = useAuthStore()
|
||||
|
||||
const PURCHASE_USER_ID_QUERY_KEY = 'user_id'
|
||||
const PURCHASE_AUTH_TOKEN_QUERY_KEY = 'token'
|
||||
const PURCHASE_THEME_QUERY_KEY = 'theme'
|
||||
const PURCHASE_UI_MODE_QUERY_KEY = 'ui_mode'
|
||||
const PURCHASE_UI_MODE_EMBEDDED = 'embedded'
|
||||
|
||||
const loading = ref(false)
|
||||
const purchaseTheme = ref<'light' | 'dark'>('light')
|
||||
let themeObserver: MutationObserver | null = null
|
||||
@@ -93,37 +88,9 @@ const purchaseEnabled = computed(() => {
|
||||
return appStore.cachedPublicSettings?.purchase_subscription_enabled ?? false
|
||||
})
|
||||
|
||||
function detectTheme(): 'light' | 'dark' {
|
||||
if (typeof document === 'undefined') return 'light'
|
||||
return document.documentElement.classList.contains('dark') ? 'dark' : 'light'
|
||||
}
|
||||
|
||||
function buildPurchaseUrl(
|
||||
baseUrl: string,
|
||||
userId?: number,
|
||||
authToken?: string | null,
|
||||
theme: 'light' | 'dark' = 'light',
|
||||
): string {
|
||||
if (!baseUrl) return baseUrl
|
||||
try {
|
||||
const url = new URL(baseUrl)
|
||||
if (userId) {
|
||||
url.searchParams.set(PURCHASE_USER_ID_QUERY_KEY, String(userId))
|
||||
}
|
||||
if (authToken) {
|
||||
url.searchParams.set(PURCHASE_AUTH_TOKEN_QUERY_KEY, authToken)
|
||||
}
|
||||
url.searchParams.set(PURCHASE_THEME_QUERY_KEY, theme)
|
||||
url.searchParams.set(PURCHASE_UI_MODE_QUERY_KEY, PURCHASE_UI_MODE_EMBEDDED)
|
||||
return url.toString()
|
||||
} catch {
|
||||
return baseUrl
|
||||
}
|
||||
}
|
||||
|
||||
const purchaseUrl = computed(() => {
|
||||
const baseUrl = (appStore.cachedPublicSettings?.purchase_subscription_url || '').trim()
|
||||
return buildPurchaseUrl(baseUrl, authStore.user?.id, authStore.token, purchaseTheme.value)
|
||||
return buildEmbeddedUrl(baseUrl, authStore.user?.id, authStore.token, purchaseTheme.value)
|
||||
})
|
||||
|
||||
const isValidUrl = computed(() => {
|
||||
|
||||
369
frontend/src/views/user/SoraView.vue
Normal file
369
frontend/src/views/user/SoraView.vue
Normal file
@@ -0,0 +1,369 @@
|
||||
<template>
|
||||
<div class="sora-root">
|
||||
<!-- Sora 页面内容 -->
|
||||
<div class="sora-page">
|
||||
<!-- 功能未启用提示 -->
|
||||
<div v-if="!soraEnabled" class="sora-not-enabled">
|
||||
<svg class="sora-not-enabled-icon" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9.813 15.904L9 18.75l-.813-2.846a4.5 4.5 0 00-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 003.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 003.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 00-3.09 3.09zM18.259 8.715L18 9.75l-.259-1.035a3.375 3.375 0 00-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 002.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 002.455 2.456L21.75 6l-1.036.259a3.375 3.375 0 00-2.455 2.456z" />
|
||||
</svg>
|
||||
<h2 class="sora-not-enabled-title">{{ t('sora.notEnabled') }}</h2>
|
||||
<p class="sora-not-enabled-desc">{{ t('sora.notEnabledDesc') }}</p>
|
||||
</div>
|
||||
|
||||
<!-- Sora 主界面 -->
|
||||
<template v-else>
|
||||
<!-- 自定义 Sora 头部 -->
|
||||
<header class="sora-header">
|
||||
<div class="sora-header-left">
|
||||
<!-- 返回主页按钮 -->
|
||||
<router-link :to="dashboardPath" class="sora-back-btn" :title="t('common.back')">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M15 19l-7-7 7-7" />
|
||||
</svg>
|
||||
</router-link>
|
||||
<nav class="sora-nav-tabs">
|
||||
<button
|
||||
v-for="tab in tabs"
|
||||
:key="tab.key"
|
||||
:class="['sora-nav-tab', activeTab === tab.key && 'active']"
|
||||
@click="activeTab = tab.key"
|
||||
>
|
||||
{{ tab.label }}
|
||||
</button>
|
||||
</nav>
|
||||
</div>
|
||||
<div class="sora-header-right">
|
||||
<SoraQuotaBar v-if="quota" :quota="quota" />
|
||||
<div v-if="activeTaskCount > 0" class="sora-queue-indicator">
|
||||
<span class="sora-queue-dot" :class="{ busy: hasGeneratingTask }"></span>
|
||||
<span>{{ activeTaskCount }} {{ t('sora.queueTasks') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- 内容区域 -->
|
||||
<main class="sora-main">
|
||||
<SoraGeneratePage
|
||||
v-show="activeTab === 'generate'"
|
||||
@task-count-change="onTaskCountChange"
|
||||
/>
|
||||
<SoraLibraryPage
|
||||
v-show="activeTab === 'library'"
|
||||
@switch-to-generate="activeTab = 'generate'"
|
||||
/>
|
||||
</main>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useAppStore, useAuthStore } from '@/stores'
|
||||
import SoraQuotaBar from '@/components/sora/SoraQuotaBar.vue'
|
||||
import SoraGeneratePage from '@/components/sora/SoraGeneratePage.vue'
|
||||
import SoraLibraryPage from '@/components/sora/SoraLibraryPage.vue'
|
||||
import soraAPI, { type QuotaInfo } from '@/api/sora'
|
||||
|
||||
const { t } = useI18n()
|
||||
const authStore = useAuthStore()
|
||||
const appStore = useAppStore()
|
||||
|
||||
const soraEnabled = computed(() => appStore.cachedPublicSettings?.sora_client_enabled ?? false)
|
||||
|
||||
const activeTab = ref<'generate' | 'library'>('generate')
|
||||
const quota = ref<QuotaInfo | null>(null)
|
||||
const activeTaskCount = ref(0)
|
||||
const hasGeneratingTask = ref(false)
|
||||
const dashboardPath = computed(() => (authStore.isAdmin ? '/admin/dashboard' : '/dashboard'))
|
||||
|
||||
const tabs = computed(() => [
|
||||
{ key: 'generate' as const, label: t('sora.tabGenerate') },
|
||||
{ key: 'library' as const, label: t('sora.tabLibrary') }
|
||||
])
|
||||
|
||||
function onTaskCountChange(counts: { active: number; generating: boolean }) {
|
||||
activeTaskCount.value = counts.active
|
||||
hasGeneratingTask.value = counts.generating
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
if (!soraEnabled.value) return
|
||||
try {
|
||||
quota.value = await soraAPI.getQuota()
|
||||
} catch {
|
||||
// 配额查询失败不阻塞页面
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* ============================================================
|
||||
Sora 主题 CSS 变量 — 亮色模式(跟随应用主题)
|
||||
============================================================ */
|
||||
.sora-root {
|
||||
--sora-bg-primary: #F9FAFB;
|
||||
--sora-bg-secondary: #FFFFFF;
|
||||
--sora-bg-tertiary: #F3F4F6;
|
||||
--sora-bg-elevated: #FFFFFF;
|
||||
--sora-bg-hover: #E5E7EB;
|
||||
--sora-bg-input: #FFFFFF;
|
||||
--sora-text-primary: #111827;
|
||||
--sora-text-secondary: #6B7280;
|
||||
--sora-text-tertiary: #9CA3AF;
|
||||
--sora-text-muted: #D1D5DB;
|
||||
--sora-accent-primary: #14b8a6;
|
||||
--sora-accent-secondary: #0d9488;
|
||||
--sora-accent-gradient: linear-gradient(135deg, #14b8a6 0%, #0d9488 100%);
|
||||
--sora-accent-gradient-hover: linear-gradient(135deg, #2dd4bf 0%, #14b8a6 100%);
|
||||
--sora-success: #10B981;
|
||||
--sora-warning: #F59E0B;
|
||||
--sora-error: #EF4444;
|
||||
--sora-info: #3B82F6;
|
||||
--sora-border-color: #E5E7EB;
|
||||
--sora-border-subtle: #F3F4F6;
|
||||
--sora-radius-sm: 8px;
|
||||
--sora-radius-md: 12px;
|
||||
--sora-radius-lg: 16px;
|
||||
--sora-radius-xl: 20px;
|
||||
--sora-radius-full: 9999px;
|
||||
--sora-shadow-sm: 0 1px 2px rgba(0,0,0,0.05);
|
||||
--sora-shadow-md: 0 4px 12px rgba(0,0,0,0.08);
|
||||
--sora-shadow-lg: 0 8px 32px rgba(0,0,0,0.12);
|
||||
--sora-shadow-glow: 0 0 20px rgba(20,184,166,0.25);
|
||||
--sora-transition-fast: 150ms ease;
|
||||
--sora-transition-normal: 250ms ease;
|
||||
--sora-header-height: 56px;
|
||||
--sora-header-bg: rgba(249, 250, 251, 0.85);
|
||||
--sora-placeholder-gradient: linear-gradient(135deg, #e0e7ff 0%, #dbeafe 50%, #cffafe 100%);
|
||||
--sora-modal-backdrop: rgba(0, 0, 0, 0.4);
|
||||
|
||||
min-height: 100vh;
|
||||
background: var(--sora-bg-primary);
|
||||
color: var(--sora-text-primary);
|
||||
font-family: -apple-system, BlinkMacSystemFont, "SF Pro Display", "Segoe UI", "PingFang SC", "Noto Sans SC", sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
页面布局
|
||||
============================================================ */
|
||||
.sora-page {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
头部导航栏
|
||||
============================================================ */
|
||||
.sora-header {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 30;
|
||||
height: var(--sora-header-height);
|
||||
background: var(--sora-header-bg);
|
||||
backdrop-filter: blur(20px);
|
||||
-webkit-backdrop-filter: blur(20px);
|
||||
border-bottom: 1px solid var(--sora-border-subtle);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 0 24px;
|
||||
}
|
||||
|
||||
.sora-header-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
.sora-header-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
/* 返回按钮 */
|
||||
.sora-back-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: var(--sora-radius-sm);
|
||||
color: var(--sora-text-secondary);
|
||||
text-decoration: none;
|
||||
transition: all var(--sora-transition-fast);
|
||||
}
|
||||
|
||||
.sora-back-btn:hover {
|
||||
background: var(--sora-bg-tertiary);
|
||||
color: var(--sora-text-primary);
|
||||
}
|
||||
|
||||
/* Tab 导航 */
|
||||
.sora-nav-tabs {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
background: var(--sora-bg-secondary);
|
||||
border-radius: var(--sora-radius-full);
|
||||
padding: 3px;
|
||||
}
|
||||
|
||||
.sora-nav-tab {
|
||||
padding: 6px 20px;
|
||||
border-radius: var(--sora-radius-full);
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: var(--sora-text-secondary);
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
transition: all var(--sora-transition-fast);
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.sora-nav-tab:hover {
|
||||
color: var(--sora-text-primary);
|
||||
}
|
||||
|
||||
.sora-nav-tab.active {
|
||||
background: var(--sora-bg-tertiary);
|
||||
color: var(--sora-text-primary);
|
||||
}
|
||||
|
||||
/* 队列指示器 */
|
||||
.sora-queue-indicator {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 6px 12px;
|
||||
background: var(--sora-bg-secondary);
|
||||
border-radius: var(--sora-radius-full);
|
||||
font-size: 12px;
|
||||
color: var(--sora-text-secondary);
|
||||
}
|
||||
|
||||
.sora-queue-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--sora-success);
|
||||
animation: sora-pulse-dot 2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.sora-queue-dot.busy {
|
||||
background: var(--sora-warning);
|
||||
}
|
||||
|
||||
@keyframes sora-pulse-dot {
|
||||
0%, 100% { opacity: 1; }
|
||||
50% { opacity: 0.4; }
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
主内容区
|
||||
============================================================ */
|
||||
.sora-main {
|
||||
min-height: calc(100vh - var(--sora-header-height));
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
功能未启用
|
||||
============================================================ */
|
||||
.sora-not-enabled {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 100vh;
|
||||
text-align: center;
|
||||
padding: 40px;
|
||||
}
|
||||
|
||||
.sora-not-enabled-icon {
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
color: var(--sora-text-tertiary);
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.sora-not-enabled-title {
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
color: var(--sora-text-secondary);
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.sora-not-enabled-desc {
|
||||
font-size: 14px;
|
||||
color: var(--sora-text-tertiary);
|
||||
max-width: 400px;
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
响应式
|
||||
============================================================ */
|
||||
@media (max-width: 900px) {
|
||||
.sora-header {
|
||||
padding: 0 16px;
|
||||
}
|
||||
|
||||
.sora-header-left {
|
||||
gap: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.sora-nav-tab {
|
||||
padding: 5px 14px;
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
/* 滚动条 */
|
||||
.sora-root ::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
|
||||
.sora-root ::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.sora-root ::-webkit-scrollbar-thumb {
|
||||
background: var(--sora-bg-hover);
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.sora-root ::-webkit-scrollbar-thumb:hover {
|
||||
background: var(--sora-text-tertiary);
|
||||
}
|
||||
</style>
|
||||
|
||||
<style>
|
||||
/* 暗色模式:必须明确命中 .sora-root,避免被 scoped 编译后的变量覆盖问题 */
|
||||
html.dark .sora-root {
|
||||
--sora-bg-primary: #020617;
|
||||
--sora-bg-secondary: #0f172a;
|
||||
--sora-bg-tertiary: #1e293b;
|
||||
--sora-bg-elevated: #1e293b;
|
||||
--sora-bg-hover: #334155;
|
||||
--sora-bg-input: #0f172a;
|
||||
--sora-text-primary: #f1f5f9;
|
||||
--sora-text-secondary: #94a3b8;
|
||||
--sora-text-tertiary: #64748b;
|
||||
--sora-text-muted: #475569;
|
||||
--sora-border-color: #334155;
|
||||
--sora-border-subtle: #1e293b;
|
||||
--sora-shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.3);
|
||||
--sora-shadow-md: 0 4px 12px rgba(0, 0, 0, 0.4);
|
||||
--sora-shadow-lg: 0 8px 32px rgba(0, 0, 0, 0.5);
|
||||
--sora-shadow-glow: 0 0 20px rgba(20, 184, 166, 0.3);
|
||||
--sora-header-bg: rgba(2, 6, 23, 0.85);
|
||||
--sora-placeholder-gradient: linear-gradient(135deg, #1e293b 0%, #0f172a 50%, #020617 100%);
|
||||
--sora-modal-backdrop: rgba(0, 0, 0, 0.7);
|
||||
}
|
||||
</style>
|
||||
@@ -166,13 +166,9 @@
|
||||
<template #cell-stream="{ row }">
|
||||
<span
|
||||
class="inline-flex items-center rounded px-2 py-0.5 text-xs font-medium"
|
||||
:class="
|
||||
row.stream
|
||||
? 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200'
|
||||
: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200'
|
||||
"
|
||||
:class="getRequestTypeBadgeClass(row)"
|
||||
>
|
||||
{{ row.stream ? t('usage.stream') : t('usage.sync') }}
|
||||
{{ getRequestTypeLabel(row) }}
|
||||
</span>
|
||||
</template>
|
||||
|
||||
@@ -473,12 +469,13 @@ import TablePageLayout from '@/components/layout/TablePageLayout.vue'
|
||||
import DataTable from '@/components/common/DataTable.vue'
|
||||
import Pagination from '@/components/common/Pagination.vue'
|
||||
import EmptyState from '@/components/common/EmptyState.vue'
|
||||
import Select from '@/components/common/Select.vue'
|
||||
import DateRangePicker from '@/components/common/DateRangePicker.vue'
|
||||
import Icon from '@/components/icons/Icon.vue'
|
||||
import type { UsageLog, ApiKey, UsageQueryParams, UsageStatsResponse } from '@/types'
|
||||
import type { Column } from '@/components/common/types'
|
||||
import { formatDateTime, formatReasoningEffort } from '@/utils/format'
|
||||
import Select from '@/components/common/Select.vue'
|
||||
import DateRangePicker from '@/components/common/DateRangePicker.vue'
|
||||
import Icon from '@/components/icons/Icon.vue'
|
||||
import type { UsageLog, ApiKey, UsageQueryParams, UsageStatsResponse } from '@/types'
|
||||
import type { Column } from '@/components/common/types'
|
||||
import { formatDateTime, formatReasoningEffort } from '@/utils/format'
|
||||
import { resolveUsageRequestType } from '@/utils/usageRequestType'
|
||||
|
||||
const { t } = useI18n()
|
||||
const appStore = useAppStore()
|
||||
@@ -577,6 +574,30 @@ const formatUserAgent = (ua: string): string => {
|
||||
return ua
|
||||
}
|
||||
|
||||
const getRequestTypeLabel = (log: UsageLog): string => {
|
||||
const requestType = resolveUsageRequestType(log)
|
||||
if (requestType === 'ws_v2') return t('usage.ws')
|
||||
if (requestType === 'stream') return t('usage.stream')
|
||||
if (requestType === 'sync') return t('usage.sync')
|
||||
return t('usage.unknown')
|
||||
}
|
||||
|
||||
const getRequestTypeBadgeClass = (log: UsageLog): string => {
|
||||
const requestType = resolveUsageRequestType(log)
|
||||
if (requestType === 'ws_v2') return 'bg-violet-100 text-violet-800 dark:bg-violet-900 dark:text-violet-200'
|
||||
if (requestType === 'stream') return 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200'
|
||||
if (requestType === 'sync') return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200'
|
||||
return 'bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-200'
|
||||
}
|
||||
|
||||
const getRequestTypeExportText = (log: UsageLog): string => {
|
||||
const requestType = resolveUsageRequestType(log)
|
||||
if (requestType === 'ws_v2') return 'WS'
|
||||
if (requestType === 'stream') return 'Stream'
|
||||
if (requestType === 'sync') return 'Sync'
|
||||
return 'Unknown'
|
||||
}
|
||||
|
||||
const formatTokens = (value: number): string => {
|
||||
if (value >= 1_000_000_000) {
|
||||
return `${(value / 1_000_000_000).toFixed(2)}B`
|
||||
@@ -768,7 +789,7 @@ const exportToCSV = async () => {
|
||||
log.api_key?.name || '',
|
||||
log.model,
|
||||
formatReasoningEffort(log.reasoning_effort),
|
||||
log.stream ? 'Stream' : 'Sync',
|
||||
getRequestTypeExportText(log),
|
||||
log.input_tokens,
|
||||
log.output_tokens,
|
||||
log.cache_read_tokens,
|
||||
|
||||
Reference in New Issue
Block a user