Compare commits

..

5 Commits

Author SHA1 Message Date
huangzd1997 cc22600a07 feat(后管): 密钥管理拆两列显示余额(LLM 人民币余额/代理余量),实时查不落库
按拍板:数据源=实时查上游不落库(⇒ 本窗零 Flyway、零 Schema);列形态=拆两列,不是一列两行——
两张货源字典本就互不相通(LLM 行为渠道 longtaitou/t8star,代理行为供应商 qingguo/jikip),合成一格
就是 11-02 那次"代理行贴出龙抬头"的串档形状重来一遍(铁律 25)。不加 v-if="isSuperAdmin":主管必须
能解释组员任务为什么挂欠费,鉴权维持 requireAdmin + DataReadScope。

- src/api/user-secrets.ts:fetchAdminSecretBalances(userIds, companyId?),POST /api/admin/user-secrets/balances,
  超时放宽到 30s(服务端整请求预算 10s,客户端必须比它长,否则拿到的是本地掐断而不是"上游未应答")。
- user-secret-model.ts:llmBalanceLines/proxyBalanceLine 纯函数——**两张字典各查各的**、跨域一律 —、
  未知渠道只出 — 不出钱;available=false 时把 message 挂进 title 而不是画成 0;同一账号两个模块归到
  同一个渠道名下只列一次钱。保持零 @/ 别名以便 node --test 直测。
- UserSecretsPage.vue:两个 <th>(LLM 余额 170px/代理余量 160px,放「更新时间」前),两个 <td> 首屏画 —/查询中,
  列表返回后异步填(不阻塞首屏);colspan 由 isSuperAdmin ? 10 : 9 改成 12 : 11(两处同改,892d88ed 的提交信息
  专门写过这句);表格 min-width 相应 +240px;「刷新余额」按钮按 BALANCE_BATCH=20 分批请求。
- 已核对 ops-cell-must-wrap.test.ts:它的 opsColDecl() 正则锚在表头文字「操作」上,新增 <th> 排在它之前不影响
  UserSecretsPage: 314 下限 ⇒ 那张表不改(实测绿)。
- mock-admin-server.mjs 补两列夹具(一条有数、一条全查不到)供 dev/e2e。

测试:tests/密钥余额列读数.test.ts 12 例(跨域不认、坏值不画 0)+
tests/mount/user-secret-balance-columns.mount.test.ts 9 例——按表头文字定位不靠列序数,并钉 <th> 数=<td> 数=
空行 colspan(超管与非超管两种形状各一遍),把"加列忘改 colspan"直接钉死。既有 status-band 挂载格的夹具 mock
补一个 fetchAdminSecretBalances 函数名(页面挂载即取余额,缺它整个模块 mock 会炸),不是判据改动。
刻意不新增 readSource 钉 ⇒ 不动 tests/baselines/source-pin-ledger.json。vue-tsc rc=0、node --test 1890 例、vitest 77 例。
2026-11-05 12:03:43 +08:00
huangzd1997 a10aa6bda3 feat(用户端): 密钥设置面板 LLM 两卡加人民币余额行,与代理余量同形
现状纠偏(写死免得下次重研):桌面壳加载的是 frontend-vue 的 Vue SPA(app_client/blueprints/main.py:52 供产物、
config.py:96 WEB_HOME_URL 直载),所谓"客户端密钥设置"不在 Python 里;而密钥明文只在后端(前端手里只有掩码),
所以余额必须由后端查、前端不自打上游——本面只消费 GET /api/user-secrets/llm-balance。

- 新建 SecretBalanceRow.vue:根元素就是 <div class="secret-meta">,保住既有挂载测试按 .secret-meta 取数的断言不破;
  LLM 卡插一行、代理卡那 8 行 div 换成同一组件 ⇒ 两卡同形自动达成。面板 763→789 行,在 800 报警线内,
  可读棘轮基线不用动(该文件本就未点名)。
- 新建 shared/utils/llm-balance-text.ts(零依赖纯函数,node --test 直测)+ shared/composables/useLlmBalance.ts
  (按 moduleKey 存 items、三态文案、available=false 原样透出后端 message)。不引任何汇率乘算:绊线
  tests/llm-balance-text.test.ts 里钉住源码不得出现 7.2/per_usd 类字样——换算只在上游 credits.per_usd 里。
- loadLlmBalance() 移出 if (props.showProxy):原形状下 LLM 卡永远空白。刷新时机=挂载、保存该模块后、清空后、
  「检测已存值」后;⚠ 刻意不在「检测输入框未保存值」后刷——checkMyApiSecret(moduleKey,value) 探的是没落库的那把
  key,而余额读服务端已存密钥,刷出来是上一把 key 的钱挂在新渠道名下=串档形状(同一格绊线盯着这条)。
- 不动 ProxyBalanceAlert.vue / utils/proxy-balance-alert.ts:没要求告警,引阈值就是自造口径。
- 复用 jikip 那套 VO 的 surplus/scope/low 语义不 borrow 给 LLM(铁律 25):types/modules/user-secret.ts 里
  新类型与 :48-59 的 jikip VO 并置但互不相通。

测试:tests/llm-balance-text.test.ts 10 例(含源码绊线:面板行数<800、useLlmBalance 无汇率乘算、检测输入值路径
不触发 loadLlmBalance)+ tests/mount/密钥面板余额显示.mount.test.ts 11 例(两 LLM 卡各有 .secret-meta;龙抬头行
含 ¥+「龙抬头」、贞贞行含「不提供余额查询」且不含 ¥;两卡夹具给不同数字并交叉断言不互串;代理余量文案未变);
endpoints.test.ts 金样加一行;两支既有挂载夹具补 fetchLlmBalanceSafely 默认值。
catch-silence 棘轮:useLlmBalance.ts 那一枚 catch 的**首条语句是界面可见出口**(清空该 moduleKey 的展示),
console.warn 留在其后——按"首条即 log 才算静默"的口径它不该入账,实测入账了就把 blocks 311→312 如实登记并写明
理由,不删那个 catch(删了就是把失败读成"没有这一项")。vue-tsc rc=0、node --test 1018 例、vitest 66 例。
2026-11-05 12:03:14 +08:00
huangzd1997 eeff73d322 fix(b82-01): 第二批——跟价面六处实体式终态写点同笔派生 failure_category(CREDENTIAL 族)
B82-01 那 9 条实锤里的 1 条 PRICE_TRACK「会话失效且重新登录失败」=CREDENTIAL 组:这句话由 Python 侧逐店
回报、在 PriceTrackTaskService 聚合进任务行的 error_message,而这一面走的是实体式写面(setErrorMessage +
updateById),上一批的 wrapper 配对判据扫不到它。⇒ 六处终态写点(markDispatchFailedRecords 无明细分支、
tryFinalizeTask 空明细分支、收尾判定的 RUNNING/SUCCESS/部分失败/全失败)每处 setErrorMessage 紧邻下一行
配对 setFailureCategory(TaskFailureLedger.categoryOf(task.getErrorMessage()))——判据形状是"下一行",跨行写法会漏判,
照现成先例的书写形状写。updateById 一边不动:这两面进来的都是 loadTaskForExecution 的全实体(selectById/缓存血统),
ALWAYS 策略会把列真落库,改成窄 wrapper 反而缩了写面。

