fix(appearance-patent): 代理缺失回填与任务前置提示
- 本地代理回填兼容旧版全局 proxy_url,补报成功后重拉服务端快照 - 创建任务前检查服务端代理,缺失时弹窗拦截并引导配置 - 商标查询失败的真实原因写入结果原因列,不再只显示查询失败
This commit is contained in:
+7
-1
@@ -1156,7 +1156,13 @@ public class AppearancePatentLlmClient {
|
||||
row.setPatentRisk(result.patent());
|
||||
row.setConclusion(buildConclusion(row.getTitleRisk(), row.getAppearanceRisk(), result.result()));
|
||||
row.setStatus(result.status());
|
||||
row.setTitleReason(result.titleReason());
|
||||
// 商标查询失败时把上游给的真实原因(如「用户未配置代理」「品牌检测服务不可达」)
|
||||
// 落进「原因」sheet:只写「商标查询失败」时,用户和运维都看不出该去配代理还是等上游恢复。
|
||||
String titleReason = result.titleReason();
|
||||
if ((titleReason == null || titleReason.isBlank()) && isBrandQueryFailed(row.getTitleRisk())) {
|
||||
titleReason = brandCheck == null ? "" : brandCheck.reason();
|
||||
}
|
||||
row.setTitleReason(titleReason);
|
||||
row.setAppearanceReason(result.appearanceReason());
|
||||
row.setPatentReason(result.patentReason());
|
||||
row.setScore(result.score());
|
||||
|
||||
+30
@@ -78,6 +78,36 @@ class AppearancePatentBrandBatchTest {
|
||||
assertThat(merged.get(1).getTitleRisk()).as("干净行不得继承别行的侵权词").isEqualTo("无侵权");
|
||||
}
|
||||
|
||||
/**
|
||||
* 商标查询失败时,上游给的真实原因要落进行级原因,不能只留一句「商标查询失败」。
|
||||
* 2026-10-25 账号 1210 的 32300/32309 整批就是这个形状:服务端缺代理,
|
||||
* 交付表上每行只有「商标查询失败」,用户和运维都看不出该去配代理。
|
||||
*/
|
||||
@Test
|
||||
void brandQueryFailureReasonIsKeptForTheResult() throws Exception {
|
||||
when(brandCheckClient.checkTitleTexts(anyList(), eq("Terms"), any())).thenAnswer(invocation -> {
|
||||
List<String> titles = invocation.getArgument(0);
|
||||
List<BrandCheckClient.BrandCheckBatchResult> results = new ArrayList<>();
|
||||
for (String title : titles) {
|
||||
results.add(new BrandCheckClient.BrandCheckBatchResult(
|
||||
List.of(title), List.of(), List.of(title), "用户未配置代理"));
|
||||
}
|
||||
return results;
|
||||
});
|
||||
List<AppearancePatentResultRowDto> rows = List.of(row("1"));
|
||||
String dataText = """
|
||||
{"data":[{"row_id":"1","title":"小米","appearance":"无侵权","result":"无侵权"}]}
|
||||
""";
|
||||
|
||||
List<AppearancePatentResultRowDto> merged = client.mergeRowsFromDataText(rows, dataText);
|
||||
|
||||
assertThat(merged.get(0).getTitleRisk()).startsWith("商标查询失败");
|
||||
assertThat(merged.get(0).getConclusion()).isEqualTo("外观无侵权·商标待复核");
|
||||
assertThat(merged.get(0).getTitleReason())
|
||||
.as("原因列要能直接告诉用户/运维缺的是代理")
|
||||
.isEqualTo("用户未配置代理");
|
||||
}
|
||||
|
||||
@Test
|
||||
void batchWithNothingToCheckSendsNoBrandQueryAtAll() throws Exception {
|
||||
List<AppearancePatentResultRowDto> rows = List.of(row("1"));
|
||||
|
||||
@@ -73,7 +73,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||
import { userNotice } from '@/shared/utils/user-notice'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
|
||||
import FileUploadZone from '@/shared/components/FileUploadZone.vue'
|
||||
import ModuleTemplateDownload from '@/shared/components/ModuleTemplateDownload.vue'
|
||||
@@ -105,7 +105,7 @@ import { checkParseResult } from '@/shared/dispatch-guard'
|
||||
import { passGuard } from '@/shared/dispatch-guard-ui'
|
||||
import { formatDateTime } from '@/shared/utils/datetime'
|
||||
import { resultBuildFailed, taskStatusClass, taskStatusText } from '@/shared/utils/task-status-text'
|
||||
import { getStoredApiSecret } from '@/shared/utils/api-secret-store'
|
||||
import { ensureBrandCheckProxy, getStoredApiSecret } from '@/shared/utils/api-secret-store'
|
||||
|
||||
// ---- 文件选择 / 上传(公共组合式函数)----
|
||||
const {
|
||||
@@ -392,6 +392,26 @@ function toTaskSummary(result: AppearancePatentParseVo): TaskSummary {
|
||||
* 逐行抓取用例钉住:maixiang_run_task/test/maixiang_ops/test_proxy_cost_leaks.py。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 创建任务前确认服务端有代理:商标维度依赖服务端代理,缺代理时整批都会落成
|
||||
* 「商标查询失败」且状态为失败。服务端读不到(unknown)不拦,避免网络抖动误伤。
|
||||
*/
|
||||
async function ensureBrandCheckProxyReady(): Promise<boolean> {
|
||||
const check = await ensureBrandCheckProxy()
|
||||
if (check.ok) return true
|
||||
await ElMessageBox.alert(
|
||||
'当前账号未在服务端配置代理,商标维度将无法查询,整批结果会显示「商标查询失败」。'
|
||||
+ '请先点击右上角「密钥设置」,在「代理地址」中保存代理后再创建任务。',
|
||||
'未配置代理,无法检测商标',
|
||||
{ type: 'warning', confirmButtonText: '知道了' },
|
||||
).then(
|
||||
// 关闭弹窗会以 reject 收尾,属正常交互而不是错误,不新增 catch 块
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
)
|
||||
return false
|
||||
}
|
||||
|
||||
async function parseFiles() {
|
||||
if (!uploadedFiles.value.length) {
|
||||
ElMessage.warning('请先选择 Excel')
|
||||
@@ -403,6 +423,9 @@ async function parseFiles() {
|
||||
}
|
||||
parsing.value = true
|
||||
try {
|
||||
if (!(await ensureBrandCheckProxyReady())) {
|
||||
return
|
||||
}
|
||||
const files: UploadedFileRef[] = uploadedFiles.value.map((f) => ({
|
||||
fileKey: f.fileKey,
|
||||
originalFilename: f.originalFilename,
|
||||
|
||||
@@ -442,15 +442,16 @@ function proxyUserId() {
|
||||
}
|
||||
|
||||
/** 代理地址按登录用户隔离:proxy_users[uid],各自计费各自复用;
|
||||
* 未登录(uid=0)回退全局 proxy_url(兼容旧版本已保存的配置)。 */
|
||||
* 用户项为空(含老版本只存了全局 proxy_url 的账号)回退全局,口径与客户端任务链
|
||||
* `resolve_current_proxy` 一致——否则这些账号的代理既显示不出来,也补报不到服务端。 */
|
||||
function readUserProxy(config: Record<string, unknown> | null | undefined) {
|
||||
const uid = proxyUserId()
|
||||
if (uid !== '0') {
|
||||
const users = (config?.proxy_users ?? {}) as Record<string, unknown>
|
||||
const own = (users[uid] ?? {}) as Record<string, unknown>
|
||||
return {
|
||||
url: typeof own.proxy_url === 'string' ? own.proxy_url : '',
|
||||
mode: Number(own.proxy_mode) === 2 ? 2 : 1,
|
||||
const ownUrl = typeof own.proxy_url === 'string' ? own.proxy_url.trim() : ''
|
||||
if (ownUrl) {
|
||||
return { url: ownUrl, mode: Number(own.proxy_mode) === 2 ? 2 : 1 }
|
||||
}
|
||||
}
|
||||
return {
|
||||
|
||||
@@ -54,6 +54,12 @@ export interface ServerProxySnapshot extends ApiSecretSnapshot {
|
||||
full: string
|
||||
}
|
||||
|
||||
/** 商标检测前置代理检查结果:unknown 表示服务端读不到,按软失败放行(与密钥门禁同口径)。 */
|
||||
export interface BrandCheckProxyStatus {
|
||||
ok: boolean
|
||||
state: 'server' | 'missing' | 'unknown'
|
||||
}
|
||||
|
||||
interface ApiSecretCacheEntry extends ApiSecretSnapshot {
|
||||
schema: 2
|
||||
}
|
||||
@@ -327,6 +333,22 @@ export function getServerProxySnapshot(): ServerProxySnapshot | null {
|
||||
return serverProxy
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建商标检测任务前的代理检查:服务端没有代理时先尝试把本地代理补报上去,
|
||||
* 仍没有就返回 missing 交给页面弹窗拦截。服务端读不到(unknown)不拦——
|
||||
* 那种情况下任务创建本身会报错,不能把网络抖动误判成"未配置代理"。
|
||||
*/
|
||||
export async function ensureBrandCheckProxy(): Promise<BrandCheckProxyStatus> {
|
||||
const state = await loadApiSecrets({ force: true })
|
||||
if (getServerProxySnapshot()?.exists) {
|
||||
return { ok: true, state: 'server' }
|
||||
}
|
||||
if (state === 'unknown') {
|
||||
return { ok: true, state: 'unknown' }
|
||||
}
|
||||
return { ok: false, state: 'missing' }
|
||||
}
|
||||
|
||||
export function subscribeApiSecrets(listener: () => void): () => void {
|
||||
listeners.add(listener)
|
||||
return () => {
|
||||
@@ -391,7 +413,14 @@ async function doLoad(): Promise<ApiSecretLoadState> {
|
||||
}
|
||||
notify()
|
||||
}
|
||||
await tryBackfillProxyToServer()
|
||||
const backfilled = await tryBackfillProxyToServer()
|
||||
if (backfilled) {
|
||||
// 补报已写入服务端:重拉一次让 serverProxy 反映新状态,
|
||||
// 否则任务提交前的代理检查会拿到上一轮的空快照。
|
||||
const refreshed = await fetchMyApiSecrets()
|
||||
serverProxy = toServerProxy(refreshed?.proxy)
|
||||
notify()
|
||||
}
|
||||
return computeApiSecretsComplete() ? 'complete' : 'incomplete'
|
||||
} catch (error) {
|
||||
console.warn('[api-secret] 服务端密钥拉取失败,本次按未知处理(不阻断使用):', error)
|
||||
@@ -440,33 +469,60 @@ async function tryMigrateLocalSecrets(serverItems: UserApiSecretItem[]): Promise
|
||||
|
||||
/**
|
||||
* 本地代理配置补报服务端(只写空缺、不覆盖;后台密钥管理观测/检测用)。
|
||||
* 非桌面环境、未登录、无本地代理时静默跳过;失败静默,下次加载重试。
|
||||
* 桥模块动态导入:node 测试环境不触发(currentUid 为 0 时直接返回),避免加载浏览器侧依赖。
|
||||
* 未登录、无本地代理时静默跳过;失败静默,下次加载重试。
|
||||
*
|
||||
* @returns 是否真的补报了一条(migrated > 0);调用方据此决定要不要重拉服务端快照。
|
||||
*/
|
||||
async function tryBackfillProxyToServer(): Promise<void> {
|
||||
async function tryBackfillProxyToServer(): Promise<boolean> {
|
||||
try {
|
||||
if (currentUid() === '0') return
|
||||
const { getPywebviewApi } = await import('../bridges/pywebview.ts')
|
||||
const api = getPywebviewApi()
|
||||
if (!api?.read_config) return
|
||||
const config = (await api.read_config()) as Record<string, unknown> | null
|
||||
if (currentUid() === '0') return false
|
||||
const config = await readConfigForBackfill()
|
||||
if (!config) return false
|
||||
const url = readLocalProxyUrl(config)
|
||||
if (!url) return
|
||||
await migrateMyApiSecrets([{ moduleKey: 'proxy', value: url }])
|
||||
if (!url) return false
|
||||
const result = await migrateMyApiSecrets([{ moduleKey: 'proxy', value: url }])
|
||||
return Number(result?.migrated || 0) > 0
|
||||
} catch (error) {
|
||||
console.warn('[api-secret] 代理配置补报失败(下次加载重试):', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** 读取当前登录用户的本地代理地址:proxy_users[uid] 优先,未登录回退全局 proxy_url。 */
|
||||
/**
|
||||
* 读代理补报所需的本地配置:桌面真实桥优先(与 syncLockedProxyToLocal 同口径),
|
||||
* 纯浏览器再走降级桥。静态 import 会把 web-fallback 的 @ 别名依赖拖进 node 用例,
|
||||
* 所以降级那条只在需要时才动态加载。
|
||||
*/
|
||||
async function readConfigForBackfill(): Promise<Record<string, unknown> | null> {
|
||||
if (typeof window === 'undefined') return null
|
||||
const direct = window.pywebview?.api
|
||||
if (direct?.read_config) {
|
||||
return (await direct.read_config()) as Record<string, unknown> | null
|
||||
}
|
||||
// 无 DOM 的 node 用例不是浏览器环境:降级桥模块带着 @ 别名依赖,加载只会留下噪声报错
|
||||
if (typeof document === 'undefined') return null
|
||||
const { getPywebviewApi } = await import('../bridges/pywebview.ts')
|
||||
const api = getPywebviewApi()
|
||||
if (!api?.read_config) return null
|
||||
return (await api.read_config()) as Record<string, unknown> | null
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取当前登录用户的本地代理地址:proxy_users[uid] 优先,用户项为空时回退全局 proxy_url。
|
||||
* 回退口径与客户端任务链 `resolve_current_proxy` 一致——老版本把代理存在全局 proxy_url,
|
||||
* 若这里只认 proxy_users[uid],这些账号的代理永远补报不到服务端,外观专利任务会在
|
||||
* 商标维度整批判失败(2026-10-25 账号 1210 的 32300/32309 就是这么来的)。
|
||||
*/
|
||||
function readLocalProxyUrl(config: Record<string, unknown> | null | undefined): string {
|
||||
if (!config) return ''
|
||||
const uid = currentUid()
|
||||
if (uid !== '0') {
|
||||
const users = (config?.proxy_users ?? {}) as Record<string, unknown>
|
||||
const users = (config.proxy_users ?? {}) as Record<string, unknown>
|
||||
const own = (users[uid] ?? {}) as Record<string, unknown>
|
||||
return typeof own.proxy_url === 'string' ? own.proxy_url.trim() : ''
|
||||
const ownUrl = typeof own.proxy_url === 'string' ? own.proxy_url.trim() : ''
|
||||
if (ownUrl) return ownUrl
|
||||
}
|
||||
return typeof config?.proxy_url === 'string' ? config.proxy_url.trim() : ''
|
||||
return typeof config.proxy_url === 'string' ? config.proxy_url.trim() : ''
|
||||
}
|
||||
|
||||
function toServerProxy(proxy: UserApiSecretItem | null | undefined): ServerProxySnapshot | null {
|
||||
|
||||
@@ -43,3 +43,16 @@ test('test_failed_hint_marks_task_failed_and_download_later', () => {
|
||||
assert.match(body, /'FAILED'\s*\?\s*'任务已失败'/, '提示文案应按 FAILED 切换为任务已失败')
|
||||
assert.match(body, /下载按钮稍后出现/, '失败后仍提示结果文件生成后会给出下载按钮')
|
||||
})
|
||||
|
||||
// 服务端缺代理时商标维度整批失败,必须在创建任务前弹窗拦截(2026-10-25 32300/32309)。
|
||||
test('test_missing_proxy_blocks_task_creation_with_popup', () => {
|
||||
const parseBody = functionBody('parseFiles')
|
||||
const guardIdx = parseBody.indexOf('ensureBrandCheckProxyReady')
|
||||
const createIdx = parseBody.indexOf('parseAppearancePatent(')
|
||||
assert.ok(guardIdx >= 0, 'parseFiles 必须先做服务端代理检查')
|
||||
assert.ok(createIdx > guardIdx, '代理检查必须发生在创建任务之前')
|
||||
|
||||
const guardBody = functionBody('ensureBrandCheckProxyReady')
|
||||
assert.match(guardBody, /ElMessageBox\.alert/, '缺代理时应弹窗提示,不能只 console.warn')
|
||||
assert.match(guardBody, /密钥设置/, '弹窗要告诉用户去哪里补代理')
|
||||
})
|
||||
|
||||
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict'
|
||||
import { http } from '../src/shared/api/http.ts'
|
||||
import {
|
||||
clearApiSecretCache,
|
||||
ensureBrandCheckProxy,
|
||||
getServerProxySnapshot,
|
||||
getStoredApiSecret,
|
||||
getStoredApiSecretSnapshot,
|
||||
@@ -191,6 +192,93 @@ test('test_secret_store_locked_proxy_aligns_local_config_once', async (t) => {
|
||||
assert.equal(saveCalls.length, 1, '本地配置已一致时不应重复写入')
|
||||
})
|
||||
|
||||
test('test_secret_store_backfills_legacy_global_proxy_to_server', async (t) => {
|
||||
setupWindow()
|
||||
clearApiSecretCache()
|
||||
const globalUrl = 'https://api.jikip.com/ip-get?num=2&key=legacy'
|
||||
const migratePayloads: Array<{ items?: Array<{ moduleKey?: string; value?: string }> }> = []
|
||||
let bundleCalls = 0
|
||||
// 老版本只把代理存在全局 proxy_url,proxy_users 里没有该用户
|
||||
attachDesktopBridge(() => ({ proxy_url: globalUrl, proxy_mode: 2 }), (patch) => patch)
|
||||
mockRequest(t, (req) => {
|
||||
if ((req.url || '').includes('/migrate')) {
|
||||
migratePayloads.push(req.data as { items?: Array<{ moduleKey?: string; value?: string }> })
|
||||
return okResponse({ migrated: 1 })
|
||||
}
|
||||
bundleCalls += 1
|
||||
return okResponse({
|
||||
items: [serverItem('appearance-patent'), serverItem('similar-asin')],
|
||||
requiredModules: ['appearance-patent', 'similar-asin'],
|
||||
complete: false,
|
||||
// 补报前无代理;补报后服务端有了代理
|
||||
proxy: bundleCalls > 1
|
||||
? { ...serverItem('proxy'), exists: true, masked: 'https://api.jikip.com' }
|
||||
: undefined,
|
||||
})
|
||||
})
|
||||
|
||||
await loadApiSecrets({ force: true })
|
||||
|
||||
const proxyMigrate = migratePayloads
|
||||
.flatMap((payload) => payload.items || [])
|
||||
.find((item) => item.moduleKey === 'proxy')
|
||||
assert.equal(proxyMigrate?.value, globalUrl, '旧版全局代理应补报到服务端')
|
||||
assert.equal(getServerProxySnapshot()?.exists, true, '补报后应重拉服务端代理快照')
|
||||
})
|
||||
|
||||
test('test_secret_store_user_proxy_wins_over_legacy_global', async (t) => {
|
||||
setupWindow()
|
||||
clearApiSecretCache()
|
||||
const userUrl = 'https://api.jikip.com/ip-get?num=1&key=user'
|
||||
const globalUrl = 'https://api.jikip.com/ip-get?num=2&key=global'
|
||||
const migratePayloads: Array<{ items?: Array<{ moduleKey?: string; value?: string }> }> = []
|
||||
attachDesktopBridge(
|
||||
() => ({ proxy_users: { '42': { proxy_url: userUrl, proxy_mode: 1 } }, proxy_url: globalUrl, proxy_mode: 2 }),
|
||||
(patch) => patch,
|
||||
)
|
||||
mockRequest(t, (req) => {
|
||||
if ((req.url || '').includes('/migrate')) {
|
||||
migratePayloads.push(req.data as { items?: Array<{ moduleKey?: string; value?: string }> })
|
||||
return okResponse({ migrated: 1 })
|
||||
}
|
||||
return bundleResponse([serverItem('appearance-patent'), serverItem('similar-asin')])
|
||||
})
|
||||
|
||||
await loadApiSecrets({ force: true })
|
||||
|
||||
const proxyMigrate = migratePayloads
|
||||
.flatMap((payload) => payload.items || [])
|
||||
.find((item) => item.moduleKey === 'proxy')
|
||||
assert.equal(proxyMigrate?.value, userUrl, '用户自己的代理优先于旧版全局代理')
|
||||
})
|
||||
|
||||
test('test_secret_store_brand_check_proxy_missing_is_visible', async (t) => {
|
||||
setupWindow()
|
||||
clearApiSecretCache()
|
||||
mockRequest(t, () => bundleResponse([serverItem('appearance-patent'), serverItem('similar-asin')]))
|
||||
|
||||
const result = await ensureBrandCheckProxy()
|
||||
|
||||
assert.deepEqual(result, { ok: false, state: 'missing' })
|
||||
})
|
||||
|
||||
test('test_secret_store_brand_check_proxy_present_passes', async (t) => {
|
||||
setupWindow()
|
||||
clearApiSecretCache()
|
||||
mockRequest(t, () =>
|
||||
okResponse({
|
||||
items: [serverItem('appearance-patent'), serverItem('similar-asin')],
|
||||
requiredModules: ['appearance-patent', 'similar-asin'],
|
||||
complete: false,
|
||||
proxy: { ...serverItem('proxy'), exists: true, masked: 'https://api.jikip.com' },
|
||||
}),
|
||||
)
|
||||
|
||||
const result = await ensureBrandCheckProxy()
|
||||
|
||||
assert.deepEqual(result, { ok: true, state: 'server' })
|
||||
})
|
||||
|
||||
test('test_secret_store_locked_proxy_not_in_module_cards', async (t) => {
|
||||
setupWindow()
|
||||
clearApiSecretCache()
|
||||
|
||||
Reference in New Issue
Block a user