Files
crawler-plugin/admin-frontend-vue/src/pages/account/UserSecretsPage.vue
T

547 lines
24 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script setup lang="ts">
import BatchDeleteActions from '@/components/BatchDeleteActions.vue'
import BatchDeleteCheckbox from '@/components/BatchDeleteCheckbox.vue'
import { useRowSelection } from '@/utils/use-row-selection'
import { createLatestRequestGate } from '@/utils/latest-request'
import { computed, onMounted, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { formatDateTime } from '@/utils/datetime'
import OldPagination from '@/components/OldPagination.vue'
import ProxyEntryDialog from './ProxyEntryDialog.vue'
import {
checkUserSecret,
clearUserSecretModule,
deleteUserSecret,
fetchAdminSecretBalances,
fetchUserSecretList,
type AdminUserSecretBalanceItem,
type AdminUserSecretModule,
type AdminUserSecretRow,
type GroupOption,
} from '@/api/user-secrets'
import {
PROXY_MODULE_KEY,
llmBalanceLines,
llmSourceLabel,
moduleStatusBand,
proxyBalanceLine,
proxyDisplayText,
proxySourceLabel,
rowDetailLines,
rowStatusBand,
} from './user-secret-model.ts'
import { useAdminSessionStore } from '@/stores/admin-session'
import { useCompanyTabStore } from '@/stores/company-tab'
import { showAdminFeedback } from '@/components/admin-feedback-ui'
import { openAdminConfirm } from '@/components/admin-confirm'
import LoadFailureBar from '@/components/LoadFailureBar.vue'
const session = useAdminSessionStore()
const companyTab = useCompanyTabStore()
/** 仅超管需要分组维度:非超管数据由后端裁剪到本人分组,分组筛选/列一律不展示。 */
const isSuperAdmin = computed(() => session.isSuperAdmin)
const loading = ref(false)
const loadFailure = ref('')
const rows = ref<AdminUserSecretRow[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(15)
const keyword = ref('')
const statusFilter = ref('')
const groupFilter = ref<number | null>(null)
/** 分组下拉(超管=全部;主管=自己带的分组,由列表接口带回)。 */
const groupOptions = ref<GroupOption[]>([])
/** 正在检测的行 userId,用于按钮 loading 态。 */
const checkingId = ref<number | null>(null)
/** 正在解锁代理的行 userId,避免重复点击(代填在弹窗里自己管 busy)。 */
const proxyBusyId = ref<number | null>(null)
/** 代填/改代理弹窗的目标行(脱敏后没有原文可预填,只能重填账密)。 */
const proxyDialog = ref<{ userId: number; username: string; provider: string | null; locked: boolean } | null>(null)
/** 余额侧写(实时查上游、不落库):按 userId 存,列表接口本身不带这些数。 */
const balances = ref<Record<number, AdminUserSecretBalanceItem>>({})
const balanceLoading = ref(false)
/** 本轮「没取到」的原因(越权剔除/上游未应答/请求失败):进工具行悬停,不弹全局打扰。 */
const balanceNotice = ref('')
/** 服务端单次上限 20 个用户;超出会被当场拒,所以这里按批顺取(并发留给服务端那个线程池)。 */
const BALANCE_BATCH = 20
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))
const STATUS_OPTIONS = [
{ value: '', label: '全部状态' },
{ value: 'passed', label: '检测通过' },
{ value: 'failed', label: '检测失败' },
{ value: 'incomplete', label: '未配齐' },
// 后端的行级值仍是 error:这一档现在既可能是「问不出结论」,也可能是「通道还没释放、等一会再点」,
// 界面按码把后者补成「可重试」(见 user-secret-model.ts 的档位表),筛选项就得把两档都点名。
{ value: 'error', label: '无法判定/可重试' },
{ value: 'unknown', label: '未检测' },
]
/* 状态药丸的档位表在 `user-secret-model.ts`(唯一出处,页面不带第二张表):
行级传整行而不是 `row.status`——后端把 failed/incomplete 都判掉之后就只剩一个「error」,
这一行到底是「查不出」还是「等青果释放」只有逐格的 `check_code` 说得清。 */
/**
* 单格悬停详情:后端下发的**脱敏值** + 锁定说明 + **检测结果原文 `check_message`** + 检测时间 + 耗时。
* 运维要判「是欠费还是被自己的采集占着」,靠的就是这句后端原文——档名只是扫一眼用的短词,
* 前端一律不按码自己拼句子。
* ⚠ 只读 `masked`:`full` 在后台侧恒空(2026-11-02 `SecretMasking.maskProxy` 收口),
* 这里不做任何「masked 空就回落原文」的兜底,也不给复制整条链接的旁路。
*/
function moduleTooltip(module: AdminUserSecretModule | undefined) {
if (!module || !module.exists) return '未配置'
const parts: string[] = []
const display = String(module.masked || '').trim()
if (display) {
parts.push(isProxyModule(module) ? `代理地址(已脱敏,不含 key/pwd):${display}` : `密钥:${display}`)
}
if (module.locked) parts.push('已由后台代填并锁定:客户端不可修改或清空,改代理需重新填写账密')
// 后端的这句话就是给人看的结论,原样透出(不动一个字、不按码另拼一句)
const message = String(module.checkMessage || '').trim()
if (message) parts.push(message)
if (module.checkedAt) parts.push(`检测时间:${formatDateTime(module.checkedAt)}`)
if (module.checkLatencyMs != null) parts.push(`耗时:${module.checkLatencyMs}ms`)
return parts.join(';') || '暂无检测记录'
}
/** 该格是不是代理模块:按后端下发的 moduleKey 判,货源标签与文案都走这一条口径。 */
function isProxyModule(module: AdminUserSecretModule) {
return String(module.moduleKey || '').trim().toLowerCase() === PROXY_MODULE_KEY
}
/** 分组列文案:优先分组名;未建分组的用户回退展示所属主管,便于判断归属。 */
function groupTextOf(row: AdminUserSecretRow) {
if (row.groups?.length) return row.groups.join('、')
if (row.leaderUsername) return `${row.leaderUsername}(未建分组)`
return '—'
}
/**
* 行级悬停详情:后端的行级摘要 + 逐格的 `check_message` 原文 + 更新时间。
* 行级状态一旦补成「可重试」,管理员得能立刻看出是哪一格在等、后端原话怎么说;
* 逐格那句一律取后端下发文本(`rowDetailLines` 只搬运、不改写、不另拼一句)。
*/
function rowStatusTooltip(row: AdminUserSecretRow) {
const parts: string[] = []
if (row.statusMessage) parts.push(row.statusMessage)
parts.push(...rowDetailLines(row))
if (row.updatedAt) parts.push(`最近更新:${formatDateTime(row.updatedAt)}`)
return parts.join(';') || '暂无检测记录'
}
const batchListGate = createLatestRequestGate()
async function load() {
const token = batchListGate.begin()
loading.value = true
loadFailure.value = ''
try {
const result = await fetchUserSecretList({
keyword: keyword.value.trim() || undefined,
checkStatus: statusFilter.value || undefined,
groupId: groupFilter.value || undefined,
companyId: companyTab.requestCompanyId,
page: page.value,
pageSize: pageSize.value,
})
if (!batchListGate.isCurrent(token)) return
rows.value = result?.items || []
total.value = Number(result?.total || 0)
groupOptions.value = result?.groupOptions || []
void loadBalances()
} catch (error) {
if (!batchListGate.isCurrent(token)) return
loadFailure.value = error instanceof Error ? error.message : '加载失败'
showAdminFeedback(loadFailure.value, 'error')
} finally {
if (batchListGate.isCurrent(token)) loading.value = false
}
}
/**
* 取本页用户的余额:列表已经画完,这两列随后填(余额要实时打上游,不能让它在列表主数据前占位)。
*
* 失败只影响这两列并留一句说明——不 `showAdminFeedback`、不把整页判成加载失败:
* 一次上游抖动就红整页,管理员会以为密钥数据本身出了问题。
*/
async function loadBalances() {
const ids = rows.value.map((row) => row.userId)
balances.value = {}
balanceNotice.value = ''
if (!ids.length) return
balanceLoading.value = true
try {
const merged: Record<number, AdminUserSecretBalanceItem> = {}
let denied = 0
let timedOut = 0
for (let start = 0; start < ids.length; start += BALANCE_BATCH) {
const batch = ids.slice(start, start + BALANCE_BATCH)
const result = await fetchAdminSecretBalances(batch, companyTab.requestCompanyId)
for (const item of result?.items || []) {
if (item && item.userId != null) merged[Number(item.userId)] = item
}
denied += result?.deniedUserIds?.length || 0
timedOut += result?.timedOutUserIds?.length || 0
}
balances.value = merged
const notices: string[] = []
if (denied) notices.push(`${denied} 个用户不在当前数据权限内,本轮未查`)
if (timedOut) notices.push(`${timedOut} 个用户本轮上游未应答(不是余额为 0)`)
balanceNotice.value = notices.join(';')
} catch (error) {
balanceNotice.value = error instanceof Error ? error.message : '余额本轮没取到(不是余额为 0)'
} finally {
balanceLoading.value = false
}
}
/** 某行的 LLM 余额行(按渠道折叠);没取到时给一格占位而不是空白。 */
function llmLinesOf(userId: number) {
const lines = llmBalanceLines(balances.value[userId]?.llm, balanceLoading.value)
return lines.length ? lines : [{ text: '—', title: balanceNotice.value || '本轮没取到数(不是余额为 0)' }]
}
function proxyLineOf(userId: number) {
const item = balances.value[userId]
if (item?.proxy) return proxyBalanceLine(item.proxy, false)
return balanceLoading.value
? { text: '查询中…', title: '余额按实时查询,不落库' }
: { text: '—', title: balanceNotice.value || '本轮没取到数(不是余量为 0)' }
}
// 切公司 = 重新取数。不重取的页 = tab 在那页上是假的(G1 的 pageFiles 断言盯着这条)。
watch(() => companyTab.activeId, () => void load())
function search() {
page.value = 1
load()
}
function reset() {
keyword.value = ''
statusFilter.value = ''
groupFilter.value = null
page.value = 1
load()
}
/** 立即检测:真实请求该用户全部已配置项并把结果落库。 */
async function check(row: AdminUserSecretRow) {
checkingId.value = row.userId
try {
const results = await checkUserSecret(row.userId)
if (!results || !results.length) {
ElMessage.warning('该用户尚未配置任何密钥或代理')
} else {
const failed = results.filter((item) => item.checkStatus === 'failed')
const errors = results.filter((item) => item.checkStatus === 'error')
if (failed.length) {
ElMessage.warning(failed[0].checkMessage || '存在检测失败项')
} else if (errors.length) {
// 后端这句话会区分「通道被你自己占着,等约 3 分钟」与「真的问不出结论」;
// 硬写「无法判定」等于把可重试那一族又抹回一坨(现网 uid=1 就是这个形状)。
ElMessage.warning(errors[0].checkMessage || '部分配置本次无法判定')
} else {
ElMessage.success('检测通过')
}
}
load()
} catch (error) {
showAdminFeedback(error instanceof Error ? error.message : '检测失败', 'error')
} finally {
checkingId.value = null
}
}
const batch = useRowSelection({
pageRows: () => rows.value,
rowId: (row) => row.userId,
rowLabel: (row) => row.username || `UID ${row.userId}`,
deleteOne: (id) => deleteUserSecret(id),
refresh: load,
blocked: () => loading.value || !!loadFailure.value,
scope: () => companyTab.activeId,
consequence: '将清空这些用户的全部密钥与代理配置;后台锁定的代理也会一并清除并解锁,用户需要重新配置。',
verb: '清空',
})
async function remove(row: AdminUserSecretRow) {
if (batch.busy) return
const who = row.username || `UID ${row.userId}`
if (!(await openAdminConfirm({ message: `确定清空「${who}」的全部密钥与代理配置吗?后台锁定的代理会一并清除并解锁,该用户需要重新配置。`, danger: true }))) return
try {
await deleteUserSecret(row.userId)
batch.removeFromSelection(row.userId)
ElMessage.success('已清空')
load()
} catch (error) {
showAdminFeedback(error instanceof Error ? error.message : '清空失败', 'error')
}
}
/**
* 打开代填/改代理弹窗。
* ⚠ 不预填任何已有值:后台侧 `full` 恒空(代理链接里带着 key/pwd,2026-11-02 收口后不再下发),
* 所以这一单的语义就是「重新填账密」,界面上也没有把原文取回来的旁路。
*/
function openProxyDialog(row: AdminUserSecretRow) {
proxyDialog.value = {
userId: row.userId,
username: row.username || `UID ${row.userId}`,
provider: row.proxy?.channel ?? null,
locked: Boolean(row.proxy?.locked),
}
}
/** 弹窗保存成功:关掉并重新取数(列表只拿脱敏值,不参与拼装)。 */
function onProxySaved() {
proxyDialog.value = null
load()
}
/** 解锁代理:清空后台代填值,该用户恢复自行配置。 */
async function unlockProxy(row: AdminUserSecretRow) {
const who = row.username || `UID ${row.userId}`
if (!(await openAdminConfirm({ message: `确定解除「${who}」的代理锁定吗?解锁后当前后台代理值会被清空,客户端恢复自行配置。`, danger: true }))) return
proxyBusyId.value = row.userId
try {
await clearUserSecretModule(row.userId, PROXY_MODULE_KEY)
ElMessage.success('已解锁')
load()
} catch (error) {
showAdminFeedback(error instanceof Error ? error.message : '解锁失败', 'error')
} finally {
proxyBusyId.value = null
}
}
function changePage(next: number) {
if (next < 1 || next > totalPages.value) return
page.value = next
load()
}
function changeSize(size: number) {
pageSize.value = size
page.value = 1
load()
}
onMounted(load)
</script>
<template>
<div class="user-secrets-view">
<section class="panel-box">
<div class="secrets-head">
<h3>用户密钥列表</h3>
</div>
<div class="form-row secrets-filter-row">
<div class="form-group" style="min-width: 220px">
<label>用户名</label>
<input v-model="keyword" type="text" placeholder="模糊搜索用户名" @keyup.enter="search" />
</div>
<div class="form-group" style="min-width: 170px">
<label>状态(三项都通过才算通过)</label>
<!-- 2026-11-17 用户口径「和亚马逊不统一」:原生 select 的弹层是浏览器直角原生物
⇒ 换 el-select(admin-filter 同壳 42px/9px 圆角,弹层是 EP 圆角面板)。
「全部状态」仍是 STATUS_OPTIONS 里的空串档(下游 checkStatus 照旧传 ''→undefined);
model 为空串时 EP 走 placeholder 显示,故 placeholder 与首档同文案。 -->
<el-select v-model="statusFilter" class="admin-filter" placeholder="全部状态" aria-label="筛选密钥状态">
<el-option v-for="option in STATUS_OPTIONS" :key="option.value" :label="option.label" :value="option.value" />
</el-select>
</div>
<div class="form-group" v-if="isSuperAdmin && groupOptions.length" style="min-width: 170px">
<label>分组</label>
<!-- 同上(2026-11-17 换 el-select):分组可能很多 ⇒ 保留 filterable 可搜。
「全部分组」的值仍是 null(下游 groupId 照旧 `|| undefined`),空档时由
placeholder 显示同一句文案。 -->
<el-select v-model="groupFilter" class="admin-filter" filterable placeholder="全部分组" aria-label="筛选分组">
<el-option label="全部分组" :value="null" />
<el-option v-for="group in groupOptions" :key="group.id" :label="group.groupName" :value="group.id" />
</el-select>
</div>
<div class="form-group">
<label>&nbsp;</label>
<div class="filter-actions">
<button class="btn" type="button" @click="search">查询</button>
<button class="btn btn-ghost" type="button" @click="reset">重置</button>
<button
class="btn btn-ghost"
type="button"
:disabled="balanceLoading || !rows.length"
:title="balanceNotice || '余额是实时查上游、不落库;这两列没取到时显示 —,不是 0'"
@click="loadBalances"
>
{{ balanceLoading ? '余额查询中…' : '刷新余额' }}
</button>
</div>
</div>
</div>
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
<BatchDeleteActions :batch="batch" />
<div class="secrets-table-scroll">
<table>
<thead>
<tr>
<th class="batch-delete-cell" scope="col">
<BatchDeleteCheckbox label="全选当前页可删除记录" :checked="batch.pageAll" :partial="batch.pageSome"
:disabled="batch.disabled || batch.pageEmpty" @change="batch.togglePage" />
</th>
<th style="width: 58px">序号</th>
<th style="width: 260px">用户</th>
<th v-if="isSuperAdmin" style="width: 130px">分组</th>
<th style="width: 230px">货源查询密钥</th>
<th style="width: 230px">外观专利密钥</th>
<th style="width: 170px">LLM 余额</th>
<th style="width: 380px">代理设置</th>
<th style="width: 160px">代理余量</th>
<th style="width: 130px">状态</th>
<th style="width: 170px">创建时间</th>
<th style="width: 170px">更新时间</th>
<th style="width: 315px">操作</th>
</tr>
</thead>
<tbody>
<template v-if="rows.length">
<tr v-for="(row, index) in rows" :key="row.userId" :class="{ 'batch-selected': batch.isSelected(row) }">
<td class="batch-delete-cell">
<BatchDeleteCheckbox :label="batch.reason(row) || `选择 ${batch.label(row)}`" :checked="batch.isSelected(row)"
:disabled="batch.disabled || !!batch.reason(row)" @change="batch.toggle(row)" />
</td>
<td>{{ (page - 1) * pageSize + index + 1 }}</td>
<td>
<span class="user-name">{{ row.username || '—' }}</span>
</td>
<td v-if="isSuperAdmin">
<span class="creator-name">{{ groupTextOf(row) }}</span>
</td>
<td>
<div class="module-cell">
<span v-if="row.similarAsin?.exists" class="mono-mask" :title="moduleTooltip(row.similarAsin)">{{ row.similarAsin.masked }}</span>
<span v-else class="empty-value">未配置</span>
<span v-if="row.similarAsin?.exists" class="wh-pill is-source" title="该用户这把密钥所属渠道">
{{ llmSourceLabel(row.similarAsin.channel) }}
</span>
<span class="wh-pill" :class="moduleStatusBand(row.similarAsin).tone" :title="moduleTooltip(row.similarAsin)">
{{ moduleStatusBand(row.similarAsin).label }}
</span>
</div>
</td>
<td>
<div class="module-cell">
<span v-if="row.appearancePatent?.exists" class="mono-mask" :title="moduleTooltip(row.appearancePatent)">{{ row.appearancePatent.masked }}</span>
<span v-else class="empty-value">未配置</span>
<span v-if="row.appearancePatent?.exists" class="wh-pill is-source" title="该用户这把密钥所属渠道">
{{ llmSourceLabel(row.appearancePatent.channel) }}
</span>
<span class="wh-pill" :class="moduleStatusBand(row.appearancePatent).tone" :title="moduleTooltip(row.appearancePatent)">
{{ moduleStatusBand(row.appearancePatent).label }}
</span>
</div>
</td>
<td>
<div class="module-cell module-cell--stack">
<span
v-for="(line, lineIndex) in llmLinesOf(row.userId)"
:key="`llm-${lineIndex}`"
class="balance-line"
:title="line.title"
>{{ line.text }}</span>
</div>
</td>
<td>
<div class="module-cell module-cell--stack">
<span v-if="row.proxy?.exists" class="mono-mask" :title="moduleTooltip(row.proxy)">{{ proxyDisplayText(row.proxy) }}</span>
<span v-else class="empty-value">未配置</span>
<span class="module-cell-pills">
<span v-if="row.proxy?.exists" class="wh-pill is-source" title="该用户代理所属供应商">
{{ proxySourceLabel(row.proxy.channel) }}
</span>
<span class="wh-pill" :class="moduleStatusBand(row.proxy).tone" :title="moduleTooltip(row.proxy)">
{{ moduleStatusBand(row.proxy).label }}
</span>
<span
v-if="row.proxy?.locked"
class="wh-pill is-locked"
title="已由管理员代填并锁定:客户端不可修改或清空"
>
已锁定
</span>
</span>
</div>
</td>
<td>
<div class="module-cell module-cell--stack">
<span class="balance-line" :title="proxyLineOf(row.userId).title">
{{ proxyLineOf(row.userId).text }}
</span>
</div>
</td>
<td>
<span class="wh-pill" :class="rowStatusBand(row).tone" :title="rowStatusTooltip(row)">
{{ rowStatusBand(row).label }}
</span>
</td>
<td>{{ formatDateTime(row.createdAt) }}</td>
<td>{{ formatDateTime(row.updatedAt) }}</td>
<td class="ops-cell">
<button
class="btn btn-sm"
type="button"
:disabled="checkingId === row.userId"
@click="check(row)"
>
{{ checkingId === row.userId ? '检测中…' : '立即检测' }}
</button>
<button
class="btn btn-sm btn-ghost"
type="button"
@click="openProxyDialog(row)"
>
{{ row.proxy?.locked ? '改代理' : '代填代理' }}
</button>
<button
v-if="row.proxy?.locked"
class="btn btn-sm btn-ghost"
type="button"
:disabled="proxyBusyId === row.userId"
@click="unlockProxy(row)"
>
解锁
</button>
<button class="btn btn-sm btn-danger" type="button" :disabled="batch.busy" @click="remove(row)">清空</button>
</td>
</tr>
</template>
<tr v-else-if="loading">
<td :colspan="isSuperAdmin ? 13 : 12" class="empty-tip">加载中...</td>
</tr>
<tr v-else>
<td :colspan="isSuperAdmin ? 13 : 12" class="empty-tip">{{ keyword || statusFilter || groupFilter ? '暂无匹配记录' : '暂无用户密钥记录' }}</td>
</tr>
</tbody>
</table>
</div>
<OldPagination :total="total" :page="page" :page-size="pageSize" @change="changePage" @size-change="changeSize" />
</section>
<ProxyEntryDialog
:model-value="proxyDialog != null"
:user-id="proxyDialog?.userId ?? null"
:username="proxyDialog?.username ?? ''"
:provider="proxyDialog?.provider ?? null"
:locked="Boolean(proxyDialog?.locked)"
@update:model-value="(open: boolean) => { if (!open) proxyDialog = null }"
@saved="onProxySaved"
/>
</div>
</template>
<style scoped src="./UserSecretsPage.css"></style>