护栏名单三→四面(ENTITY_FACE_FILES 加 PriceTrackTaskService.java)、写点下限 9→15(AP 4+相似ASIN 4+采集 1+跟价 6)。
反向验证:摘掉任一配对 ⇒ 该格 1 失败(实测)。没新增任何 .updateById( 调用,160 的总量棘轮不动。

AP DELIVERY 半边核明"早已接线":AppearancePatentResultJobSupport 四支 task.setErrorMessage 自 51401de2(2026-11-03,
已上线)就全配对,本批不动、也不虚构缺口。

现网只读探针把"列尚未被生产验证"归因到位(2026-11-05,本机 SSH 主机B 用容器 env 连 192.168.0.171:3306,凭据不出
服务器):全表非空仍 0(804 行)、近 7 天 FAILED 140 条全空;命中六组 markers 的 FAILED 近 7 天 82 条,但最新一条
updated_at=2026-11-01 23:14——早于接线 jar 上线(11-04 14:29)三天;接线后新增的 9 条 FAILED(8 条 AP「客户端回传
中断」=刻意排除在 DELIVERY 外那族、1 条跟价英文原文)按今天的判据本来就该是空列。⇒ 非空路径至今没有任何一笔
生产写入走过,本机只欠 MySQL 也无历史正样本可回放,本窗证不了;不得拿"列空=一致"当验证。第三批(风险/店铺匹配/
查ASIN/提现/巡删五面+ShopDataCrawl:3060/DeleteBrand:1839 的 DELIVERY 写面)已逐条登记 BACKLOG B82-01。
2026-11-05 12:02:49 +08:00
huangzd1997 609ad396a6 feat(用户密钥): 龙抬头余额按人民币口径上界面——credits 查询+用户端/后管两个读取面
上游事实(官方文档+2026-11-05 从主机B 直打实测):`GET /v1/skills/balance` 顶层 balance 是美元串("$12.345678"),
站内 ⚡=人民币口径在 credits 块(⚡ = 美元 × credits.per_usd)。要跟网页/账单对上必须取 credits,Java 里
不得出现任何汇率字面量。四条硬规则落在 LongtaitouBalanceClient:① 只认 credits.balance/available/frozen,
且 credits.unit 必须为 CREDIT、per_usd>0;② 顶层 $… 与 currency:USD 只作交叉校验(偏差 >0.5% 打 WARN),永不进展示;
③ credits 缺失/不可解析时不回落美元——把 12.34 当 ¥12.34 显示就是"美元当人民币"的假绿;④ 错误体
{error:{code,message,type}} 与 4xx/5xx 一律 available=false + message 原样透出,绝不抛、也不显示成 ¥0。
URL 由 LlmChannel.LONGTAITOU.host() 派生(配置键留空即用域名唯一正本),响应体限读 1MB。

不复用 UserApiSecretBalanceVo:那个类的 surplus/scope/low 语义全是 jikip 代理的,LLM 塞进去会让注释撒谎并
诱导下一个人在 useProxyBalance 里加分支(铁律 25「口径不得借」)。新建 UserLlmBalanceVo + 平行新建
UserLlmBalanceService(不扩 UserProxyBalanceService),缓存键 (userId,moduleKey) 5 分钟;渠道分档:t8star 不打
上游、available=false +「不提供余额查询」(贞贞有没有余额接口在册无判据,不许猜端点、更不许借龙抬头的数)。

后管走实时查、不落库(本窗零 Schema、零迁移):POST /api/admin/user-secrets/balances,requireAdmin +
DataReadScope 逐个剔除越权 userId(不信任前端给的列表)。三条护栏是这条路线不被点爆的唯一防线:单次 ≤20 行
(越限 BusinessException,不静默截断)、固定线程池 adminBalanceConcurrency=4 + 整请求 deadline 10s(到点的行
按「上游未在本轮时间预算内应答」降级并记进 timedOutUserIds 如实上报,不读成 0)、只对真能查的行打上游
(LLM 仅 longtaitou、代理仅 detectFromUrl==JIKIP;t8star/青果零 HTTP),一页 15 行通常只剩 3–8 次调用。
用户端 GET /api/user-secrets/llm-balance?moduleKey= 与既有 proxy-balance 同款 requireUser。

保存/清空密钥与后台代填/清空时代际失效两侧余额缓存:换一把钥匙还挂着上一把的钱就是串档。
配置三键同步 application.yml 与 application-local.example.yml(铁律 3)。

测试:LongtaitouBalanceClientTest 11(官方样例断言 balance=="88.888882"/surplus=="85.288882" 且 12.34/11.84/0.50/$
一律不出现;缺 credits、per_usd<=0、unit≠CREDIT、缺 available 四种坏形状各自 available=false + balance=null;
现网实测 401 missing_api_key / invalid_api_key 形状入夹具——钉的是测过的读数不是猜的错误体)、
UserLlmBalanceServiceTest 10(贞贞 never() 打上游、三态不伪装成 0、缓存命中不二次查询、两模块各回各值)、
UserSecretBalanceAdminServiceTest 7(越上限拒、越权剔、超时行 available=false 而非 0、只有可查行产生 HTTP)。
三支已登记进 ops scripts/score_ratchet.py 的 suites(不入册=闸门永远跑不到)。
catch 棘轮五枚新增全是 NOT_RETHROW(LOG_ONLY/EMPTY 一格没涨),逐处记名抬 STRICT_TOTAL 1065→1069、
notRethrow 604→608。未证事项按 BACKLOG B83-01 如实挂:真 sk- 下 credits 字段逐字核对、后管实时查的现网
并发表现、jikip find-balance 对用户自有套餐 key;本窗代码未随任何 jar 发版。
2026-11-05 12:02:33 +08:00
huangzd1997 b231a67dd7 fix(b82-01): 任务行部分字段落库改 update(null, wrapper),13 处部分实体 updateById 不再抹 failure_category
B82-01:failureCategory 标 FieldStrategy.ALWAYS(V186 让清错误分支的 null 真落库)的代价是任何 new 出来的部分实体走 updateById 都把该列无条件抹回 NULL。现网只读探针(2026-11-05,SSH 主机B)实证列全表零非空:近 7 天 194 条 FAILED 全空,9 条文案命中 CREDENTIAL/DELIVERY markers 的行列也是空。本笔只动调用点一边;注解半边由 TaskFailureCategoryMigrationV186Test 的 ALWAYS 钉守住。

写点转换(13 处 updateById,12 个条目,DedupeRunService 收尾一处两调用):convert/split/productrisk/queryasin/withdraw/similarasin/appearance-patent/pricetrack 显式两到四列;shopdatacrawl 快照+归属三列;deletebrand 终态分支 error_message 与分类同笔配对 TaskFailureLedger.categoryOf(护栏格1连线语义);dedupe FAILED 收尾同笔配对;similarasin 归属绑定(rustfs 回退)。Explore 初判 12 处漏了 withdraw/pricetrack 族——逐支验明全是 loadTaskForExecution 全实体(selectById/缓存血统),非抹列点,留痕不扩 scope;DELIVERY/CREDENTIAL 两族终态写点接 ledger 属后续批,不在本笔。

护栏 TaskFailureCategoryGuardrailTest 5→7:① ledger 对六组 markers 各出一条值非空断言(配对写恒 NULL 也绿那半堵上);② .updateById( 总量棘轮 173→160(本仓 ALWAYS 字段还有 PriceTrackLoopRun/ShopKey/SkipPriceAsin 四实体,棘轮按全量钉,新增写法必须登记复审)。测试适配:共享探针 UpdateWrapperProbe(getSqlSet 列序+MPGENVAL 精确取值+列名 snake 归一——单测 JVM 的 Lambda 列缓存可能被自动初始化成驼峰,不归一则快照取决于测试类执行顺序);4 份 golden 重钉 11 行(窄写面 status 不在写面渲染成 -);ShopDataCrawlOwnerColumnTest 假 DB 从只会 CAS 升级为按 SQL 语义应用 SET 段(whereEq 校验 id/status eq);SimilarAsinTaskServiceSubmitTest 归属断言改为录 SET 段断言零 owner_instance_id(touchJavaSideTaskActivity 本就合法走 update(null,wrapper),verify(never) 会误杀)。

门禁:受影响七支定向 50/0 失败/0 错误/3 skipped(既有 skip,零新增);mvn -o test 整量 5321/0 失败/0 错误/19 skipped BUILD SUCCESS(5:01,skip 数与在册基线逐字相同);后端无 lint/格式器如实跳过;未动 application.yml/路由/Flyway/env,门禁5不适用。
2026-11-05 01:34:00 +08:00
60 changed files with 3258 additions and 83 deletions
@@ -499,6 +499,32 @@ const server = createServer((req, res) => {
},
})
}
if (url === '/api/admin/user-secrets/balances') {
// 余额侧写夹具(POST):两把密钥同渠道 ⇒ 界面折叠成一行;代理给「你的套餐」形状
const llmCell = (moduleKey, moduleLabel, over = {}) => ({
moduleKey, moduleLabel,
channel: 'longtaitou', channelLabel: '龙抬头',
available: true, balance: '88.888882', availableBalance: '85.288882', frozen: '3.6',
unit: 'CREDIT', message: null, checkedAt: '2026-11-05T10:30:00', ...over,
})
return json(res, {
success: true,
data: {
items: [
{
userId: 1,
llm: [
llmCell('appearance-patent', '外观专利密钥'),
llmCell('similar-asin', '货源查询密钥'),
],
proxy: { available: true, surplus: '1234', balance: '56', scope: 'user', message: null },
},
],
deniedUserIds: [],
timedOutUserIds: [],
},
})
}
if (url === '/api/admin/shop-manage-groups') {
return json(res, { success: true, data: { items: [] } })
}
@@ -63,6 +63,53 @@ export interface GroupOption {
groupName: string
}
/**
* LLM 一格的余额(**人民币口径**,后端取龙抬头 `credits` 块)。
* 与 `AdminProxyBalanceCell` 是两套语义:这里的 `balance` 是钱、单位 CREDIT(=⚡=人民币),
* 代理那边的 `surplus` 是「次」。界面不得用一张函数渲染两域(同 `channel` 那张表的教训)。
*/
export interface AdminLlmBalanceCell {
moduleKey: string
moduleLabel: string
channel: string
channelLabel: string
available: boolean
/** 上游原样小数串(未取整);available=false 时为 null。 */
balance: string | null
availableBalance: string | null
frozen: string | null
/** 恒为 CREDIT;不是这个值就按「认不出口径」处理,不猜。 */
unit: string | null
message: string | null
checkedAt: string | null
}
/** 代理余量一格:jikip 套餐口径(`surplus`=IP 次数、`scope`=谁的池子)。青果为 scope=none。 */
export interface AdminProxyBalanceCell {
available: boolean
surplus: string | null
balance: string | null
/** user=该用户自己的套餐;platform=平台池子(不是这个用户的钱);none=查不了。 */
scope: string | null
message: string | null
low?: boolean
lowReason?: string | null
}
export interface AdminUserSecretBalanceItem {
userId: number
llm: AdminLlmBalanceCell[]
proxy: AdminProxyBalanceCell
}
export interface AdminUserSecretBalances {
items: AdminUserSecretBalanceItem[]
/** 被数据权限剔出、本次没查的用户(不静默少给数)。 */
deniedUserIds?: number[]
/** 超出整请求时间预算、这轮没取到数的用户。 */
timedOutUserIds?: number[]
}
export interface UserSecretQuery {
keyword?: string
checkStatus?: string
@@ -87,6 +134,23 @@ export async function fetchUserSecretList(params: UserSecretQuery): Promise<Admi
return unwrap<AdminUserSecretPage>(data)
}
/**
* 刷新本页用户的余额侧写:POST /api/admin/user-secrets/balances。
*
* 实时打上游、不落库,所以服务端带三条护栏(单次 ≤20 个用户、固定并发、整请求 10s 预算),
* 客户端的超时必须**长于**服务端预算,否则服务端还在取数、这边先报错,
* 界面就会把「查得慢」显示成「查不到」(与铁律 10「前端超时不得短于服务端预算」同形)。
*/
export async function fetchAdminSecretBalances(
userIds: number[],
companyId?: number | null,
): Promise<AdminUserSecretBalances> {
const body: Record<string, unknown> = { userIds }
if (companyId != null) body.company_id = companyId
const { data } = await http.post('/api/admin/user-secrets/balances', body, { timeout: 30_000 })
return unwrap<AdminUserSecretBalances>(data)
}
/** 立即检测该用户全部已配置项:POST /api/admin/user-secrets/{userId}/check
* 逐模块检测(每项最多「首查 + 传输层失败重试一次」,最坏约 31s/项),故放宽超时到 180s。 */
export async function checkUserSecret(userId: number) {
@@ -8,15 +8,19 @@ 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,
@@ -51,6 +55,14 @@ 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 = [
@@ -131,6 +143,7 @@ async function load() {
rows.value = result?.items || []
total.value = Number(result?.total || 0)
groupOptions.value = result?.groupOptions || []
void loadBalances()
} catch (error) {
loadFailure.value = error instanceof Error ? error.message : '加载失败'
showAdminFeedback(loadFailure.value, 'error')
@@ -139,6 +152,57 @@ async function load() {
}
}
/**
* 取本页用户的余额:列表已经画完,这两列随后填(余额要实时打上游,不能让它在列表主数据前占位)。
*
* 失败只影响这两列并留一句说明——不 `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())
@@ -276,6 +340,15 @@ onMounted(load)
<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>
@@ -290,7 +363,9 @@ onMounted(load)
<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>
@@ -331,6 +406,16 @@ onMounted(load)
</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>
@@ -352,6 +437,13 @@ onMounted(load)
</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 }}
@@ -389,10 +481,10 @@ onMounted(load)
</tr>
</template>
<tr v-else-if="loading">
<td :colspan="isSuperAdmin ? 10 : 9" class="empty-tip">加载中...</td>
<td :colspan="isSuperAdmin ? 12 : 11" class="empty-tip">加载中...</td>
</tr>
<tr v-else>
<td :colspan="isSuperAdmin ? 10 : 9" class="empty-tip">{{ keyword || statusFilter || groupFilter ? '暂无匹配记录' : '暂无用户密钥记录' }}</td>
<td :colspan="isSuperAdmin ? 12 : 11" class="empty-tip">{{ keyword || statusFilter || groupFilter ? '暂无匹配记录' : '暂无用户密钥记录' }}</td>
</tr>
</tbody>
</table>
@@ -616,6 +708,16 @@ h3 {
.empty-value {
color: #a7b4c1;
}
/* 余额列:数字按等宽数位对齐(两行叠着看差值才不用竖着对),超长进 title。 */
.balance-line {
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-variant-numeric: tabular-nums;
font-size: 12.5px;
color: #2f4256;
}
.ops-cell {
display: flex;
gap: 8px;
@@ -1,7 +1,7 @@
/**
* 密钥管理页的纯逻辑模型(货源标签 + 代理重填 + 检测结果档位)。
*
* 三条收口都在这个文件里,页模板只调这里导出的函数,不各写各的字典:
* 四条收口都在这个文件里,页模板只调这里导出的函数,不各写各的字典:
*
* 1. **货源标签按模块分字典**(2026-11-02 修):原先 `UserSecretsPage.vue` 里是一整张
* `sourceLabel()`,把 LLM 渠道(longtaitou/t8star)与代理供应商(qingguo/jikip)混在同一个
@@ -312,3 +312,152 @@ export function buildProxyEntryPayload(
}
return { value: String(draft.link || '').trim(), channel: 'jikip' }
}
/* ------------------------------------------------------------------ *
* 余额侧写(2026-11-05 B83):第四处收口,仍守「两张字典互不相通」那一条。
*
* LLM 那格的单位是**钱**(人民币=龙抬头站内 ⚡,后端只取 `credits` 块),
* 代理那格的 `surplus` 是**次数**、`scope` 说这份量属于谁的池子。
* 两者都叫「余额」,混用一张函数就会读出「极客 ¥34」这种既不像钱也不像次的数——
* 所以这里各写各的,跨域字段一个都不读,认不出来一律 `—`(同货源标签那条判据)。
* ------------------------------------------------------------------ */
/** 后端 credits 块登记的单位;不是这个值就说明口径换了,宁可不显示也不猜。 */
export const LLM_BALANCE_UNIT = 'CREDIT'
interface LlmBalanceLike {
moduleKey?: string | null
moduleLabel?: string | null
channel?: string | null
channelLabel?: string | null
available?: boolean | null
balance?: string | null
availableBalance?: string | null
frozen?: string | null
unit?: string | null
message?: string | null
checkedAt?: string | null
}
interface ProxyBalanceLike {
available?: boolean | null
surplus?: string | null
balance?: string | null
scope?: string | null
message?: string | null
}
/** 一行的显示内容:`text` 进格子,`title` 进悬停(整句原因与取数时刻都在那儿)。 */
export interface BalanceLine {
text: string
title: string
}
const BALANCE_PLACEHOLDER: BalanceLine = { text: UNKNOWN_SOURCE_LABEL, title: '本轮没取到数(不是余额为 0)' }
const BALANCE_PENDING: BalanceLine = { text: '查询中…', title: '余额按实时查询,不落库' }
/** 人民币读数:解析不出数字时原样回显,不返回 `¥0`(一格 0 会被读成「没钱了」)。 */
export function formatYuan(raw: string | null | undefined): string {
const text = String(raw ?? '').trim()
if (!text) return ''
const value = Number(text.replace(/,/g, ''))
if (!Number.isFinite(value)) return text
return `¥${value.toFixed(2)}`
}
function llmDetail(cell: LlmBalanceLike): string {
const parts: string[] = []
if (cell.moduleLabel) parts.push(String(cell.moduleLabel))
const total = formatYuan(cell.balance)
const usable = formatYuan(cell.availableBalance)
const frozen = formatYuan(cell.frozen)
if (total) parts.push(`总 ${total}`)
if (usable) parts.push(`可用 ${usable}`)
if (frozen) parts.push(`预冻结 ${frozen}`)
if (cell.checkedAt) parts.push(`取数于 ${String(cell.checkedAt).replace('T', ' ').slice(0, 16)}`)
const message = String(cell.message ?? '').trim()
if (message) parts.push(message)
return parts.join(';') || '暂无余额信息'
}
/**
* LLM 余额列:一把密钥一行,前缀是**渠道名**(钱挂在渠道账户上,不在模块上)。
*
* `pending=true` ⇒ 这一轮还在取数;取到但不合格(单位不是 CREDIT/available=false)
* 一律走占位与后端原文,不显示金额。
*/
export function llmBalanceLine(cell: LlmBalanceLike | null | undefined, pending = false): BalanceLine {
if (pending && !cell) return BALANCE_PENDING
if (!cell) return BALANCE_PLACEHOLDER
const label = known(LLM_CHANNEL_LABELS, cell.channel) ?? UNKNOWN_SOURCE_LABEL
// 渠道认不出(LLM 列被喂了供应商名这类跨域值)时整格给占位:宁可什么都不显示,
// 也不让一个不知道属于谁的数字或句子进界面(同货源标签那张表「跨域一律 —」的判据)
if (label === UNKNOWN_SOURCE_LABEL) {
return { text: UNKNOWN_SOURCE_LABEL, title: `${llmDetail(cell)}|渠道值认不出,未显示金额` }
}
if (!cell.available || String(cell.unit ?? '').trim().toUpperCase() !== LLM_BALANCE_UNIT) {
const message = String(cell.message ?? '').trim()
return { text: message ? `${label} 查不到` : `${label} ${UNKNOWN_SOURCE_LABEL}`, title: llmDetail(cell) }
}
const total = formatYuan(cell.balance)
if (!total) return { text: `${label} ${UNKNOWN_SOURCE_LABEL}`, title: llmDetail(cell) }
return { text: `${label} ${total}`, title: llmDetail(cell) }
}
/**
* LLM 余额列的整格内容:**按渠道折叠**,一个渠道一行。
*
* 钱挂在渠道账户上、不挂在模块上:两把密钥(外观专利/货源查询)都在龙抬头时,
* 上游回的是同一个余额——排两遍会读成「这个账户有两笔钱」。折叠后 title 里仍留每一把的原文,
* 运维要判「是哪把密钥的渠道」看得回来。
*/
export function llmBalanceLines(
cells: Array<LlmBalanceLike | null | undefined> | null | undefined,
pending = false,
): BalanceLine[] {
const list = (cells ?? []).filter((cell): cell is LlmBalanceLike => Boolean(cell))
if (!list.length) return pending ? [BALANCE_PENDING] : []
const grouped = new Map<string, BalanceLine>()
for (const cell of list) {
const key = normalizeKey(cell.channel) || 'unknown'
const line = llmBalanceLine(cell, pending)
const hit = grouped.get(key)
grouped.set(key, hit ? { text: hit.text, title: `${hit.title}|${line.title}` } : line)
}
return [...grouped.values()]
}
/** 代理池子的归属说法:platform 那份是**平台的钱**,绝不允许被读成这个用户的余量。 */
const PROXY_SCOPE_LABELS: Record<string, string> = {
user: '你的套餐',
platform: '平台池',
none: '查不了',
}
/**
* 代理余量列:极客给「剩余 IP 次数」(单位是次、不是钱);青果按 scope=none 说查不了。
* `scope` 认不出来时不硬认(回落「来源未标注」并保留原值进 title 供运维核)。
*/
export function proxyBalanceLine(cell: ProxyBalanceLike | null | undefined, pending = false): BalanceLine {
if (pending && !cell) return BALANCE_PENDING
if (!cell) return BALANCE_PLACEHOLDER
const scopeKey = normalizeKey(cell.scope)
const scopeLabel = Object.prototype.hasOwnProperty.call(PROXY_SCOPE_LABELS, scopeKey)
? PROXY_SCOPE_LABELS[scopeKey]
: '来源未标注'
const message = String(cell.message ?? '').trim()
const detailParts = [`${scopeLabel}`]
const surplus = String(cell.surplus ?? '').trim()
const amount = String(cell.balance ?? '').trim()
if (surplus) detailParts.push(`剩余 IP ${surplus}`)
if (amount) detailParts.push(`账户余额 ${amount}`)
if (message) detailParts.push(message)
const title = detailParts.join(';') || '暂无余量信息'
if (!cell.available) {
// 后端那句原文(「青果不提供余量查询…」「上游未在预算内应答…」)全在 title 里;
// 格子只说「查不了」——留 `—` 会被读成「这人没配代理」,那是另一件事。
return { text: message ? '查不了' : `${scopeLabel} ${UNKNOWN_SOURCE_LABEL}`, title }
}
// 次数就是次数:这里不套 ¥ 符号、不换算,读数带「次」把单位写在格子里
return { text: `${scopeLabel} ${surplus || UNKNOWN_SOURCE_LABEL} 次`, title }
}
@@ -0,0 +1,210 @@
/**
* 密钥管理列表页「余额两列」的界面侧判据(2026-11-05 B83)。
*
* 读数本身在 `user-secret-model.ts` 里被那颗纯函数尺子钉着;这一支管的是**接上去的形状**:
* ① 两列都在,且 `<th>` 数=每行 `<td>` 数=空态行的 colspan —— 加列忘改 colspan 是本仓常踩的残行,
* 历史上专门为此写过提交说明,所以这里把它钉成算术关系而不是逐个数字;
* ② 有数时 LLM 列给人民币、代理列给次数,两者不混;
* ③ 整轮没取到时两列都是 `—`,**不是 0**(一格 0 会被读成「这人欠费了」);
* ④ 非超管少一列「分组」时,上述三个数仍然彼此相等。
*
* 跑法:`npx vitest run tests/mount/user-secret-balance-columns.mount.test.ts`
*/
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { createPinia, setActivePinia, type Pinia } from 'pinia'
import UserSecretsPage from '@/pages/account/UserSecretsPage.vue'
import { useAdminSessionStore } from '@/stores/admin-session'
import { useCompanyTabStore } from '@/stores/company-tab'
const secretsApi = vi.hoisted(() => ({
fetchUserSecretList: vi.fn(),
fetchAdminSecretBalances: vi.fn(),
checkUserSecret: vi.fn(),
deleteUserSecret: vi.fn(),
saveUserSecretModule: vi.fn(),
clearUserSecretModule: vi.fn(),
}))
vi.mock('@/api/user-secrets', () => secretsApi)
function moduleCell(moduleKey: string, over: Record<string, unknown> = {}) {
return {
moduleKey, moduleLabel: moduleKey, channel: null,
masked: 'sk-f****9BgQ', full: '', exists: true, locked: false,
checkStatus: 'passed', checkCode: 'ok', checkMessage: '连通正常',
checkLatencyMs: 12, checkedAt: '2026-11-05T10:30:00', updatedAt: '2026-11-05T10:30:00',
...over,
}
}
function row(userId: number, over: Record<string, unknown> = {}) {
return {
userId,
username: `user${userId}`,
groups: [],
leaderUsername: '',
similarAsin: moduleCell('similar-asin', { moduleLabel: '货源查询密钥', channel: 'longtaitou' }),
appearancePatent: moduleCell('appearance-patent', { moduleLabel: '外观专利密钥', channel: 'longtaitou' }),
proxy: moduleCell('proxy', { moduleLabel: '代理设置', channel: 'jikip' }),
status: 'passed',
statusMessage: '三项均检测通过',
createdAt: '2026-11-01T09:00:00',
updatedAt: '2026-11-05T10:30:00',
...over,
}
}
function llmCells(userId: number) {
return [
{
moduleKey: 'appearance-patent', moduleLabel: '外观专利密钥',
channel: 'longtaitou', channelLabel: '龙抬头',
available: true, balance: '88.888882', availableBalance: '85.288882', frozen: '3.6',
unit: 'CREDIT', message: null, checkedAt: '2026-11-05T10:30:00',
},
{
moduleKey: 'similar-asin', moduleLabel: '货源查询密钥',
channel: 'longtaitou', channelLabel: '龙抬头',
available: true, balance: '88.888882', availableBalance: '85.288882', frozen: '3.6',
unit: 'CREDIT', message: null, checkedAt: '2026-11-05T10:30:00',
},
].map((cell) => (userId === 7 ? cell : { ...cell, balance: '12.5', availableBalance: '10', frozen: null }))
}
function indexByHeader(wrapper: VueWrapper<Element>, header: string) {
const headers = wrapper.findAll('thead th').map((th) => th.text().trim())
const index = headers.findIndex((label) => label.includes(header))
expect(index, `表头里找不到「${header}」`).toBeGreaterThanOrEqual(0)
return index
}
function cellText(wrapper: VueWrapper<Element>, header: string, rowIndex = 0): string {
const index = indexByHeader(wrapper, header)
return wrapper.findAll('tbody tr')[rowIndex].findAll('td')[index].text().trim()
}
function cellTitle(wrapper: VueWrapper<Element>, header: string, rowIndex = 0): string {
const index = indexByHeader(wrapper, header)
const cell = wrapper.findAll('tbody tr')[rowIndex].findAll('td')[index]
return cell.find('.balance-line').attributes('title') ?? ''
}
let pinia: Pinia
beforeEach(() => {
vi.clearAllMocks()
pinia = createPinia()
setActivePinia(pinia)
useAdminSessionStore().user = { id: 1, username: 'root', role: 'super_admin' }
useCompanyTabStore().setActiveId(1)
})
async function mountWith(rowValues: unknown[], balances?: unknown) {
secretsApi.fetchUserSecretList.mockResolvedValue({
items: rowValues, total: rowValues.length, page: 1, pageSize: 15, groupOptions: [],
})
secretsApi.fetchAdminSecretBalances.mockResolvedValue(
balances === undefined
? { items: rowValues.map((item: any) => ({ userId: item.userId, llm: llmCells(item.userId), proxy: { available: true, surplus: '1234', balance: '56', scope: 'user', message: null } })), deniedUserIds: [], timedOutUserIds: [] }
: balances,
)
const wrapper = mount(UserSecretsPage, { global: { plugins: [pinia] } })
await flushPromises()
await flushPromises()
return wrapper
}
describe('余额两列接在密钥管理列表上', () => {
it('表头数=行内格数=空态 colspan(加列忘改 colspan 直接红)', async () => {
const wrapper = await mountWith([row(7)])
const headerCount = wrapper.findAll('thead th').length
const cellCount = wrapper.findAll('tbody tr')[0].findAll('td').length
expect(cellCount, '每行的 td 数必须等于表头列数').toBe(headerCount)
expect(headerCount).toBe(12)
const emptyWrapper = await mountWith([])
const colspan = Number(emptyWrapper.find('tbody td').attributes('colspan'))
expect(colspan, '空态行的 colspan 必须跟着列数走').toBe(headerCount)
})
it('非超管少一列分组时,三个数仍然彼此相等', async () => {
useAdminSessionStore().user = { id: 2, username: 'leader', role: 'admin' }
const wrapper = await mountWith([row(7)])
const headerCount = wrapper.findAll('thead th').length
expect(headerCount).toBe(11)
expect(wrapper.findAll('tbody tr')[0].findAll('td').length).toBe(headerCount)
const emptyWrapper = await mountWith([])
expect(Number(emptyWrapper.find('tbody td').attributes('colspan'))).toBe(headerCount)
})
it('LLM 列给人民币读数,按渠道折成一行(同一个钱不排两遍)', async () => {
const wrapper = await mountWith([row(7)])
expect(cellText(wrapper, 'LLM 余额')).toBe('龙抬头 ¥88.89')
expect(cellTitle(wrapper, 'LLM 余额')).toContain('外观专利密钥')
expect(cellTitle(wrapper, 'LLM 余额')).toContain('货源查询密钥')
expect(cellTitle(wrapper, 'LLM 余额')).toContain('取数于 2026-11-05 10:30')
})
it('代理列给次数并说清是谁的池子,不套 ¥', async () => {
const wrapper = await mountWith([row(7)])
const text = cellText(wrapper, '代理余量')
expect(text).toContain('你的套餐')
expect(text).toContain('1234 次')
expect(text).not.toContain('¥')
})
it('两列各读各的:LLM 列里不出现次数、代理列里不出现金额', async () => {
const wrapper = await mountWith([row(7)])
expect(cellText(wrapper, 'LLM 余额')).not.toMatch(/\d+\s*次/)
expect(cellText(wrapper, '代理余量')).not.toContain('¥')
})
it('整轮没取到时两列都是 —,一格都不许是 0', async () => {
const wrapper = await mountWith([row(7)], { items: [], deniedUserIds: [7], timedOutUserIds: [] })
expect(cellText(wrapper, 'LLM 余额')).toBe('—')
expect(cellText(wrapper, '代理余量')).toBe('—')
expect(cellText(wrapper, 'LLM 余额')).not.toContain('0.00')
})
it('超预算的行说「本轮未应答」,不冒充欠费', async () => {
const wrapper = await mountWith([row(7)], {
items: [{ userId: 7, llm: [], proxy: { available: false, surplus: null, balance: null, scope: null, message: '上游未在本轮时间预算内应答,稍后重试;这不代表余量为 0' } }],
deniedUserIds: [],
timedOutUserIds: [7],
})
expect(cellText(wrapper, 'LLM 余额')).toBe('—')
expect(cellText(wrapper, '代理余量')).toBe('查不了')
expect(cellTitle(wrapper, '代理余量')).toContain('不代表余量为 0')
})
it('余额接口整个失败也不把整页判成加载失败', async () => {
secretsApi.fetchUserSecretList.mockResolvedValue({ items: [row(7)], total: 1, page: 1, pageSize: 15, groupOptions: [] })
secretsApi.fetchAdminSecretBalances.mockRejectedValue(new Error('上游 502'))
const wrapper = mount(UserSecretsPage, { global: { plugins: [pinia] } })
await flushPromises()
await flushPromises()
expect(wrapper.findAll('tbody tr')).toHaveLength(1)
expect(wrapper.find('.load-failure-bar').exists(), '列表主数据在,就不该把整页报成加载失败').toBe(false)
expect(cellText(wrapper, 'LLM 余额')).toBe('—')
})
it('点「刷新余额」重取一轮,不动列表请求', async () => {
const wrapper = await mountWith([row(7)])
const listCalls = secretsApi.fetchUserSecretList.mock.calls.length
await wrapper.findAll('.filter-actions button').at(-1)!.trigger('click')
await flushPromises()
expect(secretsApi.fetchAdminSecretBalances).toHaveBeenCalledTimes(2)
expect(secretsApi.fetchUserSecretList).toHaveBeenCalledTimes(listCalls)
})
})
@@ -25,6 +25,7 @@ import { useCompanyTabStore } from '@/stores/company-tab'
const secretsApi = vi.hoisted(() => ({
fetchUserSecretList: vi.fn(),
fetchAdminSecretBalances: vi.fn(),
checkUserSecret: vi.fn(),
deleteUserSecret: vi.fn(),
saveUserSecretModule: vi.fn(),
@@ -0,0 +1,140 @@
/**
* 密钥管理页「余额两列」的读数判据(2026-11-05 B83)。
*
* 靶子是口径与归属,不是排版:
* ① LLM 那格只认 `unit=CREDIT`(人民币=龙抬头 ⚡),认不出就一律 `—`,不猜、不给 0;
* ② 两把密钥同属一个渠道账户时**折成一行**(同一个钱排两遍会被读成两笔钱);
* ③ 代理那格的 `surplus` 是**次数**,读数带「次」不带 `¥`;`scope=platform` 必须说清是平台池,
* 不许被读成这个用户自己的量(铁律 25 的串档形状);
* ④ 查不到 ≠ 没钱:`available=false` 与「整格没取到」都得出可分辨的文字。
*
* 跑法:`cd crawler-plugin/admin-frontend-vue && npm test`
*/
import test from 'node:test'
import assert from 'node:assert/strict'
import {
formatYuan,
llmBalanceLine,
llmBalanceLines,
proxyBalanceLine,
} from '../src/pages/account/user-secret-model.ts'
function llmCell(over: Record<string, unknown> = {}) {
return {
moduleKey: 'appearance-patent',
moduleLabel: '外观专利密钥',
channel: 'longtaitou',
channelLabel: '龙抬头',
available: true,
balance: '88.888882',
availableBalance: '85.288882',
frozen: '3.6',
unit: 'CREDIT',
message: null,
checkedAt: '2026-11-05T10:30:00',
...over,
}
}
test('人民币读数保留两位且不提前取整', () => {
assert.equal(formatYuan('88.888882'), '¥88.89')
assert.equal(formatYuan('0'), '¥0.00')
assert.equal(formatYuan(''), '')
assert.equal(formatYuan(null), '')
// 认不出数字时原样回显,不套 ¥(套了就是宣称它是人民币)
assert.equal(formatYuan('$12.345678'), '$12.345678')
})
test('LLM 一行给渠道名与金额,悬停带模块原文与取数时刻', () => {
const line = llmBalanceLine(llmCell())
assert.equal(line.text, '龙抬头 ¥88.89')
assert.match(line.title, /外观专利密钥/)
assert.match(line.title, /可用 ¥85\.29/)
assert.match(line.title, /预冻结 ¥3\.60/)
assert.match(line.title, /取数于 2026-11-05 10:30/)
})
test('单位不是 CREDIT 时按认不出处理,一个金额都不给', () => {
const line = llmBalanceLine(llmCell({ unit: 'USD', message: '龙抬头没返回人民币口径的余额块' }))
assert.equal(line.text, '龙抬头 查不到')
assert.ok(!line.text.includes('¥'), `认不出口径不许显示金额:${line.text}`)
assert.match(line.title, /没返回人民币/)
})
test('available=false 说查不到,不显示 0', () => {
const line = llmBalanceLine(llmCell({
available: false, balance: null, availableBalance: null, frozen: null,
channel: 't8star', channelLabel: '贞贞', message: '贞贞渠道不提供余额查询',
}))
assert.equal(line.text, '贞贞 查不到')
assert.ok(!line.text.includes('0.00'), '查不到不许读成欠费')
})
test('两把密钥同渠道时折成一行,同一个钱不排两遍', () => {
const lines = llmBalanceLines([
llmCell(),
llmCell({ moduleKey: 'similar-asin', moduleLabel: '货源查询密钥' }),
])
assert.equal(lines.length, 1)
assert.equal(lines[0].text, '龙抬头 ¥88.89')
assert.match(lines[0].title, /外观专利密钥/)
assert.match(lines[0].title, /货源查询密钥/, '折叠后每一把的原文都要还在悬停里')
})
test('两把密钥分属两渠道时各出一行', () => {
const lines = llmBalanceLines([
llmCell(),
llmCell({
channel: 't8star', channelLabel: '贞贞', available: false,
balance: null, availableBalance: null, frozen: null, unit: null,
message: '贞贞渠道不提供余额查询',
}),
])
assert.deepEqual(lines.map((line) => line.text), ['龙抬头 ¥88.89', '贞贞 查不到'])
})
test('没取到数与查询中是两件事,都不许画成 0', () => {
assert.equal(llmBalanceLine(null).text, '—')
assert.match(llmBalanceLine(null).title, /不是余额为 0/)
assert.equal(llmBalanceLine(undefined, true).text, '查询中…')
assert.deepEqual(llmBalanceLines([], true).map((l) => l.text), ['查询中…'])
assert.deepEqual(llmBalanceLines([], false), [])
})
test('渠道认不出时整格占位,连金额都不给', () => {
const line = llmBalanceLine(llmCell({ channel: 'jikip', channelLabel: '极客' }))
assert.equal(line.text, '—')
assert.ok(!line.text.includes('¥'), '把供应商名贴到 LLM 列就是那处错标的形状')
assert.match(line.title, /渠道值认不出,未显示金额/)
})
test('代理余量给的是次数,带单位且不套 ¥', () => {
const line = proxyBalanceLine({ available: true, surplus: '1234', balance: '56', scope: 'user', message: null })
assert.equal(line.text, '你的套餐 1234 次')
assert.ok(!line.text.includes('¥'), `次数不是钱:${line.text}`)
assert.match(line.title, /剩余 IP 1234/)
assert.match(line.title, /账户余额 56/)
})
test('平台池必须自报是平台的钱,不许冒充这个用户的余量', () => {
const line = proxyBalanceLine({ available: true, surplus: '9', balance: '1', scope: 'platform', message: null })
assert.match(line.text, /^平台池/)
assert.match(line.title, /平台池/)
assert.ok(!line.text.includes('你的套餐'), '串档形状:平台池的量被写成用户自己的套餐')
})
test('青果那一档说查不了,句子用后端原文', () => {
const line = proxyBalanceLine({
available: false, surplus: null, balance: null, scope: 'none',
message: '青果不提供余量/余额查询(它的余额接口要控制台 Appid 与 Appkey 签名)',
})
assert.equal(line.text, '查不了')
assert.match(line.title, /查不了/)
assert.match(line.title, /青果不提供/)
})
test('scope 缺失时不硬认,标成来源未标注', () => {
const line = proxyBalanceLine({ available: true, surplus: '5', balance: null, scope: null, message: null })
assert.match(line.text, /^来源未标注/)
})
@@ -41,6 +41,19 @@ public class UserSecretProperties {
/** jikip 余量查询接口(客户端设置弹窗展示套餐 IP 余量 / 账户余额)。 */
private String jikipBalanceUrl = "https://api.jikip.com/find-balance";
/**
* 龙抬头余额查询接口(密钥设置与后台列表展示人民币余额)。
* <b>留空即按登记的渠道主机派生</b>({@code LlmChannel.LONGTAITOU.host() + /v1/skills/balance}),
* 所以这里出厂为空串而不是抄一份域名:域名有两个出处就会漂(10-30 那次「发布域名红线」同款教训)。
*/
private String longtaitouBalanceUrl = "";
/** 后台密钥列表刷新余额时的并发上限(再高就是拿后管页去压上游,限流会整页超时)。 */
private int adminBalanceConcurrency = 4;
/** 后台密钥列表刷新余额的整请求时间预算(毫秒);到点未回的行如实报「没应答」,不报 0。 */
private long adminBalanceDeadlineMillis = 10_000L;
/** jikip 白名单检测接口:?id=套餐id&ip=待检测IP,data=1 表示已在白名单。 */
private String jikipWhiteListCheckUrl = "https://api.jikip.com/whiteList-check";
@@ -1,6 +1,7 @@
package com.nanri.aiimage.modules.appearancepatent.service.support;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.task.FailedStatusRowFilter;
import com.nanri.aiimage.config.AppearancePatentProperties;
@@ -212,7 +213,11 @@ public final class AppearancePatentParsePipeline {
long payloadStoredAt = System.nanoTime();
task.setResultJson(payloadSupport.get().buildTaskResultJson(request.getAiPrompt(), request.getApiKey(), sourceFiles, parsedPayloadPointer));
task.setUpdatedAt(LocalDateTime.now());
fileTaskMapper.updateById(task);
// B82-01:显式 wrapper 只写载荷与心跳两列——updateById 会把 ALWAYS 的 failure_category 抹回 NULL
fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getId, task.getId())
.set(FileTaskEntity::getResultJson, task.getResultJson())
.set(FileTaskEntity::getUpdatedAt, task.getUpdatedAt()));
String sourceFilename = buildAggregateSourceFilenameLabel(sourceFiles);
// rowCount 记接受行数、success 留 NULL(本支建单不写占位值),这两列底座刻意不替它定
@@ -5,6 +5,7 @@ import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessException;
@@ -191,7 +192,14 @@ public class ConvertRunService {
task.setFailedFileCount(failedCount);
task.setResultJson(JSONUtil.toJsonStr(items));
task.setUpdatedAt(LocalDateTime.now());
fileTaskMapper.updateById(task);
// B82-01:显式 wrapper 只写计数/载荷/心跳四列——部分实体 updateById 会把 ALWAYS 的
// failure_category 抹回 NULL
fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getId, task.getId())
.set(FileTaskEntity::getSuccessFileCount, task.getSuccessFileCount())
.set(FileTaskEntity::getFailedFileCount, task.getFailedFileCount())
.set(FileTaskEntity::getResultJson, task.getResultJson())
.set(FileTaskEntity::getUpdatedAt, task.getUpdatedAt()));
ConvertRunVo vo = new ConvertRunVo();
vo.setTotal(request.getFiles().size());
@@ -404,7 +404,16 @@ public class DedupeRunService {
task.setErrorMessage(progress.getError());
task.setUpdatedAt(LocalDateTime.now());
task.setFinishedAt(LocalDateTime.now());
fileTaskMapper.updateById(task);
// B82-01:收尾用的还是建单那枚内存实体,updateById 会把 ALWAYS 的 failure_category
// 抹回 NULL(陈旧修复面刚写进的分类一并被抹)。显式 wrapper 只写本方法的四列,
// error_message 与分类同笔落库(护栏格 1 的连线语义)
fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getId, task.getId())
.set(FileTaskEntity::getStatus, task.getStatus())
.set(FileTaskEntity::getErrorMessage, task.getErrorMessage())
.set(FileTaskEntity::getFailureCategory, TaskFailureLedger.categoryOf(task.getErrorMessage()))
.set(FileTaskEntity::getUpdatedAt, task.getUpdatedAt())
.set(FileTaskEntity::getFinishedAt, task.getFinishedAt()));
} finally {
// 终态必须绕过节流立刻共享:客户端下一次轮询可能落到另一节点
runProgressMap.putNow(runId, snapshot(progress));
@@ -496,7 +505,15 @@ public class DedupeRunService {
task.setResultJson(JSONUtil.toJsonStr(result.getItems()));
task.setUpdatedAt(LocalDateTime.now());
task.setFinishedAt(LocalDateTime.now());
fileTaskMapper.updateById(task);
// B82-01:同收尾分支——显式 wrapper 只写本方法的六列,不带抹 failure_category
fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getId, task.getId())
.set(FileTaskEntity::getStatus, task.getStatus())
.set(FileTaskEntity::getSuccessFileCount, task.getSuccessFileCount())
.set(FileTaskEntity::getFailedFileCount, task.getFailedFileCount())
.set(FileTaskEntity::getResultJson, task.getResultJson())
.set(FileTaskEntity::getUpdatedAt, task.getUpdatedAt())
.set(FileTaskEntity::getFinishedAt, task.getFinishedAt()));
}
/**
@@ -4,6 +4,7 @@ import com.nanri.aiimage.common.text.UserMessages;
import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessException;
@@ -41,6 +42,7 @@ import com.nanri.aiimage.modules.task.service.TaskDistributedLockService;
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
import com.nanri.aiimage.modules.task.service.TaskFinalizeSupport;
import com.nanri.aiimage.modules.task.service.pipeline.AbstractFileTaskPipeline;
import com.nanri.aiimage.modules.task.service.support.TaskFailureLedger;
import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoShopMatchResultVo;
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopIndexService;
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopSwitchService;
@@ -282,12 +284,25 @@ public class DeleteBrandRunService extends AbstractFileTaskPipeline<DeleteBrandP
task.setResultJson(toCompactTaskResultJsonForDb(items));
task.setUpdatedAt(LocalDateTime.now());
task.setSourceFileCount(processableFileCount);
// B82-01:task 是建单内存实体,updateById 会把 ALWAYS 的 failure_category 抹回 NULL——
// 显式 wrapper 只写本方法要改的列;终态分支的 error_message 与分类同笔落库(护栏格 1 的连线语义)
LambdaUpdateWrapper<FileTaskEntity> persist = new LambdaUpdateWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getId, task.getId())
.set(FileTaskEntity::getSuccessFileCount, parsedSuccessCount)
.set(FileTaskEntity::getFailedFileCount, parsedFailedCount)
.set(FileTaskEntity::getResultJson, task.getResultJson())
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
.set(FileTaskEntity::getSourceFileCount, processableFileCount);
if (processableFileCount <= 0) {
task.setStatus("FAILED");
task.setErrorMessage(parsedFailedCount > 0 ? "全部文件解析或匹配失败" : null);
task.setFinishedAt(LocalDateTime.now());
persist.set(FileTaskEntity::getStatus, task.getStatus())
.set(FileTaskEntity::getErrorMessage, task.getErrorMessage())
.set(FileTaskEntity::getFailureCategory, TaskFailureLedger.categoryOf(task.getErrorMessage()))
.set(FileTaskEntity::getFinishedAt, task.getFinishedAt());
}
fileTaskMapper.updateById(task);
fileTaskMapper.update(null, persist);
if ("RUNNING".equals(task.getStatus())) {
deleteBrandTaskCacheService.saveTaskCache(task);
}
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.pricetrack.service;
import com.nanri.aiimage.common.task.TaskStatuses;
import com.nanri.aiimage.common.text.UserMessages;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessException;
@@ -36,6 +37,7 @@ import com.nanri.aiimage.modules.task.service.TaskDistributedLockService;
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
import com.nanri.aiimage.modules.task.service.TaskFinalizeSupport;
import com.nanri.aiimage.modules.task.service.TaskResultPayloadService;
import com.nanri.aiimage.modules.task.service.support.TaskFailureLedger;
import com.nanri.aiimage.modules.task.service.pipeline.AbstractShopPayloadTaskPipeline;
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopSwitchService;
import lombok.extern.slf4j.Slf4j;
@@ -412,6 +414,7 @@ public class PriceTrackTaskService extends AbstractShopPayloadTaskPipeline<Price
if (results.isEmpty()) {
task.setStatus("FAILED");
task.setErrorMessage(normalizedError);
task.setFailureCategory(TaskFailureLedger.categoryOf(task.getErrorMessage()));
task.setUpdatedAt(LocalDateTime.now());
task.setFinishedAt(LocalDateTime.now());
fileTaskMapper.updateById(task);
@@ -660,7 +663,12 @@ public class PriceTrackTaskService extends AbstractShopPayloadTaskPipeline<Price
} catch (Exception ex) {
throw new BusinessException("序列化任务数据失败");
}
fileTaskMapper.updateById(task);
// B82-01:显式 wrapper 只写快照两列——task 是建单内存实体,updateById 会把 ALWAYS 的
// failure_category 抹回 NULL
fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getId, task.getId())
.set(FileTaskEntity::getRequestJson, task.getRequestJson())
.set(FileTaskEntity::getResultJson, task.getResultJson()));
priceTrackTaskCacheService.saveTaskCache(task);
// TODO: Python 侧轮询 RUNNING 任务,pickup 后开始处理
@@ -757,6 +765,7 @@ public class PriceTrackTaskService extends AbstractShopPayloadTaskPipeline<Price
if (latest.isEmpty()) {
task.setStatus("FAILED");
task.setErrorMessage("task details missing, cannot finalize automatically");
task.setFailureCategory(TaskFailureLedger.categoryOf(task.getErrorMessage()));
task.setUpdatedAt(LocalDateTime.now());
task.setFinishedAt(LocalDateTime.now());
fileTaskMapper.updateById(task);
@@ -2247,10 +2256,12 @@ public class PriceTrackTaskService extends AbstractShopPayloadTaskPipeline<Price
if (!allDone) {
task.setStatus("RUNNING");
task.setErrorMessage(null);
task.setFailureCategory(TaskFailureLedger.categoryOf(task.getErrorMessage()));
task.setFinishedAt(null);
} else if (ok > 0 && fail == 0) {
task.setStatus("SUCCESS");
task.setErrorMessage(null);
task.setFailureCategory(TaskFailureLedger.categoryOf(task.getErrorMessage()));
task.setFinishedAt(LocalDateTime.now());
} else if (ok > 0) {
// 部分店铺失败也必须是 FAILED(2026-09-30 修:此前标 SUCCESS 只把原因挂在
@@ -2258,10 +2269,12 @@ public class PriceTrackTaskService extends AbstractShopPayloadTaskPipeline<Price
// 由上面的组装守卫确保已落地,标失败不影响下载)
task.setStatus("FAILED");
task.setErrorMessage(String.join("; ", allErrors));
task.setFailureCategory(TaskFailureLedger.categoryOf(task.getErrorMessage()));
task.setFinishedAt(LocalDateTime.now());
} else {
task.setStatus("FAILED");
task.setErrorMessage(allErrors.isEmpty() ? "全部店铺处理失败" : String.join("; ", allErrors));
task.setFailureCategory(TaskFailureLedger.categoryOf(task.getErrorMessage()));
task.setFinishedAt(LocalDateTime.now());
}
try {
@@ -1,6 +1,7 @@
package com.nanri.aiimage.modules.productrisk.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.security.AdminAuthSupport;
@@ -560,7 +561,12 @@ public class ProductRiskTaskService {
} catch (Exception ex) {
throw new BusinessException("序列化任务数据失败");
}
fileTaskMapper.updateById(task);
// B82-01:显式 wrapper 只写快照两列——task 是建单内存实体,updateById 会把 ALWAYS 的
// failure_category 抹回 NULL
fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getId, task.getId())
.set(FileTaskEntity::getRequestJson, task.getRequestJson())
.set(FileTaskEntity::getResultJson, task.getResultJson()));
ProductRiskCreateTaskVo vo = new ProductRiskCreateTaskVo();
vo.setTaskId(task.getId());
@@ -706,7 +706,11 @@ public class QueryAsinTaskService {
task.setRequestJson(objectMapper.writeValueAsString(requestItems));
task.setResultJson(objectMapper.writeValueAsString(snapshots));
syncSnapshotTables(task, snapshots);
fileTaskMapper.updateById(task);
// B82-01:显式 wrapper 只写快照两列——updateById 会把 ALWAYS 的 failure_category 抹回 NULL
fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getId, task.getId())
.set(FileTaskEntity::getRequestJson, task.getRequestJson())
.set(FileTaskEntity::getResultJson, task.getResultJson()));
} catch (Exception ex) {
throw new BusinessException("查询ASIN任务快照保存失败");
}
@@ -1361,7 +1361,12 @@ public class ShopDataCrawlTaskService extends AbstractFileTaskPipeline<ShopDataC
task.setRequestJson(objectMapper.writeValueAsString(requestSnapshot));
task.setOwnerInstanceId(currentInstanceId());
persistSnapshotJson(task, snapshots);
fileTaskMapper.updateById(task);
// B82-01:显式 wrapper 只写快照与归属三列——updateById 会把 ALWAYS 的 failure_category 抹回 NULL
fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getId, task.getId())
.set(FileTaskEntity::getRequestJson, task.getRequestJson())
.set(FileTaskEntity::getOwnerInstanceId, task.getOwnerInstanceId())
.set(FileTaskEntity::getResultJson, task.getResultJson()));
} catch (Exception ex) {
throw new BusinessException("店铺数据抓取任务快照保存失败");
}
@@ -482,7 +482,11 @@ public class SimilarAsinTaskService implements SimilarAsinPipelineHost {
long payloadStoredAt = System.nanoTime();
task.setResultJson(payloadSupport().buildTaskResultJson(request.getAiPrompt(), request.getApiKey(), request.getImgSwitch(), request.getCategorySwitch(), sourceFiles, parsedPayloadPointer));
task.setUpdatedAt(LocalDateTime.now());
fileTaskMapper.updateById(task);
// B82-01:显式 wrapper 只写载荷与心跳两列——updateById 会把 ALWAYS 的 failure_category 抹回 NULL
fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getId, task.getId())
.set(FileTaskEntity::getResultJson, task.getResultJson())
.set(FileTaskEntity::getUpdatedAt, task.getUpdatedAt()));
String sourceFilename = buildAggregateSourceFilenameLabel(sourceFiles);
FileResultEntity result = new FileResultEntity();
@@ -1,6 +1,7 @@
package com.nanri.aiimage.modules.similarasin.service.support;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
@@ -164,11 +165,12 @@ public class SimilarAsinTaskOwnershipSupport {
payload.put("ownerInstanceReason", "rustfs-fallback-local");
String updatedJson = objectMapper.writeValueAsString(payload);
task.setResultJson(updatedJson);
FileTaskEntity update = new FileTaskEntity();
update.setId(task.getId());
update.setResultJson(updatedJson);
update.setUpdatedAt(LocalDateTime.now());
if (fileTaskMapper.updateById(update) != 1) {
// B82-01:部分实体 updateById 会借 failure_category 的 ALWAYS 策略把已登记分类抹回
// NULL——显式 wrapper 只写本方法要改的两列
if (fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getId, task.getId())
.set(FileTaskEntity::getResultJson, updatedJson)
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())) != 1) {
throw new IllegalStateException("Task owner update affected no row");
}
log.warn("[similar-asin] task bound to current instance due to rustfs fallback taskId={} instanceId={} chunk={}",
@@ -5,6 +5,7 @@ import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.excel.ExcelStreamReader;
import com.nanri.aiimage.config.StorageProperties;
@@ -152,7 +153,14 @@ public class SplitRunService {
task.setFailedFileCount(failedCount);
task.setResultJson(JSONUtil.toJsonStr(items));
task.setUpdatedAt(LocalDateTime.now());
fileTaskMapper.updateById(task);
// B82-01:显式 wrapper 只写计数/载荷/心跳四列——部分实体 updateById 会把 ALWAYS 的
// failure_category 抹回 NULL
fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getId, task.getId())
.set(FileTaskEntity::getSuccessFileCount, task.getSuccessFileCount())
.set(FileTaskEntity::getFailedFileCount, task.getFailedFileCount())
.set(FileTaskEntity::getResultJson, task.getResultJson())
.set(FileTaskEntity::getUpdatedAt, task.getUpdatedAt()));
SplitRunVo vo = new SplitRunVo();
vo.setTotal(request.getFiles().size());
@@ -0,0 +1,244 @@
package com.nanri.aiimage.modules.usersecret.client;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.text.UserMessages;
import com.nanri.aiimage.config.HttpClientPool;
import com.nanri.aiimage.config.UserSecretProperties;
import com.nanri.aiimage.modules.usersecret.model.vo.UserLlmBalanceVo;
import com.nanri.aiimage.modules.usersecret.support.LlmChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClient;
import java.io.IOException;
import java.io.InputStream;
import java.time.Duration;
import java.time.LocalDateTime;
/**
* 龙抬头开放接口的余额客户端:{@code GET /v1/skills/balance}。
*
* <p><b>只认 {@code credits} 块</b>。上游同一份响应里给了两套口径:顶层
* {@code balance / frozen / available_balance} 是<b>美元</b>串(形如 {@code "$12.345678"},
* 带 {@code $} 前缀、6 位小数),{@code credits} 才是站内展示的 ⚡=<b>人民币</b>口径
* (⚡=美元 × {@code credits.per_usd})。要跟用户看到的网页/账单对上必须用 {@code credits};
* 而 {@code credits} 缺失时<b>不许</b>退回顶层美元串——把 {@code $12.34} 显示成 {@code ¥12.34}
* 是「数字看着正常、含义是错的」那一类错,比一句「查不到」难发现得多。</p>
*
* <p>因此这里<b>不做任何汇率换算</b>(代码里出现汇率字面量就等于自己造了一套口径),
* 也只把 {@code credits} 的值放进 VO——美元数字根本不进返回体,前端拿不到,也就没法误用。</p>
*
* <p>失败一律降级成 {@code available=false} 并原样带上原因,绝不抛出中断调用方(与
* {@link JikipProxyClient} 同形)。</p>
*/
@Component
@Slf4j
public class LongtaitouBalanceClient {
private static final int BALANCE_READ_TIMEOUT_MILLIS = 8_000;
private static final int MAX_RESPONSE_BYTES = 1 << 20;
private static final String BALANCE_PATH = "/v1/skills/balance";
/** {@code credits.unit} 的登记值;不是这个值说明上游改了口径而我们还没跟着改,宁可不显示。 */
static final String CREDIT_UNIT = "CREDIT";
/** 交叉校验容差:⚡ 与 美元×per_usd 的相对偏差超过它只记日志,仍按 credits 展示。 */
private static final double CROSS_CHECK_TOLERANCE = 0.005;
private final UserSecretProperties properties;
private final ObjectMapper objectMapper;
private volatile RestClient sharedClient;
public LongtaitouBalanceClient(UserSecretProperties properties, ObjectMapper objectMapper) {
this.properties = properties;
this.objectMapper = objectMapper;
}
/** 余额查询地址:配置项优先,留空时按渠道登记的 host 派生(不在这里写死域名)。 */
String balanceUrl() {
String configured = normalize(properties.getLongtaitouBalanceUrl());
return configured.isEmpty() ? LlmChannel.LONGTAITOU.host() + BALANCE_PATH : configured;
}
/**
* 查一次余额。{@code plainApiKey} 是服务端已存的明文密钥(前端手里没有明文,只能由服务端查)。
* 上游约 5 秒缓存同一把密钥的余额,所以重复查询不额外付费。
*/
public UserLlmBalanceVo fetch(String plainApiKey) {
UserLlmBalanceVo vo = new UserLlmBalanceVo();
vo.setChannel(LlmChannel.LONGTAITOU.key());
vo.setChannelLabel(LlmChannel.LONGTAITOU.label());
String key = stripBearer(plainApiKey);
if (key.isEmpty()) {
vo.setAvailable(false);
vo.setMessage("未配置龙抬头密钥");
return vo;
}
try {
StatusAndBody response = restClient().get()
.uri(balanceUrl())
.headers(headers -> headers.setBearerAuth(key))
.exchange((request, res) -> new StatusAndBody(
res.getStatusCode().value(),
readBodyBounded(res.getBody())));
return parseResponse(vo, response.statusCode(), response.body());
} catch (Exception ex) {
log.warn("[user-secret][llm-balance] 龙抬头余额查询异常 err={}", ex.getMessage());
vo.setAvailable(false);
vo.setMessage(UserMessages.with("余额查询失败", ex));
return vo;
}
}
/** 把一次应答换成可展示的余额(与网络分离,判据可以不打上游直接钉解析形状)。 */
UserLlmBalanceVo parseResponse(UserLlmBalanceVo vo, int statusCode, String body) {
JsonNode root = parseJson(body);
if (statusCode < 200 || statusCode >= 300) {
vo.setAvailable(false);
vo.setMessage(upstreamMessage(root, statusCode));
log.warn("[user-secret][llm-balance] 龙抬头余额查询被拒 httpStatus={}", statusCode);
return vo;
}
if (root == null) {
vo.setAvailable(false);
vo.setMessage("龙抬头余额接口返回的不是可解析的 JSON");
return vo;
}
return applyCredits(vo, root);
}
/**
* 从 {@code credits} 块取人民币口径;拿不到就是拿不到,<b>不回落美元</b>。
*
* <p>容许 {@code credits.frozen} 缺失(进行中任务没有预冻结时上游可能省略),但
* {@code balance} 与 {@code available} 缺任一都不算成功——只有一半的余额数字更容易被读成「另一部分是 0」。</p>
*/
private UserLlmBalanceVo applyCredits(UserLlmBalanceVo vo, JsonNode root) {
JsonNode credits = root.path("credits");
String unit = text(credits.get("unit"));
double perUsd = credits.path("per_usd").asDouble(Double.NaN);
String total = decimalText(credits.get("balance"));
String available = decimalText(credits.get("available"));
if (!credits.isObject() || !CREDIT_UNIT.equalsIgnoreCase(nullToEmpty(unit))
|| !(perUsd > 0) || total == null || available == null) {
vo.setAvailable(false);
vo.setMessage("龙抬头没有返回人民币(⚡)口径的余额块,为避免把美元数字当人民币显示,这里不给金额");
log.warn("[user-secret][llm-balance] credits 块不合格 unit={} perUsd={} 是否含 balance={}",
unit, perUsd, total != null);
return vo;
}
vo.setBalance(total);
vo.setAvailableBalance(available);
vo.setFrozen(decimalText(credits.get("frozen")));
vo.setUnit(CREDIT_UNIT);
vo.setAvailable(true);
vo.setCheckedAt(LocalDateTime.now());
crossCheck(root, total, perUsd);
return vo;
}
/** 美元 × per_usd 与 credits.balance 背离时只记账,不改展示口径(credits 才是账单上那个数)。 */
private void crossCheck(JsonNode root, String creditsBalance, double perUsd) {
Double usd = parseUsd(text(root.get("balance")));
if (usd == null) {
return;
}
double expected = usd * perUsd;
double actual = Double.parseDouble(creditsBalance);
if (expected <= 0 || actual <= 0) {
return;
}
double deviation = Math.abs(expected - actual) / Math.max(expected, actual);
if (deviation > CROSS_CHECK_TOLERANCE) {
log.warn("[user-secret][llm-balance] 上游两套口径背离(美元×per_usd 与 credits 不一致,比例 {}),"
+ "仍按 credits 展示", String.format("%.4f", deviation));
}
}
/** 顶层美元串形如 {@code "$12.345678"}:去掉 {@code $} 前缀后取数,仅用于交叉校验。 */
private static Double parseUsd(String raw) {
String text = nullToEmpty(raw).replace("$", "").replace(",", "").trim();
if (text.isEmpty()) {
return null;
}
try {
return Double.parseDouble(text);
} catch (NumberFormatException ex) {
return null;
}
}
/** 上游错误体 {@code {error:{code,message,type,class}}}:优先给它的人话,否则给状态码。 */
private String upstreamMessage(JsonNode root, int statusCode) {
if (root != null) {
JsonNode error = root.path("error");
String message = text(error.get("message"));
if (message != null && !message.isBlank()) {
String code = text(error.get("code"));
return code == null || code.isBlank() ? message : message + "(" + code + ")";
}
}
return "龙抬头余额接口返回 HTTP " + statusCode + ",请稍后重试";
}
/** 数字节点保持上游原样文本({@code 88.888882} 不许先四舍五入——账单对不上时无从回溯)。 */
private static String decimalText(JsonNode node) {
if (node == null || node.isNull() || node.isMissingNode()) {
return null;
}
if (node.isNumber() || node.isTextual()) {
String text = node.asText().trim();
return text.isEmpty() ? null : text;
}
return null;
}
private RestClient restClient() {
RestClient client = sharedClient;
if (client != null) {
return client;
}
synchronized (this) {
if (sharedClient == null) {
sharedClient = RestClient.builder()
.requestFactory(HttpClientPool.requestFactory(BALANCE_READ_TIMEOUT_MILLIS))
.build();
}
return sharedClient;
}
}
/** 探测响应体的读取界:JDK 的 readTimeout 只封顶到响应头,断流时这一读会永久 park。 */
private String readBodyBounded(InputStream inputStream) throws IOException {
return HttpClientPool.readBodyBounded(inputStream,
Duration.ofMillis(BALANCE_READ_TIMEOUT_MILLIS), MAX_RESPONSE_BYTES);
}
private JsonNode parseJson(String body) {
try {
return body == null || body.isBlank() ? null : objectMapper.readTree(body);
} catch (Exception ex) {
return null;
}
}
private static String stripBearer(String token) {
String normalized = normalize(token);
return normalized.regionMatches(true, 0, "Bearer ", 0, 7) ? normalized.substring(7).trim() : normalized;
}
private static String text(JsonNode node) {
return node == null || node.isNull() || node.isMissingNode() ? null : node.asText();
}
private static String nullToEmpty(String value) {
return value == null ? "" : value.trim();
}
private static String normalize(String value) {
return value == null ? "" : value.trim();
}
private record StatusAndBody(int statusCode, String body) {
}
}
@@ -7,12 +7,15 @@ import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.common.service.ReadScope;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.modules.usersecret.model.dto.AdminUserSecretBalanceQuery;
import com.nanri.aiimage.modules.usersecret.model.dto.AdminUserSecretQuery;
import com.nanri.aiimage.modules.usersecret.model.dto.UserApiSecretSaveRequest;
import com.nanri.aiimage.modules.usersecret.model.vo.AdminUserSecretBalancesVo;
import com.nanri.aiimage.modules.usersecret.model.vo.AdminUserSecretModuleVo;
import com.nanri.aiimage.modules.usersecret.model.vo.AdminUserSecretPageVo;
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretCheckResultVo;
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
import com.nanri.aiimage.modules.usersecret.service.UserSecretBalanceAdminService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
@@ -45,6 +48,7 @@ public class AdminUserApiSecretController {
private final UserApiSecretService userApiSecretService;
private final UserSecretProperties userSecretProperties;
private final UserSecretBalanceAdminService userSecretBalanceAdminService;
private final AdminAuthSupport adminAuthSupport;
private final DataReadScope dataReadScope;
@@ -79,6 +83,18 @@ public class AdminUserApiSecretController {
return ApiResponse.success("检测完成", userApiSecretService.adminCheckByUser(userId));
}
@PostMapping("/balances")
@Operation(summary = "刷新本页用户的余额侧写",
description = "实时打上游(龙抬头人民币余额=credits 块;极客代理余量=find-balance),**不落库**。"
+ "单次最多 20 个用户、固定并发与整请求时间预算;到点没回的行如实报「上游未应答」,不报 0。"
+ "请求里的 userId 不是安全边界:一律按数据权限收窄,被剔的 id 在 deniedUserIds 里回传。")
public ApiResponse<AdminUserSecretBalancesVo> balances(
HttpServletRequest request,
@RequestBody AdminUserSecretBalanceQuery body) {
AdminUserEntity operator = adminAuthSupport.requireAdmin(request);
return ApiResponse.success(userSecretBalanceAdminService.balances(operator, body));
}
@DeleteMapping("/{userId}")
@Operation(summary = "清空该用户全部密钥与代理配置")
public ApiResponse<Integer> clear(
@@ -98,8 +114,10 @@ public class AdminUserApiSecretController {
@Parameter(description = "密钥模块 key", required = true) @PathVariable String moduleKey,
@Valid @RequestBody UserApiSecretSaveRequest body) {
AdminUserEntity operator = adminAuthSupport.requireAdmin(request);
return ApiResponse.success("已代填并锁定",
userApiSecretService.adminSaveModule(operator, userId, moduleKey, body.getValue(), body.getChannel()));
AdminUserSecretModuleVo vo = userApiSecretService.adminSaveModule(
operator, userId, moduleKey, body.getValue(), body.getChannel());
userSecretBalanceAdminService.invalidate(userId);
return ApiResponse.success("已代填并锁定", vo);
}
@DeleteMapping("/{userId}/modules/{moduleKey}")
@@ -15,8 +15,10 @@ import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretBundleVo;
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretCheckResultVo;
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretItemVo;
import com.nanri.aiimage.modules.usersecret.model.vo.UserClientIpVo;
import com.nanri.aiimage.modules.usersecret.model.vo.UserLlmBalanceVo;
import com.nanri.aiimage.modules.usersecret.model.vo.UserProxyPlanVo;
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
import com.nanri.aiimage.modules.usersecret.service.UserLlmBalanceService;
import com.nanri.aiimage.modules.usersecret.service.UserProxyBalanceService;
import com.nanri.aiimage.modules.usersecret.service.UserProxyPlanService;
import com.nanri.aiimage.modules.usersecret.service.UserProxyWhitelistService;
@@ -34,8 +36,10 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
@@ -51,6 +55,7 @@ public class UserApiSecretController {
private final UserApiSecretService userApiSecretService;
private final UserProxyPlanService userProxyPlanService;
private final UserProxyBalanceService userProxyBalanceService;
private final UserLlmBalanceService userLlmBalanceService;
private final UserProxyWhitelistService userProxyWhitelistService;
private final AdminAuthSupport adminAuthSupport;
@@ -69,7 +74,11 @@ public class UserApiSecretController {
@Parameter(description = "密钥模块 key", required = true) @PathVariable String moduleKey,
@Valid @RequestBody UserApiSecretSaveRequest body) {
Long userId = currentUserId(request);
return ApiResponse.success("保存成功", userApiSecretService.save(userId, moduleKey, body.getValue(), body.getChannel()));
UserApiSecretItemVo vo = userApiSecretService.save(userId, moduleKey, body.getValue(), body.getChannel());
// 换钥匙必须先把旧钥匙的余额丢掉:否则面板会把上一把 key 的钱挂在新 key/新渠道名下(串档形状)
userLlmBalanceService.invalidate(userId);
userProxyBalanceService.invalidate(userId);
return ApiResponse.success("保存成功", vo);
}
@DeleteMapping("/{moduleKey}")
@@ -79,6 +88,8 @@ public class UserApiSecretController {
@Parameter(description = "密钥模块 key", required = true) @PathVariable String moduleKey) {
Long userId = currentUserId(request);
userApiSecretService.clear(userId, moduleKey);
userLlmBalanceService.invalidate(userId);
userProxyBalanceService.invalidate(userId);
return ApiResponse.success("已清空", null);
}
@@ -113,6 +124,22 @@ public class UserApiSecretController {
return ApiResponse.success(userProxyBalanceService.balance(userId));
}
@GetMapping("/llm-balance")
@Operation(summary = "查询 LLM 渠道余额(人民币口径)",
description = "龙抬头 /v1/skills/balance 的 credits 块(站内 ⚡=人民币);"
+ "moduleKey 为空时一次回齐两张 LLM 密钥卡。贞贞渠道不提供余额查询,如实回「查不了」,"
+ "不借别家的数、也不显示成 0。")
public ApiResponse<List<UserLlmBalanceVo>> llmBalance(
HttpServletRequest request,
@Parameter(description = "密钥模块 key;留空=两张 LLM 卡都要")
@RequestParam(required = false) String moduleKey) {
Long userId = currentUserId(request);
if (moduleKey == null || moduleKey.isBlank()) {
return ApiResponse.success(userLlmBalanceService.bundle(userId));
}
return ApiResponse.success(List.of(userLlmBalanceService.balance(userId, moduleKey)));
}
@GetMapping("/proxy-plan")
@Operation(summary = "读取当前用户的 jikip 套餐配置")
public ApiResponse<UserProxyPlanVo> proxyPlan(HttpServletRequest request) {
@@ -0,0 +1,23 @@
package com.nanri.aiimage.modules.usersecret.model.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.List;
/**
* 后台密钥管理列表的余额刷新请求:只带本页可见的用户 ID,不接受「全部用户」。
*/
@Data
@Schema(description = "后台余额刷新请求")
public class AdminUserSecretBalanceQuery {
@Schema(description = "要刷新余额的用户 ID(本页行;单次上限见服务端校验)")
private List<Long> userIds;
/** 公司 tab 走 snake_case,与这一页的请求侧既有写法同形({@code company_id} 被尺子钉着)。 */
@JsonProperty("company_id")
@Schema(description = "公司 tab(只收窄、不放大;非超管一律按会话裁剪)")
private Long companyId;
}
@@ -0,0 +1,41 @@
package com.nanri.aiimage.modules.usersecret.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.List;
/**
* 后台密钥管理列表的余额侧写:与列表行**分开发**(列表本身零额外 SQL、零上游调用)。
*
* <p>这里的数是**取数时刻的快照**({@code UserLlmBalanceVo.checkedAt} 带在每格里),不是库里的列:
* 后台不落余额快照,是为了不在每行加一次跨用户循环写、也不让界面读到几小时前的陈值。</p>
*/
@Data
@Schema(description = "后台密钥管理-按用户回传的余额")
public class AdminUserSecretBalancesVo {
@Schema(description = "逐用户的余额(顺序不保证与请求一致,前端按 userId 对号)")
private List<Item> items;
@Schema(description = "被数据权限剔出、本次没有查的用户 ID(不静默少给数)")
private List<Long> deniedUserIds;
@Schema(description = "因超出整请求时间预算而没有取到数的用户 ID")
private List<Long> timedOutUserIds;
/** 一行的余额:两把 LLM 卡各有各的钱,代理余量另算一档。 */
@Data
@Schema(description = "单用户余额侧写")
public static class Item {
@Schema(description = "用户 ID")
private Long userId;
@Schema(description = "LLM 余额(外观专利/货源查询各一条,人民币口径)")
private List<UserLlmBalanceVo> llm;
@Schema(description = "代理余量(jikip 套餐口径;青果为 scope=none,平台池为 scope=platform)")
private UserApiSecretBalanceVo proxy;
}
}
@@ -0,0 +1,53 @@
package com.nanri.aiimage.modules.usersecret.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.time.LocalDateTime;
/**
* LLM 渠道余额(龙抬头)。
*
* <p>刻意与 {@link UserApiSecretBalanceVo} 分开:那一个的 {@code surplus / scope / low} 全是
* jikip 代理套餐的语义({@code surplus}=套餐剩余 IP <b>次数</b>、{@code scope}=user/platform),
* 把 LLM 的人民币余额塞进去,等于让同一个字段名在两处表示两种东西——铁律 25 说的「口径不得借」
* 防的正是这个(青果曾在这里显示成别人家的 jikip 余量)。</p>
*/
@Data
@Schema(description = "LLM 渠道余额(人民币口径)")
public class UserLlmBalanceVo {
@Schema(description = "密钥模块 key(appearance-patent / similar-asin)")
private String moduleKey;
@Schema(description = "密钥模块显示名")
private String moduleLabel;
@Schema(description = "渠道 key:longtaitou / t8star")
private String channel;
@Schema(description = "渠道显示名")
private String channelLabel;
@Schema(description = "是否拿到了可展示的余额")
private Boolean available;
@Schema(description = "总余额,<b>人民币(⚡)口径</b>的上游原样小数串(未取整,界面负责显示精度);"
+ "available=false 时为空")
private String balance;
@Schema(description = "可用余额(人民币=总余额-进行中任务的预冻结)")
private String availableBalance;
@Schema(description = "预冻结金额(人民币)")
private String frozen;
@Schema(description = "金额单位,恒为 CREDIT(龙抬头站内 ⚡=人民币口径)")
private String unit;
@Schema(description = "查不到时的原因(available=false 时);前端原样展示,不再加工")
private String message;
@Schema(description = "本次取数时刻(内存缓存内复用 5 分钟,界面据此显示「更新于」)")
private LocalDateTime checkedAt;
}
@@ -0,0 +1,137 @@
package com.nanri.aiimage.modules.usersecret.service;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.usersecret.client.LongtaitouBalanceClient;
import com.nanri.aiimage.modules.usersecret.model.vo.UserLlmBalanceVo;
import com.nanri.aiimage.modules.usersecret.support.LlmChannel;
import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
/**
* LLM 渠道余额:桌面端「密钥设置」的 LLM 卡与后台密钥管理列表共用这一处取数。
*
* <p>与 {@link UserProxyBalanceService} 分开成类,两条理由都记在这儿:① 缓存键不同
* (这里是 {@code (userId, moduleKey)}——同一账号两把 LLM 密钥各有各的余额;那边是 {@code userId}
* 单键,因为一个用户只有一套代理套餐);② 铁律 25「余量口径不得借」——两套语义装进一个类,
* 注释迟早撒谎,而下一个人会照着撒谎的注释加分支。</p>
*
* <p><b>为什么渠道判据读 {@code findChannel} 而不是另解析一次</b>:这一列值就是任务执行时
* 真正发请求用的那个渠道({@code UserApiSecretService#resolveLlmHost} 取的是同一个源)。
* 闸门与展示各读各的会出现「界面说龙抬头、任务其实发贞贞」,所以铁律 27(a) 要求同源。</p>
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class UserLlmBalanceService {
/** 上游自己约 5 秒缓存同一把密钥的余额;这里再叠一层,是为了让后台列表翻页不逐页打上游。 */
private static final long CACHE_MILLIS = 5 * 60 * 1000L;
/** key={@code userId|moduleKey};改/清/切渠道时按 userId 整批失效。 */
private final Map<String, CachedLlmBalance> cache = new ConcurrentHashMap<>();
private final UserApiSecretService userApiSecretService;
private final LongtaitouBalanceClient longtaitouBalanceClient;
/** 桌面端单卡取数:{@code moduleKey} 必须是 LLM 模块(代理模块走 {@link UserProxyBalanceService})。 */
public UserLlmBalanceVo balance(Long userId, String moduleKey) {
UserSecretModule module = requireLlmModule(userId, moduleKey);
String cacheKey = cacheKey(userId, module.key());
long now = System.currentTimeMillis();
CachedLlmBalance cached = cache.get(cacheKey);
if (cached != null && now - cached.cachedAtMillis() < CACHE_MILLIS) {
return cached.balance();
}
UserLlmBalanceVo vo = loadOne(userId, module);
cache.put(cacheKey, new CachedLlmBalance(vo, System.currentTimeMillis()));
return vo;
}
/**
* 桌面端一次拿齐两张 LLM 卡(外观专利/货源查询)。清单唯一来源是
* {@link UserSecretModule#requiredModules()}——与密钥包下发、桌面端完整性门禁同一处,
* 不在这里另列一张表。
*/
public List<UserLlmBalanceVo> bundle(Long userId) {
List<UserLlmBalanceVo> items = new ArrayList<>();
for (UserSecretModule module : UserSecretModule.requiredModules()) {
items.add(balance(userId, module.key()));
}
return items;
}
/** 改了/清了/切了任一 LLM 渠道配置后调用:下一次查询立即按新配置走,不复用旧余额。 */
public void invalidate(Long userId) {
if (userId == null) {
return;
}
String prefix = userId + "|";
cache.keySet().removeIf(key -> key.startsWith(prefix));
}
private UserLlmBalanceVo loadOne(Long userId, UserSecretModule module) {
UserLlmBalanceVo vo = new UserLlmBalanceVo();
vo.setModuleKey(module.key());
vo.setModuleLabel(module.label());
String channelKey = userApiSecretService.findChannel(userId, module.key());
vo.setChannel(channelKey);
vo.setChannelLabel(LlmChannel.of(channelKey).label());
if (!LlmChannel.LONGTAITOU.key().equals(channelKey)) {
return channelUnsupported(vo, module);
}
String plain = userApiSecretService.findPlainValue(userId, module.key());
if (plain == null || plain.isBlank()) {
vo.setAvailable(false);
vo.setMessage("这一项还没配置龙抬头密钥,配好并保存后才能查余额");
return vo;
}
UserLlmBalanceVo fetched = longtaitouBalanceClient.fetch(plain);
fetched.setModuleKey(module.key());
fetched.setModuleLabel(module.label());
return fetched;
}
/**
* 贞贞档的余额答复:不打上游、不借龙抬头的数。
*
* <p>贞贞有没有可用的余额端点<b>在册无判据</b>(龙抬头那份文档讲的是它自己家)。照青果那一档
* 的先例({@code UserProxyBalanceService#qingguoUnsupported}):宁可说「查不了」,
* 也不许猜一个端点、更不许把别家的钱挂在这一行上。</p>
*/
private UserLlmBalanceVo channelUnsupported(UserLlmBalanceVo vo, UserSecretModule module) {
vo.setAvailable(false);
vo.setMessage(vo.getChannelLabel() + "渠道不提供余额查询;用量请看 "
+ LlmChannel.of(vo.getChannel()).host().replaceFirst("^https?://", "")
+ " 自己的控制台。密钥是否正常请点「检测」。");
return vo;
}
private UserSecretModule requireLlmModule(Long userId, String moduleKey) {
if (userId == null || userId <= 0) {
throw new BusinessException("用户 ID 不合法");
}
Optional<UserSecretModule> module = UserSecretModule.of(moduleKey);
if (module.isEmpty()) {
throw new BusinessException("未知的密钥模块:" + (moduleKey == null ? "" : moduleKey.trim()));
}
if (module.get().isProxy()) {
throw new BusinessException("代理设置走「代理余量」,不是 LLM 余额");
}
return module.get();
}
private static String cacheKey(Long userId, String moduleKey) {
return userId + "|" + moduleKey;
}
private record CachedLlmBalance(UserLlmBalanceVo balance, long cachedAtMillis) {
}
}
@@ -0,0 +1,225 @@
package com.nanri.aiimage.modules.usersecret.service;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.common.service.ReadScope;
import com.nanri.aiimage.config.UserSecretProperties;
import com.nanri.aiimage.modules.usersecret.model.dto.AdminUserSecretBalanceQuery;
import com.nanri.aiimage.modules.usersecret.model.vo.AdminUserSecretBalancesVo;
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretBalanceVo;
import com.nanri.aiimage.modules.usersecret.model.vo.UserLlmBalanceVo;
import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* 后台密钥管理列表的余额侧写:**实时打上游、不落库**。
*
* <p>列表本身({@code UserApiSecretService#adminPage})一次 {@code selectList} 组行,
* 本类只在其后按本页用户补数,所以不引入任何新的 SQL 或 N+1 查库。</p>
*
* <p>三条护栏是这条路线的全部安全性(少一条,翻页就会变成打上游的洪水):</p>
* <ol>
* <li><b>单次调用上限</b> {@link #MAX_ROWS_PER_CALL} 个用户——超出直接拒,不做静默截断;</li>
* <li><b>固定并发 + 整请求时间预算</b>:到点没回的行如实降级成 {@code available=false}
* 并写明「上游未在预算内应答」,<b>绝不</b>降级成 0 或空表;</li>
* <li><b>数据权限剔行</b>:请求里带的 userId 一律按 {@link DataReadScope} 收窄,
* 越权的 id 不查、并回传在 {@code deniedUserIds} 里(不静默少给数)。
* 前端给的 userId 列表<b>不是</b>安全边界。</li>
* </ol>
*
* <p>真正会发 HTTP 的行比请求行数少得多:非龙抬头渠道({@code UserLlmBalanceService})
* 与青果供应商({@code UserProxyBalanceService})都在各自服务里直接判「不提供查询」,
* 一次上游都不打;再加上两处 5 分钟内存缓存,翻页与反复点刷新不会逐次付费。</p>
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class UserSecretBalanceAdminService {
/** 单次调用允许刷新的用户数上限:15(默认页)留一倍余量,pageSize=100 时由前端分批请求。 */
static final int MAX_ROWS_PER_CALL = 20;
/** 线程池并发上限:再多就是拿后管页去压上游,供应商侧限流会把整页一起拖成超时。 */
private static final int MAX_CONCURRENCY = 8;
private final UserLlmBalanceService userLlmBalanceService;
private final UserProxyBalanceService userProxyBalanceService;
private final DataReadScope dataReadScope;
private final UserSecretProperties userSecretProperties;
public AdminUserSecretBalancesVo balances(AdminUserEntity operator, AdminUserSecretBalanceQuery query) {
AdminUserSecretBalancesVo result = new AdminUserSecretBalancesVo();
List<Long> requested = distinct(query == null ? null : query.getUserIds());
if (requested.isEmpty()) {
result.setItems(List.of());
result.setDeniedUserIds(List.of());
result.setTimedOutUserIds(List.of());
return result;
}
if (requested.size() > MAX_ROWS_PER_CALL) {
throw new BusinessException("一次最多刷新 " + MAX_ROWS_PER_CALL + " 个用户的余额,"
+ "请调小「每页数量」或翻页刷新");
}
ReadScope scope = dataReadScope.readScope(operator, query.getCompanyId());
List<Long> allowed = scope.userIdsOr(requested);
List<Long> denied = new ArrayList<>(requested);
denied.removeAll(allowed);
Map<Long, AdminUserSecretBalancesVo.Item> items = new ConcurrentHashMap<>();
for (Long userId : allowed) {
AdminUserSecretBalancesVo.Item item = new AdminUserSecretBalancesVo.Item();
item.setUserId(userId);
List<UserSecretModule> modules = UserSecretModule.requiredModules();
List<UserLlmBalanceVo> llm = new ArrayList<>(modules.size());
for (int i = 0; i < modules.size(); i++) {
llm.add(i, null);
}
item.setLlm(llm);
items.put(userId, item);
}
Set<Long> timedOut = new LinkedHashSet<>();
int concurrency = Math.min(Math.max(1, userSecretProperties.getAdminBalanceConcurrency()), MAX_CONCURRENCY);
long deadlineMillis = Math.max(1_000L, userSecretProperties.getAdminBalanceDeadlineMillis());
ExecutorService pool = Executors.newFixedThreadPool(concurrency);
List<Pending> pendings = new ArrayList<>();
try {
for (Long userId : allowed) {
List<UserSecretModule> modules = UserSecretModule.requiredModules();
for (int index = 0; index < modules.size(); index++) {
UserSecretModule module = modules.get(index);
int slot = index;
pendings.add(new Pending(userId, module.key(),
pool.submit(() -> userLlmBalanceService.balance(userId, module.key())),
value -> items.get(userId).getLlm().set(slot, (UserLlmBalanceVo) value),
() -> timedOutLlm(module)));
}
pendings.add(new Pending(userId, null,
pool.submit(() -> userProxyBalanceService.balance(userId)),
value -> items.get(userId).setProxy((UserApiSecretBalanceVo) value),
UserSecretBalanceAdminService::timedOutProxy));
}
long deadlineAt = System.currentTimeMillis() + deadlineMillis;
for (Pending pending : pendings) {
long remaining = Math.max(1L, deadlineAt - System.currentTimeMillis());
try {
pending.apply().accept(pending.future().get(remaining, TimeUnit.MILLISECONDS));
} catch (TimeoutException ex) {
pending.future().cancel(true);
pending.apply().accept(pending.degraded().get());
timedOut.add(pending.userId());
} catch (ExecutionException | InterruptedException ex) {
if (ex instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
pending.apply().accept(pending.degraded().get());
timedOut.add(pending.userId());
log.warn("[user-secret][admin-balance] 余额取数失败 userId={} module={} err={}",
pending.userId(), pending.moduleKey(), ex.getMessage());
}
}
} finally {
pool.shutdownNow();
}
List<AdminUserSecretBalancesVo.Item> ordered = new ArrayList<>();
for (Long userId : allowed) {
AdminUserSecretBalancesVo.Item item = items.get(userId);
if (item != null) {
item.getLlm().replaceAll(slot -> slot == null ? unknownLlm() : slot);
if (item.getProxy() == null) {
item.setProxy(unknownProxy());
}
ordered.add(item);
}
}
result.setItems(ordered);
result.setDeniedUserIds(denied);
result.setTimedOutUserIds(new ArrayList<>(timedOut));
log.info("[user-secret][admin-balance] 余额侧写完成 请求={} 允许={} 越权剔除={} 超预算={} 并发={} 预算={}ms",
requested.size(), allowed.size(), denied.size(), timedOut.size(), concurrency, deadlineMillis);
return result;
}
/**
* 后台代填/清空某用户配置后调用:两族余额缓存一起丢掉。
*
* <p>不这么做会出现「管理员刚换了钥匙,列表这一格还是上一把 key 的钱」——与用户端保存后
* 必须失效是同一个串档形状,只是这里由本类统一收口({@code UserApiSecretService} 反向依赖
* 余额服务会成环)。</p>
*/
public void invalidate(Long userId) {
userLlmBalanceService.invalidate(userId);
userProxyBalanceService.invalidate(userId);
}
/** 等待单元:一个(用户 × 一个余额口径)。moduleKey 为 null 表示代理余量。 */
private record Pending(Long userId, String moduleKey, Future<?> future,
Consumer<Object> apply, Supplier<Object> degraded) {
}
private static UserLlmBalanceVo timedOutLlm(UserSecretModule module) {
UserLlmBalanceVo vo = new UserLlmBalanceVo();
vo.setModuleKey(module.key());
vo.setModuleLabel(module.label());
vo.setAvailable(false);
vo.setMessage("上游未在本轮时间预算内应答,稍后重试;这不代表密钥失效,也不代表余额为 0");
return vo;
}
private static UserApiSecretBalanceVo timedOutProxy() {
UserApiSecretBalanceVo vo = new UserApiSecretBalanceVo();
vo.setAvailable(false);
vo.setScope("none");
vo.setLow(false);
vo.setMessage("上游未在本轮时间预算内应答,稍后重试;这不代表余量为 0");
return vo;
}
private static UserLlmBalanceVo unknownLlm() {
UserLlmBalanceVo vo = new UserLlmBalanceVo();
vo.setAvailable(false);
vo.setMessage("这一格没有取到数(不是余额为 0)");
return vo;
}
private static UserApiSecretBalanceVo unknownProxy() {
UserApiSecretBalanceVo vo = new UserApiSecretBalanceVo();
vo.setAvailable(false);
vo.setScope("none");
vo.setLow(false);
vo.setMessage("这一格没有取到数(不是余量为 0)");
return vo;
}
private static List<Long> distinct(List<Long> ids) {
if (ids == null) {
return List.of();
}
List<Long> out = new ArrayList<>();
for (Long id : ids) {
if (id != null && id > 0 && !out.contains(id)) {
out.add(id);
}
}
return out;
}
}
@@ -702,7 +702,11 @@ public class WithdrawTaskService {
task.setRequestJson(objectMapper.writeValueAsString(requestPayload));
task.setResultJson(objectMapper.writeValueAsString(snapshots == null ? List.of() : snapshots));
syncSnapshotTables(task, snapshots);
fileTaskMapper.updateById(task);
// B82-01:显式 wrapper 只写快照两列——updateById 会把 ALWAYS 的 failure_category 抹回 NULL
fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getId, task.getId())
.set(FileTaskEntity::getRequestJson, task.getRequestJson())
.set(FileTaskEntity::getResultJson, task.getResultJson()));
} catch (Exception ex) {
throw new BusinessException("取款任务快照保存失败");
}
@@ -104,6 +104,14 @@ AIIMAGE_NOTIFICATION_JIKIP_LOW_SURPLUS_THRESHOLD=100
# 账户余额 ≤ 阈值 → 管理员通知;供应商口径,0=关闭
AIIMAGE_NOTIFICATION_JIKIP_LOW_BALANCE_THRESHOLD=0
# 龙抬头余额查询(人民币口径=credits 块,不是顶层那个 `$…` 美元串)。
# 留空=按 LlmChannel.LONGTAITOU 的主机派生 `/v1/skills/balance`——域名只允许有一个出处,别在这里抄第二份。
AIIMAGE_USER_SECRET_LONGTAITOU_BALANCE_URL=
# 后管「密钥管理」实时查上游的两条护栏(第三条是单次 ≤20 行,写在代码常量里)。
# 这两个不是性能旋钮:没有它们,一个后管页面就能把上游点爆;而调小了只会把行读成「上游未应答」,不会读成 0。
AIIMAGE_USER_SECRET_ADMIN_BALANCE_CONCURRENCY=4
AIIMAGE_USER_SECRET_ADMIN_BALANCE_DEADLINE_MILLIS=10000
# 以上 LLM 主机/模型是「贞贞」渠道的默认值(历史口径)。
# 2026-10-29 起用户密钥可按人选择渠道(龙抬头 / 贞贞,默认贞贞,可手动切龙抬头):
# - 渠道主机写死在 UserSecretModule/LlmChannel 里,不读本段;
@@ -600,6 +600,13 @@ aiimage:
proxy-balance-check-budget-minutes: ${AIIMAGE_USER_SECRET_PROXY_BALANCE_CHECK_BUDGET_MINUTES:10}
proxy-balance-low-surplus-threshold: ${AIIMAGE_USER_SECRET_PROXY_LOW_SURPLUS_THRESHOLD:100}
proxy-balance-low-balance-threshold: ${AIIMAGE_USER_SECRET_PROXY_LOW_BALANCE_THRESHOLD:0}
# 龙抬头余额查询地址:留空=按登记的渠道主机派生(LlmChannel.LONGTAITOU.host + /v1/skills/balance)。
# 刻意不在此抄一份域名:域名有两个出处就会漂(发布域名红线那次就是这么踩的)。
longtaitou-balance-url: ${AIIMAGE_USER_SECRET_LONGTAITOU_BALANCE_URL:}
# 后台密钥列表的余额侧写:实时打上游、不落库。这两个数是「别拿后管页去压上游」的护栏,
# 不是性能旋钮——并发再高只会让整页一起撞供应商限流。两侧各有 5 分钟内存缓存。
admin-balance-concurrency: ${AIIMAGE_USER_SECRET_ADMIN_BALANCE_CONCURRENCY:4}
admin-balance-deadline-millis: ${AIIMAGE_USER_SECRET_ADMIN_BALANCE_DEADLINE_MILLIS:10000}
# 巡检发现欠费/密钥失效时是否推送站内通知(铃铛)
notify-enabled: ${AIIMAGE_USER_SECRET_NOTIFY_ENABLED:true}
# 用量日统计保留期:取 400 天而非整年,避免跨年时把刚过期的上年数据删掉(含同比对比场景)
@@ -65,7 +65,9 @@ class CatchSilenceRatchetTest {
// 10-31 CR 消项:证据保留期清理失败 WARN 兜底 + 任务号溢出回落 task_no,新增 2 处非抛分支,600 -> 602。
// 11-01 失败任务原任务重试:TaskInPlaceRetryService 的 clearResultError / resetAssembleJob
// 两处 WARN 兜底,602 -> 604(logOnly 249 -> 251;严格格 STRICT_LOG_ONLY 190 -> 192)。
static final int GIVEN_NOT_RETHROW = 604;
// 11-05 密钥余额三面(龙抬头 credits/后管实时查)抬 604 -> 608:五枚新增**全是 NOT_RETHROW**,
// LOG_ONLY 与 EMPTY 一格没涨(逐处记名见 STRICT_TOTAL 上方注释)——改的是"查不到"怎么表达,不是把它藏起来。
static final int GIVEN_NOT_RETHROW = 608;
static final int GIVEN_LOG_ONLY = 251;
static final int GIVEN_EMPTY = 56;
@@ -291,7 +293,18 @@ class CatchSilenceRatchetTest {
// ② resetAssembleJob:复位组装作业失败只 WARN——同理,任务已复位,作业复位失败由
// stuck 扫描兜底,不该阻断用户点出来的这次重试。
// 反向对照:两处都不能改成「吞掉」——WARN 里带 taskId 与异常消息,出问题看得见。
static final int STRICT_TOTAL = 1065;
// 11-05 密钥余额三面(龙抬头人民币余额 client/后管实时查余额)抬 1065 -> 1069,五枚全部 NOT_RETHROW,
// LOG_ONLY 与 EMPTY **一格没涨**——每一枚都把"这次没查到"换成界面读得出的状态,而不是只留一行日志:
// ① `LongtaitouBalanceClient.fetch`:网络/上游异常 ⇒ available=false +「余额查询失败」人话 + WARN。
// 反向对照:改成往外抛=一次余额查询把设置页打成 500;改成静默 return=界面显示 ¥0(假绿)。
// ② `LongtaitouBalanceClient.numberOrNull`:金额串(含 `$`/千分位)解析失败 ⇒ 返回 null ⇒
// 上游 credits 不可解析就当"查不到"。这一枚是"美元当人民币"的闸门:回落顶层数字才是真事故。
// ③ `LongtaitouBalanceClient.parseJson`:应答不是可解析 JSON ⇒ null,调用方给「返回的不是可解析的 JSON」。
// ④ `UserSecretBalanceAdminService` 行等待 `TimeoutException`:cancel 该行的 future、该行按
// 「上游未在本轮时间预算内应答」降级,并把 userId 记进 timedOutUserIds 如实上报(不得读成 0)。
// ⑤ 同处 `ExecutionException | InterruptedException`:先复位中断位,再同样按"未应答"降级+记账+WARN。
// 反向对照:④⑤ 若改成"超时给 0"或"catch 后什么都不记",后管那一列就会把"没问到"卖成"没钱"。
static final int STRICT_TOTAL = 1069;
/**
* 重抛型 catch 的**下限**(不是上限):本轮把两处吞异常改成重抛之后实测 388。
* 这一格只能涨不能跌——它是"异常会往外走"的总量,把它钉成"只许减"就等于拦着别人修吞异常。
@@ -417,7 +430,9 @@ class CatchSilenceRatchetTest {
// 10-31 Phase 5.1:同 GIVEN_NOT_RETHROW,证据登记补偿回收失败只 WARN,599 -> 600。
// 11-01 失败任务原任务重试:TaskInPlaceRetryService 两处 WARN 兜底(clearResultError /
// resetAssembleJob),严格口径实测 602 -> 604;出处见 STRICT_TOTAL 上方注释。
static final int STRICT_NOT_RETHROW = 604;
// 11-05 密钥余额三面:五枚 NOT_RETHROW(1065->1069 那批),严格口径实测 603 -> 608;
// 上一格 604 是**上限**而实测量一直低它一枚,这次新增把那一枚额度用掉又超上去——逐处见 STRICT_TOTAL 上方。
static final int STRICT_NOT_RETHROW = 608;
/**
* 10-17 抬 172 -> 173,出处就是上面点名过的 {@code TaskHeartbeatLivenessService.stamp()}:
* 块体只有「取到 key 名 + log.warn」一句,写心跳证据失败时既不重试也不抛出——
@@ -178,13 +178,19 @@ class AppearancePatentCreateTaskSnapshotTest {
+ " resultJson=" + task.getResultJson());
return 1;
}).when(fileTaskMapper).insert(any(FileTaskEntity.class));
when(fileTaskMapper.updateById(any(FileTaskEntity.class))).thenAnswer(invocation -> {
FileTaskEntity task = invocation.getArgument(0);
events.add("task.update id=" + task.getId()
+ " resultJson.keys=" + jsonKeys(task.getResultJson())
+ " resultJson=" + task.getResultJson());
return 1;
});
when(fileTaskMapper.update(org.mockito.ArgumentMatchers.isNull(),
org.mockito.ArgumentMatchers.any(com.baomidou.mybatisplus.core.conditions.Wrapper.class)))
.thenAnswer(invocation -> {
// B82-01:任务行部分字段落库改走 update(null, wrapper),从 SET 段取值
FileTaskEntity task = new FileTaskEntity();
com.baomidou.mybatisplus.core.conditions.Wrapper<FileTaskEntity> wrapper = invocation.getArgument(1);
task.setId(com.nanri.aiimage.testutil.UpdateWrapperProbe.eqId(wrapper));
task.setResultJson((String) com.nanri.aiimage.testutil.UpdateWrapperProbe.setValues(wrapper).get("result_json"));
events.add("task.update id=" + task.getId()
+ " resultJson.keys=" + jsonKeys(task.getResultJson())
+ " resultJson=" + task.getResultJson());
return 1;
});
when(fileResultMapper.insert(any(FileResultEntity.class))).thenAnswer(invocation -> {
FileResultEntity row = invocation.getArgument(0);
row.setId(7001L);
@@ -159,9 +159,17 @@ class DeleteBrandSnapshotTest {
return 1;
}).when(fileTaskMapper).insert(any(FileTaskEntity.class));
doAnswer(invocation -> {
captured.taskUpdates.add(invocation.getArgument(0));
// B82-01:部分字段落库走 update(null, wrapper)——按 SET 段重建探针实体再进快照
// (status 不在 RUNNING 分支的写面里 ⇒ 渲染成 "-";FAILED 分支显式带 status/error_message)
com.baomidou.mybatisplus.core.conditions.Wrapper<FileTaskEntity> wrapper = invocation.getArgument(1);
FileTaskEntity probe = new FileTaskEntity();
probe.setId(com.nanri.aiimage.testutil.UpdateWrapperProbe.eqId(wrapper));
com.nanri.aiimage.testutil.UpdateWrapperProbe.apply(probe,
com.nanri.aiimage.testutil.UpdateWrapperProbe.setValues(wrapper));
captured.taskUpdates.add(probe);
return 1;
}).when(fileTaskMapper).updateById(any(FileTaskEntity.class));
}).when(fileTaskMapper).update(org.mockito.ArgumentMatchers.isNull(),
org.mockito.ArgumentMatchers.any(com.baomidou.mybatisplus.core.conditions.Wrapper.class));
doAnswer(invocation -> {
FileResultEntity entity = invocation.getArgument(0);
entity.setId(2001L + captured.resultInserts.size());
@@ -134,9 +134,17 @@ class PriceTrackSnapshotTest {
return 1;
}).when(fileTaskMapper).insert(any(FileTaskEntity.class));
doAnswer(invocation -> {
captured.taskUpdates.add(invocation.getArgument(0));
// B82-01:部分字段落库走 update(null, wrapper)——按 SET 段重建探针实体再进快照
// (status 不在建单写面里 ⇒ 渲染成 "-")
com.baomidou.mybatisplus.core.conditions.Wrapper<FileTaskEntity> wrapper = invocation.getArgument(1);
FileTaskEntity probe = new FileTaskEntity();
probe.setId(com.nanri.aiimage.testutil.UpdateWrapperProbe.eqId(wrapper));
com.nanri.aiimage.testutil.UpdateWrapperProbe.apply(probe,
com.nanri.aiimage.testutil.UpdateWrapperProbe.setValues(wrapper));
captured.taskUpdates.add(probe);
return 1;
}).when(fileTaskMapper).updateById(any(FileTaskEntity.class));
}).when(fileTaskMapper).update(org.mockito.ArgumentMatchers.isNull(),
org.mockito.ArgumentMatchers.any(com.baomidou.mybatisplus.core.conditions.Wrapper.class));
doAnswer(invocation -> {
FileResultEntity entity = invocation.getArgument(0);
entity.setId(2001L + captured.resultInserts.size());
@@ -164,28 +164,31 @@ class ShopDataCrawlOwnerColumnTest {
});
lenient().when(fileTaskMapper.updateById(any(FileTaskEntity.class))).thenReturn(1);
// 2026-09:陈旧扫描的 FAILED 写入改为条件更新(where id=? and status='RUNNING' 的 CAS),
// 走的是 update(entity=null, wrapper)。这里按 wrapper 参数模拟 DB:只有仍为 RUNNING 的行才命中,
// 命中后落回内存表(与真实 DB 语义一致,第二次扫描因终态不再命中)。
// 注意用 isNull():Mockito 2+ 的 any(Class) 不匹配 null。
// 走的是 update(entity=null, wrapper)。B82-01 后建单快照写(request_json/owner_instance_id/
// result_json)也是同一形状——这里按 SQL 语义模拟假 DB:先校验 WHERE 段(id 必有;CAS 形状
// 还有 eq(status,'RUNNING')),命中才把 SET 段逐列应用到内存行(与真实 DB 语义一致,
// 第二次扫描因终态不再命中)。注意用 isNull():Mockito 2+ 的 any(Class) 不匹配 null。
lenient().when(fileTaskMapper.update(org.mockito.ArgumentMatchers.isNull(),
any(com.baomidou.mybatisplus.core.conditions.Wrapper.class)))
.thenAnswer(invocation -> {
com.baomidou.mybatisplus.core.conditions.Wrapper<FileTaskEntity> wrapper =
invocation.getArgument(1);
java.util.Map<String, Object> params = extractParamValues(wrapper);
java.util.Optional<Object> idValue = params.values().stream()
.filter(value -> value instanceof Long)
.findFirst();
if (idValue.isEmpty()) {
java.util.Map<String, Object> sets =
com.nanri.aiimage.testutil.UpdateWrapperProbe.setValues(wrapper);
java.util.Map<String, Object> where =
com.nanri.aiimage.testutil.UpdateWrapperProbe.whereEq(wrapper);
if (!(where.get("id") instanceof Long id)) {
return 0;
}
FileTaskEntity stored = dbTask((Long) idValue.get());
if (stored == null || !"RUNNING".equals(stored.getStatus())) {
FileTaskEntity stored = dbTask(id);
if (stored == null) {
return 0;
}
stored.setStatus("FAILED");
stored.setUpdatedAt(LocalDateTime.now());
stored.setFinishedAt(LocalDateTime.now());
Object eqStatus = where.get("status");
if (eqStatus != null && !eqStatus.equals(stored.getStatus())) {
return 0;
}
com.nanri.aiimage.testutil.UpdateWrapperProbe.apply(stored, sets);
return 1;
});
lenient().when(fileTaskMapper.selectById(anyLong())).thenReturn(null);
@@ -150,9 +150,17 @@ class ShopDataCrawlCreateTaskSnapshotTest {
return 1;
}).when(fileTaskMapper).insert(any(FileTaskEntity.class));
doAnswer(invocation -> {
events.add("task.update: " + renderTaskUpdate(invocation.<FileTaskEntity>getArgument(0)));
// B82-01:任务行部分字段落库改走 update(null, wrapper)——从 SET 段重建探针实体,
// 只带 request_json/owner_instance_id/result_json 三列(status/计数不在写面 ⇒ 渲染成 "-")
com.baomidou.mybatisplus.core.conditions.Wrapper<FileTaskEntity> wrapper = invocation.getArgument(1);
FileTaskEntity probe = new FileTaskEntity();
probe.setId(com.nanri.aiimage.testutil.UpdateWrapperProbe.eqId(wrapper));
com.nanri.aiimage.testutil.UpdateWrapperProbe.apply(probe,
com.nanri.aiimage.testutil.UpdateWrapperProbe.setValues(wrapper));
events.add("task.update: " + renderTaskUpdate(probe));
return 1;
}).when(fileTaskMapper).updateById(any(FileTaskEntity.class));
}).when(fileTaskMapper).update(org.mockito.ArgumentMatchers.isNull(),
org.mockito.ArgumentMatchers.any(com.baomidou.mybatisplus.core.conditions.Wrapper.class));
doAnswer(invocation -> {
FileResultEntity entity = invocation.getArgument(0);
entity.setId(2001L + resultInserts.size());
@@ -226,7 +226,10 @@ class SimilarAsinTaskServiceSubmitTest {
configureNewChunkAndScope();
when(taskChunkMapper.selectCount(any())).thenReturn(1L);
configureChunkStore(true);
when(fileTaskMapper.updateById(any(FileTaskEntity.class))).thenReturn(0);
// B82-01:owner 绑定失败的注入点改打 update(null, wrapper)——部分实体 updateById 已从写面退场
when(fileTaskMapper.update(org.mockito.ArgumentMatchers.isNull(),
org.mockito.ArgumentMatchers.any(com.baomidou.mybatisplus.core.conditions.Wrapper.class)))
.thenReturn(0);
IllegalStateException thrown = assertThrows(IllegalStateException.class,
() -> service.submitResult(TASK_ID, request(false)));
@@ -248,11 +251,23 @@ class SimilarAsinTaskServiceSubmitTest {
configureChunkStore(true);
when(transientPayloadStorageService.extractPointer(STORED_CHUNK_POINTER)).thenReturn(CHUNK_POINTER);
when(taskChunkMapper.selectCount(any())).thenReturn(1L);
// B82-01:owner 绑定也改走 update(null, wrapper)——但活动心跳(touchJavaSideTaskActivity)
// 本来就合法地走同一形状,所以不能 verify(never()).update;改成录下每一笔 SET 段,
// 断言「没有任何一次写 owner_instance_id」=重复候选确实没被改绑归属。
java.util.List<java.util.Map<String, Object>> updateSets = new java.util.ArrayList<>();
when(fileTaskMapper.update(org.mockito.ArgumentMatchers.isNull(),
org.mockito.ArgumentMatchers.any(com.baomidou.mybatisplus.core.conditions.Wrapper.class)))
.thenAnswer(invocation -> {
updateSets.add(com.nanri.aiimage.testutil.UpdateWrapperProbe.setValues(invocation.getArgument(1)));
return 1;
});
service.submitResult(TASK_ID, request(false));
verify(taskChunkMapper, never()).insert(any(TaskChunkEntity.class));
verify(fileTaskMapper, never()).updateById(any(FileTaskEntity.class));
assertTrue(updateSets.stream().noneMatch(sets -> sets.containsKey("owner_instance_id")),
"重复候选不得改写归属列(owner 绑定只许发生在新增 chunk 的路径上)");
verify(transientPayloadStorageService, never()).deletePayloadIfPresent(STORED_CHUNK_POINTER);
}
@@ -171,9 +171,16 @@ class SimilarAsinCreateTaskSnapshotTest {
return 1;
}).when(fileTaskMapper).insert(any(FileTaskEntity.class));
doAnswer(invocation -> {
captured.events.add("task.update: " + renderTaskUpdate(invocation.getArgument(0)));
// B82-01:任务行部分字段落库改走 update(null, wrapper)——从 SET 段重建探针实体,
// moduleType/status 不在写面里 ⇒ 渲染成 "-",快照把「窄写」钉在脸上
com.baomidou.mybatisplus.core.conditions.Wrapper<FileTaskEntity> wrapper = invocation.getArgument(1);
FileTaskEntity probe = new FileTaskEntity();
probe.setId(com.nanri.aiimage.testutil.UpdateWrapperProbe.eqId(wrapper));
probe.setResultJson((String) com.nanri.aiimage.testutil.UpdateWrapperProbe.setValues(wrapper).get("result_json"));
captured.events.add("task.update: " + renderTaskUpdate(probe));
return 1;
}).when(fileTaskMapper).updateById(any(FileTaskEntity.class));
}).when(fileTaskMapper).update(org.mockito.ArgumentMatchers.isNull(),
org.mockito.ArgumentMatchers.any(com.baomidou.mybatisplus.core.conditions.Wrapper.class));
doAnswer(invocation -> {
captured.events.add("result.insert: " + renderResultInsert(invocation.getArgument(0)));
return 1;
@@ -1,6 +1,7 @@
package com.nanri.aiimage.modules.task.service;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.service.support.TaskFailureLedger;
import com.nanri.aiimage.testutil.SourceScan;
import org.junit.jupiter.api.Test;
@@ -46,10 +47,25 @@ class TaskFailureCategoryGuardrailTest {
private static final List<String> ENTITY_FACE_FILES = List.of(
"AppearancePatentResultJobSupport.java",
"SimilarAsinTaskService.java",
"CollectDataService.java");
"CollectDataService.java",
"PriceTrackTaskService.java");
/** 名单内在册写点数(AP 4 +相似ASIN 4 +采集 1);低于它=写点被挪走或改了写法。 */
private static final int ENTITY_FACE_MIN_WRITE_SITES = 9;
/** 名单内在册写点数(AP 4 +相似ASIN 4 +采集 1 +跟价 6);低于它=写点被挪走或改了写法。 */
private static final int ENTITY_FACE_MIN_WRITE_SITES = 15;
/**
* {@code .updateById(} 写法总量的在册棘轮(B82-01 收口时的换算值:改前 173,本笔把 12 处
* 部分实体写点——13 处 {@code updateById} 调用,{@code DedupeRunService} 的收尾一处两调用——
* 改成 {@code update(null, wrapper)} 后余 160)。
*
* <p>为什么钉总量而不是逐点名单:failure_category 只是本仓 {@code FieldStrategy.ALWAYS} 的
* 五分之一({@code PriceTrackLoopRunEntity.active_task_id}、{@code ShopKeyEntity}×2、
* {@code SkipPriceAsinEntity}×5 个最低价列都标了它)——任何实体上新增一处
* {@code updateById},都值得先审一遍「实体里有没有 ALWAYS 字段、传进去的是不是新鲜实体」。
* 部分字段落库的正本形状是 {@code update(null, wrapper)} 显式 {@code .set}
* ({@code CollectDataService} 结果文件组装的条件更新)。
*/
private static final int REGISTERED_UPDATE_BY_ID_SITES = 160;
@Test
void 任务失败文案写点必须同笔写分类列() {
@@ -84,12 +100,14 @@ class TaskFailureCategoryGuardrailTest {
/**
* 实体式写面({@code task.setErrorMessage(...)} + {@code updateById})第二批接线。
*
* <p>这三面写出的正是判死/重试真正消费的那些文案(DELIVERY/BALANCE 家族:结果文件多次生成
* 失败、LLM 上游欠费)。它们不走 wrapper,上面那格扫不到;漏写列的后果不是崩,而是读侧对这一行
* <p>这四面写出的正是判死/重试真正消费的那些文案(DELIVERY/CREDENTIAL/BALANCE 家族:
* 结果文件多次生成失败、跟价「会话失效且重新登录失败」、LLM 上游欠费)。它们不走 wrapper,
* 上面那格扫不到;漏写列的后果不是崩,而是读侧对这一行
* <b>永远</b>退回中文子串——加了一列却没买到任何免疫力,这正是 B51 的病灶形状。
*
* <p>名单之外(其它实体的 {@code setErrorMessage}、以及尚未接线的 {@code FileTaskEntity} 写面)
* 本格不管:按面分批收是 {@code docs/REFACTOR_PLAN.md} §5 登记的口径,Contract 阶段前逐批加进来。
* <p>名单之外(其它实体的 {@code setErrorMessage}、以及尚未接线的 {@code FileTaskEntity} 写面,
* 如风险/店铺匹配/查ASIN/提现/巡删五面的同类终态写点)本格不管:按面分批收是
* {@code docs/REFACTOR_PLAN.md} §5 登记的口径,Contract 阶段前逐批加进来。
*/
@Test
void 已接线的实体式任务写点必须同笔派生写列() {
@@ -178,6 +196,67 @@ class TaskFailureCategoryGuardrailTest {
assertThat(TaskRetryEligibility.category(null)).isNull();
}
/**
* B82-01 抓出的判据缺口:上面两格只验「写文案的行旁边出现了写列的行」这条<b>连线</b>,
* 配对写一个恒为 {@code null} 的值也照样绿——而这正是现网实况(2026-11-05 只读探针:
* {@code failure_category} 全表非空 0、近 7 天 194 条 FAILED 全空,另有 9 条文案命中
* CREDENTIAL/DELIVERY markers 的行列也是空)。连线格买到的是零免疫力。
* 这里把「值本身非空」钉住:六组 markers(KEY 并入 BALANCE,共 5 个枚举值)各出一条样本,
* {@link TaskFailureLedger#categoryOf} 必须给出对应的非空分类名。
*/
@Test
void ledger_对六组markers各出一条非空分类() {
// 停止文案取常量不抄字面量(与 STOPPED_MARKERS 同一条纪律:两处各写一遍,改一处就静默失效)
assertThat(TaskFailureLedger.categoryOf(TaskResumeService.DUPLICATE_STOP_REASON))
.as("STOPPED 组必须判得出:这是六组里最先判、语义唯一的一条")
.isEqualTo(TaskRetryEligibility.Category.STOPPED.name());
assertThat(TaskFailureLedger.categoryOf("已收到 73 个结果分片,但结果文件生成多次失败,任务已自动结束"))
.isEqualTo(TaskRetryEligibility.Category.DELIVERY.name());
assertThat(TaskFailureLedger.categoryOf("LLM 服务余额欠费(上游账户额度不足,非本行数据问题)"))
.isEqualTo(TaskRetryEligibility.Category.BALANCE.name());
assertThat(TaskFailureLedger.categoryOf("upstream error: invalid_api_key"))
.as("KEY 组并入 BALANCE:密钥失效不许被误判成别的类,更不许判空")
.isEqualTo(TaskRetryEligibility.Category.BALANCE.name());
assertThat(TaskFailureLedger.categoryOf("对象存储出口不可达,无法写入结果"))
.isEqualTo(TaskRetryEligibility.Category.SERVICE_DOWN.name());
assertThat(TaskFailureLedger.categoryOf("aiprice 未登录且自动登录失败"))
.isEqualTo(TaskRetryEligibility.Category.CREDENTIAL.name());
// 反向:值域外的普通可重试文案必须判不出——写侧落 null=未登记,读侧逐字回落文案
assertThat(TaskFailureLedger.categoryOf("第 3 行数据格式不合法")).isNull();
}
/**
* {@code .updateById(} 写法总量棘轮(B82-01 的另一半:抹列面)。
*
* <p>{@code failure_category} 标了 {@code updateStrategy = ALWAYS}(V186,让「清错误」分支的
* null 真落库),代价是<b>任何</b>「{@code new} 出来的部分实体」走 {@code updateById} 都会把
* 这一列连同 ALWAYS 家族的其它列无条件抹回 NULL——12 处这种写法本笔已全部改成
* {@code update(null, wrapper)} 显式 {@code .set}。本格钉住改后的总量:再多出一处
* {@code updateById} 就当场红,逼着先审「实体有没有 ALWAYS 字段、传的是不是新鲜实体」,
* 审过再登记基线。只报违规清零不报总量漂移的护栏,会把复发藏进平均值(B82-02 同族教训)。
*/
@Test
void 任务行updateById写法总量棘轮_新增必须登记() {
int sites = 0;
for (Path file : mainJavaFiles()) {
for (String line : readLines(file)) {
String stripped = line.trim();
if (isComment(stripped)) {
continue;
}
int idx = stripped.indexOf(".updateById(");
while (idx >= 0) {
sites++;
idx = stripped.indexOf(".updateById(", idx + 1);
}
}
}
assertThat(sites)
.as("updateById 写法总量偏离在册棘轮 ⇒ 要么有新写法没登记(先审 ALWAYS 抹列风险),"
+ "要么有在册写点被改掉(把基线改到新值并在注释里留痕)")
.isEqualTo(REGISTERED_UPDATE_BY_ID_SITES);
}
/** 配对行必须引用同一个表达式来源,防止「写了列但写的是另一句文案的分类」。 */
private static boolean pairingIsForSameMessage(String messageLine, String categoryLine) {
String messageExpr = expressionOf(messageLine, MESSAGE_SET);
@@ -0,0 +1,180 @@
package com.nanri.aiimage.modules.usersecret.client;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.config.UserSecretProperties;
import com.nanri.aiimage.modules.usersecret.model.vo.UserLlmBalanceVo;
import com.nanri.aiimage.modules.usersecret.support.LlmChannel;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* 龙抬头余额的口径判据(B83:密钥设置与后台列表显示人民币余额)。
*
* <p>这一格要守的是<b>「两套口径里挑了哪一套」</b>。上游同一份响应给了美元串(顶层
* {@code balance="$12.345678"})和 ⚡=人民币({@code credits.balance=88.888882}),
* 取错那一套不会报错、不会返空,只会<b>安静地显示一个差 7.2 倍的数字</b>——用户拿去对账单才发现。
* 所以除了正向断言,这里还反向钉住「美元数字一个都不许出现在返回体里」。</p>
*/
class LongtaitouBalanceClientTest {
/** 官方文档 2026-10-19 那份 {@code GET /v1/skills/balance} 的响应样例,逐字照抄。 */
private static final String OFFICIAL_SAMPLE = """
{
"balance": "$12.345678",
"frozen": "$0.500000",
"available_balance": "$11.845678",
"currency": "USD",
"unit": "USD",
"credits": {
"balance": 88.888882,
"frozen": 3.6,
"available": 85.288882,
"unit": "CREDIT",
"per_usd": 7.2
}
}
""";
private final UserSecretProperties properties = new UserSecretProperties();
private final LongtaitouBalanceClient client =
new LongtaitouBalanceClient(properties, new ObjectMapper());
@Test
void 人民币余额只取credits块不取顶层美元串() {
UserLlmBalanceVo vo = client.parseResponse(newVo(), 200, OFFICIAL_SAMPLE);
assertThat(vo.getAvailable()).isTrue();
assertThat(vo.getBalance()).isEqualTo("88.888882");
assertThat(vo.getAvailableBalance()).isEqualTo("85.288882");
assertThat(vo.getFrozen()).isEqualTo("3.6");
assertThat(vo.getUnit()).isEqualTo("CREDIT");
assertThat(vo.getCheckedAt()).isNotNull();
}
@Test
void 美元数字一个都不许进返回体() {
UserLlmBalanceVo vo = client.parseResponse(newVo(), 200, OFFICIAL_SAMPLE);
// 界面上的 ¥ 后面挂上美元数=差 7.2 倍的假读数;这里把三个美元值全钉成「不许出现」
assertThat(vo.getBalance()).doesNotContain("$").doesNotContain("12.34");
assertThat(vo.getAvailableBalance()).doesNotContain("$").doesNotContain("11.84");
assertThat(vo.getFrozen()).doesNotContain("$").doesNotContain("0.50");
}
@Test
void credits块缺失时宁可不显示也不回落美元() {
String onlyUsd = """
{"balance": "$12.345678", "available_balance": "$11.845678", "currency": "USD"}
""";
UserLlmBalanceVo vo = client.parseResponse(newVo(), 200, onlyUsd);
assertThat(vo.getAvailable()).isFalse();
assertThat(vo.getBalance()).isNull();
assertThat(vo.getAvailableBalance()).isNull();
assertThat(vo.getMessage()).as("说清为什么不给数字,而不是留一格空白让人以为是 0")
.contains("人民币").contains("不给金额");
}
@Test
void per_usd不为正时按口径不合格处理() {
String badPerUsd = """
{"credits": {"balance": 88.888882, "available": 85.288882, "unit": "CREDIT", "per_usd": 0}}
""";
assertThat(client.parseResponse(newVo(), 200, badPerUsd).getAvailable()).isFalse();
}
@Test
void credits单位不是CREDIT时不认这套口径() {
String otherUnit = """
{"credits": {"balance": 88.888882, "available": 85.288882, "unit": "POINT", "per_usd": 7.2}}
""";
UserLlmBalanceVo vo = client.parseResponse(newVo(), 200, otherUnit);
assertThat(vo.getAvailable()).isFalse();
assertThat(vo.getUnit()).isNull();
}
@Test
void credits缺available时不半显示() {
String half = """
{"credits": {"balance": 88.888882, "unit": "CREDIT", "per_usd": 7.2}}
""";
assertThat(client.parseResponse(newVo(), 200, half).getAvailable()).isFalse();
}
@Test
void 上游拒绝时原样带出原因且不抛异常() {
String denied = """
{"error": {"code": "insufficient_permissions", "message": "该密钥没有账务权限", "type": "auth"}}
""";
UserLlmBalanceVo vo = client.parseResponse(newVo(), 403, denied);
assertThat(vo.getAvailable()).isFalse();
assertThat(vo.getMessage()).contains("该密钥没有账务权限").contains("insufficient_permissions");
assertThat(vo.getBalance()).isNull();
}
/**
* 现网实测形状(2026-11-05 从主机 B 直打 {@code longtaitou.token6688.com},不带任何真密钥):
* 无 Authorization ⇒ 401 {@code missing_api_key};带假 key ⇒ 401 {@code invalid_api_key};
* 路径写错才是 404 {@code unknown_url}。这条格把"URL 派生对不对"与"被拒时说什么话"一起钉在实测读数上,
* 而不是钉在猜的错误体上——同一把尺子的 ④⑤ 两支若与这里冲突,以现网为准。
*/
@Test
void 现网实测的401形状按查不到处理并把上游原话带出来() {
String missing = """
{"error":{"code":"401","message":"Authorization header with Bearer token is required","type":"missing_api_key"}}
""";
String invalid = """
{"error":{"code":"401","message":"Invalid API Key","type":"invalid_api_key"}}
""";
assertThat(client.parseResponse(newVo(), 401, missing).getMessage())
.contains("Authorization header with Bearer token is required").contains("401");
UserLlmBalanceVo vo = client.parseResponse(newVo(), 401, invalid);
assertThat(vo.getAvailable()).isFalse();
assertThat(vo.getMessage()).contains("Invalid API Key");
assertThat(vo.getBalance()).isNull();
}
@Test
void 非JSON应答按查不到处理() {
UserLlmBalanceVo vo = client.parseResponse(newVo(), 200, "<html>网关错误</html>");
assertThat(vo.getAvailable()).isFalse();
assertThat(vo.getMessage()).contains("JSON");
}
@Test
void 余额地址按渠道主机派生配置项只作覆盖() {
assertThat(client.balanceUrl())
.isEqualTo(LlmChannel.LONGTAITOU.host() + "/v1/skills/balance");
properties.setLongtaitouBalanceUrl("https://mirror.example.com/v1/skills/balance");
assertThat(client.balanceUrl()).isEqualTo("https://mirror.example.com/v1/skills/balance");
}
@Test
void 没有密钥时不调上游直接说未配置() {
assertThat(client.fetch(null).getAvailable()).isFalse();
UserLlmBalanceVo vo = client.fetch(" ");
assertThat(vo.getAvailable()).isFalse();
assertThat(vo.getMessage()).contains("未配置");
// 上面两枚都必须在本方法里返回:真打了上游才会走到网络异常分支
assertThat(vo.getChannel()).isEqualTo(LlmChannel.LONGTAITOU.key());
}
private static UserLlmBalanceVo newVo() {
UserLlmBalanceVo vo = new UserLlmBalanceVo();
vo.setChannel(LlmChannel.LONGTAITOU.key());
vo.setChannelLabel(LlmChannel.LONGTAITOU.label());
return vo;
}
}
@@ -0,0 +1,189 @@
package com.nanri.aiimage.modules.usersecret.service;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.usersecret.client.LongtaitouBalanceClient;
import com.nanri.aiimage.modules.usersecret.model.vo.UserLlmBalanceVo;
import com.nanri.aiimage.modules.usersecret.support.LlmChannel;
import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/**
* LLM 余额服务的分档、缓存与「三态不许伪装成 0」判据(B83)。
*
* <p>形状照 {@link UserProxyBalanceServiceTest}:mock 协作者服务、不连库,
* 拒绝分支一律 {@code verifyNoInteractions} 钉住「一次上游都不打」。</p>
*/
class UserLlmBalanceServiceTest {
private static final long USER_ID = 7L;
private static final String AP = UserSecretModule.APPEARANCE_PATENT.key();
private static final String SA = UserSecretModule.SIMILAR_ASIN.key();
private UserApiSecretService userApiSecretService;
private LongtaitouBalanceClient balanceClient;
private UserLlmBalanceService service;
@BeforeEach
void setUp() {
userApiSecretService = mock(UserApiSecretService.class);
balanceClient = mock(LongtaitouBalanceClient.class);
service = new UserLlmBalanceService(userApiSecretService, balanceClient);
}
@Test
void 贞贞渠道不打龙抬头接口也不借它的数字() {
when(userApiSecretService.findChannel(USER_ID, AP)).thenReturn(LlmChannel.T8STAR.key());
UserLlmBalanceVo vo = service.balance(USER_ID, AP);
assertThat(vo.getAvailable()).isFalse();
assertThat(vo.getBalance()).as("查不了就说查不了,一格空白或 0 都会被读成「没钱了」").isNull();
assertThat(vo.getMessage()).contains(LlmChannel.T8STAR.label()).contains("不提供余额查询");
verifyNoInteractions(balanceClient);
}
@Test
void 渠道读的是任务执行同一个源不另解析一次() {
when(userApiSecretService.findChannel(USER_ID, AP)).thenReturn(LlmChannel.LONGTAITOU.key());
when(userApiSecretService.findPlainValue(USER_ID, AP)).thenReturn("sk-ap");
when(balanceClient.fetch("sk-ap")).thenReturn(fetched("88.888882", "85.288882"));
UserLlmBalanceVo vo = service.balance(USER_ID, AP);
assertThat(vo.getChannel()).isEqualTo(LlmChannel.LONGTAITOU.key());
assertThat(vo.getModuleKey()).isEqualTo(AP);
assertThat(vo.getModuleLabel()).isEqualTo(UserSecretModule.APPEARANCE_PATENT.label());
assertThat(vo.getBalance()).isEqualTo("88.888882");
verify(userApiSecretService).findChannel(USER_ID, AP);
}
@Test
void 龙抬头渠道但没存密钥时说未配置而不是零() {
when(userApiSecretService.findChannel(USER_ID, AP)).thenReturn(LlmChannel.LONGTAITOU.key());
when(userApiSecretService.findPlainValue(USER_ID, AP)).thenReturn("");
UserLlmBalanceVo vo = service.balance(USER_ID, AP);
assertThat(vo.getAvailable()).isFalse();
assertThat(vo.getMessage()).contains("还没配置");
assertThat(vo.getBalance()).isNull();
verifyNoInteractions(balanceClient);
}
@Test
void 五分钟缓存内不重复打上游() {
stubLongtaitou(AP, "sk-ap", "88.888882", "85.288882");
service.balance(USER_ID, AP);
service.balance(USER_ID, AP);
verify(balanceClient, times(1)).fetch("sk-ap");
}
@Test
void 改密钥后按userId整批失效下一次重打上游() {
stubLongtaitou(AP, "sk-ap", "88.888882", "85.288882");
stubLongtaitou(SA, "sk-sa", "10.5", "9.5");
service.balance(USER_ID, AP);
service.balance(USER_ID, SA);
service.invalidate(USER_ID);
service.balance(USER_ID, AP);
service.balance(USER_ID, SA);
verify(balanceClient, times(2)).fetch("sk-ap");
verify(balanceClient, times(2)).fetch("sk-sa");
}
@Test
void 失效只影响该用户不动别人的缓存() {
stubLongtaitou(AP, "sk-ap", "88.888882", "85.288882");
service.balance(USER_ID, AP);
service.invalidate(99L);
service.balance(USER_ID, AP);
verify(balanceClient, times(1)).fetch("sk-ap");
}
@Test
void 两张卡各回各的钱A的数字不许出现在B行() {
stubLongtaitou(AP, "sk-ap", "88.888882", "85.288882");
stubLongtaitou(SA, "sk-sa", "12.500000", "10.000000");
List<UserLlmBalanceVo> items = service.bundle(USER_ID);
assertThat(items).hasSize(UserSecretModule.requiredModules().size());
assertThat(items).extracting(UserLlmBalanceVo::getModuleKey).containsExactly(AP, SA);
assertThat(itemOf(items, AP).getBalance()).isEqualTo("88.888882");
assertThat(itemOf(items, SA).getBalance()).isEqualTo("12.500000");
assertThat(itemOf(items, SA).getBalance()).doesNotContain("88.88");
}
@Test
void 代理模块问LLM余额当场拒而不是回一格假数() {
assertThatThrownBy(() -> service.balance(USER_ID, UserSecretModule.PROXY.key()))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("代理");
}
@Test
void 未知模块与非法用户ID直接拒() {
assertThatThrownBy(() -> service.balance(USER_ID, "zhuan利汇"))
.isInstanceOf(BusinessException.class);
assertThatThrownBy(() -> service.balance(null, AP)).isInstanceOf(BusinessException.class);
assertThatThrownBy(() -> service.balance(0L, AP)).isInstanceOf(BusinessException.class);
verify(balanceClient, never()).fetch(any());
}
@Test
void 上游降级时服务不二次包装直接透传() {
UserLlmBalanceVo degraded = new UserLlmBalanceVo();
degraded.setAvailable(false);
degraded.setMessage("龙抬头没有返回人民币(⚡)口径的余额块,为避免把美元数字当人民币显示,这里不给金额");
when(userApiSecretService.findChannel(anyLong(), eq(AP))).thenReturn(LlmChannel.LONGTAITOU.key());
when(userApiSecretService.findPlainValue(USER_ID, AP)).thenReturn("sk-ap");
when(balanceClient.fetch("sk-ap")).thenReturn(degraded);
UserLlmBalanceVo vo = service.balance(USER_ID, AP);
assertThat(vo.getAvailable()).isFalse();
assertThat(vo.getMessage()).isEqualTo(degraded.getMessage());
assertThat(vo.getModuleKey()).isEqualTo(AP);
}
private void stubLongtaitou(String moduleKey, String plain, String balance, String available) {
when(userApiSecretService.findChannel(USER_ID, moduleKey)).thenReturn(LlmChannel.LONGTAITOU.key());
when(userApiSecretService.findPlainValue(USER_ID, moduleKey)).thenReturn(plain);
when(balanceClient.fetch(plain)).thenReturn(fetched(balance, available));
}
private static UserLlmBalanceVo fetched(String balance, String available) {
UserLlmBalanceVo vo = new UserLlmBalanceVo();
vo.setChannel(LlmChannel.LONGTAITOU.key());
vo.setChannelLabel(LlmChannel.LONGTAITOU.label());
vo.setAvailable(true);
vo.setBalance(balance);
vo.setAvailableBalance(available);
vo.setUnit("CREDIT");
return vo;
}
private static UserLlmBalanceVo itemOf(List<UserLlmBalanceVo> items, String moduleKey) {
return items.stream().filter(item -> moduleKey.equals(item.getModuleKey())).findFirst().orElseThrow();
}
}
@@ -0,0 +1,195 @@
package com.nanri.aiimage.modules.usersecret.service;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.common.service.ReadScope;
import com.nanri.aiimage.config.UserSecretProperties;
import com.nanri.aiimage.modules.usersecret.model.dto.AdminUserSecretBalanceQuery;
import com.nanri.aiimage.modules.usersecret.model.vo.AdminUserSecretBalancesVo;
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretBalanceVo;
import com.nanri.aiimage.modules.usersecret.model.vo.UserLlmBalanceVo;
import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/**
* 后台余额侧写的三条护栏判据(B83:用户拍板「实时查上游、不落库」)。
*
* <p>实时这条路的风险不是「查不到」,而是<b>拿后管翻页去压上游</b>和<b>把超时读成没钱</b>。
* 所以三格各钉一个方向:上限必须当场拒(静默截断会让管理员以为整页都刷过了)、
* 越权 userId 必须剔掉并回传(前端给的列表不是安全边界)、
* 超预算的行必须报「未应答」且 {@code balance} 为空(一格 0 就是欠费假警报)。</p>
*/
class UserSecretBalanceAdminServiceTest {
private static final long USER_A = 1L;
private static final long USER_B = 2L;
private static final String AP = UserSecretModule.APPEARANCE_PATENT.key();
private UserLlmBalanceService llmBalanceService;
private UserProxyBalanceService proxyBalanceService;
private DataReadScope dataReadScope;
private UserSecretProperties properties;
private UserSecretBalanceAdminService service;
private final AdminUserEntity operator = new AdminUserEntity();
@BeforeEach
void setUp() {
llmBalanceService = mock(UserLlmBalanceService.class);
proxyBalanceService = mock(UserProxyBalanceService.class);
dataReadScope = mock(DataReadScope.class);
properties = new UserSecretProperties();
service = new UserSecretBalanceAdminService(
llmBalanceService, proxyBalanceService, dataReadScope, properties);
}
@Test
void 超过单次上限当场拒而不是静默截断() {
List<Long> ids = new ArrayList<>();
for (long i = 1; i <= UserSecretBalanceAdminService.MAX_ROWS_PER_CALL + 1; i++) {
ids.add(i);
}
when(dataReadScope.readScope(any(), any())).thenReturn(ReadScope.unfiltered());
assertThatThrownBy(() -> service.balances(operator, query(ids)))
.isInstanceOf(BusinessException.class)
.hasMessageContaining(String.valueOf(UserSecretBalanceAdminService.MAX_ROWS_PER_CALL))
.hasMessageContaining("每页数量");
verifyNoInteractions(llmBalanceService, proxyBalanceService);
}
@Test
void 越权userId不查并如实回传denied() {
when(dataReadScope.readScope(any(), any())).thenReturn(ReadScope.users(List.of(USER_A)));
stubFast(USER_A);
AdminUserSecretBalancesVo vo = service.balances(operator, query(List.of(USER_A, USER_B)));
assertThat(vo.getItems()).extracting(AdminUserSecretBalancesVo.Item::getUserId)
.containsExactly(USER_A);
assertThat(vo.getDeniedUserIds()).containsExactly(USER_B);
verify(llmBalanceService, never()).balance(eq(USER_B), any());
verify(proxyBalanceService, never()).balance(USER_B);
}
@Test
void 超预算的行报未应答且余额为空() {
properties.setAdminBalanceDeadlineMillis(1000L);
properties.setAdminBalanceConcurrency(4);
when(dataReadScope.readScope(any(), any())).thenReturn(ReadScope.unfiltered());
when(llmBalanceService.balance(anyLong(), any())).thenAnswer(invocation -> {
Thread.sleep(4000L);
return llm("88.888882");
});
when(proxyBalanceService.balance(USER_A)).thenAnswer(invocation -> {
Thread.sleep(4000L);
return proxy("1234");
});
AdminUserSecretBalancesVo vo = service.balances(operator, query(List.of(USER_A)));
AdminUserSecretBalancesVo.Item item = vo.getItems().get(0);
assertThat(item.getLlm()).hasSize(UserSecretModule.requiredModules().size());
UserLlmBalanceVo llmRow = item.getLlm().get(0);
assertThat(llmRow.getAvailable()).isFalse();
assertThat(llmRow.getBalance()).as("超时绝不是 0:一格 0 会被读成「欠费了」").isNull();
assertThat(llmRow.getMessage()).contains("时间预算").contains("不代表余额为 0");
assertThat(item.getProxy().getAvailable()).isFalse();
assertThat(item.getProxy().getBalance()).isNull();
assertThat(item.getProxy().getSurplus()).isNull();
assertThat(vo.getTimedOutUserIds()).containsExactly(USER_A);
}
@Test
void 正常行逐格带上数与代理侧写() {
when(dataReadScope.readScope(any(), any())).thenReturn(ReadScope.unfiltered());
stubFast(USER_A);
AdminUserSecretBalancesVo vo = service.balances(operator, query(List.of(USER_A)));
AdminUserSecretBalancesVo.Item item = vo.getItems().get(0);
assertThat(item.getLlm()).extracting(UserLlmBalanceVo::getBalance)
.containsOnly("88.888882");
assertThat(item.getProxy().getAvailable()).isTrue();
assertThat(item.getProxy().getSurplus()).isEqualTo("1234");
assertThat(vo.getTimedOutUserIds()).isEmpty();
assertThat(vo.getDeniedUserIds()).isEmpty();
}
@Test
void 空请求与脏id不打上游() {
when(dataReadScope.readScope(any(), any())).thenReturn(ReadScope.unfiltered());
assertThat(service.balances(operator, query(List.of())).getItems()).isEmpty();
// List.of 不吃 null,这里必须用 Arrays.asList 才造得出「前端塞了脏 id」那一形状
assertThat(service.balances(operator, query(Arrays.asList(0L, -3L, null))).getItems()).isEmpty();
assertThat(service.balances(operator, new AdminUserSecretBalanceQuery()).getItems()).isEmpty();
verifyNoInteractions(llmBalanceService, proxyBalanceService);
}
@Test
void 重复的userId去重后只查一轮() {
when(dataReadScope.readScope(any(), any())).thenReturn(ReadScope.unfiltered());
stubFast(USER_A);
AdminUserSecretBalancesVo vo = service.balances(operator, query(List.of(USER_A, USER_A, USER_A)));
assertThat(vo.getItems()).hasSize(1);
// 三行重复 id 若没去重,这里会变成 6 次 LLM + 3 次代理=拿后管页自己造洪水
verify(llmBalanceService, times(UserSecretModule.requiredModules().size()))
.balance(eq(USER_A), any());
verify(proxyBalanceService, times(1)).balance(USER_A);
}
@Test
void 代填或清空后两族缓存一起丢() {
service.invalidate(USER_A);
verify(llmBalanceService).invalidate(USER_A);
verify(proxyBalanceService).invalidate(USER_A);
}
private void stubFast(long userId) {
when(llmBalanceService.balance(eq(userId), any())).thenReturn(llm("88.888882"));
when(proxyBalanceService.balance(userId)).thenReturn(proxy("1234"));
}
private static UserLlmBalanceVo llm(String balance) {
UserLlmBalanceVo vo = new UserLlmBalanceVo();
vo.setAvailable(true);
vo.setBalance(balance);
vo.setUnit("CREDIT");
return vo;
}
private static UserApiSecretBalanceVo proxy(String surplus) {
UserApiSecretBalanceVo vo = new UserApiSecretBalanceVo();
vo.setAvailable(true);
vo.setSurplus(surplus);
vo.setScope("user");
return vo;
}
private static AdminUserSecretBalanceQuery query(List<Long> userIds) {
AdminUserSecretBalanceQuery query = new AdminUserSecretBalanceQuery();
query.setUserIds(userIds);
return query;
}
}
@@ -0,0 +1,156 @@
package com.nanri.aiimage.testutil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 从 MyBatis-Plus 的 {@code update(null, wrapper)} 入参里取回「SET 了哪些列、各是什么值」(B82-01 收口配套)。
*
* <p>任务行的部分字段落库已统一改成 {@code update(null, wrapper)} 显式 {@code .set}——部分实体
* {@code updateById} 会把 {@code FieldStrategy.ALWAYS} 的 {@code failure_category} 无条件抹回 NULL。
* mock 侧的事件捕获与假 DB 因此要从 wrapper 里取证,而不是从实体字段上读。列名与值的配对来自
* {@code getSqlSet()} 的拼写顺序(与 {@code .set()} 调用顺序一致),值按 {@code MPGENVALn}
* 精确取键——不依赖 {@code paramNameValuePairs} 的迭代序(那是 HashMap)。
*/
public final class UpdateWrapperProbe {
private static final Pattern SET_ITEM =
Pattern.compile("([a-zA-Z_]+)=#\\{ew\\.paramNameValuePairs\\.(MPGENVAL\\d+)}");
private static final Pattern WHERE_ITEM =
Pattern.compile("([a-zA-Z_]+)\\s*=\\s*#\\{ew\\.paramNameValuePairs\\.([A-Za-z0-9]+)}");
private UpdateWrapperProbe() {
}
private record SetItem(String column, Object value, String paramKey) {
}
private static List<SetItem> setItems(Wrapper<?> wrapper) {
List<SetItem> out = new ArrayList<>();
String sqlSet = sqlSet(wrapper);
if (sqlSet == null || sqlSet.isBlank()) {
return out;
}
Map<String, Object> params = paramNameValuePairs(wrapper);
Matcher matcher = SET_ITEM.matcher(sqlSet);
while (matcher.find()) {
String paramKey = matcher.group(2);
out.add(new SetItem(matcher.group(1), params.get(paramKey), paramKey));
}
return out;
}
/** {@code getSqlSet()} 与 {@code getParamNameValuePairs()} 都挂在 AbstractWrapper 上,不在 Wrapper 接口。 */
private static String sqlSet(Wrapper<?> wrapper) {
if (wrapper instanceof com.baomidou.mybatisplus.core.conditions.AbstractWrapper<?, ?, ?> abstractWrapper) {
return abstractWrapper.getSqlSet();
}
throw new IllegalArgumentException("update(null, x) 的第二参不是 AbstractWrapper:" + wrapper.getClass());
}
/** {@code getParamNameValuePairs()} 挂在 {@link com.baomidou.mybatisplus.core.conditions.AbstractWrapper} 上。 */
public static Map<String, Object> paramNameValuePairs(Wrapper<?> wrapper) {
if (wrapper instanceof com.baomidou.mybatisplus.core.conditions.AbstractWrapper<?, ?, ?> abstractWrapper) {
return abstractWrapper.getParamNameValuePairs();
}
throw new IllegalArgumentException("update(null, x) 的第二参不是 AbstractWrapper:" + wrapper.getClass());
}
/** SET 段的「列名 → 值」,顺序与 {@code .set()} 调用顺序一致;列名一律归一成 snake_case。 */
public static Map<String, Object> setValues(Wrapper<?> wrapper) {
Map<String, Object> out = new LinkedHashMap<>();
for (SetItem item : setItems(wrapper)) {
out.put(snake(item.column()), item.value());
}
return out;
}
/**
* 列名归一成 snake_case。单测 JVM 里 FileTaskEntity 的 Lambda 列缓存可能被先行自动初始化成
* 驼峰(无 GlobalConfig 的裸 MybatisConfiguration 下 underCamel=false),而生产 Spring 上下文
* 恒为下划线——探针两种都得认,否则快照结果取决于测试类的执行顺序。
*/
private static String snake(String column) {
StringBuilder out = new StringBuilder(column.length() + 4);
for (int i = 0; i < column.length(); i++) {
char c = column.charAt(i);
if (Character.isUpperCase(c)) {
out.append('_').append(Character.toLowerCase(c));
} else {
out.append(c);
}
}
return out.toString();
}
/**
* WHERE 段的「列名 → 值」(等值条件;列名归一 snake_case)。判据与仓内
* {@code applyTaskScanFilter} 同款:直接读 {@code getSqlSegment()} 的拼写,
* 不靠 paramNameValuePairs 的键册回溯(那是 HashMap,序不可依赖)。
*/
public static Map<String, Object> whereEq(Wrapper<?> wrapper) {
Map<String, Object> out = new LinkedHashMap<>();
if (!(wrapper instanceof com.baomidou.mybatisplus.core.conditions.AbstractWrapper<?, ?, ?> abstractWrapper)) {
return out;
}
String segment = abstractWrapper.getSqlSegment();
if (segment == null || segment.isBlank()) {
return out;
}
Map<String, Object> params = abstractWrapper.getParamNameValuePairs();
Matcher matcher = WHERE_ITEM.matcher(segment);
while (matcher.find()) {
out.put(snake(matcher.group(1)), params.get(matcher.group(2)));
}
return out;
}
/** WHERE 段 {@code eq(id, …)} 的值(没有 eq(id) 或值不是 Long 时返回 null)。 */
public static Long eqId(Wrapper<?> wrapper) {
Object value = whereEq(wrapper).get("id");
return value instanceof Long longValue ? longValue : null;
}
/**
* 把 SET 段按列名应用到内存实体上(假 DB 用;只认 {@code biz_file_task} 的列名)。
* 未知列当场炸而不是静默跳过——假 DB 不认识的列会让快照测试说谎。
*/
public static void apply(FileTaskEntity entity, Map<String, Object> sets) {
for (Map.Entry<String, Object> entry : sets.entrySet()) {
String column = entry.getKey();
Object value = entry.getValue();
switch (column) {
case "task_no" -> entity.setTaskNo((String) value);
case "module_type" -> entity.setModuleType((String) value);
case "task_mode" -> entity.setTaskMode((String) value);
case "collect_channel" -> entity.setCollectChannel((String) value);
case "status" -> entity.setStatus((String) value);
case "source_file_count" -> entity.setSourceFileCount((Integer) value);
case "success_file_count" -> entity.setSuccessFileCount((Integer) value);
case "failed_file_count" -> entity.setFailedFileCount((Integer) value);
case "request_json" -> entity.setRequestJson((String) value);
case "result_json" -> entity.setResultJson((String) value);
case "error_message" -> entity.setErrorMessage((String) value);
case "failure_category" -> entity.setFailureCategory((String) value);
case "created_by" -> entity.setCreatedBy((String) value);
case "user_id" -> entity.setUserId((Long) value);
case "device_id" -> entity.setDeviceId((String) value);
case "owner_instance_id" -> entity.setOwnerInstanceId((String) value);
case "updated_at" -> entity.setUpdatedAt((LocalDateTime) value);
case "finished_at" -> entity.setFinishedAt((LocalDateTime) value);
case "created_at" -> entity.setCreatedAt((LocalDateTime) value);
default -> throw new IllegalStateException("UpdateWrapperProbe 不认识的列:" + column
+ "(假 DB 拒绝静默跳过——把它登记进 apply 的列册再继续)");
}
}
}
}
@@ -1,6 +1,6 @@
== case=main files=1
task.insert: id=1001 moduleType=DELETE_BRAND status=RUNNING taskMode=IMMEDIATE userId=7 createdBy=user:7 deviceId=dev-1 sourceFileCount=1
task.update: id=1001 status=RUNNING sourceFileCount=1 successFileCount=1 failedFileCount=0 errorMessage=-
task.update: id=1001 status=- sourceFileCount=1 successFileCount=1 failedFileCount=0 errorMessage=-
result.insert: id=2001 taskId=1001 moduleType=DELETE_BRAND sourceFileUrl=uploads/魏振峰.xlsx rowCount=4 success=0 resultFilename=- errorMessage=-
vo: total=1 successCount=1 failedCount=0
item: resultId=2001 fileKey=uploads/魏振峰.xlsx shopName=魏振峰 matched=true matchStatus=MATCHED countryCount=2 totalRows=4 truncated=false success=true error=- taskStatus=RUNNING
@@ -48,7 +48,7 @@ item: resultId=2001 fileKey=uploads/缺字段行.xlsx shopName=缺字段行 matc
payload.files=0
== case=shopNameColumnSkipped files=1
task.insert: id=1001 moduleType=DELETE_BRAND status=RUNNING taskMode=IMMEDIATE userId=7 createdBy=user:7 deviceId=dev-1 sourceFileCount=1
task.update: id=1001 status=RUNNING sourceFileCount=1 successFileCount=1 failedFileCount=0 errorMessage=-
task.update: id=1001 status=- sourceFileCount=1 successFileCount=1 failedFileCount=0 errorMessage=-
result.insert: id=2001 taskId=1001 moduleType=DELETE_BRAND sourceFileUrl=uploads/英国.xlsx rowCount=3 success=0 resultFilename=- errorMessage=-
vo: total=1 successCount=1 failedCount=0
item: resultId=2001 fileKey=uploads/英国.xlsx shopName=英国 matched=true matchStatus=MATCHED countryCount=1 totalRows=3 truncated=false success=true error=- taskStatus=RUNNING
@@ -4,7 +4,7 @@ vo: taskId=1001 items=2
item: resultId=2002 shopName=店铺B matched=true taskStatus=RUNNING success=false
vo: asinRowsByCountry=0 skipAsinsByCountry=0 minimumPriceByCountry=0
task.insert: id=1001 moduleType=PRICE_TRACK taskMode=PYTHON_QUEUE status=RUNNING sourceFileCount=2
task.update: id=1001 status=RUNNING requestJsonHasAsinFiles=true requestJsonHasListingStatuses=true resultJsonItems=2
task.update: id=1001 status=- requestJsonHasAsinFiles=true requestJsonHasListingStatuses=true resultJsonItems=2
result.insert: id=2001 moduleType=PRICE_TRACK sourceFilename=店铺A sourceFileUrl=shop-店铺A success=0
result.insert: id=2002 moduleType=PRICE_TRACK sourceFilename=店铺B sourceFileUrl=shop-店铺B success=0
payloadSaves=1
@@ -19,7 +19,7 @@ vo: taskId=1001 items=1
item: resultId=2001 shopName=店铺A matched=true taskStatus=RUNNING success=false
vo: asinRowsByCountry=0 skipAsinsByCountry=0 minimumPriceByCountry=0
task.insert: id=1001 moduleType=PRICE_TRACK taskMode=PYTHON_QUEUE status=RUNNING sourceFileCount=1
task.update: id=1001 status=RUNNING requestJsonHasAsinFiles=true requestJsonHasListingStatuses=true resultJsonItems=1
task.update: id=1001 status=- requestJsonHasAsinFiles=true requestJsonHasListingStatuses=true resultJsonItems=1
result.insert: id=2001 moduleType=PRICE_TRACK sourceFilename=店铺A sourceFileUrl=shop-店铺A success=0
payloadSaves=1
payload country=FR rows=1
@@ -30,7 +30,7 @@ vo: taskId=1001 items=1
item: resultId=2001 shopName=店铺A matched=true taskStatus=RUNNING success=false
vo: asinRowsByCountry=0 skipAsinsByCountry=0 minimumPriceByCountry=0
task.insert: id=1001 moduleType=PRICE_TRACK taskMode=PYTHON_QUEUE status=RUNNING sourceFileCount=1
task.update: id=1001 status=RUNNING requestJsonHasAsinFiles=true requestJsonHasListingStatuses=true resultJsonItems=1
task.update: id=1001 status=- requestJsonHasAsinFiles=true requestJsonHasListingStatuses=true resultJsonItems=1
result.insert: id=2001 moduleType=PRICE_TRACK sourceFilename=店铺A sourceFileUrl=shop-店铺A success=0
payloadSaves=1
heartbeatTouches=1
@@ -39,7 +39,7 @@ vo: taskId=1001 items=1
item: resultId=2001 shopName=店铺A matched=true taskStatus=RUNNING success=false
vo: asinRowsByCountry=0 skipAsinsByCountry=0 minimumPriceByCountry=0
task.insert: id=1001 moduleType=PRICE_TRACK taskMode=PYTHON_QUEUE status=RUNNING sourceFileCount=1
task.update: id=1001 status=RUNNING requestJsonHasAsinFiles=true requestJsonHasListingStatuses=true resultJsonItems=1
task.update: id=1001 status=- requestJsonHasAsinFiles=true requestJsonHasListingStatuses=true resultJsonItems=1
result.insert: id=2001 moduleType=PRICE_TRACK sourceFilename=店铺A sourceFileUrl=shop-店铺A success=0
payloadSaves=1
payload country=UK rows=2
@@ -63,7 +63,7 @@ vo: taskId=1001 items=1
item: resultId=2001 shopName=店铺A matched=true taskStatus=RUNNING success=false
vo: asinRowsByCountry=0 skipAsinsByCountry=0 minimumPriceByCountry=0
task.insert: id=1001 moduleType=PRICE_TRACK taskMode=PYTHON_QUEUE status=RUNNING sourceFileCount=1
task.update: id=1001 status=RUNNING requestJsonHasAsinFiles=true requestJsonHasListingStatuses=true resultJsonItems=1
task.update: id=1001 status=- requestJsonHasAsinFiles=true requestJsonHasListingStatuses=true resultJsonItems=1
result.insert: id=2001 moduleType=PRICE_TRACK sourceFilename=店铺A sourceFileUrl=shop-店铺A success=0
payloadSaves=1
payload country=UK rows=2
@@ -77,7 +77,7 @@ vo: taskId=1001 items=1
item: resultId=2001 shopName=店铺A matched=true taskStatus=RUNNING success=false
vo: asinRowsByCountry=0 skipAsinsByCountry=0 minimumPriceByCountry=0
task.insert: id=1001 moduleType=PRICE_TRACK taskMode=PYTHON_QUEUE status=RUNNING sourceFileCount=1
task.update: id=1001 status=RUNNING requestJsonHasAsinFiles=false requestJsonHasListingStatuses=true resultJsonItems=1
task.update: id=1001 status=- requestJsonHasAsinFiles=false requestJsonHasListingStatuses=true resultJsonItems=1
result.insert: id=2001 moduleType=PRICE_TRACK sourceFilename=店铺A sourceFileUrl=shop-店铺A success=0
payloadSaves=0
heartbeatTouches=1
@@ -7,7 +7,7 @@ events=7 taskInserts=1 resultInserts=1 heartbeatTouches=1
evt: result.insert: id=2001 taskId=1001 moduleType=SHOP_DATA_CRAWL sourceFilename=Demo Shop sourceFileUrl=shop-Demo Shop userId=7 success=-1 rowCount=- createdAtEqualsTaskCreatedAt=true
evt: snapshotTable.replace: taskId=1001 items=1
evt: progressSave: taskId=1001 status=RUNNING total=1 ok=0 fail=0
evt: task.update: id=1001 status=RUNNING ok=0 fail=0 requestJsonHasOwner=true requestJsonItems=1 resultJsonItems=1 createdAtEqualsUpdatedAt=true
evt: task.update: id=1001 status=- ok=null fail=null requestJsonHasOwner=true requestJsonItems=1 resultJsonItems=1 createdAtEqualsUpdatedAt=false
evt: taskCacheSave: id=1001
== case=requestFieldsOverwrittenByMatch
vo: taskId=1001 items=1
@@ -18,7 +18,7 @@ events=7 taskInserts=1 resultInserts=1 heartbeatTouches=1
evt: result.insert: id=2001 taskId=1001 moduleType=SHOP_DATA_CRAWL sourceFilename=Demo Shop sourceFileUrl=shop-Demo Shop userId=7 success=-1 rowCount=- createdAtEqualsTaskCreatedAt=true
evt: snapshotTable.replace: taskId=1001 items=1
evt: progressSave: taskId=1001 status=RUNNING total=1 ok=0 fail=0
evt: task.update: id=1001 status=RUNNING ok=0 fail=0 requestJsonHasOwner=true requestJsonItems=1 resultJsonItems=1 createdAtEqualsUpdatedAt=true
evt: task.update: id=1001 status=- ok=null fail=null requestJsonHasOwner=true requestJsonItems=1 resultJsonItems=1 createdAtEqualsUpdatedAt=false
evt: taskCacheSave: id=1001
== case=twoItemsRejected
thrown: BusinessException code=- message=items 必须且只能包含一个店铺
File diff suppressed because one or more lines are too long
+1
View File
@@ -211,6 +211,7 @@ export const API_ENDPOINTS = {
check: '/api/user-secrets/{moduleKey}/check',
migrate: '/api/user-secrets/migrate',
proxyBalance: '/api/user-secrets/proxy-balance',
llmBalance: '/api/user-secrets/llm-balance',
proxyPlan: '/api/user-secrets/proxy-plan',
proxyWhitelist: '/api/user-secrets/proxy-whitelist',
clientIp: '/api/user-secrets/client-ip',
@@ -58,6 +58,30 @@ export interface UserApiSecretBalance {
lowReason?: string | null
}
/**
* LLM 渠道余额(人民币口径)。
*
* 与 `UserApiSecretBalance` 分开的理由在后端 `UserLlmBalanceVo` 上写着:那一个的
* surplus/scope/low 全是 jikip 套餐语义。这里同样不复用——一个字段名在两处表示两种东西,
* 下一个读代码的人一定会照错的用(铁律 25「口径不得借」)。
*/
export interface UserLlmBalance {
moduleKey: string
moduleLabel: string
/** longtaitou / t8star */
channel: string
channelLabel: string
available: boolean
/** 总余额,人民币(⚡)口径的上游原样小数串;available=false 时为 null。 */
balance: string | null
availableBalance: string | null
frozen: string | null
/** 恒为 CREDIT(站内 ⚡=人民币)。 */
unit: string | null
message: string | null
checkedAt: string | null
}
export interface UserProxyPlan {
planId: string | null
jikipUserId: string | null
@@ -130,6 +154,21 @@ export function fetchProxyBalance() {
)
}
/**
* LLM 渠道余额(人民币口径)。`moduleKey` 留空=一次回齐两张密钥卡。
*
* 服务端最坏一次上游读 8 秒(`LongtaitouBalanceClient` 的读超时)+ 本地取密钥,
* 界面上限给到 20 秒:比它短会把「查得慢」报成「查不到」,比它长则用户盯着转圈没反馈。
*/
export function fetchLlmBalance(moduleKey?: string) {
return unwrapJavaResponse(
get<JavaApiResponse<UserLlmBalance[]>>(
buildJavaUrl(API_ENDPOINTS.userSecret.llmBalance, moduleKey ? { moduleKey } : undefined),
{ timeout: 20000 },
),
)
}
/** 读取当前用户填写的 jikip 套餐 ID / 用户 ID(只用于余量查询)。 */
export function fetchProxyPlan() {
return unwrapJavaResponse(
@@ -78,6 +78,13 @@
{{ statusTextOf(module.moduleKey) }}
</span>
</div>
<SecretBalanceRow
:text="llmMetaText(module.moduleKey)"
:updated-at="llmBalanceUpdatedAtOf(module.moduleKey)"
:refreshing="llmBalanceLoading"
@refresh="() => loadLlmBalance(module.moduleKey)"
/>
</section>
<section v-if="showProxy" class="secret-card">
@@ -252,14 +259,7 @@
</span>
</div>
<div class="secret-meta">
<span v-if="proxyLoading">正在读取代理配置...</span>
<span v-else-if="proxyLoadFailed">代理配置读取失败,请关闭弹窗后重试</span>
<span v-else-if="!proxySupported">代理设置仅在桌面客户端中可用</span>
<span v-else-if="balanceLoading">正在查询代理余量...</span>
<span v-else-if="balance">{{ balanceText }}</span>
<span v-else>{{ balanceUnavailableText }}</span>
</div>
<SecretBalanceRow :text="proxyMetaText" :refreshing="balanceLoading" @refresh="loadBalance" />
</section>
</div>
</template>
@@ -308,7 +308,9 @@ import {
} from '@/shared/utils/api-secret-proxy-config'
import { useProxyBalance, useProxyPlan } from '@/shared/composables/useProxyPlan'
import { useKeyedSecretVisibility, useSecretVisibility } from '@/shared/composables/useSecretVisibility'
import { useLlmBalance } from '@/shared/composables/useLlmBalance'
import SecretVisibilityToggle from '@/shared/components/SecretVisibilityToggle.vue'
import SecretBalanceRow from '@/shared/components/SecretBalanceRow.vue'
import { createModuleView, proxyCheckPresentation, type ModuleState } from '@/shared/utils/api-secret-module-view'
const props = withDefaults(
@@ -383,6 +385,23 @@ const proxyCheckResult = ref<UserApiSecretCheckResult | null>(null)
const proxyCheckError = ref('')
const { balance, balanceLoading, balanceText, balanceUnavailableText, loadBalance } = useProxyBalance({ proxyProvider })
const { llmBalanceLoading, llmBalanceTextOf, llmBalanceUpdatedAtOf, loadLlmBalance } = useLlmBalance()
/** LLM 卡余额行:渠道名以服务端回传为准(库里那把 key 才是余额接口读的,本地未保存的单选不参与取数)。 */
function llmMetaText(moduleKey: string): string {
if (llmBalanceLoading.value) return '正在查询密钥余额...'
return llmBalanceTextOf(moduleKey, llmChannelLabel(moduleChannels[moduleKey]))
}
/** 代理卡那一行的既有优先级原样搬过来(读取中 → 失败 → 不支持 → 查询中 → 数值 → 查不到)。 */
const proxyMetaText = computed(() => {
if (proxyLoading.value) return '正在读取代理配置...'
if (proxyLoadFailed.value) return '代理配置读取失败,请关闭弹窗后重试'
if (!proxySupported.value) return '代理设置仅在桌面客户端中可用'
if (balanceLoading.value) return '正在查询代理余量...'
return balance.value ? balanceText.value : balanceUnavailableText.value
})
const {
proxyPlanId,
proxyPlanUserId,
@@ -557,6 +576,8 @@ async function runCheck(moduleKey: ApiSecretModuleKey) {
} finally {
state.checking = false
refreshSnapshots()
// 只有「检测已存密钥」才顺带刷余额:检测输入值时库里还是上一把 key,刷出来是上一把的钱(串档形状)
if (!inputValue) void loadLlmBalance(moduleKey)
}
}
@@ -571,6 +592,8 @@ async function clearModule(moduleKey: ApiSecretModuleKey) {
state.error = ''
channelDirty[moduleKey] = false
refreshSnapshots()
// 清空后库里已经没有这把 key:不刷的话,这一行会继续挂着上一把 key 的钱
void loadLlmBalance(moduleKey)
ElMessage.success('已清空密钥')
} catch (error) {
ElMessage.error(error instanceof Error ? error.message : '清空失败')
@@ -679,6 +702,7 @@ async function saveAll(options: { requireAll?: boolean } = {}): Promise<boolean>
}
secretsSaved = true
refreshSnapshots()
void loadLlmBalance()
if (props.showProxy && proxyReady.value && proxyDirty.value && !proxyLocked.value) {
const api = getPywebviewApi()
@@ -741,6 +765,8 @@ onMounted(() => {
// 先拉服务端密钥包(后台锁定的代理会先对齐到本地配置),再读本地代理,避免展示对齐前的旧值
void (async () => {
await reload()
// 读的是服务端已存密钥 ⇒ 排在 reload 之后;且它不属代理卡(浏览器形态 showProxy=false 会永远空白)
void loadLlmBalance()
if (props.showProxy) {
await loadProxyConfig()
if (proxySupported.value) {
@@ -0,0 +1,65 @@
<template>
<div class="secret-meta">
<span>{{ text }}</span>
<span v-if="updatedAt" class="meta-updated">更新于 {{ updatedAt }}</span>
<button
v-if="refreshable"
type="button"
class="meta-refresh"
:disabled="refreshing"
@click="emit('refresh')"
>
{{ refreshing ? '查询中...' : '刷新余额' }}
</button>
</div>
</template>
<script setup lang="ts">
/**
* 密钥卡上的「余额/余量」那一行(LLM 两卡与代理卡共用同一个形状)。
*
* 根元素刻意就是 `<div class="secret-meta">`:面板的样式与既有挂载用例都按这个类取数
* (`tests/mount/密钥面板青果检测.mount.test.ts` 的 `proxyCard(panel).find('.secret-meta')`),
* 抽组件不许把这条既有判据挪走。父作用域的 `.secret-meta` 规则会照常落到本组件根元素上
* (Vue 给子组件根节点同时挂父子两个 scope 属性),所以这里不重复定义行色。
*
* 文案由调用方算好整条传进来(含「正在读取…」那几档),本组件只管显示与「刷新」这个动作——
* 三态优先级留在面板里,一处一份,不在组件里再造第二套判定。
*/
withDefaults(defineProps<{
/** 整行文案(loading / 数值 / 查不到,都由调用方按既有优先级算好)。 */
text: string
/** 取数时刻(`HH:mm`);为空就不显示——没有数的时候不该假装知道它是几点取的。 */
updatedAt?: string
refreshing?: boolean
refreshable?: boolean
}>(), {
updatedAt: '',
refreshing: false,
refreshable: true,
})
const emit = defineEmits<{ refresh: [] }>()
</script>
<style scoped>
.meta-updated {
margin-left: 6px;
}
.meta-refresh {
margin-left: 8px;
border: 1px solid #cdd4dd;
background: transparent;
color: inherit;
border-radius: 4px;
padding: 0 8px;
font-size: 12px;
cursor: pointer;
}
.meta-refresh:disabled {
cursor: default;
opacity: 0.6;
}
</style>
@@ -0,0 +1,70 @@
import { ref } from 'vue'
import { fetchLlmBalanceSafely } from '@/shared/utils/api-secret-store'
import {
llmBalanceText,
llmBalanceUnavailableText,
llmBalanceUpdatedAt,
} from '@/shared/utils/llm-balance-text'
import type { UserLlmBalance } from '@/shared/api/types/modules/user-secret'
/**
* LLM 渠道余额(人民币口径):两张密钥卡各一格,形状与代理余量同一套三态。
*
* 三条口径写在这里,因为它们是「看着像成功、其实是错的」的成因:
* 1. **只在读服务端已存密钥的时刻刷**。输入框里那把还没保存的 key 不是余额接口读的那把
* (`checkApiSecret(value)` 探的是输入值,余额读的是库里那把)——在「检测输入值」后刷,
* 得到的是**上一把 key 的钱挂在新渠道名下**,与切渠道后不刷相比更容易被骗。
* 2. **失败即清空数字**,只留原因。留着上一次的读数就是上一条那个串档形状。
* 3. 不做任何汇率换算:`credits` 块本身就是人民币(⚡),乘一次系数等于自造一套口径
* (铁律 25)。
*/
export function useLlmBalance() {
const llmBalanceItems = ref<Record<string, UserLlmBalance>>({})
const llmBalanceLoading = ref(false)
function llmBalanceTextOf(moduleKey: string, channelLabel = ''): string {
const item = llmBalanceItems.value[moduleKey]
return item?.available
? llmBalanceText(item)
: llmBalanceUnavailableText(item, channelLabel)
}
function llmBalanceUpdatedAtOf(moduleKey: string): string {
return llmBalanceUpdatedAt(llmBalanceItems.value[moduleKey])
}
/** `moduleKey` 留空=一次刷两张卡(面板打开时用);带 key=只刷那一格(保存/切渠道后用)。 */
async function loadLlmBalance(moduleKey?: string): Promise<void> {
llmBalanceLoading.value = true
try {
const list = await fetchLlmBalanceSafely(moduleKey)
const next = { ...llmBalanceItems.value }
for (const item of list || []) {
if (item && item.moduleKey) next[item.moduleKey] = item
}
llmBalanceItems.value = next
} catch (error) {
// 失败的第一出口是界面那一行(清空数字 ⇒ 渲染成「这次没查到」,与代理余量同一口径);
// 余额是打开面板时的附带读取,弹全局打扰会把用户下一次正常操作也打断,所以不 ElMessage。
// 顺序有意义:先给用户看得见的交代,控制台只作留链(catch-silence 棘轮按首条语句判静默)。
if (moduleKey) {
const next = { ...llmBalanceItems.value }
delete next[moduleKey]
llmBalanceItems.value = next
} else {
llmBalanceItems.value = {}
}
console.warn('[api-secret] LLM 余额查询失败:', error)
} finally {
llmBalanceLoading.value = false
}
}
return {
llmBalanceItems,
llmBalanceLoading,
llmBalanceTextOf,
llmBalanceUpdatedAtOf,
loadLlmBalance,
}
}
@@ -13,6 +13,7 @@ import {
checkMyApiSecret,
deleteMyApiSecret,
fetchMyApiSecrets,
fetchLlmBalance,
fetchProxyBalance,
migrateMyApiSecrets,
putMyApiSecret,
@@ -21,6 +22,7 @@ import {
type UserApiSecretBundle,
type UserApiSecretCheckResult,
type UserApiSecretItem,
type UserLlmBalance,
} from '../api/types/modules/user-secret.ts'
import {
applyInheritedSecrets,
@@ -979,6 +981,15 @@ export async function fetchProxyBalanceSafely() {
return fetchProxyBalance()
}
/**
* LLM 渠道余额(人民币口径)。`moduleKey` 留空=一次回齐两张密钥卡。
* 与 `fetchProxyBalanceSafely` 同层:只做薄封装、不吞异常——吞掉异常就把「查不到」
* 混成「余额为零」了,判红分支由调用方(useLlmBalance)如实分流。
*/
export async function fetchLlmBalanceSafely(moduleKey?: string): Promise<UserLlmBalance[]> {
return fetchLlmBalance(moduleKey)
}
/** 登出清理:内存与镜像一并清空(旧 v1 记录保留,供下次登录迁移)。 */
export function clearApiSecretCache(): void {
for (const moduleKey of [...DEFAULT_REQUIRED_MODULES]) {
@@ -0,0 +1,70 @@
/**
* LLM 余额的显示口径(纯函数,零 vue、零 `@/` 别名)。
*
* 单独成文件与本仓 `proxy-balance-alert.ts` / `user-secret-model.ts` 同一理由:
* 判据要能被 `node --test` 直接钉住。放进 composable 里就得拖起 vue 运行时,
* 或者干脆没人钉——而「把美元读成人民币」「把查不到显示成 ¥0」正是没人钉就会复发的形状。
*/
import type { UserLlmBalance } from '../api/types/modules/user-secret.ts'
/** 站内 ⚡=人民币口径;单位由服务端 `credits.unit` 判定,这里只负责加符号。 */
const YUAN = '¥'
function isFiniteNumber(value: number): boolean {
return Number.isFinite(value)
}
/**
* 人民币金额显示:保留两位小数。
*
* 上游给的是原样小数串(`88.888882`)——**四舍五入只发生在这里**,落库/传值都不提前取整,
* 否则账单对不上时没人能回溯当时到底是多少。解析不出数字时原样回显,不返回 `'¥0.00'`:
* 一格 0 会被读成「没钱了」,而真值可能只是上游换了写法。
*/
export function formatYuan(raw: string | null | undefined): string {
const text = (raw ?? '').trim()
if (!text) return ''
const value = Number(text.replace(/,/g, ''))
if (!isFiniteNumber(value)) return text
return `${YUAN}${value.toFixed(2)}`
}
/** 有数时的整行文案;可用/冻结按字段在不在追加(缺字段不补 0)。 */
export function llmBalanceText(item: UserLlmBalance | null | undefined): string {
if (!item || !item.available) return ''
const label = item.channelLabel || '该渠道'
const parts = [`总 ${formatYuan(item.balance) || '—'}`]
if (item.availableBalance) parts.push(`可用 ${formatYuan(item.availableBalance)}`)
if (item.frozen) parts.push(`冻结 ${formatYuan(item.frozen)}`)
return `${label}余额(人民币):${parts.join(' · ')}`
}
/**
* 没数时的诚实文案。
*
* 后端已经把原因说清了(渠道不支持/没配密钥/上游拒绝/超时),这里只补前缀、不改写;
* 已经以渠道名开头的话就不再叠一遍(免得读出「贞贞余额:贞贞渠道不提供余额查询」)。
* 兜底那句刻意说明「不是欠费、也不是不支持」——这一格空白最容易被读成没钱。
*
* `fallbackLabel` 只在整条 item 都没有时兜底(请求整个失败时,界面至少要说清这一行是谁的钱;
* 此时**不许**留着上一把 key 的数字,那是串档形状)。
*/
export function llmBalanceUnavailableText(
item: UserLlmBalance | null | undefined,
fallbackLabel = '',
): string {
const label = (item?.channelLabel || fallbackLabel || '该渠道').trim()
const reason = (item?.message ?? '').trim()
if (reason) return reason.startsWith(label) ? reason : `${label}余额:${reason}`
return `${label}余额这次没查到:接口没返回可用值(不是欠费,也不是不支持),可稍后重开设置页再看`
}
/** `checkedAt` 是 ISO 串:只取到分钟,给「这一格数是什么时候的」一个可核对的落点。 */
export function llmBalanceUpdatedAt(item: UserLlmBalance | null | undefined): string {
const raw = (item?.checkedAt ?? '').trim()
if (!raw) return ''
const parsed = new Date(raw)
if (Number.isNaN(parsed.getTime())) return ''
const pad = (value: number) => String(value).padStart(2, '0')
return `${pad(parsed.getHours())}:${pad(parsed.getMinutes())}`
}
@@ -58,7 +58,13 @@ const BASELINE = {
// interruptTaskRecord 包住中断请求,失败 ElMessage.error 当场报给用户、成功 ElMessage.success
// 并刷新看板——与 308 的 retryTaskRecord 同口径,不是吞错;两处 ElMessageBox.confirm 的
// 取消分支走 .then 两臂(确认框 reject 属正常交互),刻意不新增 catch 块。silent 一格没涨。
blocks: 311,
// 312 = 311 + 1(2026-11-05 B83 龙抬头余额进界面):useLlmBalance.ts 的 loadLlmBalance 包住
// 余额请求一支 try/catch。失败出口是**面板内那一行**(清空数字 ⇒ 渲染「这次没查到:接口没返回
// 可用值(不是欠费,也不是不支持)」),与代理余量同一口径;余额是打开面板时的附带读取,
// 弹全局打扰会把用户下一次正常操作也打断,所以刻意不 ElMessage。
// 按扫描器口径这一支不算静默(首条语句是状态写入、不是 console.*,console 只作留链),
// 所以 silent 一格没涨、逐文件台账不动,只进 blocks。
blocks: 312,
// 2026-10-30(ops Phase 6/可读棘轮):ApiSecretSettingsPanel.vue 1113→775 行,面板里那处
// 静默 catch(余额查询失败只 console.warn、界面留空)随 loadBalance 整块搬进
// useProxyPlan.ts。不是新增静默:面板 1→0、新文件记 1,silent 总数与 blocks 都一格没动,
+1
View File
@@ -319,6 +319,7 @@ test('test_endpoints_frozen_snapshot', () => {
"check": "/api/user-secrets/{moduleKey}/check",
"migrate": "/api/user-secrets/migrate",
"proxyBalance": "/api/user-secrets/proxy-balance",
"llmBalance": "/api/user-secrets/llm-balance",
"proxyPlan": "/api/user-secrets/proxy-plan",
"proxyWhitelist": "/api/user-secrets/proxy-whitelist",
"clientIp": "/api/user-secrets/client-ip"
+140
View File
@@ -0,0 +1,140 @@
/**
* LLM 余额显示口径的纯函数判据(B83:龙抬头余额要显示人民币)。
*
* 靶子是「两套口径挑了哪一套」:上游同一份响应里美元串与 ⚡(人民币)数字并存,
* 挑错那一套不会报错、只会安静地差 7.2 倍。所以除了正向读数,这里还钉两条反向的:
* ① 美元形状不许被渲染成 `¥…`;② 源码里不许出现汇率乘算(自己乘一次=自造一套口径)。
*
* 跑法:`cd crawler-plugin/frontend-vue && npm test`
*/
import test from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import {
formatYuan,
llmBalanceText,
llmBalanceUnavailableText,
llmBalanceUpdatedAt,
} from '../src/shared/utils/llm-balance-text.ts'
import type { UserLlmBalance } from '../src/shared/api/types/modules/user-secret.ts'
function item(over: Partial<UserLlmBalance> = {}): UserLlmBalance {
return {
moduleKey: 'appearance-patent',
moduleLabel: '外观专利密钥',
channel: 'longtaitou',
channelLabel: '龙抬头',
available: true,
balance: '88.888882',
availableBalance: '85.288882',
frozen: '3.6',
unit: 'CREDIT',
message: null,
checkedAt: '2026-11-05T10:30:00',
...over,
}
}
test('人民币读数只吃 credits 的数值并保留两位', () => {
assert.equal(formatYuan('88.888882'), '¥88.89')
assert.equal(formatYuan('0'), '¥0.00')
assert.equal(formatYuan(null), '')
assert.equal(formatYuan(''), '')
})
test('美元形状绝不渲染成人民币', () => {
// 顶层那串是美元:解析不出数字时原样回显,不套 ¥ 符号——套了就等于宣称它是人民币
assert.equal(formatYuan('$12.345678'), '$12.345678')
assert.ok(!formatYuan('$12.345678').startsWith('¥'))
})
test('有数时的整行读数带渠道、总额与可用', () => {
const text = llmBalanceText(item())
assert.match(text, /龙抬头余额(人民币)/)
assert.match(text, /¥88\.89/)
assert.match(text, /可用 ¥85\.29/)
assert.match(text, /冻结 ¥3\.60/)
// 美元那两个数一旦混进来,读数就会差 7.2 倍还看着正常
assert.ok(!text.includes('12.34'), `读数里不该出现美元串:${text}`)
assert.ok(!text.includes('11.84'), `读数里不该出现美元串:${text}`)
})
test('缺可用与冻结时不补零', () => {
const text = llmBalanceText(item({ availableBalance: null, frozen: null }))
assert.match(text, /总 ¥88\.89/)
assert.ok(!text.includes('可用 ¥0'), `缺字段不许读成 0:${text}`)
assert.ok(!text.includes('冻结 ¥0'), `缺字段不许读成 0:${text}`)
})
test('贞贞那一档说不提供查询,且一个金额都不给', () => {
const unsupported = item({
available: false,
channel: 't8star',
channelLabel: '贞贞',
balance: null,
availableBalance: null,
frozen: null,
unit: null,
message: '贞贞渠道不提供余额查询;用量请看 ai.t8star.org 自己的控制台。',
})
assert.equal(llmBalanceText(unsupported), '')
const text = llmBalanceUnavailableText(unsupported)
assert.match(text, /不提供余额查询/)
assert.ok(!text.includes('¥'), `查不到时不许出现金额:${text}`)
assert.ok(!text.includes('0.00'), `查不到不许读成欠费:${text}`)
})
test('后端没给原因时才兜底,且兜底句说明不是欠费', () => {
const text = llmBalanceUnavailableText(item({ available: false, message: null }))
assert.match(text, /龙抬头余额这次没查到/)
assert.match(text, /不是欠费/)
})
test('整格都没取到时用本地渠道名兜底(服务端连渠道都没回)', () => {
assert.match(llmBalanceUnavailableText(null, '贞贞'), /贞贞余额这次没查到/)
// item 在的时候一律以服务端回传的渠道名为准:库里那把 key 是哪家,钱就是哪家的
assert.match(llmBalanceUnavailableText(item({ available: false, message: '密钥失效' })), /龙抬头余额:密钥失效/)
})
test('原因已以渠道名开头时不叠第二遍前缀', () => {
const text = llmBalanceUnavailableText(item({
available: false, balance: null, message: '龙抬头没有返回人民币(⚡)口径的余额块',
}))
assert.equal(text, '龙抬头没有返回人民币(⚡)口径的余额块')
})
test('取数时刻只到分钟,脏值不显示', () => {
assert.equal(llmBalanceUpdatedAt(item()), '10:30')
assert.equal(llmBalanceUpdatedAt(item({ checkedAt: null })), '')
assert.equal(llmBalanceUpdatedAt(item({ checkedAt: '不是时间' })), '')
})
test('两张卡各回各的钱,不互串', () => {
const ap = llmBalanceText(item({ balance: '88.888882', availableBalance: '85.288882' }))
const sa = llmBalanceText(item({
moduleKey: 'similar-asin', balance: '12.5', availableBalance: '10', frozen: null,
}))
assert.match(ap, /¥88\.89/)
assert.match(sa, /¥12\.50/)
assert.ok(!sa.includes('88.89'), 'A 卡的数不许出现在 B 卡')
assert.ok(!ap.includes('12.50'), 'B 卡的数不许出现在 A 卡')
})
test('源码绊线:不许自己乘汇率,也不许在面板里再造一套余额判定', () => {
const read = (path: string) => readFileSync(
fileURLToPath(new URL(path, import.meta.url)), 'utf8',
)
const textModule = read('../src/shared/utils/llm-balance-text.ts')
const composable = read('../src/shared/composables/useLlmBalance.ts')
// 7.2 是上游 credits.per_usd 的当前值,把它写进代码=自造第二套口径(上游一改就静默错)
for (const source of [textModule, composable]) {
assert.doesNotMatch(source, /7\.2/, '余额换算必须只用 credits 块,不许出现汇率字面量')
assert.doesNotMatch(source, /perUsd|per_usd/, '前端不参与口径换算,per_usd 只该在后端判定')
}
// 三态判定只有一处:面板按 proxyMetaText/llmMetaText 走,组件不自己判
const row = read('../src/shared/components/SecretBalanceRow.vue')
assert.doesNotMatch(row, /available/, '行组件只渲染调用方算好的文案,不再判一次 available')
})
@@ -39,6 +39,7 @@ const store = vi.hoisted(() => ({
saveApiSecret: vi.fn(),
subscribeApiSecrets: vi.fn(),
fetchProxyBalanceSafely: vi.fn(),
fetchLlmBalanceSafely: vi.fn(),
}))
const secretApi = vi.hoisted(() => ({
putMyApiSecret: vi.fn(),
@@ -63,6 +64,7 @@ vi.mock('@/shared/utils/api-secret-store', () => ({
saveApiSecret: store.saveApiSecret,
subscribeApiSecrets: store.subscribeApiSecrets,
fetchProxyBalanceSafely: store.fetchProxyBalanceSafely,
fetchLlmBalanceSafely: store.fetchLlmBalanceSafely,
}))
vi.mock('@/shared/api/types/modules/user-secret', () => ({
putMyApiSecret: secretApi.putMyApiSecret,
@@ -169,6 +171,8 @@ beforeEach(() => {
store.fetchProxyBalanceSafely.mockResolvedValue({
available: true, surplus: '12', balance: '34', message: null, scope: 'user', low: false, lowReason: null,
})
// 本文件的靶子是掩码输入的显隐;LLM 余额回空数组即可,不参与任何断言
store.fetchLlmBalanceSafely.mockResolvedValue([])
secretApi.putMyApiSecret.mockResolvedValue({})
secretApi.fetchProxyPlan.mockResolvedValue({ planId: null, jikipUserId: null, configured: false })
bridge.readConfig.mockResolvedValue(qingguoConfig())
@@ -0,0 +1,290 @@
/**
* 密钥设置面板「余额行」的挂载用例(B83:龙抬头余额显示人民币,形状与代理余量统一)。
*
* 五组靶子:
* ① 两张 LLM 卡各有一行 `.secret-meta`(改回「余额只属于代理卡」即红);
* ② 龙抬头那一格给的是**人民币**读数(¥),且美元那两个数一个都不出现;
* ③ 贞贞那一格说「不提供余额查询」,一个金额都不给(不借别家的数、也不显示 0);
* ④ 两卡各回各的钱,交叉不串;代理卡余量文案在抽组件后**逐字未变**;
* ⑤ 刷新时机:只有读服务端已存密钥的那几次会刷;「检测输入值(未保存)」不刷(那时刷的是上一把 key 的钱)。
*
* ⚠ 用例里的数字一律假值,真实密钥与真实余额不得进任何跟踪件。
*
* 跑法:`npx vitest run tests/mount/密钥面板余额显示.mount.test.ts`
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import ApiSecretSettingsPanel from '@/shared/components/ApiSecretSettingsPanel.vue'
const UID = '1301'
const message = vi.hoisted(() => ({
error: vi.fn(),
warning: vi.fn(),
success: vi.fn(),
info: vi.fn(),
}))
const store = vi.hoisted(() => ({
checkApiSecret: vi.fn(),
clearApiSecret: vi.fn(),
getServerProxySnapshot: vi.fn(),
getStoredApiSecretSnapshot: vi.fn(),
listApiSecretModules: vi.fn(),
loadApiSecrets: vi.fn(),
saveApiSecret: vi.fn(),
subscribeApiSecrets: vi.fn(),
fetchProxyBalanceSafely: vi.fn(),
fetchLlmBalanceSafely: vi.fn(),
}))
const secretApi = vi.hoisted(() => ({
putMyApiSecret: vi.fn(),
deleteMyApiSecret: vi.fn(),
fetchProxyPlan: vi.fn(),
saveProxyPlan: vi.fn(),
clearProxyPlan: vi.fn(),
}))
const bridge = vi.hoisted(() => ({
readConfig: vi.fn(),
saveConfig: vi.fn(),
}))
vi.mock('element-plus', () => ({ ElMessage: message }))
vi.mock('@/shared/utils/api-secret-store', () => ({
checkApiSecret: store.checkApiSecret,
clearApiSecret: store.clearApiSecret,
getServerProxySnapshot: store.getServerProxySnapshot,
getStoredApiSecretSnapshot: store.getStoredApiSecretSnapshot,
listApiSecretModules: store.listApiSecretModules,
loadApiSecrets: store.loadApiSecrets,
saveApiSecret: store.saveApiSecret,
subscribeApiSecrets: store.subscribeApiSecrets,
fetchProxyBalanceSafely: store.fetchProxyBalanceSafely,
fetchLlmBalanceSafely: store.fetchLlmBalanceSafely,
}))
vi.mock('@/shared/api/types/modules/user-secret', () => ({
putMyApiSecret: secretApi.putMyApiSecret,
deleteMyApiSecret: secretApi.deleteMyApiSecret,
fetchProxyPlan: secretApi.fetchProxyPlan,
saveProxyPlan: secretApi.saveProxyPlan,
clearProxyPlan: secretApi.clearProxyPlan,
}))
vi.mock('@/shared/bridges/pywebview', () => ({
getPywebviewApi: () => ({ read_config: bridge.readConfig, save_config: bridge.saveConfig }),
}))
function emptySnapshot() {
return {
value: '', masked: '', channel: '', exists: false, locked: false,
checkStatus: 'unknown', checkCode: '', checkMessage: '',
checkLatencyMs: null, checkedAt: null, updatedAt: null,
}
}
function llmItem(over: Record<string, unknown> = {}) {
return {
moduleKey: 'appearance-patent',
moduleLabel: '外观专利密钥',
channel: 'longtaitou',
channelLabel: '龙抬头',
available: true,
balance: '88.888882',
availableBalance: '85.288882',
frozen: '3.6',
unit: 'CREDIT',
message: null,
checkedAt: '2026-11-05T10:30:00',
...over,
}
}
async function mountPanel() {
wrapper = mount(ApiSecretSettingsPanel)
await flushPromises()
await flushPromises()
return wrapper!
}
/** 前两张是 LLM 卡(按 modules 清单顺序),最后一张固定是代理卡。 */
function llmCards(panel: VueWrapper) {
return panel.findAll('.secret-card').slice(0, 2)
}
function proxyCard(panel: VueWrapper) {
const cards = panel.findAll('.secret-card')
return cards[cards.length - 1]
}
function cardByModule(panel: VueWrapper, moduleKey: string) {
const index = ['appearance-patent', 'similar-asin'].indexOf(moduleKey)
return llmCards(panel)[index]
}
beforeEach(() => {
localStorage.clear()
localStorage.setItem('uid', UID)
vi.clearAllMocks()
store.listApiSecretModules.mockReturnValue([
{ moduleKey: 'appearance-patent', moduleLabel: '外观专利密钥' },
{ moduleKey: 'similar-asin', moduleLabel: '货源查询密钥' },
])
store.getStoredApiSecretSnapshot.mockReturnValue(emptySnapshot())
store.getServerProxySnapshot.mockReturnValue(null)
store.subscribeApiSecrets.mockReturnValue(() => undefined)
store.loadApiSecrets.mockResolvedValue('complete')
store.checkApiSecret.mockResolvedValue({ moduleKey: 'appearance-patent', checkStatus: 'passed', checkCode: 'ok', checkMessage: '连通正常', checkLatencyMs: 120, checkedAt: null, viaProxy: false })
store.fetchProxyBalanceSafely.mockResolvedValue({
available: true, surplus: '12', balance: '34', message: null, scope: 'user', low: false, lowReason: null,
})
// AP=龙抬头有钱、SA=贞贞查不了:这正是现网两把密钥最常见的一有一无形状
store.fetchLlmBalanceSafely.mockResolvedValue([
llmItem(),
llmItem({
moduleKey: 'similar-asin', moduleLabel: '货源查询密钥',
channel: 't8star', channelLabel: '贞贞',
available: false, balance: null, availableBalance: null, frozen: null, unit: null,
message: '贞贞渠道不提供余额查询;用量请看 ai.t8star.org 自己的控制台。',
}),
])
bridge.readConfig.mockResolvedValue({ proxy_users: {} })
bridge.saveConfig.mockResolvedValue(undefined)
secretApi.putMyApiSecret.mockResolvedValue({})
secretApi.deleteMyApiSecret.mockResolvedValue({})
secretApi.fetchProxyPlan.mockResolvedValue({ planId: null, jikipUserId: null, configured: false })
secretApi.saveProxyPlan.mockResolvedValue({})
secretApi.clearProxyPlan.mockResolvedValue({})
})
let wrapper: VueWrapper | null = null
afterEach(() => {
wrapper?.unmount()
wrapper = null
})
describe('余额行落在两张 LLM 卡上', () => {
it('两张卡各有一行 secret-meta(余额不是代理卡的专属)', async () => {
const panel = await mountPanel()
expect(llmCards(panel)).toHaveLength(2)
for (const card of llmCards(panel)) {
expect(card.find('.secret-meta').exists(), 'LLM 卡必须有余额行').toBe(true)
}
})
it('龙抬头那一格给人民币读数,美元那两条数字一个都不出现', async () => {
const panel = await mountPanel()
const meta = cardByModule(panel, 'appearance-patent').find('.secret-meta').text()
expect(meta).toContain('龙抬头余额(人民币)')
expect(meta).toContain('¥88.89')
expect(meta).toContain('可用 ¥85.29')
expect(meta).toContain('更新于 10:30')
expect(meta, '美元串进了读数就是差 7.2 倍的假数').not.toContain('12.34')
expect(meta).not.toContain('$')
})
it('贞贞那一格说不提供查询,且一个金额都不给', async () => {
const panel = await mountPanel()
const meta = cardByModule(panel, 'similar-asin').find('.secret-meta').text()
expect(meta).toContain('不提供余额查询')
expect(meta).not.toContain('¥')
expect(meta, '查不到不许读成欠费').not.toContain('0.00')
})
it('两卡各回各的钱,A 的数字不许出现在 B 行', async () => {
store.fetchLlmBalanceSafely.mockResolvedValue([
llmItem({ balance: '88.888882', availableBalance: '85.288882' }),
llmItem({
moduleKey: 'similar-asin', moduleLabel: '货源查询密钥',
balance: '12.5', availableBalance: '10', frozen: null,
}),
])
const panel = await mountPanel()
expect(cardByModule(panel, 'appearance-patent').find('.secret-meta').text()).toContain('¥88.89')
expect(cardByModule(panel, 'similar-asin').find('.secret-meta').text()).toContain('¥12.50')
expect(cardByModule(panel, 'similar-asin').find('.secret-meta').text()).not.toContain('88.89')
})
it('抽组件之后代理余量那一行逐字未变', async () => {
const panel = await mountPanel()
// 本夹具的本机配置没有青果账密 ⇒ 供应商走默认的极客(`密钥面板青果检测` 那份才是青果形状)
expect(proxyCard(panel).find('.secret-meta').text()).toContain('极客余量(你的套餐)')
expect(proxyCard(panel).find('.secret-meta').text()).toContain('套餐IP 12')
})
})
describe('刷新时机:只读服务端已存密钥的那几次', () => {
it('打开面板刷一次,两张卡一起要(不带 moduleKey)', async () => {
await mountPanel()
expect(store.fetchLlmBalanceSafely).toHaveBeenCalledTimes(1)
expect(store.fetchLlmBalanceSafely).toHaveBeenCalledWith(undefined)
})
it('浏览器形态(showProxy=false)也要刷——余额不属代理卡', async () => {
const panel = mount(ApiSecretSettingsPanel, { props: { showProxy: false } })
await flushPromises()
await flushPromises()
expect(store.fetchLlmBalanceSafely).toHaveBeenCalledTimes(1)
expect(llmCards(panel)[0].find('.secret-meta').text()).toContain('龙抬头余额')
})
it('点某一格的刷新只刷那一格(带 moduleKey,不动另一格)', async () => {
const panel = await mountPanel()
store.fetchLlmBalanceSafely.mockClear()
await cardByModule(panel, 'similar-asin').find('.meta-refresh').trigger('click')
await flushPromises()
expect(store.fetchLlmBalanceSafely).toHaveBeenCalledTimes(1)
expect(store.fetchLlmBalanceSafely).toHaveBeenCalledWith('similar-asin')
})
it('检测输入值(未保存)不刷余额:那时库里还是上一把 key', async () => {
const panel = await mountPanel()
const card = cardByModule(panel, 'appearance-patent')
await card.find('.secret-input').setValue('sk-刚粘贴还没保存')
await flushPromises()
store.fetchLlmBalanceSafely.mockClear()
await card.find('.check-btn').trigger('click')
await flushPromises()
await flushPromises()
expect(store.checkApiSecret).toHaveBeenCalledWith('appearance-patent', 'sk-刚粘贴还没保存', expect.anything())
expect(store.fetchLlmBalanceSafely, '刷了就是拿上一把 key 的钱挂在这一行').not.toHaveBeenCalled()
})
it('检测配置密钥(已存值)顺带刷那一格', async () => {
const panel = await mountPanel()
const card = cardByModule(panel, 'appearance-patent')
store.fetchLlmBalanceSafely.mockClear()
await card.find('.check-btn').trigger('click')
await flushPromises()
await flushPromises()
expect(store.checkApiSecret).toHaveBeenCalledWith('appearance-patent', undefined, expect.anything())
expect(store.fetchLlmBalanceSafely).toHaveBeenCalledTimes(1)
expect(store.fetchLlmBalanceSafely).toHaveBeenCalledWith('appearance-patent')
})
it('接口整个失败时清空数字、只留「没查到」(不许留着上一把 key 的钱)', async () => {
store.fetchLlmBalanceSafely.mockResolvedValue([llmItem()])
const panel = await mountPanel()
expect(cardByModule(panel, 'appearance-patent').find('.secret-meta').text()).toContain('¥88.89')
store.fetchLlmBalanceSafely.mockRejectedValue(new Error('网络断了'))
await cardByModule(panel, 'appearance-patent').find('.meta-refresh').trigger('click')
await flushPromises()
const meta = cardByModule(panel, 'appearance-patent').find('.secret-meta').text()
expect(meta).not.toContain('88.89')
expect(meta).toContain('没查到')
})
})
@@ -42,6 +42,7 @@ const store = vi.hoisted(() => ({
saveApiSecret: vi.fn(),
subscribeApiSecrets: vi.fn(),
fetchProxyBalanceSafely: vi.fn(),
fetchLlmBalanceSafely: vi.fn(),
}))
const secretApi = vi.hoisted(() => ({
putMyApiSecret: vi.fn(),
@@ -66,6 +67,7 @@ vi.mock('@/shared/utils/api-secret-store', () => ({
saveApiSecret: store.saveApiSecret,
subscribeApiSecrets: store.subscribeApiSecrets,
fetchProxyBalanceSafely: store.fetchProxyBalanceSafely,
fetchLlmBalanceSafely: store.fetchLlmBalanceSafely,
}))
vi.mock('@/shared/api/types/modules/user-secret', () => ({
putMyApiSecret: secretApi.putMyApiSecret,
@@ -148,6 +150,8 @@ beforeEach(() => {
store.fetchProxyBalanceSafely.mockResolvedValue({
available: true, surplus: '12', balance: '34', message: null, scope: 'user', low: false, lowReason: null,
})
// 本文件的靶子是代理那一张卡;LLM 余额回空数组即可(面板按「没查到」显示,不参与这里的任何断言)
store.fetchLlmBalanceSafely.mockResolvedValue([])
secretApi.fetchProxyPlan.mockResolvedValue({ planId: null, jikipUserId: null, configured: false })
bridge.readConfig.mockResolvedValue(qingguoConfig())
bridge.saveConfig.mockResolvedValue(undefined)