Compare commits
3 Commits
f47d55319f
...
9843b66180
| Author | SHA1 | Date | |
|---|---|---|---|
| 9843b66180 | |||
| 0bf21b84f0 | |||
| 9ecc9f30fb |
@@ -1,4 +1,5 @@
|
||||
/** API 响应解包与错误归一化(任务 22):纯函数,无框架依赖(只借 config/app 的 base 常量)。 */
|
||||
import { userNotice } from './user-notice.ts'
|
||||
import { joinAdminPath } from '../config/app.ts'
|
||||
|
||||
export const REQUEST_FALLBACK_MESSAGE = '网络异常,请稍后重试'
|
||||
@@ -6,8 +7,8 @@ export const REQUEST_FALLBACK_MESSAGE = '网络异常,请稍后重试'
|
||||
function textOf(value: Record<string, unknown>): string {
|
||||
const message = value.message
|
||||
const error = value.error
|
||||
if (typeof message === 'string' && message.trim()) return message.trim()
|
||||
if (typeof error === 'string' && error.trim()) return error.trim()
|
||||
if (typeof message === 'string' && message.trim()) return userNotice(message)
|
||||
if (typeof error === 'string' && error.trim()) return userNotice(error)
|
||||
return ''
|
||||
}
|
||||
|
||||
@@ -31,12 +32,12 @@ export function unwrap<T>(payload: unknown): T {
|
||||
|
||||
/** 从任意负载取错误文案;缺省回退。 */
|
||||
export function errorTextOf(payload: unknown): string {
|
||||
if (payload instanceof Error) return payload.message.trim() || REQUEST_FALLBACK_MESSAGE
|
||||
if (payload instanceof Error) return userNotice(payload.message, REQUEST_FALLBACK_MESSAGE)
|
||||
if (payload && typeof payload === 'object') {
|
||||
const text = textOf(payload as Record<string, unknown>)
|
||||
if (text) return text
|
||||
}
|
||||
if (typeof payload === 'string' && payload.trim()) return payload.trim()
|
||||
if (typeof payload === 'string' && payload.trim()) return payload
|
||||
return REQUEST_FALLBACK_MESSAGE
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* 后台提示语把关(2026-10-09):只把中文给用户看。
|
||||
*
|
||||
* Java 侧仍有出口把底层异常原文写进 message/errorMessage,后台同学看到
|
||||
* `Invalid export date range` 这类句子既看不懂也没法转述给用户。这里统一换成中文兜底句,
|
||||
* 原文进 console 供对着日志核对。
|
||||
*/
|
||||
|
||||
const CJK = /[\u3400-\u4dbf\u4e00-\u9fff]/
|
||||
|
||||
export const NOTICE_FALLBACK = '操作未能完成,请稍后重试'
|
||||
|
||||
export function userNotice(text?: string | null, fallback: string = NOTICE_FALLBACK): string {
|
||||
const raw = typeof text === 'string' ? text.trim() : ''
|
||||
if (!raw) {
|
||||
return fallback
|
||||
}
|
||||
if (!CJK.test(raw)) {
|
||||
console.warn('[user-notice] 提示语原文不是中文,已换成中文兜底句,原文:', raw)
|
||||
return fallback
|
||||
}
|
||||
// 中文主干 + 英文尾巴(后端把底层异常原文拼在冒号后):留主干,尾巴只进 console
|
||||
const at = Math.max(raw.lastIndexOf(':'), raw.lastIndexOf(':'))
|
||||
if (at > 0 && !CJK.test(raw.slice(at + 1))) {
|
||||
const head = raw.slice(0, at).trim()
|
||||
if (CJK.test(head)) {
|
||||
console.warn('[user-notice] 提示语尾巴是英文,已隐去,原文:', raw)
|
||||
return head
|
||||
}
|
||||
}
|
||||
return raw
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
* 页签二「变体采集」= 麦象批量任务(variant-collection),数据口径与列不同故独立页签。
|
||||
* 30s 轮询:页面隐藏暂停、回前台立即刷新、卸载清理;另有手动刷新。 */
|
||||
import { computed, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
|
||||
import { userNotice } from '@/api/user-notice'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||
@@ -579,7 +580,7 @@ onUnmounted(() => {
|
||||
</template>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="当前处理">{{ currentScopeOf(detail) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="错误信息" :span="2">{{ detail.errorMessage || detail.message || '—' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="错误信息" :span="2">{{ userNotice(detail.errorMessage || detail.message, '—') }}</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
|
||||
<h4 class="detail-title">分组明细({{ (detail.shops || []).length }} 组)</h4>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { formatDateTime } from '@/utils/datetime'
|
||||
import { userNotice } from '@/api/user-notice'
|
||||
/** 视频任务记录页 · 像素复刻旧版 admin.html panel-image-video-tasks(自绘:form-box 筛选[用户名/提交起止+查询/重置] + panel-box toolbar[全选/批量下载/权限配置/汇总] + 任务卡片网格 + 旧式分页)。
|
||||
* script 逻辑沿用现有 Vue 实现(批量打包/明细抽屉/权限授权)。 */
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
@@ -394,7 +395,7 @@ onMounted(load)
|
||||
<el-descriptions-item label="提交时间">{{ formatDateTime(detail.submittedAt) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="生成时间">{{ formatDateTime(imageVideoGeneratedAt(detail)) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="执行ID">{{ detail.cozeExecuteId || '—' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="错误">{{ detail.errorMessage || '—' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="错误">{{ userNotice(detail.errorMessage, '—') }}</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
{
|
||||
"note": "readSource 钉子逐文件基线。两把尺子:pins=落在用例体内的读盘,reads=全文读点总数(含模块级夹具与 helper)。都只许减;pins 下降而 reads 没同步下降=把读盘挪出体内,不算改进。由 tests/source-pin-ratchet.test.ts 生成。",
|
||||
"totals": {
|
||||
"files": 237,
|
||||
"cases": 1703,
|
||||
"files": 238,
|
||||
"cases": 1707,
|
||||
"pins": 436,
|
||||
"reads": 620
|
||||
"reads": 621
|
||||
},
|
||||
"files": {
|
||||
"admin-scaffold.test.ts": {
|
||||
@@ -1191,6 +1191,11 @@
|
||||
"cases": 7,
|
||||
"pins": 2,
|
||||
"reads": 2
|
||||
},
|
||||
"user-notice-chinese-only.test.ts": {
|
||||
"cases": 4,
|
||||
"pins": 0,
|
||||
"reads": 1
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,7 +48,9 @@ test('test_task_022_envelope_rules_boundary_limit_or_missing_field', () => {
|
||||
// 边界上限/缺字段:success=false 且 message 缺失回落到通用失败。
|
||||
assert.throws(() => unwrap({ success: false }), /请求失败/)
|
||||
assert.equal(errorTextOf({ error: '权限不足' }), '权限不足')
|
||||
assert.equal(errorTextOf({ message: '', error: 'X' }), 'X')
|
||||
assert.equal(errorTextOf({ message: '', error: '参数不对' }), '参数不对')
|
||||
// 英文原文不透出:同一条空 message + 英文 error 只会给到中文兜底句
|
||||
assert.equal(errorTextOf({ message: '', error: 'Invalid export date range' }), '操作未能完成,请稍后重试')
|
||||
})
|
||||
|
||||
test('test_task_022_envelope_rules_invalid_input_rejected', () => {
|
||||
@@ -58,7 +60,8 @@ test('test_task_022_envelope_rules_invalid_input_rejected', () => {
|
||||
assert.equal(isUnauthorized({ statusCode: 401 }), true)
|
||||
assert.equal(isUnauthorized({ code: 403 }), false)
|
||||
assert.equal(isUnauthorized(null), false)
|
||||
assert.equal(requestErrorMessage(new Error('Network Error')), 'Network Error')
|
||||
assert.equal(requestErrorMessage(new Error('网络连接不上')), '网络连接不上')
|
||||
assert.equal(requestErrorMessage(new Error('Network Error')), '网络异常,请稍后重试')
|
||||
})
|
||||
|
||||
test('test_task_022_envelope_rules_dependency_failure_returns_actionable_message', () => {
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { resolve, dirname } from 'node:path'
|
||||
import { errorTextOf, requestErrorMessage, unwrap } from '../src/api/envelope.ts'
|
||||
import { userNotice, NOTICE_FALLBACK } from '../src/api/user-notice.ts'
|
||||
|
||||
/**
|
||||
* 后台中文文案尺子(2026-10-09)。
|
||||
*
|
||||
* 起因:去重库导出失败时后台弹的是 `invalid export date range`,客服照着这句话没法回答用户,
|
||||
* 也没法判断是不是自己的操作问题。写侧已把这几句改成中文,这里钉两件事:
|
||||
* ① 解包出口(textOf / errorTextOf)不许再把非中文原文透出;② 模板里直接渲染 errorMessage
|
||||
* 的两处必须过 userNotice。
|
||||
*/
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
|
||||
function read(rel: string): string {
|
||||
return readFileSync(resolve(here, '../src', rel), 'utf-8')
|
||||
}
|
||||
|
||||
test('userNotice 放行中文、替换英文', () => {
|
||||
assert.equal(userNotice('导出的日期范围不对'), '导出的日期范围不对')
|
||||
assert.equal(userNotice('export dedupe total data failed'), NOTICE_FALLBACK)
|
||||
assert.equal(userNotice('', '默认句'), '默认句')
|
||||
// 库里存的是"中文主干: 底层英文原文",界面上只留主干
|
||||
assert.equal(userNotice('去重结果打包失败: Broken pipe'), '去重结果打包失败')
|
||||
})
|
||||
|
||||
test('响应体里的英文原文不会从解包出口透出', () => {
|
||||
assert.equal(requestErrorMessage({ response: { data: { message: 'Invalid export date range' } } }), NOTICE_FALLBACK)
|
||||
const fromError = requestErrorMessage(new Error('Internal Server Error'))
|
||||
assert.ok(!/^[A-Za-z]/.test(fromError), `axios/Error 原文仍被透出: ${fromError}`)
|
||||
assert.ok(/[㐀-䶿一-鿿]/.test(fromError), `兜底句必须是中文: ${fromError}`)
|
||||
assert.equal(requestErrorMessage({ response: { data: { error: 'MinIO 连接被拒绝' } } }), 'MinIO 连接被拒绝')
|
||||
})
|
||||
|
||||
test('unwrap 抛出的错误也是中文', () => {
|
||||
assert.throws(() => unwrap({ success: false, message: 'Coze workflow finished with status FAILED' }),
|
||||
(err: unknown) => {
|
||||
assert.ok(err instanceof Error)
|
||||
assert.ok(!/^[A-Za-z]/.test(err.message), `抛给界面的还是英文: ${err.message}`)
|
||||
return true
|
||||
})
|
||||
assert.doesNotThrow(() => unwrap({ success: true, data: 1 }))
|
||||
})
|
||||
|
||||
test('直接渲染错误字段的模板已过闸', () => {
|
||||
const sites: Array<[string, string]> = [
|
||||
['pages/task-center/TaskCenterBoardPage.vue', 'detail.errorMessage || detail.message'],
|
||||
['pages/tasks/ImageVideoTasksPage.vue', 'detail.errorMessage'],
|
||||
]
|
||||
for (const [file, needle] of sites) {
|
||||
const source = read(file)
|
||||
const line = source.split(/\r?\n/).find((l) => l.includes(needle) && l.includes('{{'))
|
||||
assert.ok(line, `${file} 里找不到渲染 ${needle} 的那一行——改动没落地或字段名变了`)
|
||||
assert.ok(line.includes('userNotice('), `${file}: ${needle} 仍被直接渲染进界面`)
|
||||
assert.ok(source.includes('user-notice'), `${file} 缺 userNotice 的 import`)
|
||||
}
|
||||
})
|
||||
@@ -25,7 +25,7 @@
|
||||
|
||||
`V148__product_category_builtin_owned_by_company.sql`(把 18 行内置类目的归属从共享哨兵 0 改成厦门米椿花 1)从未上线,2026-10-06 控制方点名「商品类目做成共享的,不区分」⇒ 它的口径被 V151 整体推翻,文件连同 `ProductCategoryMigrationV148Test`、`docs/rollback-V148-product-category-builtin-shared.sql` 一起删除。它与 132/133 的区别要写清:**把新迁移编号写回 148 在 Flyway 语义上是可行的**(生产最大值仍是 147,不存在 out-of-order),这里禁它是共树并发的护栏——148 与 149/150 是同一工作区里另一路会话此刻正在引用的号,被删的 `V148` 文件可能被再次写出,而同号两个文件会让 Flyway 启动期报 "Found more than one migration with version 148" ⇒ 两台 java 同时起不来。宁可让 `integerVersionsSequentialFromOne` 的红字出现在测试里,也不把撞号留到运行期发现。因此这三个号都在 `MigrationInventoryTest.RETIRED_HOLES` 里登记。
|
||||
|
||||
后续新增迁移从 **V156** 起取号(V155 已被 `users_disabled_at` 占用:给 users 加一列可空停用时刻,回滚见 `docs/rollback-V155-users-disabled-at.sql`;V154 已被 `biz_dedupe_total_data_company_id_drop_default` 占用:只摘一列的默认值,回滚见 `docs/rollback-V154-dedupe-company-id-drop-default.sql`。只认"当前最大值 + 1",不要为还没写出来的迁移预留号段——预留会在 1..max 里留洞,`integerVersionsSequentialFromOne` 会红;也不要回填上面那三个洞)。原先挂在 V149 名下的"摘 DEFAULT"待办,`columns` 那条已与 `biz_shop_key` 合并成 **V152** 发出(V150 头注释第 6 段要求"合并成一版发出";发布前的只读取证:`columns` 154 行按公司 52/51/51、`biz_shop_key` 16 行全 company_id=1 且无 NULL,两列 COLUMN_DEFAULT 都是 1)。摘 DEFAULT 这一族到此摘完,最后一条是 **V154**:
|
||||
后续新增迁移从 **V157** 起取号(V156 已被 `dedupe_total_data_pioneer_backfill` 占用:把组 33/uid=1188「先锋」名下账号已删的 1452 行 `company_id` 从兜底 1 回填到 3,配套读侧按行 company_id 收窄的 JAR 同批上线,回滚见 `docs/rollback-V156-dedupe-pioneer-backfill.sql`;V155 已被 `users_disabled_at` 占用:给 users 加一列可空停用时刻,回滚见 `docs/rollback-V155-users-disabled-at.sql`;V154 已被 `biz_dedupe_total_data_company_id_drop_default` 占用:只摘一列的默认值,回滚见 `docs/rollback-V154-dedupe-company-id-drop-default.sql`。只认"当前最大值 + 1",不要为还没写出来的迁移预留号段——预留会在 1..max 里留洞,`integerVersionsSequentialFromOne` 会红;也不要回填上面那三个洞)。原先挂在 V149 名下的"摘 DEFAULT"待办,`columns` 那条已与 `biz_shop_key` 合并成 **V152** 发出(V150 头注释第 6 段要求"合并成一版发出";发布前的只读取证:`columns` 154 行按公司 52/51/51、`biz_shop_key` 16 行全 company_id=1 且无 NULL,两列 COLUMN_DEFAULT 都是 1)。摘 DEFAULT 这一族到此摘完,最后一条是 **V154**:
|
||||
|
||||
- `ALTER TABLE biz_dedupe_total_data ALTER COLUMN company_id DROP DEFAULT;` —— 已作为 **V154** 发出。V152 当年把它留在门外的前提是"先修写侧、上线并验证真实导入之后才谈摘",2026-10-09 只读探针(运维仓 `scripts/_probe_dedupe_default.py`,主机A,零写入)逐条对上:哨兵四张表里只剩这张仍带 DEFAULT 1(users / biz_shop_key / columns 的 COLUMN_DEFAULT 均为空);归属分布 company_id=1 共 546,344 行、=3 共 8,125 行,**没有 0 也没有 NULL**;孤儿归属 0 行;写侧显式落值那版上线后真实导入 29,555 行(2026-10-07 09:48:38 → 2026-10-08 23:57:51)。⚠ 本表批量导入走 `INSERT IGNORE`:在生产 sql_mode(实查含 STRICT_TRANS_TABLES)下省略该列不会撞 1364,而是被降级成 warning 并落成隐式默认 **0**——0 不属于任何公司,行插得进去但对所有公司隐形,比"静默归第 1 家"更难发现。⇒ **顺序必须是先上带 Java 闸门的 jar,再让本迁移随同一版生效**;闸门=`DedupeTotalDataService.requireCompanyAttribution`(接在 create 与 insertImportBatch 两条写通道上),用例 `DedupeTotalDataWriteAttributionTest` 4 例,其中接线钉按行首语句数调用点==2(避开 javadoc 同名提及那个坑)。
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
-- 回滚 V156(人工补丁,不放进 src/main/resources/db/——那里是 Flyway 扫描路径,
|
||||
-- 任何 V*.sql 都会在应用下次启动时自动执行;把回滚编成版本化迁移等于让"决定回滚"这件事
|
||||
-- 在没有人工执行的情况下自己发生)。
|
||||
--
|
||||
-- 触发场景:V156 把组 33/uid=1188(「先锋」)的 1452 行 company_id 从 1 回填到 3。
|
||||
-- 只有一种情况需要回滚本数据:控制方改判这 1452 行不属于先锋-团队。
|
||||
-- 仅仅"读侧切换的 jar 有问题要回滚"【不需要】动数据——旧读侧按上传账号认公司,
|
||||
-- 对这批 uploader 已删的行本来就不显示(company_id 是 1 还是 3 都看不见),
|
||||
-- 但**去重比对**(39de5035 已按 company_id)会跟着数据走:回滚数据 = 米椿花去重
|
||||
-- 重新吃到这 1452 个先锋 ASIN、先锋丢值,所以数据回滚必须与 jar 回滚同批做,
|
||||
-- 且回滚前先确认"改判"是真的(不是又一次误判归属)。
|
||||
--
|
||||
-- 执行顺序(两台都要,中间不停服会混版):
|
||||
-- 1) 停两台应用(docker stop java-server)
|
||||
-- 2) 在 aiimage 库执行下面的反向 UPDATE
|
||||
-- 3) DELETE FROM flyway_schema_history WHERE version = '156';
|
||||
-- 4) 回滚 jar 到上一版(读侧按上传账号的版本)
|
||||
-- 5) 起两台,确认 health=200
|
||||
-- 6) 复查:
|
||||
-- SELECT company_id, COUNT(*) FROM biz_dedupe_total_data
|
||||
-- WHERE uploader_user_id = 1188 GROUP BY company_id;
|
||||
-- 期望回到一行:1 | 1452。
|
||||
--
|
||||
-- 反向判据与 V156 原文一一对应(uploader_user_id=1188 AND group_id=33),
|
||||
-- company_id=3 限定保证重跑是 no-op;只回滚这一个精确集,不扩大射程。
|
||||
|
||||
UPDATE `biz_dedupe_total_data`
|
||||
SET `company_id` = 1
|
||||
WHERE `uploader_user_id` = 1188
|
||||
AND `group_id` = 33
|
||||
AND `company_id` = 3;
|
||||
+24
-7
@@ -3,6 +3,7 @@ package com.nanri.aiimage.common.exception;
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
|
||||
import com.nanri.aiimage.common.service.TaskOwnerForwardService;
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.config.TaskOperationLockConfig;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.validation.ConstraintViolationException;
|
||||
@@ -54,9 +55,11 @@ public class GlobalExceptionHandler {
|
||||
.headers(safeHeaders)
|
||||
.body(response.getBody());
|
||||
} catch (BusinessException forwardEx) {
|
||||
String reason = UserMessages.orFallback(
|
||||
forwardEx.getMessage(), "任务归属实例暂时联系不上,请稍后重试");
|
||||
return forwardEx.getCode() == null
|
||||
? ApiResponse.fail(forwardEx.getMessage())
|
||||
: ApiResponse.fail(forwardEx.getCode(), forwardEx.getMessage());
|
||||
? ApiResponse.fail(reason)
|
||||
: ApiResponse.fail(forwardEx.getCode(), reason);
|
||||
} catch (Exception forwardEx) {
|
||||
// 转发失败是**瞬时基础设施故障**(归属实例正在滚动重启),不是业务结论,
|
||||
// 更不能表达成「任务不存活」。原先返回 ApiResponse.fail(40903) —— HTTP 200
|
||||
@@ -100,11 +103,13 @@ public class GlobalExceptionHandler {
|
||||
}
|
||||
if (Integer.valueOf(BusinessCodes.TASK_BUSY).equals(ex.getCode())) {
|
||||
// 锁竞争:必须如实返回失败 + 可重试码,否则 worker 会把「未落库」当成功而停止重试
|
||||
return ApiResponse.fail(BusinessCodes.TASK_BUSY, ex.getMessage());
|
||||
return ApiResponse.fail(BusinessCodes.TASK_BUSY,
|
||||
UserMessages.orFallback(ex.getMessage(), "这个任务正在处理中,请稍后重试"));
|
||||
}
|
||||
String userMessage = UserMessages.orFallback(ex.getMessage(), chineseFallbackFor(ex.getCode()));
|
||||
return ex.getCode() == null
|
||||
? ApiResponse.fail(ex.getMessage())
|
||||
: ApiResponse.fail(ex.getCode(), ex.getMessage());
|
||||
? ApiResponse.fail(userMessage)
|
||||
: ApiResponse.fail(ex.getCode(), userMessage);
|
||||
}
|
||||
|
||||
@ExceptionHandler(NoResourceFoundException.class)
|
||||
@@ -122,6 +127,17 @@ public class GlobalExceptionHandler {
|
||||
|| Integer.valueOf(DeviceSessionPolicy.CODE_KICKED).equals(code);
|
||||
}
|
||||
|
||||
/** 兜底句按码分档:整条消息被换成中文时,鉴权类失败不能说得像个业务错。 */
|
||||
private String chineseFallbackFor(Integer code) {
|
||||
if (Integer.valueOf(DeviceSessionPolicy.CODE_KICKED).equals(code)) {
|
||||
return "该账号已在其他设备登录,当前会话已下线";
|
||||
}
|
||||
if (Integer.valueOf(401).equals(code)) {
|
||||
return "登录状态已失效,请重新登录";
|
||||
}
|
||||
return "操作未能完成,请稍后重试";
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public ApiResponse<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) { String message = ex.getBindingResult().getFieldError() != null
|
||||
? ex.getBindingResult().getFieldError().getDefaultMessage()
|
||||
@@ -131,7 +147,7 @@ public class GlobalExceptionHandler {
|
||||
|
||||
@ExceptionHandler(ConstraintViolationException.class)
|
||||
public ApiResponse<Void> handleConstraintViolationException(ConstraintViolationException ex) {
|
||||
return ApiResponse.fail(ex.getMessage());
|
||||
return ApiResponse.fail(UserMessages.orFallback(ex.getMessage(), "填写的内容不符合要求,请检查后重试"));
|
||||
}
|
||||
|
||||
@ExceptionHandler(AsyncRequestNotUsableException.class)
|
||||
@@ -142,7 +158,8 @@ public class GlobalExceptionHandler {
|
||||
@ExceptionHandler(ResponseStatusException.class)
|
||||
public ResponseEntity<ApiResponse<Void>> handleResponseStatusException(ResponseStatusException ex) {
|
||||
String message = ex.getReason() == null || ex.getReason().isBlank() ? ex.getMessage() : ex.getReason();
|
||||
return ResponseEntity.status(ex.getStatusCode()).body(ApiResponse.fail(message));
|
||||
return ResponseEntity.status(ex.getStatusCode())
|
||||
.body(ApiResponse.fail(UserMessages.orFallback(message, "请求未能完成,请稍后重试")));
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
|
||||
@@ -47,6 +47,27 @@ public class DataReadScope {
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 公司 tab 的<b>行级</b>归属收窄:{@code null} = 不筛,正数 = 该表按行自己的 {@code company_id} 列筛。
|
||||
*
|
||||
* <p>与 {@link #superAdminScopedUserIds} 平行(同样只在站点超管身上收窄、其余一律 {@code null}),
|
||||
* 区别是收窄维度:那个给的是"上传账号集合",这个给的是"行归属的公司 id"。适用于把归属
|
||||
* <b>物化到行上</b>的表——去重库 {@code biz_dedupe_total_data}(V145 加列、写侧 39de5035 起
|
||||
* 一律显式落值、V154 摘 DEFAULT)。该表此前按上传账号推导公司,2026-10-09 控制方截图暴露出
|
||||
* 两类错归:超管代导入的行(company_id=操作 tab 的公司、uploader=超管自己)在目标公司的 tab
|
||||
* 看不见、却出现在超管自己那一家;上传账号被硬删的行(JOIN 不上任何成员集)在每一个 tab 都
|
||||
* 看不见。写侧与库唯一键(uk_company_data_value)都已经是 company_id 口径,读侧在此对齐。</p>
|
||||
*
|
||||
* <p>非超管仍返回 {@code null}(不叠这一层),纪律与 {@code readScope} 非超管分支一致:
|
||||
* 非超管的可见集锁在自己的账号/分组上,公司维度由会话独家决定;在这一层再加一刀
|
||||
* company_id 会把"靠分组可见、而行列值尚未一致"的历史行静默删掉。</p>
|
||||
*/
|
||||
public Long superAdminScopedCompanyId(AdminUserEntity operator, Long requestedCompanyId) {
|
||||
return isPlatformSuperAdmin(operator)
|
||||
? (requestedCompanyId != null && requestedCompanyId > 0 ? requestedCompanyId : null)
|
||||
: null;
|
||||
}
|
||||
|
||||
public ReadScope readScope(AdminUserEntity operator, Long requestedCompanyId) {
|
||||
Long companyId = requestedCompanyId != null && requestedCompanyId > 0 ? requestedCompanyId : null;
|
||||
if (isPlatformSuperAdmin(operator)) {
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.common.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.exception.TaskOwnerMismatchException;
|
||||
import com.nanri.aiimage.config.InstanceRoutingProperties;
|
||||
@@ -173,7 +174,7 @@ public class TaskOwnerForwardService {
|
||||
try {
|
||||
return StreamUtils.copyToByteArray(request.getInputStream());
|
||||
} catch (IOException ex) {
|
||||
throw new BusinessException("读取转发请求体失败:" + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("读取转发请求体失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.nanri.aiimage.common.util;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* 用户可见文案把关(2026-10-09 收口)。
|
||||
*
|
||||
* <p>背景:任务 30456 的结果文件其实已经生成、能下载,卡片上却跟着一条
|
||||
* {@code Similar ASIN result rows are empty; please retry result generation}。文案是英文不是
|
||||
* 最要命的——最要命的是它是**底层异常原文**:全仓有 61 处把 {@code ex.getMessage()} 直接
|
||||
* 拼进用户可见字段(异常响应、任务 error_message、结果作业 error_msg、看板 message),
|
||||
* 底层抛什么用户就看什么。逐条翻译译不完,因为新的 catch 天天在加。
|
||||
*
|
||||
* <p>本类把"只把中文给用户看"做成出口处的代码约束:中文照原样过,非中文换成中文句子,
|
||||
* 原文只进日志。诊断信息不丢——调用点本来就带着 {@code log.warn} 的堆栈。
|
||||
*/
|
||||
public final class UserMessages {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(UserMessages.class);
|
||||
|
||||
private UserMessages() {
|
||||
}
|
||||
|
||||
/** 中文主干 + 异常详情:详情是中文才拼接,英文详情丢弃(原文进 debug 日志)。 */
|
||||
public static String with(String headline, Throwable ex) {
|
||||
return with(headline, ex == null ? null : ex.getMessage());
|
||||
}
|
||||
|
||||
/** 中文主干 + 详情:详情是中文才拼接。 */
|
||||
public static String with(String headline, String detail) {
|
||||
String head = headline == null ? "" : headline.trim().replaceAll("[::]\\s*$", "");
|
||||
if (detail == null || detail.isBlank()) {
|
||||
return head;
|
||||
}
|
||||
if (hasChinese(detail)) {
|
||||
return head + ":" + detail.trim();
|
||||
}
|
||||
log.debug("[user-message] dropped non-chinese detail headline={} detail={}", head, detail);
|
||||
return head;
|
||||
}
|
||||
|
||||
/**
|
||||
* 整句把关:原文含中文则照原样返回,否则返回中文兜底句。
|
||||
*
|
||||
* <p>用于"整条消息都来自底层"的出口({@code ApiResponse.fail(ex.getMessage())}、
|
||||
* {@code setErrorMessage(ex.getMessage())})。被换掉时原文进 WARN,因为这类出口
|
||||
* 调用点未必另外记日志,静默替换会把根因从系统里彻底抹掉。
|
||||
*/
|
||||
public static String orFallback(String raw, String fallback) {
|
||||
if (raw != null && !raw.isBlank() && hasChinese(raw)) {
|
||||
return raw.trim();
|
||||
}
|
||||
log.warn("[user-message] replaced non-chinese message fallback={} raw={}",
|
||||
fallback, raw == null ? "" : raw);
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/** 是否含汉字:含则认为是给人看的中文文案,可以原样透出。 */
|
||||
public static boolean hasChinese(String text) {
|
||||
if (text == null) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < text.length(); i++) {
|
||||
char c = text.charAt(i);
|
||||
if (c >= '一' && c <= '鿿') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -79,7 +79,7 @@ public class TaskOperationLockConfig implements WebMvcConfigurer {
|
||||
if (lockHandle == null) {
|
||||
log.info("[task-operation-lock] rejected busy task operation method={} uri={} moduleType={} taskId={} waitMillis={}",
|
||||
request.getMethod(), uri, moduleType, taskId, waitMillis);
|
||||
throw new BusinessException(40902, "TASK_LOCK_BUSY");
|
||||
throw new BusinessException(40902, "这个任务正在处理中,请稍后重试");
|
||||
}
|
||||
request.setAttribute(LOCK_ATTRIBUTE, lockHandle);
|
||||
return true;
|
||||
|
||||
+5
-5
@@ -1878,7 +1878,7 @@ public class AppearancePatentTaskService {
|
||||
|
||||
public boolean processResultFileJob(TaskFileJobEntity job) {
|
||||
if (job == null || job.getTaskId() == null || job.getResultId() == null) {
|
||||
throw new BusinessException("result file job arguments are incomplete");
|
||||
throw new BusinessException("结果文件作业参数不完整");
|
||||
}
|
||||
TaskDistributedLockService.LockHandle lockHandle = acquireTaskLock(job.getTaskId(), TASK_LOCK_WAIT_MILLIS);
|
||||
if (lockHandle == null) {
|
||||
@@ -1894,7 +1894,7 @@ public class AppearancePatentTaskService {
|
||||
private boolean processResultFileJobLocked(TaskFileJobEntity job) {
|
||||
FileTaskEntity task = fileTaskMapper.selectById(job.getTaskId());
|
||||
if (task == null || !MODULE_TYPE.equals(task.getModuleType())) {
|
||||
throw new BusinessException("task not found");
|
||||
throw new BusinessException("任务不存在");
|
||||
}
|
||||
ensureTaskOwnedByCurrentInstance(task, "assemble result file");
|
||||
job.setScopeKey(buildTaskOwnerScopeKey(task));
|
||||
@@ -1905,7 +1905,7 @@ public class AppearancePatentTaskService {
|
||||
}
|
||||
FileResultEntity result = fileResultMapper.selectById(job.getResultId());
|
||||
if (result == null || !MODULE_TYPE.equals(result.getModuleType())) {
|
||||
throw new BusinessException("result record not found");
|
||||
throw new BusinessException("结果记录不存在");
|
||||
}
|
||||
List<TaskChunkEntity> chunks = taskChunkMapper.selectList(new LambdaQueryWrapper<TaskChunkEntity>()
|
||||
.eq(TaskChunkEntity::getTaskId, task.getId())
|
||||
@@ -2766,7 +2766,7 @@ public class AppearancePatentTaskService {
|
||||
throw new BusinessException(FailedStatusRowFilter.noMatchedRowsMessage());
|
||||
}
|
||||
if (allRows.isEmpty()) {
|
||||
throw new BusinessException("no valid appearance patent rows");
|
||||
throw new BusinessException("没有解析到可检测的外观专利行,请检查表格内容");
|
||||
}
|
||||
return new ParsedWorkbook(total, dropped, new ArrayList<>(headers), allRows);
|
||||
}
|
||||
@@ -3193,7 +3193,7 @@ public class AppearancePatentTaskService {
|
||||
+ " taskId={} chunk={}", chunk.getTaskId(), chunk.getChunkIndex());
|
||||
return rows;
|
||||
}
|
||||
throw new BusinessException("appearance patent chunk payload read failed chunk="
|
||||
throw new BusinessException("读取外观专利结果分片失败,分片="
|
||||
+ chunk.getChunkIndex() + ": " + ex.getMessage(), ex);
|
||||
}
|
||||
return rows;
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.appearancepatent.service.support;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentHistoryItemVo;
|
||||
import com.nanri.aiimage.modules.appearancepatent.service.AppearancePatentTaskService;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileResultEntity;
|
||||
@@ -132,7 +133,7 @@ public class AppearancePatentHistoryAssembler {
|
||||
vo.setFileProgressCurrent(current);
|
||||
vo.setFileProgressTotal(total);
|
||||
vo.setFileProgressPercent(percent);
|
||||
vo.setFileProgressMessage(snapshot.getMessage());
|
||||
vo.setFileProgressMessage(UserMessages.orFallback(snapshot.getMessage(), ""));
|
||||
}
|
||||
|
||||
private String fmt(LocalDateTime t) {
|
||||
|
||||
+16
-14
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.brand.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.json.JSONUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
@@ -269,14 +270,14 @@ public class BrandTaskService {
|
||||
|
||||
public void submitCrawlResult(Long taskId, BrandCrawlResultRequest request) {
|
||||
if (taskId == null || taskId <= 0) {
|
||||
throw new BusinessException("taskId invalid");
|
||||
throw new BusinessException("任务 id 不合法");
|
||||
}
|
||||
try (TaskDistributedLockService.LockHandle ignored = acquireTaskLockOrThrow(taskId, RESULT_SUBMIT_WAIT_MILLIS)) {
|
||||
long startedAt = System.currentTimeMillis();
|
||||
BrandCrawlTaskEntity task = requireActiveTask(taskId);
|
||||
List<BrandSourceFileDto> sourceFiles = parseSourceFiles(task.getFilePaths());
|
||||
if (sourceFiles.isEmpty()) {
|
||||
throw new BusinessException("task source files missing");
|
||||
throw new BusinessException("任务缺少源文件");
|
||||
}
|
||||
|
||||
Map<String, BrandSourceFileDto> sourceByUrl = new LinkedHashMap<>();
|
||||
@@ -288,7 +289,7 @@ public class BrandTaskService {
|
||||
}
|
||||
List<BrandParsedFileCacheDto> cachedFiles = brandTaskStorageService.getParsedPayload(taskId);
|
||||
if (cachedFiles == null || cachedFiles.isEmpty()) {
|
||||
throw new BusinessException("task parsed payload missing");
|
||||
throw new BusinessException("任务解析结果不存在");
|
||||
}
|
||||
Map<String, BrandParsedFileCacheDto> cachedByUrl = new LinkedHashMap<>();
|
||||
for (BrandParsedFileCacheDto cachedFile : cachedFiles) {
|
||||
@@ -297,7 +298,7 @@ public class BrandTaskService {
|
||||
|
||||
List<BrandCrawlResultFileDto> resultFiles = request.getFiles() == null ? List.of() : request.getFiles();
|
||||
if (resultFiles.isEmpty()) {
|
||||
throw new BusinessException("files is empty");
|
||||
throw new BusinessException("文件列表为空");
|
||||
}
|
||||
ensureNoDuplicateResultFiles(resultFiles);
|
||||
|
||||
@@ -315,21 +316,21 @@ public class BrandTaskService {
|
||||
for (BrandCrawlResultFileDto resultFile : resultFiles) {
|
||||
String fileUrl = blankToNull(resultFile.getFileUrl());
|
||||
if (fileUrl == null) {
|
||||
throw new BusinessException("fileUrl is blank");
|
||||
throw new BusinessException("文件地址为空");
|
||||
}
|
||||
BrandSourceFileDto sourceFile = sourceByUrl.get(fileUrl);
|
||||
if (sourceFile == null) {
|
||||
throw new BusinessException("unknown fileUrl: " + fileUrl);
|
||||
throw new BusinessException("未识别的文件地址: " + fileUrl);
|
||||
}
|
||||
BrandParsedFileCacheDto cachedFile = cachedByUrl.get(fileUrl);
|
||||
if (cachedFile == null) {
|
||||
throw new BusinessException("parsed cache missing: " + fileUrl);
|
||||
throw new BusinessException("解析缓存不存在: " + fileUrl);
|
||||
}
|
||||
int totalLines = cachedFile.getRows() == null ? 0 : cachedFile.getRows().size();
|
||||
if (resultFile.getTotalLines() == null || resultFile.getTotalLines() <= 0) {
|
||||
resultFile.setTotalLines(totalLines);
|
||||
} else if (totalLines > 0 && resultFile.getTotalLines() > totalLines) {
|
||||
throw new BusinessException("totalLines exceeds source rows: " + fileUrl);
|
||||
throw new BusinessException("行数超过源数据行数: " + fileUrl);
|
||||
}
|
||||
BrandTaskStorageService.ChunkStoreResult storeResult = brandTaskStorageService.storeChunk(taskId, resultFile);
|
||||
BrandTaskStorageService.ChunkStoreResult refreshResult = brandTaskStorageService.refreshFileAggregate(taskId, fileUrl);
|
||||
@@ -718,13 +719,14 @@ public class BrandTaskService {
|
||||
.set(BrandCrawlTaskEntity::getStatus, STATUS_FAILED)
|
||||
.set(BrandCrawlTaskEntity::getProgressCurrent, brandTaskStorageService.countCompletedFiles(taskId))
|
||||
.set(BrandCrawlTaskEntity::getProgressTotal, totalCount)
|
||||
.set(BrandCrawlTaskEntity::getErrorMessage, ex.getMessage()));
|
||||
brandTaskProgressCacheService.markFailed(taskId, ex.getMessage());
|
||||
saveBrandProgressSnapshot(taskId, STATUS_FAILED, totalCount, brandTaskStorageService.countCompletedFiles(taskId), 1, ex.getMessage());
|
||||
.set(BrandCrawlTaskEntity::getErrorMessage, UserMessages.orFallback(ex.getMessage(), "品牌检测任务执行失败")));
|
||||
brandTaskProgressCacheService.markFailed(taskId, UserMessages.orFallback(ex.getMessage(), "品牌检测任务执行失败"));
|
||||
saveBrandProgressSnapshot(taskId, STATUS_FAILED, totalCount, brandTaskStorageService.countCompletedFiles(taskId), 1,
|
||||
UserMessages.orFallback(ex.getMessage(), "品牌检测任务执行失败"));
|
||||
if (ex instanceof BusinessException businessException) {
|
||||
throw businessException;
|
||||
}
|
||||
throw new BusinessException(ex.getMessage());
|
||||
throw new BusinessException(UserMessages.orFallback(ex.getMessage(), "品牌检测任务执行失败,请稍后重试"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -821,7 +823,7 @@ public class BrandTaskService {
|
||||
*/
|
||||
public Map<String, Object> abortTask(Long taskId, String errorMessage) {
|
||||
if (taskId == null || taskId <= 0) {
|
||||
throw new BusinessException("taskId invalid");
|
||||
throw new BusinessException("任务 id 不合法");
|
||||
}
|
||||
try (TaskDistributedLockService.LockHandle ignored = acquireTaskLockOrThrow(taskId, RESULT_SUBMIT_WAIT_MILLIS)) {
|
||||
BrandCrawlTaskEntity task = requireTask(taskId);
|
||||
@@ -1661,7 +1663,7 @@ public class BrandTaskService {
|
||||
private TaskDistributedLockService.LockHandle acquireTaskLockOrThrow(Long taskId, long waitMillis) {
|
||||
TaskDistributedLockService.LockHandle lockHandle = acquireTaskLock(taskId, waitMillis);
|
||||
if (lockHandle == null) {
|
||||
throw new BusinessException("task lock is busy");
|
||||
throw new BusinessException("任务正被占用,请稍后重试");
|
||||
}
|
||||
return lockHandle;
|
||||
}
|
||||
|
||||
+16
-16
@@ -52,7 +52,7 @@ public class BrandTaskStorageService {
|
||||
}
|
||||
String scopeKey = normalize(item.getFileUrl());
|
||||
String scopeHash = hash(scopeKey);
|
||||
String parsedJson = storeParsedPayload(taskId, scopeHash, writeJson(item, "Save brand task parsed payload failed"));
|
||||
String parsedJson = storeParsedPayload(taskId, scopeHash, writeJson(item, "保存品牌任务解析结果失败"));
|
||||
TaskScopeStateEntity state = getScopeState(taskId, scopeHash);
|
||||
if (state == null) {
|
||||
TaskScopeStateEntity entity = new TaskScopeStateEntity();
|
||||
@@ -74,7 +74,7 @@ public class BrandTaskStorageService {
|
||||
}
|
||||
}
|
||||
if (state == null) {
|
||||
throw new BusinessException("Save brand task parsed payload failed");
|
||||
throw new BusinessException("保存品牌任务解析结果失败");
|
||||
}
|
||||
transientPayloadStorageService.deleteReplacedPayloadIfNeeded(state.getParsedPayloadJson(), parsedJson);
|
||||
taskScopeStateMapper.update(null, new LambdaUpdateWrapper<TaskScopeStateEntity>()
|
||||
@@ -106,7 +106,7 @@ public class BrandTaskStorageService {
|
||||
try {
|
||||
result.add(objectMapper.readValue(payloadJson, BrandParsedFileCacheDto.class));
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Read brand task parsed payload failed");
|
||||
throw new BusinessException("读取品牌任务解析结果失败");
|
||||
}
|
||||
}
|
||||
return result;
|
||||
@@ -133,7 +133,7 @@ public class BrandTaskStorageService {
|
||||
saveAggregate(taskId, scopeKey, scopeHash, aggregate, now);
|
||||
return new ChunkStoreResult(false, false, countCompletedFiles(taskId), aggregate);
|
||||
}
|
||||
throw new BusinessException("Brand task chunk conflict: " + scopeKey + "#" + file.getChunkIndex());
|
||||
throw new BusinessException("品牌任务分片冲突: " + scopeKey + "#" + file.getChunkIndex());
|
||||
}
|
||||
|
||||
String storedPayload = transientPayloadStorageService.storeChunkPayload(MODULE_TYPE, taskId, scopeHash, file.getChunkIndex(), payloadJson);
|
||||
@@ -164,7 +164,7 @@ public class BrandTaskStorageService {
|
||||
return new ChunkStoreResult(false, false, countCompletedFiles(taskId), aggregate);
|
||||
}
|
||||
transientPayloadStorageService.deletePayloadIfPresent(storedPayload);
|
||||
throw new BusinessException("Brand task chunk conflict: " + scopeKey + "#" + file.getChunkIndex());
|
||||
throw new BusinessException("品牌任务分片冲突: " + scopeKey + "#" + file.getChunkIndex());
|
||||
}
|
||||
|
||||
BrandFileAggregateCacheDto aggregate = rebuildAggregate(taskId, scopeKey, scopeHash);
|
||||
@@ -182,7 +182,7 @@ public class BrandTaskStorageService {
|
||||
String aggregateJson = transientPayloadStorageService.resolvePayload(state.getStateJson(), "read brand task aggregate failed");
|
||||
return objectMapper.readValue(aggregateJson, BrandFileAggregateCacheDto.class);
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Read brand task aggregate failed");
|
||||
throw new BusinessException("读取品牌任务汇总状态失败");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,7 +207,7 @@ public class BrandTaskStorageService {
|
||||
String aggregateJson = transientPayloadStorageService.resolvePayload(state.getStateJson(), "read brand task aggregate failed");
|
||||
result.put(state.getScopeKey(), objectMapper.readValue(aggregateJson, BrandFileAggregateCacheDto.class));
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Read brand task aggregate failed");
|
||||
throw new BusinessException("读取品牌任务汇总状态失败");
|
||||
}
|
||||
}
|
||||
return result;
|
||||
@@ -328,7 +328,7 @@ public class BrandTaskStorageService {
|
||||
String aggregateJson = writeJson(aggregate, "Save brand task aggregate failed");
|
||||
TaskScopeStateEntity state = getScopeState(taskId, scopeHash);
|
||||
if (state == null) {
|
||||
throw new BusinessException("Brand task aggregate state missing: " + scopeKey);
|
||||
throw new BusinessException("品牌任务汇总状态不存在: " + scopeKey);
|
||||
}
|
||||
String storedAggregate = transientPayloadStorageService.storeScopePayloadVersioned(MODULE_TYPE, taskId, scopeHash, aggregateJson, true);
|
||||
int chunkTotal = aggregate.getChunkTotal() == null ? 0 : aggregate.getChunkTotal();
|
||||
@@ -383,7 +383,7 @@ public class BrandTaskStorageService {
|
||||
|
||||
private void ensureChunkConsistency(BrandFileAggregateCacheDto aggregate, BrandCrawlResultFileDto file) {
|
||||
if (aggregate.getChunkTotal() != null && file.getChunkTotal() != null && !aggregate.getChunkTotal().equals(file.getChunkTotal())) {
|
||||
throw new BusinessException("Brand task chunkTotal mismatch: " + aggregate.getFileUrl());
|
||||
throw new BusinessException("品牌任务分片总数对不上: " + aggregate.getFileUrl());
|
||||
}
|
||||
if (aggregate.getChunkTotal() == null) {
|
||||
aggregate.setChunkTotal(file.getChunkTotal());
|
||||
@@ -454,7 +454,7 @@ public class BrandTaskStorageService {
|
||||
mergeAggregate(aggregate, chunkPayload);
|
||||
}
|
||||
if (aggregate == null) {
|
||||
throw new BusinessException("Read brand task aggregate data failed");
|
||||
throw new BusinessException("读取品牌任务汇总数据失败");
|
||||
}
|
||||
aggregate.setFileUrl(scopeKey);
|
||||
aggregate.setReceivedChunkCount(chunks.size());
|
||||
@@ -469,20 +469,20 @@ public class BrandTaskStorageService {
|
||||
String resolvedPayload = transientPayloadStorageService.resolvePayload(payloadJson, "read brand task chunk failed");
|
||||
return objectMapper.readValue(resolvedPayload, BrandCrawlResultFileDto.class);
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Read brand task chunk failed");
|
||||
throw new BusinessException("读取品牌任务分片失败");
|
||||
}
|
||||
}
|
||||
|
||||
private void validateChunk(BrandCrawlResultFileDto file) {
|
||||
if (file == null) {
|
||||
throw new BusinessException("Brand task chunk must not be null");
|
||||
throw new BusinessException("品牌任务分片不能为空");
|
||||
}
|
||||
if (file.getChunkIndex() == null || file.getChunkTotal() == null || file.getChunkIndex() <= 0
|
||||
|| file.getChunkTotal() <= 0 || file.getChunkIndex() > file.getChunkTotal()) {
|
||||
throw new BusinessException("Brand task chunk parameters are invalid");
|
||||
throw new BusinessException("品牌任务分片参数不合法");
|
||||
}
|
||||
if (isBlank(file.getFileUrl())) {
|
||||
throw new BusinessException("fileUrl must not be blank");
|
||||
throw new BusinessException("文件地址不能为空");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -492,9 +492,9 @@ public class BrandTaskStorageService {
|
||||
|
||||
private String resolveParsedPayload(String value) {
|
||||
try {
|
||||
return transientPayloadStorageService.resolvePayload(value, "Read brand task parsed payload failed");
|
||||
return transientPayloadStorageService.resolvePayload(value, "读取品牌任务解析结果失败");
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Read brand task parsed payload failed");
|
||||
throw new BusinessException("读取品牌任务解析结果失败");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.collectdata.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.util.SxssfWorkbookWriter;
|
||||
import com.nanri.aiimage.modules.collectdata.model.dto.CollectDataSummaryRowDto;
|
||||
@@ -98,7 +99,7 @@ public class CollectDataExcelAssemblyService {
|
||||
} catch (Exception ex) {
|
||||
log.warn("[collect-data] write workbook failed: {}", ex.getMessage());
|
||||
deleteQuietly(tmpFile);
|
||||
throw new BusinessException("生成采集数据 Excel 失败: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("生成采集数据 Excel 失败", ex));
|
||||
} finally {
|
||||
writer.close();
|
||||
deleteQuietly(tmpFile);
|
||||
|
||||
+13
-12
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.convert.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import cn.hutool.json.JSONUtil;
|
||||
@@ -90,7 +91,7 @@ public class ConvertRunService {
|
||||
try {
|
||||
File inputFile = findLocalSourceFile(sourceFile.getFileKey());
|
||||
if (inputFile == null || !inputFile.exists()) {
|
||||
throw new BusinessException("Uploaded source file does not exist, please upload again.");
|
||||
throw new BusinessException("上传的源文件不存在,请重新上传。");
|
||||
}
|
||||
|
||||
String inputName = sourceFile.getOriginalFilename() == null
|
||||
@@ -143,7 +144,7 @@ public class ConvertRunService {
|
||||
ConvertResultItemVo item = new ConvertResultItemVo();
|
||||
item.setSourceFilename(sourceFile.getOriginalFilename());
|
||||
item.setSuccess(false);
|
||||
item.setError(ex.getMessage());
|
||||
item.setError(UserMessages.orFallback(ex.getMessage(), "这个文件转换失败,请检查内容后重新上传"));
|
||||
items.add(item);
|
||||
failedCount++;
|
||||
|
||||
@@ -152,7 +153,7 @@ public class ConvertRunService {
|
||||
resultEntity.setModuleType(MODULE_TYPE);
|
||||
resultEntity.setSourceFilename(sourceFile.getOriginalFilename());
|
||||
resultEntity.setSuccess(0);
|
||||
resultEntity.setErrorMessage(ex.getMessage());
|
||||
resultEntity.setErrorMessage(UserMessages.orFallback(ex.getMessage(), "这个文件转换失败,请检查内容后重新上传"));
|
||||
resultEntity.setUserId(request.getUserId());
|
||||
resultEntity.setCreatedAt(LocalDateTime.now());
|
||||
fileResultMapper.insert(resultEntity);
|
||||
@@ -260,7 +261,7 @@ public class ConvertRunService {
|
||||
public void deleteHistory(Long resultId, Long userId) {
|
||||
FileResultEntity entity = fileResultMapper.selectById(resultId);
|
||||
if (entity == null || !MODULE_TYPE.equals(entity.getModuleType()) || !userId.equals(entity.getUserId())) {
|
||||
throw new BusinessException("Convert result record does not exist.");
|
||||
throw new BusinessException("没有这条转换结果。");
|
||||
}
|
||||
fileResultMapper.deleteById(resultId);
|
||||
}
|
||||
@@ -268,7 +269,7 @@ public class ConvertRunService {
|
||||
public String getResultDownloadUrl(Long resultId, Long userId) {
|
||||
FileResultEntity entity = fileResultMapper.selectById(resultId);
|
||||
if (entity == null || entity.getResultFileUrl() == null || !MODULE_TYPE.equals(entity.getModuleType()) || !userId.equals(entity.getUserId())) {
|
||||
throw new BusinessException("Convert result file does not exist.");
|
||||
throw new BusinessException("转换结果文件不存在。");
|
||||
}
|
||||
return ossStorageService.generateFreshDownloadUrl(entity.getResultFileUrl());
|
||||
}
|
||||
@@ -347,7 +348,7 @@ public class ConvertRunService {
|
||||
.filter(column -> !resolvedHeaderMap.containsKey(column))
|
||||
.toList();
|
||||
if (!missing.isEmpty()) {
|
||||
throw new BusinessException("Missing required columns: " + String.join(", ", missing));
|
||||
throw new BusinessException("缺少必需列: " + String.join(", ", missing));
|
||||
}
|
||||
headerRead[0] = true;
|
||||
headerMapHolder.set(resolvedHeaderMap);
|
||||
@@ -364,7 +365,7 @@ public class ConvertRunService {
|
||||
public void onRow(String sheetName, Integer sheetNo, int excelRowIndex, Map<Integer, String> headerMap, Map<Integer, String> rowMap) throws Exception {
|
||||
Map<String, Integer> resolvedHeaderMap = headerMapHolder.get();
|
||||
if (resolvedHeaderMap == null) {
|
||||
throw new BusinessException("Excel header row is empty.");
|
||||
throw new BusinessException("Excel 表头行为空。");
|
||||
}
|
||||
int asinIndex = resolvedHeaderMap.getOrDefault("ASIN", -1);
|
||||
String asin = asinIndex >= 0 ? normalizeCellText(rowMap.get(asinIndex)) : "";
|
||||
@@ -400,7 +401,7 @@ public class ConvertRunService {
|
||||
}
|
||||
});
|
||||
if (!headerRead[0]) {
|
||||
throw new BusinessException("Excel header row is empty.");
|
||||
throw new BusinessException("Excel 表头行为空。");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -419,7 +420,7 @@ public class ConvertRunService {
|
||||
return objectMapper.readValue(json, new TypeReference<List<String>>() {
|
||||
});
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Template config parsing failed.");
|
||||
throw new BusinessException("模板配置解析失败。");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -434,7 +435,7 @@ public class ConvertRunService {
|
||||
zos.closeEntry();
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Convert result packaging failed: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("转换结果打包失败", ex));
|
||||
}
|
||||
return zipFile;
|
||||
}
|
||||
@@ -450,7 +451,7 @@ public class ConvertRunService {
|
||||
zos.closeEntry();
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Convert folder result packaging failed: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("转换目录结果打包失败", ex));
|
||||
}
|
||||
return zipFile;
|
||||
}
|
||||
@@ -489,7 +490,7 @@ public class ConvertRunService {
|
||||
return objectMapper.readValue(json, new TypeReference<Map<String, String>>() {
|
||||
});
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Template config parsing failed.");
|
||||
throw new BusinessException("模板配置解析失败。");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+12
-14
@@ -94,12 +94,10 @@ public class DedupeTotalDataController {
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireDedupeTotalDataAccess(request);
|
||||
AdminUserEntity user = operator.user();
|
||||
List<Long> memberIds = operator.superAdmin()
|
||||
? dataReadScope.readScope(user, companyId).userIdsOr(null)
|
||||
: null;
|
||||
Long scopedCompanyId = dataReadScope.superAdminScopedCompanyId(user, companyId);
|
||||
return ApiResponse.success(dedupeTotalDataService.page(
|
||||
page, pageSize, keyword, username, startDate, endDate, groupId, country, lastId,
|
||||
operator.id(), memberIds));
|
||||
operator.id(), scopedCompanyId));
|
||||
}
|
||||
|
||||
@GetMapping("/export")
|
||||
@@ -115,14 +113,12 @@ public class DedupeTotalDataController {
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
|
||||
HttpServletRequest request) {
|
||||
if (startDate != null && endDate != null && startDate.isAfter(endDate)) {
|
||||
throw new BusinessException(400, "invalid export date range");
|
||||
throw new BusinessException(400, "导出的日期范围不对,请重新选择开始和结束日期");
|
||||
}
|
||||
RequestOperator operator = requireDedupeTotalDataAccess(request);
|
||||
AdminUserEntity user = operator.user();
|
||||
Long operatorId = operator.id();
|
||||
List<Long> memberIds = operator.superAdmin()
|
||||
? dataReadScope.readScope(user, companyId).userIdsOr(null)
|
||||
: null;
|
||||
Long scopedCompanyId = dataReadScope.superAdminScopedCompanyId(user, companyId);
|
||||
boolean monthlyZip = isCrossMonthRange(startDate, endDate);
|
||||
String filename = "dedupe-total-data-" + LocalDateTime.now().format(EXPORT_FILENAME_FORMATTER)
|
||||
+ (monthlyZip ? ".zip" : ".xlsx");
|
||||
@@ -130,9 +126,9 @@ public class DedupeTotalDataController {
|
||||
// 会把它当成"范围没交给任何调用"而假红),所以 operatorId 先在局部变量里落好。
|
||||
StreamingResponseBody body = monthlyZip
|
||||
? outputStream -> dedupeTotalDataService.writeMonthlyZipExport(
|
||||
outputStream, username, startDate, endDate, groupId, country, operatorId, memberIds)
|
||||
outputStream, username, startDate, endDate, groupId, country, operatorId, scopedCompanyId)
|
||||
: outputStream -> dedupeTotalDataService.writeExport(
|
||||
outputStream, username, startDate, endDate, groupId, country, operatorId, memberIds);
|
||||
outputStream, username, startDate, endDate, groupId, country, operatorId, scopedCompanyId);
|
||||
return ResponseEntity.ok()
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, DownloadHeaderUtil.contentDisposition(filename))
|
||||
.contentType(MediaType.parseMediaType(monthlyZip ? ZIP_CONTENT_TYPE : XLSX_CONTENT_TYPE))
|
||||
@@ -301,10 +297,12 @@ public class DedupeTotalDataController {
|
||||
|
||||
// 公司 tab 的读范围与写侧归属(create / import / delete-import)都就地算在 handler 里,
|
||||
// 不留私有收口方法:G2 的断言 A 只在这支 handler 的
|
||||
// 块内找 readScope(,私有方法在它自己的闭括号处收口、不算在内(CompanyIdParamGoesThroughReadScopeTest
|
||||
// 类注释第 5、7 条),挪进去 = 这一页的 tab 没人看守。收窄只给超管:非超管已由 resolveAccessScope
|
||||
// 按会话裁剪,且他的可见集里含「靠分组可见」的行,叠一层账号 IN 会把那批行静默删掉
|
||||
// (同 ShopManageController 的口径)。
|
||||
// 块内找正门调用,私有方法在它自己的闭括号处收口、不算在内(CompanyIdParamGoesThroughReadScopeTest
|
||||
// 类注释第 5、7 条),挪进去 = 这一页的 tab 没人看守。读侧收窄走 superAdminScopedCompanyId
|
||||
// (2026-10-09 口径切换:从"上传账号集合"改到"行自己的 company_id",超管代导入与上传者已删
|
||||
// 两类行原口径都归错,见该方法 javadoc);写侧 create/import 走 readCompanyIdOrOwn。
|
||||
// 两条都只对超管生效:非超管已由 resolveAccessScope 按会话裁剪,且他的可见集里含
|
||||
// 「靠分组可见」的行,叠一层公司谓词会把那批行静默删掉(同 ShopManageController 的口径)。
|
||||
|
||||
private record RequestOperator(Long id, boolean superAdmin, AdminUserEntity user) {
|
||||
}
|
||||
|
||||
+6
-5
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.dedupe.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import cn.hutool.json.JSONUtil;
|
||||
@@ -197,7 +198,7 @@ public class DedupeRunService {
|
||||
} catch (Exception e) {
|
||||
runProgressMap.remove(runId);
|
||||
decrementRunningCount(request.getUserId());
|
||||
throw new BusinessException("提交去重任务失败:" + e.getMessage());
|
||||
throw new BusinessException(UserMessages.with("提交去重任务失败", e));
|
||||
}
|
||||
|
||||
return snapshot(progress);
|
||||
@@ -375,7 +376,7 @@ public class DedupeRunService {
|
||||
synchronized (progress) {
|
||||
progress.setStatus("failed");
|
||||
progress.setFinished(true);
|
||||
progress.setError("去重任务收尾失败:" + ex.getMessage());
|
||||
progress.setError(UserMessages.with("去重任务收尾失败", ex));
|
||||
}
|
||||
task.setStatus("FAILED");
|
||||
task.setErrorMessage(progress.getError());
|
||||
@@ -558,7 +559,7 @@ public class DedupeRunService {
|
||||
return item;
|
||||
} catch (Exception ex) {
|
||||
item.setSuccess(false);
|
||||
item.setError(ex.getMessage());
|
||||
item.setError(UserMessages.orFallback(ex.getMessage(), "这个文件去重失败,请检查内容后重新上传"));
|
||||
log.error("dedupe run file failed fileKey={} filename={} error",
|
||||
sourceFile.getFileKey(), sourceFile.getOriginalFilename(), ex);
|
||||
try {
|
||||
@@ -567,7 +568,7 @@ public class DedupeRunService {
|
||||
resultEntity.setModuleType("DEDUPE");
|
||||
resultEntity.setSourceFilename(sourceFile.getOriginalFilename());
|
||||
resultEntity.setSuccess(0);
|
||||
resultEntity.setErrorMessage(ex.getMessage());
|
||||
resultEntity.setErrorMessage(UserMessages.orFallback(ex.getMessage(), "这个文件去重失败,请检查内容后重新上传"));
|
||||
resultEntity.setUserId(request.getUserId());
|
||||
resultEntity.setCreatedAt(LocalDateTime.now());
|
||||
fileResultMapper.insert(resultEntity);
|
||||
@@ -963,7 +964,7 @@ public class DedupeRunService {
|
||||
zos.closeEntry();
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("去重结果打包失败:" + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("去重结果打包失败", ex));
|
||||
}
|
||||
return zipFile;
|
||||
}
|
||||
|
||||
+53
-40
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.dedupe.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
@@ -171,12 +172,12 @@ public class DedupeTotalDataService {
|
||||
/**
|
||||
* @param lastId keyset 游标(上一页返回的 nextLastId);非空时忽略 page 偏移,
|
||||
* 直接按 id 倒序取"比它小"的一页,避免深分页 offset 扫索引的代价
|
||||
* @param companyMemberIds 公司 tab 收窄后的成员账号集({@code DataReadScope} 给出);
|
||||
* null = 不筛(超管没选公司 / 非超管走会话范围)
|
||||
* @param scopedCompanyId 公司 tab 收窄后的公司 id({@code DataReadScope#superAdminScopedCompanyId} 给出);
|
||||
* null = 不筛(超管没选公司 / 非超管走会话范围)
|
||||
*/
|
||||
public DedupeTotalDataPageVo page(long page, long pageSize, String keyword, String username,
|
||||
LocalDate startDate, LocalDate endDate, Long groupId, String country,
|
||||
Long lastId, Long operatorId, List<Long> companyMemberIds) {
|
||||
Long lastId, Long operatorId, Long scopedCompanyId) {
|
||||
if (startDate != null && endDate != null && startDate.isAfter(endDate)) {
|
||||
throw new BusinessException("开始日期不能晚于结束日期");
|
||||
}
|
||||
@@ -201,7 +202,7 @@ public class DedupeTotalDataService {
|
||||
endDate == null ? null : endDate.plusDays(1).atStartOfDay())
|
||||
.orderByDesc(DedupeTotalDataEntity::getId);
|
||||
applyGroupScope(query, scope, groupId);
|
||||
applyCompanyScope(query, companyMemberIds);
|
||||
applyCompanyScope(query, scopedCompanyId);
|
||||
Long total = dedupeTotalDataMapper.selectCount(query);
|
||||
boolean keyset = lastId != null && lastId > 0;
|
||||
if (keyset) {
|
||||
@@ -274,17 +275,17 @@ public class DedupeTotalDataService {
|
||||
Long groupId,
|
||||
String country,
|
||||
Long operatorId,
|
||||
List<Long> companyMemberIds) {
|
||||
Long scopedCompanyId) {
|
||||
if (outputStream == null) {
|
||||
throw new BusinessException("导出输出流不能为空");
|
||||
}
|
||||
if (startDate != null && endDate != null && startDate.isAfter(endDate)) {
|
||||
throw new BusinessException("invalid export date range");
|
||||
throw new BusinessException("导出的日期范围不对,请重新选择开始和结束日期");
|
||||
}
|
||||
String safeUsername = username == null ? "" : username.trim();
|
||||
AccessScope scope = resolveAccessScope(operatorId);
|
||||
buildExportWorkbook(outputStream, safeUsername, startDate, endDate, groupId, country, scope, false,
|
||||
companyMemberIds);
|
||||
scopedCompanyId);
|
||||
}
|
||||
|
||||
public void writeMonthlyZipExport(OutputStream outputStream,
|
||||
@@ -313,16 +314,16 @@ public class DedupeTotalDataService {
|
||||
Long groupId,
|
||||
String country,
|
||||
Long operatorId,
|
||||
List<Long> companyMemberIds) {
|
||||
Long scopedCompanyId) {
|
||||
if (outputStream == null) {
|
||||
throw new BusinessException("export output stream cannot be null");
|
||||
throw new BusinessException("导出文件写入失败,请稍后重试");
|
||||
}
|
||||
if (startDate == null || endDate == null || YearMonth.from(startDate).equals(YearMonth.from(endDate))) {
|
||||
writeExport(outputStream, username, startDate, endDate, groupId, country, operatorId, companyMemberIds);
|
||||
writeExport(outputStream, username, startDate, endDate, groupId, country, operatorId, scopedCompanyId);
|
||||
return;
|
||||
}
|
||||
if (startDate.isAfter(endDate)) {
|
||||
throw new BusinessException("invalid export date range");
|
||||
throw new BusinessException("导出的日期范围不对,请重新选择开始和结束日期");
|
||||
}
|
||||
String safeUsername = username == null ? "" : username.trim();
|
||||
String safeCountry = country == null ? "" : country.trim();
|
||||
@@ -342,7 +343,7 @@ public class DedupeTotalDataService {
|
||||
LocalDate entryEndDate = endDate.isBefore(monthEnd) ? endDate : monthEnd;
|
||||
zipOutputStream.putNextEntry(new ZipEntry(monthlyExportEntryName(currentMonth)));
|
||||
buildExportWorkbook(zipOutputStream, safeUsername, entryStartDate, entryEndDate,
|
||||
groupId, safeCountry, scope, groupPrevalidated, companyMemberIds);
|
||||
groupId, safeCountry, scope, groupPrevalidated, scopedCompanyId);
|
||||
zipOutputStream.closeEntry();
|
||||
currentMonth = currentMonth.plusMonths(1);
|
||||
}
|
||||
@@ -350,7 +351,7 @@ public class DedupeTotalDataService {
|
||||
} catch (BusinessException ex) {
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("export dedupe total data failed");
|
||||
throw new BusinessException("去重库数据导出失败,请稍后重试");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -372,7 +373,7 @@ public class DedupeTotalDataService {
|
||||
String country,
|
||||
AccessScope scope,
|
||||
boolean groupPrevalidated,
|
||||
List<Long> companyMemberIds) {
|
||||
Long scopedCompanyId) {
|
||||
try (SXSSFWorkbook workbook = new SXSSFWorkbook(100)) {
|
||||
Sheet sheet = workbook.createSheet("DedupeTotalData");
|
||||
Row header = sheet.createRow(0);
|
||||
@@ -386,7 +387,7 @@ public class DedupeTotalDataService {
|
||||
int rowIndex = 1;
|
||||
while (true) {
|
||||
LambdaQueryWrapper<DedupeTotalDataEntity> pageQuery = buildExportQuery(
|
||||
username, startDate, endDate, groupId, country, scope, groupPrevalidated, companyMemberIds);
|
||||
username, startDate, endDate, groupId, country, scope, groupPrevalidated, scopedCompanyId);
|
||||
if (lastId != null) {
|
||||
pageQuery.lt(DedupeTotalDataEntity::getId, lastId);
|
||||
}
|
||||
@@ -444,7 +445,7 @@ public class DedupeTotalDataService {
|
||||
String country,
|
||||
AccessScope scope,
|
||||
boolean groupPrevalidated,
|
||||
List<Long> companyMemberIds) {
|
||||
Long scopedCompanyId) {
|
||||
String safeUsername = username == null ? "" : username.trim();
|
||||
String safeCountry = country == null ? "" : country.trim();
|
||||
LambdaQueryWrapper<DedupeTotalDataEntity> query = new LambdaQueryWrapper<DedupeTotalDataEntity>()
|
||||
@@ -458,7 +459,7 @@ public class DedupeTotalDataService {
|
||||
endDate == null ? null : endDate.plusDays(1).atStartOfDay())
|
||||
.orderByDesc(DedupeTotalDataEntity::getId);
|
||||
applyGroupScope(query, scope, groupId, groupPrevalidated);
|
||||
applyCompanyScope(query, companyMemberIds);
|
||||
applyCompanyScope(query, scopedCompanyId);
|
||||
return query;
|
||||
}
|
||||
|
||||
@@ -670,7 +671,7 @@ public class DedupeTotalDataService {
|
||||
progress.setStatus("success");
|
||||
} catch (Exception e) {
|
||||
progress.setStatus("failed");
|
||||
progress.setErrorMessage(e instanceof BusinessException ? e.getMessage() : "删除 Excel 匹配数据失败");
|
||||
progress.setErrorMessage(UserMessages.orFallback(e.getMessage(), "删除 Excel 匹配数据失败"));
|
||||
} finally {
|
||||
deleteQuietly(tempFile);
|
||||
deleteImportCompletedAtMap.put(importId, System.currentTimeMillis());
|
||||
@@ -697,7 +698,7 @@ public class DedupeTotalDataService {
|
||||
progress.setStatus("success");
|
||||
} catch (Exception e) {
|
||||
progress.setStatus("failed");
|
||||
progress.setErrorMessage(e instanceof BusinessException ? e.getMessage() : "导入 Excel 失败");
|
||||
progress.setErrorMessage(UserMessages.orFallback(e.getMessage(), "导入 Excel 失败"));
|
||||
// 此前该 catch 既不记日志也不带 cause,线上只有一句「导入 Excel 失败」,无栈无定位线索
|
||||
log.error("[dedupe-total-data] 异步导入失败 filename={} userId={}", filename, uploaderUserId, e);
|
||||
} finally {
|
||||
@@ -1257,7 +1258,7 @@ public class DedupeTotalDataService {
|
||||
private AccessScope resolveAccessScope(Long operatorId) {
|
||||
AdminUserEntity operator = getOperator(operatorId);
|
||||
if (isSuperAdmin(operator)) {
|
||||
return new AccessScope(true, Set.of(), Set.of(), false);
|
||||
return new AccessScope(true, Set.of(), Set.of(), false, null);
|
||||
}
|
||||
if ("company_super_admin".equals(operator.getRole() == null
|
||||
? "" : operator.getRole().trim().toLowerCase(Locale.ROOT))) {
|
||||
@@ -1272,7 +1273,8 @@ public class DedupeTotalDataService {
|
||||
// allUsers 与 groupIds 两样,读侧才走 wholeCompany 那一支。这里留空集的表现是
|
||||
// 「下拉选得到自己公司的分组、提交必 403」,而 403 是 HTTP 状态不是中文文案。
|
||||
Set<Long> companyGroupIds = shopManageGroupService.listCompanyGroupIds(List.copyOf(companyUserIds));
|
||||
return new AccessScope(false, companyGroupIds, Set.copyOf(companyUserIds), true);
|
||||
return new AccessScope(false, companyGroupIds, Set.copyOf(companyUserIds), true,
|
||||
operator.getCompanyId());
|
||||
}
|
||||
List<Long> accessibleGroupIds = shopManageGroupMapper.selectAccessibleGroupIds(operator.getId());
|
||||
LinkedHashSet<Long> visibleUserIds = new LinkedHashSet<>();
|
||||
@@ -1295,7 +1297,8 @@ public class DedupeTotalDataService {
|
||||
false,
|
||||
Set.copyOf(accessibleGroupIds == null ? List.of() : accessibleGroupIds),
|
||||
Set.copyOf(visibleUserIds),
|
||||
false);
|
||||
false,
|
||||
null);
|
||||
}
|
||||
|
||||
private void applyGroupScope(LambdaQueryWrapper<DedupeTotalDataEntity> query,
|
||||
@@ -1316,8 +1319,16 @@ public class DedupeTotalDataService {
|
||||
return;
|
||||
}
|
||||
if (scope.wholeCompany()) {
|
||||
// 公司超管:整家公司成员上传的行全可见,不再按 group_id 切
|
||||
query.in(DedupeTotalDataEntity::getUploaderUserId, scope.userIds());
|
||||
// 公司超管:整家公司名下的行全可见,不再按 group_id 切。
|
||||
// 2026-10-09 与 tab 收窄同批从"成员上传"切到行 company_id:原口径漏
|
||||
// 「代导入行」(uploader 不属本公司)与「上传账号已删的行」(JOIN 不上成员集),
|
||||
// 先锋公司超管(uid=1206)对这两族一行都看不到。companyId 空属异常态
|
||||
// (company_super_admin 必挂公司),给不可能命中的条件而不是"不筛"。
|
||||
if (scope.companyId() == null) {
|
||||
query.eq(DedupeTotalDataEntity::getId, -1L);
|
||||
return;
|
||||
}
|
||||
query.eq(DedupeTotalDataEntity::getCompanyId, scope.companyId());
|
||||
return;
|
||||
}
|
||||
query.and(wrapper -> {
|
||||
@@ -1331,24 +1342,22 @@ public class DedupeTotalDataService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 公司 tab 收窄:本表按「上传账号」认公司——{@code uploader_user_id} 是 NOT NULL(V75 先回灌再收紧),
|
||||
* 且有 idx_uploader_user_id_id 可走点查。
|
||||
* 公司 tab 收窄:按行自己的 {@code company_id} 筛(V145 物化的列、uk_company_data_value 的第一列)。
|
||||
*
|
||||
* <p>不按 V145 加的 company_id 筛:那一列对 V145 之前的历史行全部是 DEFAULT 兜的 1,没有区分力。
|
||||
* 写侧现已显式落值(create 与 insertBatchIgnore 都带 company_id),但读侧一旦改用它,历史行会整批归到
|
||||
* 公司 1——所以那列只供写入留存与 uk_company_data_value 使用,读侧口径维持按上传账号推导。</p>
|
||||
* <p>2026-10-09 从"按上传账号推导"切到这里(控制方截图为证:超管 admin 在「先锋」tab 代导入的
|
||||
* 行 uploader=admin,读侧整批出现在 admin 自己那一家、目标 tab 反而看不到)。切换的历史行风险
|
||||
* 已逐项处置:V145 第 2 段迁移当时就按上传账号反推过一遍(非公司 1 账号的行 company_id 已是真值);
|
||||
* 写侧自 39de5035 起 create/insertBatchIgnore/导入一律显式落值、V154 已摘 DEFAULT,漏传即报错
|
||||
* 而不会兜进公司 1;剩余一批"上传账号被硬删、归属兜成 1"的历史行(组 33「先锋」,1452 行)
|
||||
* 由 V156 回填到真实归属。切换后本表读、写、去重比对、唯一键四侧同一口径。</p>
|
||||
*
|
||||
* <p>空集给一条不可能命中的条件而不是"不筛":tab 选了这家公司却看得到全平台,比看不到更坏。</p>
|
||||
* <p>{@code null} = 不筛(超管没选公司 / 非超管走会话范围)。</p>
|
||||
*/
|
||||
private void applyCompanyScope(LambdaQueryWrapper<DedupeTotalDataEntity> query, List<Long> companyMemberIds) {
|
||||
if (companyMemberIds == null) {
|
||||
private void applyCompanyScope(LambdaQueryWrapper<DedupeTotalDataEntity> query, Long scopedCompanyId) {
|
||||
if (scopedCompanyId == null) {
|
||||
return;
|
||||
}
|
||||
if (companyMemberIds.isEmpty()) {
|
||||
query.eq(DedupeTotalDataEntity::getId, -1L);
|
||||
return;
|
||||
}
|
||||
query.in(DedupeTotalDataEntity::getUploaderUserId, companyMemberIds);
|
||||
query.eq(DedupeTotalDataEntity::getCompanyId, scopedCompanyId);
|
||||
}
|
||||
|
||||
private ShopManageGroupEntity resolveWritableGroup(Long groupId, AdminUserEntity operator) {
|
||||
@@ -1523,9 +1532,13 @@ public class DedupeTotalDataService {
|
||||
|
||||
/**
|
||||
* @param allUsers 超管直通
|
||||
* @param wholeCompany 公司超管:不做分组维度裁剪,userIds = 本公司全体成员,
|
||||
* 查询条件退化为 uploader_user_id IN (成员)——公司超管的"组"就是整家公司
|
||||
* @param wholeCompany 公司超管:不做分组维度裁剪,查询条件退化为 company_id = companyId
|
||||
* (2026-10-09 起按行归属列;见 {@code applyGroupScope} 该分支的切换理由)。
|
||||
* 公司超管的"组"就是整家公司;userIds 仅剩写侧闸门(ensureRecordAccess 的
|
||||
* group_id IS NULL 那一支)在用
|
||||
* @param companyId 公司超管所属公司;仅 wholeCompany=true 时有值
|
||||
*/
|
||||
record AccessScope(boolean allUsers, Set<Long> groupIds, Set<Long> userIds, boolean wholeCompany) {
|
||||
record AccessScope(boolean allUsers, Set<Long> groupIds, Set<Long> userIds, boolean wholeCompany,
|
||||
Long companyId) {
|
||||
}
|
||||
}
|
||||
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.deletebrand.controller;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
@@ -148,10 +149,10 @@ public class DeleteBrandRunController {
|
||||
return ApiResponse.success(null);
|
||||
} catch (BusinessException ex) {
|
||||
response.setStatus(HttpStatus.BAD_REQUEST.value());
|
||||
return ApiResponse.fail(ex.getMessage());
|
||||
return ApiResponse.fail(UserMessages.orFallback(ex.getMessage(), "删除ASIN提交失败,请稍后重试"));
|
||||
} catch (Exception ex) {
|
||||
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
|
||||
return ApiResponse.fail("服务异常:" + ex.getMessage());
|
||||
return ApiResponse.fail(UserMessages.with("删除ASIN提交失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+13
-12
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.deletebrand.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import cn.hutool.json.JSONUtil;
|
||||
@@ -246,7 +247,7 @@ public class DeleteBrandRunService {
|
||||
item.setResultId(resultEntity.getId());
|
||||
} catch (Exception ex) {
|
||||
item.setSuccess(false);
|
||||
item.setError(ex.getMessage());
|
||||
item.setError(UserMessages.orFallback(ex.getMessage(), "这个文件解析失败,请检查内容后重新上传"));
|
||||
parsedFailedCount++;
|
||||
|
||||
FileResultEntity resultEntity = new FileResultEntity();
|
||||
@@ -255,7 +256,7 @@ public class DeleteBrandRunService {
|
||||
resultEntity.setSourceFilename(sourceFile.getOriginalFilename());
|
||||
resultEntity.setSourceFileUrl(sourceFile.getFileKey());
|
||||
resultEntity.setSuccess(0);
|
||||
resultEntity.setErrorMessage(ex.getMessage());
|
||||
resultEntity.setErrorMessage(UserMessages.orFallback(ex.getMessage(), "这个文件解析失败,请检查内容后重新上传"));
|
||||
resultEntity.setUserId(request.getUserId());
|
||||
resultEntity.setCreatedAt(LocalDateTime.now());
|
||||
fileResultMapper.insert(resultEntity);
|
||||
@@ -1345,18 +1346,18 @@ public class DeleteBrandRunService {
|
||||
@Transactional(propagation = org.springframework.transaction.annotation.Propagation.NEVER)
|
||||
public void submitResult(Long taskId, DeleteBrandSubmitResultRequest request) {
|
||||
if (taskId == null || taskId <= 0) {
|
||||
throw new BusinessException("taskId invalid");
|
||||
throw new BusinessException("任务 id 不合法");
|
||||
}
|
||||
try (TaskDistributedLockService.LockHandle ignored = acquireTaskLockOrThrow(taskId, TASK_LOCK_WAIT_MILLIS)) {
|
||||
log.info("[DeleteBrand] Received submitResult for taskId: {}, files count: {}", taskId, request == null || request.getFiles() == null ? 0 : request.getFiles().size());
|
||||
|
||||
if (request == null || request.getFiles() == null || request.getFiles().isEmpty()) {
|
||||
throw new BusinessException("files is empty");
|
||||
throw new BusinessException("文件列表为空");
|
||||
}
|
||||
|
||||
FileTaskEntity task = loadTaskForExecution(taskId);
|
||||
if (task == null || !MODULE_TYPE.equals(task.getModuleType())) {
|
||||
throw new BusinessException("task not found");
|
||||
throw new BusinessException("任务不存在");
|
||||
}
|
||||
if ("SUCCESS".equals(task.getStatus()) || "FAILED".equals(task.getStatus())) {
|
||||
log.warn("[DeleteBrand] submitResult rejected because task is terminal -> taskId: {}, status: {}, createdAt: {}, updatedAt: {}, finishedAt: {}, error: {}, sourceFiles: {}, successFiles: {}, failedFiles: {}",
|
||||
@@ -1369,12 +1370,12 @@ public class DeleteBrandRunService {
|
||||
task.getSourceFileCount(),
|
||||
task.getSuccessFileCount(),
|
||||
task.getFailedFileCount());
|
||||
throw new BusinessException("task already finished");
|
||||
throw new BusinessException("任务已结束");
|
||||
}
|
||||
|
||||
Map<String, DeleteBrandParsedFileCacheDto> parsedPayload = deleteBrandTaskStorageService.loadParsedPayload(taskId);
|
||||
if (parsedPayload == null || parsedPayload.isEmpty()) {
|
||||
throw new BusinessException("task parsed payload missing");
|
||||
throw new BusinessException("任务解析结果不存在");
|
||||
}
|
||||
|
||||
if (!"RUNNING".equals(task.getStatus())) {
|
||||
@@ -1397,12 +1398,12 @@ public class DeleteBrandRunService {
|
||||
|
||||
String fileIdentity = resolveFileIdentity(fileDto);
|
||||
if (fileIdentity.isBlank()) {
|
||||
throw new BusinessException("file identity is blank");
|
||||
throw new BusinessException("文件标识为空");
|
||||
}
|
||||
DeleteBrandParsedFileCacheDto parsedFile = parsedPayload.get(fileIdentity);
|
||||
if (parsedFile == null) {
|
||||
log.warn("[DeleteBrand] parsed payload not found for identity: {}", fileIdentity);
|
||||
throw new BusinessException("parsed file not found: " + fileIdentity);
|
||||
throw new BusinessException("找不到已解析文件: " + fileIdentity);
|
||||
}
|
||||
|
||||
validateChunk(fileDto, parsedFile);
|
||||
@@ -1562,7 +1563,7 @@ public class DeleteBrandRunService {
|
||||
log.info("[DeleteBrand] tryFinalizeTask calling finalizeTask -> finishedFiles: {}, expectedFiles: {}", finishedFiles, expectedFiles);
|
||||
finalizeTask(task, parsedPayload, mergedByFile);
|
||||
} catch (BusinessException ex) {
|
||||
if (ex.getMessage() != null && ex.getMessage().contains("task lock is busy")) {
|
||||
if (ex.getMessage() != null && ex.getMessage().contains("任务正被占用,请稍后重试")) {
|
||||
log.info("[DeleteBrand] tryFinalizeTask skipped because task lock is busy taskId={} fromCompensation={}", taskId, fromCompensation);
|
||||
return;
|
||||
}
|
||||
@@ -1842,7 +1843,7 @@ public class DeleteBrandRunService {
|
||||
cleanupCompletedTaskDataIfNoPendingFileJobs(task.getId());
|
||||
} catch (Exception ex) {
|
||||
task.setStatus("FAILED");
|
||||
task.setErrorMessage(ex.getMessage());
|
||||
task.setErrorMessage(UserMessages.orFallback(ex.getMessage(), "删除ASIN任务执行失败"));
|
||||
task.setUpdatedAt(LocalDateTime.now());
|
||||
task.setFinishedAt(LocalDateTime.now());
|
||||
fileTaskMapper.updateById(task);
|
||||
@@ -2250,7 +2251,7 @@ public class DeleteBrandRunService {
|
||||
private TaskDistributedLockService.LockHandle acquireTaskLockOrThrow(Long taskId, long waitMillis) {
|
||||
TaskDistributedLockService.LockHandle lockHandle = acquireTaskLock(taskId, waitMillis);
|
||||
if (lockHandle == null) {
|
||||
throw new BusinessException("task lock is busy");
|
||||
throw new BusinessException("任务正被占用,请稍后重试");
|
||||
}
|
||||
return lockHandle;
|
||||
}
|
||||
|
||||
+9
-9
@@ -54,7 +54,7 @@ public class DeleteBrandTaskStorageService {
|
||||
}
|
||||
String scopeHash = hash(scopeKey);
|
||||
TaskScopeStateEntity existing = existingByHash.get(scopeHash);
|
||||
String payloadJson = writeJson(entry.getValue(), "failed to save delete-brand parsed payload");
|
||||
String payloadJson = writeJson(entry.getValue(), "保存删品牌任务解析结果失败");
|
||||
String parsedPayloadPointer = storeParsedPayload(taskId, scopeHash, payloadJson);
|
||||
if (existing == null) {
|
||||
TaskScopeStateEntity entity = new TaskScopeStateEntity();
|
||||
@@ -80,7 +80,7 @@ public class DeleteBrandTaskStorageService {
|
||||
}
|
||||
}
|
||||
if (existing == null) {
|
||||
throw new BusinessException("failed to save delete-brand parsed payload");
|
||||
throw new BusinessException("保存删品牌任务解析结果失败");
|
||||
}
|
||||
transientPayloadStorageService.deleteReplacedPayloadIfNeeded(existing.getParsedPayloadJson(), parsedPayloadPointer);
|
||||
taskScopeStateMapper.update(null, new LambdaUpdateWrapper<TaskScopeStateEntity>()
|
||||
@@ -115,7 +115,7 @@ public class DeleteBrandTaskStorageService {
|
||||
try {
|
||||
result.put(state.getScopeKey(), objectMapper.readValue(payloadJson, DeleteBrandParsedFileCacheDto.class));
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("failed to load delete-brand parsed payload");
|
||||
throw new BusinessException("读取删品牌任务解析结果失败");
|
||||
}
|
||||
}
|
||||
return result;
|
||||
@@ -146,14 +146,14 @@ public class DeleteBrandTaskStorageService {
|
||||
@Transactional
|
||||
public boolean storeResultChunkIfChanged(Long taskId, String scopeKey, Integer chunkIndex, DeleteBrandResultFileDto chunk) {
|
||||
if (taskId == null || taskId <= 0) {
|
||||
throw new BusinessException("taskId is invalid");
|
||||
throw new BusinessException("任务 id 不合法");
|
||||
}
|
||||
if (chunkIndex == null || chunkIndex <= 0) {
|
||||
throw new BusinessException("chunkIndex is invalid");
|
||||
throw new BusinessException("分片序号不合法");
|
||||
}
|
||||
String normalizedScopeKey = normalizeScopeKey(scopeKey);
|
||||
if (normalizedScopeKey.isBlank()) {
|
||||
throw new BusinessException("scopeKey must not be blank");
|
||||
throw new BusinessException("范围标识不能为空");
|
||||
}
|
||||
String scopeHash = hash(normalizedScopeKey);
|
||||
String payloadJson = writeJson(chunk, "failed to save delete-brand result chunk");
|
||||
@@ -244,7 +244,7 @@ public class DeleteBrandTaskStorageService {
|
||||
} catch (Exception ex) {
|
||||
log.warn("[delete-brand-storage] failed to load result chunk taskId={} scopeKey={} chunkIndex={} payload={}",
|
||||
taskId, entity.getScopeKey(), entity.getChunkIndex(), entity.getPayloadJson(), ex);
|
||||
throw new BusinessException("failed to load delete-brand result chunks: taskId="
|
||||
throw new BusinessException("读取删品牌任务结果分片失败: taskId="
|
||||
+ taskId + ", scopeKey=" + entity.getScopeKey() + ", chunkIndex=" + entity.getChunkIndex());
|
||||
}
|
||||
}
|
||||
@@ -417,9 +417,9 @@ public class DeleteBrandTaskStorageService {
|
||||
|
||||
private String resolveParsedPayload(String value) {
|
||||
try {
|
||||
return transientPayloadStorageService.resolvePayload(value, "failed to load delete-brand parsed payload");
|
||||
return transientPayloadStorageService.resolvePayload(value, "读取删品牌任务解析结果失败");
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("failed to load delete-brand parsed payload");
|
||||
throw new BusinessException("读取删品牌任务解析结果失败");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.digitalhuman.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
@@ -96,7 +97,7 @@ public class DigitalHumanVersionService {
|
||||
return toVo(entity);
|
||||
} catch (IOException e) {
|
||||
log.error("上传数字人版本失败", e);
|
||||
throw new BusinessException("文件处理失败:" + e.getMessage());
|
||||
throw new BusinessException(UserMessages.with("文件处理失败", e));
|
||||
} catch (RuntimeException e) {
|
||||
log.error("[digital-human-version] upload failed version={} filename={} elapsedMs={} err={}",
|
||||
version, originalFilename, elapsedMs(startedAt), e.getMessage(), e);
|
||||
@@ -277,7 +278,7 @@ public class DigitalHumanVersionService {
|
||||
BigInteger bigInt = new BigInteger(1, digest);
|
||||
return bigInt.toString(16).toLowerCase();
|
||||
} catch (Exception e) {
|
||||
throw new BusinessException("计算 MD5 失败:" + e.getMessage());
|
||||
throw new BusinessException(UserMessages.with("计算 MD5 失败", e));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.imagevideo.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
@@ -204,7 +205,7 @@ public class ImageVideoAdminTaskService {
|
||||
deleteQuietly(zipFile);
|
||||
throw ex instanceof BusinessException business
|
||||
? business
|
||||
: new BusinessException("批量打包失败: " + messageOf(ex), ex);
|
||||
: new BusinessException(UserMessages.with("批量打包失败", ex), ex);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+9
-9
@@ -124,7 +124,7 @@ public class ImageVideoAsyncTaskService {
|
||||
.eq(ImageVideoAsyncTaskEntity::getId, taskId)
|
||||
.eq(ImageVideoAsyncTaskEntity::getUserId, userId));
|
||||
if (task == null) {
|
||||
throw new BusinessException("Image video task not found");
|
||||
throw new BusinessException("图像视频任务不存在");
|
||||
}
|
||||
ensureTaskOwnedByCurrentInstance(task, "query async task");
|
||||
task = recoverFalseFailedTask(task);
|
||||
@@ -260,7 +260,7 @@ public class ImageVideoAsyncTaskService {
|
||||
|
||||
private ImageVideoAsyncTaskVo submit(TaskType type, Long userId, Object payload) {
|
||||
if (userId == null || userId <= 0) {
|
||||
throw new BusinessException("userId is required");
|
||||
throw new BusinessException("缺少用户 id");
|
||||
}
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
ImageVideoAsyncTaskEntity task = new ImageVideoAsyncTaskEntity();
|
||||
@@ -330,7 +330,7 @@ public class ImageVideoAsyncTaskService {
|
||||
task.setResultJson(writeJson(result));
|
||||
String businessError = resolveCozeBusinessError(result);
|
||||
failTask(task, new BusinessException(businessError.isBlank()
|
||||
? "Coze workflow finished with status " + cozeStatus
|
||||
? "Coze 工作流已结束,状态 " + cozeStatus
|
||||
: businessError));
|
||||
} else {
|
||||
completeTask(task, transformResult(type, result), cozeStatus);
|
||||
@@ -338,7 +338,7 @@ public class ImageVideoAsyncTaskService {
|
||||
return;
|
||||
}
|
||||
if (pollingDeadlineExceeded(task)) {
|
||||
failTask(task, new BusinessException("Coze task exceeded the one-hour polling limit"));
|
||||
failTask(task, new BusinessException("Coze 任务轮询已超过一小时上限"));
|
||||
return;
|
||||
}
|
||||
task.setStatus(TaskStatus.WAITING.name());
|
||||
@@ -348,7 +348,7 @@ public class ImageVideoAsyncTaskService {
|
||||
} catch (Exception ex) {
|
||||
// Coze history calls are retried by the next polling cycle until the task's overall deadline.
|
||||
if (pollingDeadlineExceeded(task)) {
|
||||
failTask(task, new BusinessException("Coze task exceeded the one-hour polling limit", ex));
|
||||
failTask(task, new BusinessException("Coze 任务轮询已超过一小时上限", ex));
|
||||
return;
|
||||
}
|
||||
task.setStatus(TaskStatus.WAITING.name());
|
||||
@@ -423,7 +423,7 @@ public class ImageVideoAsyncTaskService {
|
||||
if (requiresVideoResult(task) && !hasFinalVideoUrl(result)) {
|
||||
task.setCozeStatus(normalizeStatus(cozeStatus));
|
||||
task.setResultJson(writeJson(result));
|
||||
failTask(task, new BusinessException("Coze workflow succeeded but video_url is empty"));
|
||||
failTask(task, new BusinessException("Coze 工作流成功但没有返回视频地址"));
|
||||
return;
|
||||
}
|
||||
task.setStatus(TaskStatus.SUCCESS.name());
|
||||
@@ -458,7 +458,7 @@ public class ImageVideoAsyncTaskService {
|
||||
return task;
|
||||
}
|
||||
String errorMessage = task.getErrorMessage() == null ? "" : task.getErrorMessage();
|
||||
if (!errorMessage.startsWith("Coze workflow finished with status ")) {
|
||||
if (!errorMessage.startsWith("Coze 工作流已结束,状态 ")) {
|
||||
return task;
|
||||
}
|
||||
task.setStatus(TaskStatus.WAITING.name());
|
||||
@@ -490,7 +490,7 @@ public class ImageVideoAsyncTaskService {
|
||||
try {
|
||||
return objectMapper.readValue(json, type);
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Image video task payload is invalid", ex);
|
||||
throw new BusinessException("图像视频任务参数不合法", ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -509,7 +509,7 @@ public class ImageVideoAsyncTaskService {
|
||||
try {
|
||||
return objectMapper.writeValueAsString(value);
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Image video task serialization failed", ex);
|
||||
throw new BusinessException("图像视频任务序列化失败", ex);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+9
-8
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.imagevideo.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
@@ -209,7 +210,7 @@ public class ImageVideoCozeService {
|
||||
public Map<String, Object> getWorkflowResult(Long userId, String workflowId, String executeId) {
|
||||
String resolvedExecuteId = firstNonBlank(executeId);
|
||||
if (!hasText(resolvedExecuteId)) {
|
||||
throw new BusinessException("execute_id cannot be blank");
|
||||
throw new BusinessException("任务执行 id 不能为空");
|
||||
}
|
||||
ImageVideoSecretService.ResolvedSecret secret = secretService.requireValid(userId);
|
||||
String cozeToken = firstNonBlank(secret.cozeToken());
|
||||
@@ -255,7 +256,7 @@ public class ImageVideoCozeService {
|
||||
vo.setMediaType(mediaType);
|
||||
return vo;
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("媒体上传失败: " + ex.getMessage(), ex);
|
||||
throw new BusinessException(UserMessages.with("媒体上传失败", ex), ex);
|
||||
} finally {
|
||||
if (tempFile != null && tempFile.exists() && !tempFile.delete()) {
|
||||
log.warn("[image-video] temp media delete failed path={}", tempFile.getAbsolutePath());
|
||||
@@ -314,7 +315,7 @@ public class ImageVideoCozeService {
|
||||
String resolvedT8Key = firstNonBlank(t8Key);
|
||||
String cozeToken = firstNonBlank(token);
|
||||
if (!hasText(resolvedT8Key)) {
|
||||
throw new BusinessException("image-video douyin copy t8_key not configured");
|
||||
throw new BusinessException("未配置抖音文案密钥 t8_key");
|
||||
}
|
||||
if (!hasText(resolvedApiKey)) {
|
||||
throw new BusinessException("图生视频抖音文案 api_key 未配置");
|
||||
@@ -408,7 +409,7 @@ public class ImageVideoCozeService {
|
||||
} catch (BusinessException ex) {
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Coze 返回解析失败: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("Coze 返回解析失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -453,7 +454,7 @@ public class ImageVideoCozeService {
|
||||
} catch (Exception ex) {
|
||||
log.warn("[image-video] parse douyin copy response failed bodyPreview={}",
|
||||
responsePreview(responseText), ex);
|
||||
throw new BusinessException("Coze 返回解析失败: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("Coze 返回解析失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -463,7 +464,7 @@ public class ImageVideoCozeService {
|
||||
} catch (BusinessException ex) {
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Coze response parse failed: " + ex.getMessage(), ex);
|
||||
throw new BusinessException(UserMessages.with("解析 Coze 响应失败", ex), ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -609,7 +610,7 @@ public class ImageVideoCozeService {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new BusinessException("Coze 调用被中断", ex);
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Coze 调用失败: " + ex.getMessage(), ex);
|
||||
throw new BusinessException(UserMessages.with("Coze 调用失败", ex), ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -639,7 +640,7 @@ public class ImageVideoCozeService {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new BusinessException("Coze 调用被中断", ex);
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Coze 调用失败: " + ex.getMessage(), ex);
|
||||
throw new BusinessException(UserMessages.with("Coze 调用失败", ex), ex);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.patroldelete.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.util.SxssfWorkbookWriter;
|
||||
import com.nanri.aiimage.modules.patroldelete.model.dto.PatrolDeleteCartRatioDto;
|
||||
@@ -83,7 +84,7 @@ public class PatrolDeleteExcelAssemblyService {
|
||||
writer.write(outputXlsx);
|
||||
} catch (Exception ex) {
|
||||
log.warn("[patrol-delete] write workbook failed: {}", ex.getMessage());
|
||||
throw new BusinessException("generate patrol-delete excel failed: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("生成巡店删除 Excel 失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.patroldelete.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.patroldelete.mapper.PatrolDeleteConditionMapper;
|
||||
@@ -232,11 +233,11 @@ public class PatrolDeleteResolveService {
|
||||
} catch (BusinessException ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(ex.getMessage());
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "该行匹配失败,请稍后重试"));
|
||||
} catch (Exception ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(Objects.toString(ex.getMessage(), "匹配异常"));
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "匹配异常"));
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
+1
-1
@@ -491,7 +491,7 @@ public class PatrolDeleteTaskService {
|
||||
inNewTransaction(() -> {
|
||||
FileResultEntity latestEntity = fileResultMapper.selectById(resultId);
|
||||
if (latestEntity == null || !MODULE_TYPE.equals(latestEntity.getModuleType()) || !userId.equals(latestEntity.getUserId())) {
|
||||
throw new BusinessException("record not found");
|
||||
throw new BusinessException("没有找到对应记录");
|
||||
}
|
||||
fileResultMapper.deleteById(resultId);
|
||||
cleanupResultAuxiliaryDataFast(taskId, resultId);
|
||||
|
||||
+2
-2
@@ -643,7 +643,7 @@ public class PermissionMenuService {
|
||||
.filter(user -> user.getId() != null && !isSuperAdmin(user))
|
||||
.collect(Collectors.toMap(AdminUserEntity::getId, Function.identity(), (left, right) -> left));
|
||||
if (requestedIds.stream().anyMatch(id -> !grantableUsers.containsKey(id))) {
|
||||
throw new BusinessException("contains unknown or non-grantable user");
|
||||
throw new BusinessException("包含不存在或不可授权的用户");
|
||||
}
|
||||
userColumnPermissionMapper.deleteByColumnId(dataPermission.getId());
|
||||
for (Long userId : requestedIds) {
|
||||
@@ -698,7 +698,7 @@ public class PermissionMenuService {
|
||||
.filter(user -> user.getId() != null && !isSuperAdmin(user))
|
||||
.collect(Collectors.toMap(AdminUserEntity::getId, Function.identity(), (left, right) -> left));
|
||||
if (requestedIds.stream().anyMatch(id -> !grantableUsers.containsKey(id))) {
|
||||
throw new BusinessException("contains unknown or non-grantable user");
|
||||
throw new BusinessException("包含不存在或不可授权的用户");
|
||||
}
|
||||
userColumnPermissionMapper.deleteByColumnId(dataPermission.getId());
|
||||
for (Long userId : requestedIds) {
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.pricetrack.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.util.SxssfWorkbookWriter;
|
||||
import com.nanri.aiimage.modules.pricetrack.model.dto.PriceTrackSubmitResultRequest;
|
||||
@@ -71,7 +72,7 @@ public class PriceTrackExcelAssemblyService {
|
||||
writer.write(outputXlsx);
|
||||
} catch (Exception ex) {
|
||||
log.warn("[price-track] write workbook failed: {}", ex.getMessage());
|
||||
throw new BusinessException("generate price-track excel failed: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("生成跟价 Excel 失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.pricetrack.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
@@ -238,11 +239,11 @@ public class PriceTrackService {
|
||||
} catch (BusinessException ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(ex.getMessage());
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "该行匹配失败,请稍后重试"));
|
||||
} catch (Exception ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(Objects.toString(ex.getMessage(), "匹配异常"));
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "匹配异常"));
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
+7
-6
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.pricetrack.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
@@ -240,7 +241,7 @@ public class PriceTrackTaskService {
|
||||
inNewTransaction(() -> {
|
||||
FileResultEntity latestEntity = fileResultMapper.selectById(resultId);
|
||||
if (latestEntity == null || !MODULE_TYPE.equals(latestEntity.getModuleType()) || !userId.equals(latestEntity.getUserId())) {
|
||||
throw new BusinessException("record not found");
|
||||
throw new BusinessException("没有找到对应记录");
|
||||
}
|
||||
fileResultMapper.deleteById(resultId);
|
||||
reconcileTaskAfterResultRemoval(taskId);
|
||||
@@ -1245,7 +1246,7 @@ public class PriceTrackTaskService {
|
||||
} catch (BusinessException ex) {
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("任务请求参数解析失败: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("任务请求参数解析失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1569,7 +1570,7 @@ public class PriceTrackTaskService {
|
||||
mergeCountryRows(merged, parseWorkbookAsinRows(file, countryCodes));
|
||||
continue;
|
||||
}
|
||||
throw new BusinessException("Unsupported ASIN file type: " + file.getName());
|
||||
throw new BusinessException("不支持的 ASIN 文件类型: " + file.getName());
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
@@ -1626,14 +1627,14 @@ public class PriceTrackTaskService {
|
||||
} catch (BusinessException ex) {
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Failed to parse ASIN workbook");
|
||||
throw new BusinessException("解析 ASIN 表格失败");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private Map<String, List<Map<String, String>>> parseCsvAsinRows(File file, List<String> countryCodes) {
|
||||
if (countryCodes == null || countryCodes.size() != 1) {
|
||||
throw new BusinessException("CSV ASIN file requires exactly one selected country");
|
||||
throw new BusinessException("CSV 格式的 ASIN 文件只能选择一个国家");
|
||||
}
|
||||
Map<String, List<Map<String, String>>> out = new LinkedHashMap<>();
|
||||
List<Map<String, String>> rows = out.computeIfAbsent(countryCodes.get(0), key -> new ArrayList<>());
|
||||
@@ -1655,7 +1656,7 @@ public class PriceTrackTaskService {
|
||||
} catch (BusinessException ex) {
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Failed to parse ASIN csv");
|
||||
throw new BusinessException("解析 ASIN CSV 失败");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.productrisk.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.util.SxssfWorkbookWriter;
|
||||
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskRowDto;
|
||||
@@ -90,7 +91,7 @@ public class ProductRiskExcelAssemblyService {
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
log.warn("[product-risk] write workbook failed: {}", ex.getMessage());
|
||||
throw new BusinessException("generate product-risk excel failed: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("生成产品风险 Excel 失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.productrisk.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
@@ -273,11 +274,11 @@ public class ProductRiskResolveService {
|
||||
} catch (BusinessException ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(ex.getMessage());
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "该行匹配失败,请稍后重试"));
|
||||
} catch (Exception ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(Objects.toString(ex.getMessage(), "匹配异常"));
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "匹配异常"));
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
+1
-1
@@ -232,7 +232,7 @@ public class ProductRiskTaskService {
|
||||
inNewTransaction(() -> {
|
||||
FileResultEntity latestEntity = fileResultMapper.selectById(resultId);
|
||||
if (latestEntity == null || !MODULE_TYPE.equals(latestEntity.getModuleType()) || !userId.equals(latestEntity.getUserId())) {
|
||||
throw new BusinessException("record not found");
|
||||
throw new BusinessException("没有找到对应记录");
|
||||
}
|
||||
taskFileJobService.deleteResultJobs(latestEntity.getTaskId(), MODULE_TYPE, latestEntity.getId());
|
||||
fileResultMapper.deleteById(resultId);
|
||||
|
||||
+7
-7
@@ -320,7 +320,7 @@ public class PublishTaskService {
|
||||
|
||||
public void submitResult(Long taskId, PublishSubmitResultRequest request) {
|
||||
if (request == null || request.getFiles() == null || request.getFiles().isEmpty()) {
|
||||
throw new BusinessException("files cannot be empty");
|
||||
throw new BusinessException("文件列表不能为空");
|
||||
}
|
||||
if (request.getUserId() != null && request.getUserId() <= 0) {
|
||||
throw new BusinessException("user_id 不合法");
|
||||
@@ -328,7 +328,7 @@ public class PublishTaskService {
|
||||
try (TaskDistributedLockService.LockHandle lock =
|
||||
taskDistributedLockService.acquire(MODULE_TYPE, taskId)) {
|
||||
if (lock == null) {
|
||||
throw new BusinessException("task lock is busy");
|
||||
throw new BusinessException("任务正被占用,请稍后重试");
|
||||
}
|
||||
List<String> uploadedPayloads = new ArrayList<>();
|
||||
PreparedResultSubmission prepared;
|
||||
@@ -534,17 +534,17 @@ public class PublishTaskService {
|
||||
|
||||
public void processResultFileJob(TaskFileJobEntity job) {
|
||||
if (job == null || job.getTaskId() == null || job.getResultId() == null) {
|
||||
throw new BusinessException("result file job arguments are incomplete");
|
||||
throw new BusinessException("结果文件作业参数不完整");
|
||||
}
|
||||
FileTaskEntity task = fileTaskMapper.selectById(job.getTaskId());
|
||||
if (task == null || !MODULE_TYPE.equals(task.getModuleType())) {
|
||||
throw new BusinessException("task not found");
|
||||
throw new BusinessException("任务不存在");
|
||||
}
|
||||
ensureTaskOwnedByCurrentInstance(task, "process publish result file");
|
||||
FileResultEntity result = fileResultMapper.selectById(job.getResultId());
|
||||
if (result == null || !MODULE_TYPE.equals(result.getModuleType())
|
||||
|| !task.getId().equals(result.getTaskId())) {
|
||||
throw new BusinessException("result record not found");
|
||||
throw new BusinessException("结果记录不存在");
|
||||
}
|
||||
|
||||
File workDirectory = FileUtil.mkdir(FileUtil.file(System.getProperty("java.io.tmpdir"),
|
||||
@@ -556,7 +556,7 @@ public class PublishTaskService {
|
||||
.toList();
|
||||
if (successfulFiles.isEmpty()) {
|
||||
markTaskAndResultFailed(task, result, "没有成功文件,无法生成结果");
|
||||
throw new BusinessException("no successful publish files");
|
||||
throw new BusinessException("没有发布成功的文件");
|
||||
}
|
||||
|
||||
TaskOptions options = readTaskOptions(task);
|
||||
@@ -1334,7 +1334,7 @@ public class PublishTaskService {
|
||||
throw new BusinessException("请先上传 Excel 文件");
|
||||
}
|
||||
if (request.getPublishCountry() == null || request.getPublishCountry().isBlank()) {
|
||||
throw new BusinessException("publish_country cannot be blank");
|
||||
throw new BusinessException("发布国家不能为空");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.queryasin.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.util.SxssfWorkbookWriter;
|
||||
import com.nanri.aiimage.modules.queryasin.model.dto.QueryAsinAsinStatusDto;
|
||||
@@ -68,7 +69,7 @@ public class QueryAsinExcelAssemblyService {
|
||||
writer.write(outputXlsx);
|
||||
} catch (Exception ex) {
|
||||
log.warn("[query-asin] write workbook failed: {}", ex.getMessage());
|
||||
throw new BusinessException("生成查询 ASIN Excel 失败: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("生成查询 ASIN Excel 失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.queryasin.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCandidateAddRequest;
|
||||
@@ -211,11 +212,11 @@ public class QueryAsinResolveService {
|
||||
} catch (BusinessException ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(ex.getMessage());
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "该行匹配失败,请稍后重试"));
|
||||
} catch (Exception ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(Objects.toString(ex.getMessage(), "匹配异常"));
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "匹配异常"));
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
+1
-1
@@ -479,7 +479,7 @@ public class QueryAsinTaskService {
|
||||
inNewTransaction(() -> {
|
||||
FileResultEntity latestEntity = fileResultMapper.selectById(resultId);
|
||||
if (latestEntity == null || !MODULE_TYPE.equals(latestEntity.getModuleType()) || !userId.equals(latestEntity.getUserId())) {
|
||||
throw new BusinessException("record not found");
|
||||
throw new BusinessException("没有找到对应记录");
|
||||
}
|
||||
fileResultMapper.deleteById(resultId);
|
||||
reconcileTaskAfterResultRemoval(taskId);
|
||||
|
||||
+4
-3
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.shopdatacrawl.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.shopdatacrawl.model.dto.ShopDataCrawlRowDto;
|
||||
import com.nanri.aiimage.modules.shopdatacrawl.model.vo.ShopDataCrawlResultItemVo;
|
||||
@@ -111,7 +112,7 @@ public class ShopDataCrawlExcelAssemblyService {
|
||||
} catch (BusinessException ex) {
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("生成店铺数据抓取 Excel 失败: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("生成店铺数据抓取 Excel 失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,7 +147,7 @@ public class ShopDataCrawlExcelAssemblyService {
|
||||
} catch (BusinessException ex) {
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("店铺数据抓取累计 Excel 按国家替换失败: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("店铺数据抓取累计 Excel 按国家替换失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,7 +185,7 @@ public class ShopDataCrawlExcelAssemblyService {
|
||||
} catch (BusinessException ex) {
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("生成店铺数据抓取流式 Excel 失败: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("生成店铺数据抓取流式 Excel 失败", ex));
|
||||
} finally {
|
||||
workbook.dispose();
|
||||
}
|
||||
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.shopdatacrawl.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
@@ -302,11 +303,11 @@ public class ShopDataCrawlResolveService {
|
||||
} catch (BusinessException ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(ex.getMessage());
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "该行匹配失败,请稍后重试"));
|
||||
} catch (Exception ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(Objects.toString(ex.getMessage(), "匹配异常"));
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "匹配异常"));
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.shopduplicatecheck.controller;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.util.DownloadHeaderUtil;
|
||||
@@ -272,7 +273,7 @@ public class AdminShopDataDuplicateCheckController {
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
log.error("[shop-duplicate-check-import] 导入端点异常 operator_id={}", operator.id(), ex);
|
||||
throw new BusinessException(500, "导入失败:" + (ex.getMessage() == null ? "未知错误" : ex.getMessage()));
|
||||
throw new BusinessException(500, UserMessages.with("导入失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.shopduplicatecheck.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.service.DistributedJobLockService;
|
||||
@@ -73,7 +74,7 @@ public class ShopDataDuplicateCheckImportService {
|
||||
rows = DuplicateCheckWorkbookParser.parse(bytes);
|
||||
} catch (Exception ex) {
|
||||
log.warn("[shop-duplicate-check-import] 解析导入 Excel 失败 shop={} msg={}", name, ex.getMessage());
|
||||
throw new BusinessException(400, "Excel 解析失败:" + (ex.getMessage() == null ? "格式错误" : ex.getMessage()));
|
||||
throw new BusinessException(400, UserMessages.with("Excel 解析失败", ex));
|
||||
}
|
||||
if (rows.isEmpty()) {
|
||||
throw new BusinessException(400, "Excel 中未读取到 ASIN 数据(需包含 ASIN 列)");
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.shopduplicatecheck.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
@@ -223,7 +224,7 @@ public class ShopDataDuplicateCheckScanService implements DuplicateCheckRefreshP
|
||||
row.setSummaryJson(objectMapper.writeValueAsString(aggregate.summary()));
|
||||
row.setPayloadJson(objectMapper.writeValueAsString(aggregate.payload()));
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("扫描结果序列化失败: " + ex.getMessage(), ex);
|
||||
throw new BusinessException(UserMessages.with("扫描结果序列化失败", ex), ex);
|
||||
}
|
||||
scanMapper.insert(row);
|
||||
log.info("[shop-duplicate-check] 扫描完成 落库行 id={} 店铺数={} ASIN数={} 记录数={}",
|
||||
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.shopkey.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
@@ -443,8 +444,8 @@ public class QueryAsinService {
|
||||
progress.setStatus("success");
|
||||
} catch (Exception ex) {
|
||||
progress.setStatus("failed");
|
||||
progress.setErrorMessage(ex instanceof BusinessException ? ex.getMessage()
|
||||
: (deleteMode ? "导入删除 Excel 失败" : "导入添加 Excel 失败"));
|
||||
progress.setErrorMessage(UserMessages.orFallback(ex.getMessage(),
|
||||
deleteMode ? "导入删除 Excel 失败" : "导入添加 Excel 失败"));
|
||||
} finally {
|
||||
deleteQuietly(tempFile);
|
||||
completedImportAtMap.put(importId, System.currentTimeMillis());
|
||||
|
||||
+4
-3
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.shopkey.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
@@ -522,8 +523,8 @@ public class SkipPriceAsinService {
|
||||
log.warn("[skip-price-asin-import] failed importId={} deleteMode={} msg={}",
|
||||
importId, deleteMode, ex.getMessage());
|
||||
progress.setStatus("failed");
|
||||
progress.setErrorMessage(ex instanceof BusinessException ? ex.getMessage()
|
||||
: (deleteMode ? "导入删除 Excel 失败" : "导入新增 Excel 失败"));
|
||||
progress.setErrorMessage(UserMessages.orFallback(ex.getMessage(),
|
||||
deleteMode ? "导入删除 Excel 失败" : "导入新增 Excel 失败"));
|
||||
} finally {
|
||||
deleteQuietly(tempFile);
|
||||
completedImportAtMap.put(importId, System.currentTimeMillis());
|
||||
@@ -1414,7 +1415,7 @@ public class SkipPriceAsinService {
|
||||
case "ES" -> query.select(SkipPriceAsinEntity::getId, SkipPriceAsinEntity::getAsinEs,
|
||||
SkipPriceAsinEntity::getMinimumPriceEs)
|
||||
.eq(SkipPriceAsinEntity::getAsinEs, asin);
|
||||
default -> throw new BusinessException("unsupported country: " + country);
|
||||
default -> throw new BusinessException("不支持的国家: " + country);
|
||||
}
|
||||
return skipPriceAsinMapper.selectOne(query.last("LIMIT 1"));
|
||||
}
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.shopmatch.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.util.SxssfWorkbookWriter;
|
||||
import com.nanri.aiimage.modules.productrisk.model.enums.ProductRiskCountryCode;
|
||||
@@ -39,7 +40,7 @@ public class ShopMatchExcelAssemblyService {
|
||||
writer.write(outputXlsx);
|
||||
} catch (Exception ex) {
|
||||
log.warn("[shop-match] write workbook failed: {}", ex.getMessage());
|
||||
throw new BusinessException("generate shop-match excel failed: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("生成店铺匹配 Excel 失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.shopmatch.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
@@ -211,11 +212,11 @@ public class ShopMatchResolveService {
|
||||
} catch (BusinessException ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(ex.getMessage());
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "该行匹配失败,请稍后重试"));
|
||||
} catch (Exception ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(Objects.toString(ex.getMessage(), "匹配异常"));
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "匹配异常"));
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
+1
-1
@@ -307,7 +307,7 @@ public class ShopMatchTaskService {
|
||||
inNewTransaction(() -> {
|
||||
FileResultEntity latestEntity = fileResultMapper.selectById(resultId);
|
||||
if (latestEntity == null || !MODULE_TYPE.equals(latestEntity.getModuleType()) || !userId.equals(latestEntity.getUserId())) {
|
||||
throw new BusinessException("record not found");
|
||||
throw new BusinessException("没有找到对应记录");
|
||||
}
|
||||
fileResultMapper.deleteById(resultId);
|
||||
reconcileTaskAfterResultRemoval(taskId);
|
||||
|
||||
+5
-5
@@ -1519,12 +1519,12 @@ public class SimilarAsinTaskService implements SimilarAsinPipelineHost {
|
||||
int totalProgressUnits,
|
||||
int llmWorkUnits) {
|
||||
if (pipelineSupport().countPendingLlmStates(task.getId()) > 0) {
|
||||
throw new BusinessException("LLM result is still processing, cannot generate result file yet");
|
||||
throw new BusinessException("LLM 检测还没全部回流,暂时不能生成结果文件");
|
||||
}
|
||||
int assembleProgress = Math.max(1, Math.min(totalProgressUnits - 2, llmWorkUnits));
|
||||
progressSupport().saveFileBuildProgress(task, job, totalProgressUnits, assembleProgress, "Assembling xlsx");
|
||||
progressSupport().saveFileBuildProgress(task, job, totalProgressUnits, assembleProgress, "正在生成结果文件");
|
||||
resultAssembler().assembleResultWorkbook(task, result);
|
||||
progressSupport().saveFileBuildProgress(task, job, totalProgressUnits, totalProgressUnits - 1, "Uploading result file");
|
||||
progressSupport().saveFileBuildProgress(task, job, totalProgressUnits, totalProgressUnits - 1, "正在上传结果文件");
|
||||
fileResultMapper.updateById(result);
|
||||
boolean taskAlreadyFailed = STATUS_FAILED.equals(task.getStatus())
|
||||
|| (task.getErrorMessage() != null && !task.getErrorMessage().isBlank());
|
||||
@@ -1537,7 +1537,7 @@ public class SimilarAsinTaskService implements SimilarAsinPipelineHost {
|
||||
task.setFinishedAt(LocalDateTime.now());
|
||||
fileTaskMapper.updateById(task);
|
||||
taskCacheService.deleteTaskCache(task.getId());
|
||||
progressSupport().saveFileBuildProgress(task, job, totalProgressUnits, totalProgressUnits, "Result file generated");
|
||||
progressSupport().saveFileBuildProgress(task, job, totalProgressUnits, totalProgressUnits, "结果文件已生成");
|
||||
// P1-1:异步 assemble 完成 → task 进入 SUCCESS/FAILED 终态,清理滑窗记录避免内存泄漏。
|
||||
poisonTracker.clear(task.getId());
|
||||
}
|
||||
@@ -1638,7 +1638,7 @@ public class SimilarAsinTaskService implements SimilarAsinPipelineHost {
|
||||
throw new BusinessException(FailedStatusRowFilter.noMatchedRowsMessage());
|
||||
}
|
||||
if (allRows.isEmpty()) {
|
||||
throw new BusinessException("no valid similar ASIN rows");
|
||||
throw new BusinessException("没有解析到可检测的货源行,请检查表格的 id / ASIN / 国家 列");
|
||||
}
|
||||
return new ParsedWorkbook(total, dropped, headers, allRows, categoryRetryRequired);
|
||||
} catch (BusinessException ex) {
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.similarasin.service.support;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.similarasin.model.dto.SimilarAsinResultRowDto;
|
||||
@@ -126,7 +127,7 @@ public final class SimilarAsinChunkMergeSupport {
|
||||
.orderByAsc("id")
|
||||
.last("limit " + batch));
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("chunk keyset 分页查询失败: " + ex.getMessage(), ex);
|
||||
throw new BusinessException(UserMessages.with("分片键集 分页查询失败", ex), ex);
|
||||
}
|
||||
if (page == null || page.isEmpty()) {
|
||||
break;
|
||||
|
||||
+19
-3
@@ -1,5 +1,7 @@
|
||||
package com.nanri.aiimage.modules.similarasin.service.support;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import cn.hutool.crypto.digest.DigestUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
@@ -99,8 +101,8 @@ public class SimilarAsinChunkPayloadSupport {
|
||||
log.warn("[similar-asin] read chunk payload failed taskId={} chunk={} crossInstance={} err={}",
|
||||
chunk.getTaskId(), chunk.getChunkIndex(), crossInstance, msg);
|
||||
recordChunkReadFailure(chunk, crossInstance, msg);
|
||||
throw new BusinessException("similar ASIN chunk payload read failed chunk="
|
||||
+ chunk.getChunkIndex() + ": " + msg, ex);
|
||||
throw new BusinessException(UserMessages.with("读取货源查询结果分片失败,分片="
|
||||
+ chunk.getChunkIndex(), msg), ex);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
@@ -141,7 +143,21 @@ public class SimilarAsinChunkPayloadSupport {
|
||||
from = end + 1;
|
||||
}
|
||||
}
|
||||
return String.join(", ", tags);
|
||||
if (tags.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
List<String> readable = new ArrayList<>();
|
||||
for (String tag : tags) {
|
||||
int open = tag.indexOf('[');
|
||||
String body = open < 0 ? tag : tag.substring(open + 1, tag.length() - 1);
|
||||
boolean cross = body.endsWith("@cross-instance");
|
||||
if (cross) {
|
||||
body = body.substring(0, body.length() - "@cross-instance".length());
|
||||
}
|
||||
readable.add(cross ? "第 " + body + " 分片跨实例读取失败"
|
||||
: "第 " + body + " 分片读取失败");
|
||||
}
|
||||
return String.join(";", readable);
|
||||
} catch (Exception ex) {
|
||||
log.warn("[similar-asin] collect chunk-read-failure summary failed taskId={} err={}", taskId, ex.getMessage());
|
||||
return "";
|
||||
|
||||
+4
-3
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.similarasin.service.support;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
@@ -197,7 +198,7 @@ public class SimilarAsinHistoryAssembler {
|
||||
vo.setFileProgressCurrent(current);
|
||||
vo.setFileProgressTotal(total);
|
||||
vo.setFileProgressPercent(percent);
|
||||
vo.setFileProgressMessage(snapshot.getMessage());
|
||||
vo.setFileProgressMessage(UserMessages.orFallback(snapshot.getMessage(), ""));
|
||||
}
|
||||
|
||||
private void attachLlmProgress(SimilarAsinHistoryItemVo vo,
|
||||
@@ -412,8 +413,8 @@ public class SimilarAsinHistoryAssembler {
|
||||
log.warn("[similar-asin] read chunk payload failed taskId={} chunk={} crossInstance={} err={}",
|
||||
chunk.getTaskId(), chunk.getChunkIndex(), crossInstance, msg);
|
||||
recordChunkReadFailure(chunk, crossInstance, msg);
|
||||
throw new BusinessException("similar ASIN chunk payload read failed chunk="
|
||||
+ chunk.getChunkIndex() + ": " + msg, ex);
|
||||
throw new BusinessException(UserMessages.with("读取货源查询结果分片失败,分片="
|
||||
+ chunk.getChunkIndex(), msg), ex);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.similarasin.service.support;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import cn.hutool.crypto.digest.DigestUtil;
|
||||
import com.nanri.aiimage.modules.similarasin.model.dto.SimilarAsinParsedPayloadDto;
|
||||
import com.nanri.aiimage.modules.similarasin.model.dto.SimilarAsinResultGroupDto;
|
||||
@@ -1490,9 +1491,9 @@ public class SimilarAsinPipelineSupport {
|
||||
} catch (Exception ex) {
|
||||
TaskFileJobEntity job = taskFileJobService.findAssembleJob(taskId, MODULE_TYPE, context.resultId());
|
||||
if (job != null) {
|
||||
taskFileJobService.markFailed(job, firstNonBlank(ex.getMessage(), "相似ASIN结果文件生成失败"));
|
||||
taskFileJobService.markFailed(job, UserMessages.orFallback(ex.getMessage(), "相似ASIN结果文件生成失败"));
|
||||
if (taskFileJobService.isRetryExhausted(job.getId())) {
|
||||
host.finalizeExhaustedResultFileJob(job, ex.getMessage());
|
||||
host.finalizeExhaustedResultFileJob(job, UserMessages.orFallback(ex.getMessage(), "相似ASIN结果文件生成失败"));
|
||||
}
|
||||
}
|
||||
log.warn("[相似ASIN] LLM 异步收尾失败 任务ID={} 结果ID={} 错误={}",
|
||||
|
||||
+9
-9
@@ -141,12 +141,12 @@ public class SimilarAsinResultWorkbookAssembler {
|
||||
List<SourceRows> sourceRows = splitRowsBySourceFile(
|
||||
parsed, parsedRows, result.getSourceFilename());
|
||||
if (sourceRows.isEmpty()) {
|
||||
throw new BusinessException("Similar ASIN result rows are empty");
|
||||
throw new BusinessException("这份文件没有解析到可导出的行,请稍后重试生成结果文件");
|
||||
}
|
||||
|
||||
File outputDir = new File(storageProperties.getLocalTempDir(), "similar-asin-result");
|
||||
if (!outputDir.exists() && !outputDir.mkdirs()) {
|
||||
throw new BusinessException("failed to create result directory");
|
||||
throw new BusinessException("创建结果目录失败");
|
||||
}
|
||||
List<SourceResultWorkbook> workbooks = new ArrayList<>();
|
||||
List<File> workbookFiles = new ArrayList<>(sourceRows.size());
|
||||
@@ -207,20 +207,20 @@ public class SimilarAsinResultWorkbookAssembler {
|
||||
} catch (InterruptedException ex) {
|
||||
cancelResultAssemblyFutures(futures);
|
||||
Thread.currentThread().interrupt();
|
||||
throw new BusinessException("result workbook assembly interrupted", ex);
|
||||
throw new BusinessException("生成相似ASIN检测结果中断", ex);
|
||||
} catch (TimeoutException ex) {
|
||||
cancelResultAssemblyFutures(futures);
|
||||
throw new BusinessException("result workbook assembly timed out", ex);
|
||||
throw new BusinessException("生成相似ASIN检测结果超时(" + timeoutMinutes + " 分钟)", ex);
|
||||
} catch (CancellationException ex) {
|
||||
cancelResultAssemblyFutures(futures);
|
||||
throw new BusinessException("result workbook assembly cancelled", ex);
|
||||
throw new BusinessException("生成相似ASIN检测结果已取消", ex);
|
||||
} catch (ExecutionException ex) {
|
||||
cancelResultAssemblyFutures(futures);
|
||||
Throwable cause = ex.getCause();
|
||||
if (cause instanceof BusinessException businessException) {
|
||||
throw businessException;
|
||||
}
|
||||
throw new BusinessException("result workbook assembly failed", cause == null ? ex : cause);
|
||||
throw new BusinessException("生成相似ASIN检测结果失败", cause == null ? ex : cause);
|
||||
}
|
||||
|
||||
int persistedResultRows = workbooks.stream()
|
||||
@@ -242,8 +242,8 @@ public class SimilarAsinResultWorkbookAssembler {
|
||||
if (resultRows == 0) {
|
||||
String failureSummary = chunkPayloadSupport.collectChunkReadFailureSummary(task.getId());
|
||||
throw new BusinessException(failureSummary.isBlank()
|
||||
? "Similar ASIN result rows are empty; please retry result generation"
|
||||
: "Similar ASIN result rows are empty (" + failureSummary + ")");
|
||||
? "相似ASIN检测结果为空,请稍后重试生成结果文件"
|
||||
: "相似ASIN检测结果为空(" + failureSummary + "),请稍后重试生成结果文件");
|
||||
}
|
||||
|
||||
taskImageCache.clear();
|
||||
@@ -941,7 +941,7 @@ public class SimilarAsinResultWorkbookAssembler {
|
||||
return new SimilarAsinImageEmbedder.ImageSpool(
|
||||
Files.createTempDirectory(outputDir.toPath(), "similar-asin-images-"));
|
||||
} catch (IOException ex) {
|
||||
throw new BusinessException("create Similar ASIN image spool failed", ex);
|
||||
throw new BusinessException("创建相似ASIN图片临时目录失败", ex);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -74,7 +74,7 @@ public class SimilarAsinTaskOwnershipSupport {
|
||||
public TaskDistributedLockService.LockHandle requireTaskLock(Long taskId, long waitMillis) {
|
||||
TaskDistributedLockService.LockHandle lockHandle = acquireTaskLock(taskId, waitMillis);
|
||||
if (lockHandle == null) {
|
||||
throw new BusinessException(40902, "Task is busy, please retry later");
|
||||
throw new BusinessException(40902, "任务正被占用,请稍后重试");
|
||||
}
|
||||
return lockHandle;
|
||||
}
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.softwareversion.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
|
||||
@@ -207,7 +208,7 @@ public class SoftwareVersionService {
|
||||
} catch (IOException e) {
|
||||
log.error("[software-version] 上传客户端软件版本文件处理失败 version={} filename={} err={}",
|
||||
normalizedVersion, originalFilename, e.getMessage(), e);
|
||||
throw new BusinessException("文件处理失败:" + e.getMessage());
|
||||
throw new BusinessException(UserMessages.with("文件处理失败", e));
|
||||
} catch (RuntimeException e) {
|
||||
log.error("[software-version] 上传客户端软件版本失败 version={} filename={} elapsedMs={} err={}",
|
||||
normalizedVersion, originalFilename, elapsedMs(startedAt), e.getMessage(), e);
|
||||
|
||||
+16
-15
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.split.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import cn.hutool.json.JSONUtil;
|
||||
@@ -81,7 +82,7 @@ public class SplitRunService {
|
||||
try {
|
||||
File inputFile = findLocalSourceFile(sourceFile.getFileKey());
|
||||
if (inputFile == null || !inputFile.exists()) {
|
||||
throw new BusinessException("Uploaded source file does not exist, please upload again.");
|
||||
throw new BusinessException("上传的源文件不存在,请重新上传。");
|
||||
}
|
||||
|
||||
String inputName = sourceFile.getOriginalFilename() == null
|
||||
@@ -97,7 +98,7 @@ public class SplitRunService {
|
||||
SplitResultItemVo item = new SplitResultItemVo();
|
||||
item.setSourceFilename(sourceFile.getOriginalFilename());
|
||||
item.setSuccess(false);
|
||||
item.setError(ex.getMessage());
|
||||
item.setError(UserMessages.orFallback(ex.getMessage(), "这个文件拆分失败,请检查内容后重新上传"));
|
||||
item.setEntries(new ArrayList<>());
|
||||
item.setEntryCount(0);
|
||||
items.add(item);
|
||||
@@ -108,7 +109,7 @@ public class SplitRunService {
|
||||
resultEntity.setModuleType(MODULE_TYPE);
|
||||
resultEntity.setSourceFilename(sourceFile.getOriginalFilename());
|
||||
resultEntity.setSuccess(0);
|
||||
resultEntity.setErrorMessage(ex.getMessage());
|
||||
resultEntity.setErrorMessage(UserMessages.orFallback(ex.getMessage(), "这个文件拆分失败,请检查内容后重新上传"));
|
||||
resultEntity.setUserId(request.getUserId());
|
||||
resultEntity.setCreatedAt(LocalDateTime.now());
|
||||
fileResultMapper.insert(resultEntity);
|
||||
@@ -224,7 +225,7 @@ public class SplitRunService {
|
||||
public void deleteHistory(Long resultId, Long userId) {
|
||||
FileResultEntity entity = fileResultMapper.selectById(resultId);
|
||||
if (entity == null || !MODULE_TYPE.equals(entity.getModuleType()) || !userId.equals(entity.getUserId())) {
|
||||
throw new BusinessException("Split result record does not exist.");
|
||||
throw new BusinessException("没有这条拆分结果。");
|
||||
}
|
||||
fileResultMapper.deleteById(resultId);
|
||||
}
|
||||
@@ -232,7 +233,7 @@ public class SplitRunService {
|
||||
public String getResultDownloadUrl(Long resultId, Long userId) {
|
||||
FileResultEntity entity = fileResultMapper.selectById(resultId);
|
||||
if (entity == null || entity.getResultFileUrl() == null || !MODULE_TYPE.equals(entity.getModuleType()) || !userId.equals(entity.getUserId())) {
|
||||
throw new BusinessException("Split result file does not exist.");
|
||||
throw new BusinessException("拆分结果文件不存在。");
|
||||
}
|
||||
return ossStorageService.generateFreshDownloadUrl(entity.getResultFileUrl());
|
||||
}
|
||||
@@ -244,7 +245,7 @@ public class SplitRunService {
|
||||
) throws Exception {
|
||||
CountResult countResult = countSplitRows(inputFile, request.getSelectedColumns());
|
||||
if (countResult.rowCount() <= 0) {
|
||||
throw new BusinessException("No data rows available for splitting.");
|
||||
throw new BusinessException("没有可拆分的数据行。");
|
||||
}
|
||||
|
||||
List<Integer> chunkSizes = buildChunkSizes(countResult.rowCount(), request);
|
||||
@@ -270,7 +271,7 @@ public class SplitRunService {
|
||||
.filter(column -> !resolvedHeaderMap.containsKey(column))
|
||||
.toList();
|
||||
if (!missing.isEmpty()) {
|
||||
throw new BusinessException("Missing required columns: " + String.join(", ", missing));
|
||||
throw new BusinessException("缺少必需列: " + String.join(", ", missing));
|
||||
}
|
||||
headerMapHolder.set(resolvedHeaderMap);
|
||||
}
|
||||
@@ -282,7 +283,7 @@ public class SplitRunService {
|
||||
}
|
||||
Map<String, Integer> resolvedHeaderMap = headerMapHolder.get();
|
||||
if (resolvedHeaderMap == null) {
|
||||
throw new BusinessException("Excel header row is empty.");
|
||||
throw new BusinessException("Excel 表头行为空。");
|
||||
}
|
||||
List<String> projected = new ArrayList<>();
|
||||
for (String column : request.getSelectedColumns()) {
|
||||
@@ -327,7 +328,7 @@ public class SplitRunService {
|
||||
.filter(column -> !resolvedHeaderMap.containsKey(column))
|
||||
.toList();
|
||||
if (!missing.isEmpty()) {
|
||||
throw new BusinessException("Missing required columns: " + String.join(", ", missing));
|
||||
throw new BusinessException("缺少必需列: " + String.join(", ", missing));
|
||||
}
|
||||
sheetName[0] = currentSheetName == null || currentSheetName.isBlank() ? "Sheet1" : currentSheetName;
|
||||
headerRead[0] = true;
|
||||
@@ -336,13 +337,13 @@ public class SplitRunService {
|
||||
@Override
|
||||
public void onRow(String currentSheetName, Integer sheetNo, int rowIndex, Map<Integer, String> headerMap, Map<Integer, String> rowMap) {
|
||||
if (!headerRead[0]) {
|
||||
throw new BusinessException("Excel header row is empty.");
|
||||
throw new BusinessException("Excel 表头行为空。");
|
||||
}
|
||||
rowCount[0]++;
|
||||
}
|
||||
});
|
||||
if (!headerRead[0]) {
|
||||
throw new BusinessException("Excel header row is empty.");
|
||||
throw new BusinessException("Excel 表头行为空。");
|
||||
}
|
||||
return new CountResult(rowCount[0], sheetName[0]);
|
||||
}
|
||||
@@ -384,15 +385,15 @@ public class SplitRunService {
|
||||
|
||||
private void validateRequest(SplitRunRequest request) {
|
||||
if (!List.of(SPLIT_MODE_ROWS_PER_FILE, SPLIT_MODE_PARTS).contains(request.getSplitMode())) {
|
||||
throw new BusinessException("Invalid split mode.");
|
||||
throw new BusinessException("拆分方式不合法。");
|
||||
}
|
||||
if (SPLIT_MODE_ROWS_PER_FILE.equals(request.getSplitMode())
|
||||
&& (request.getRowsPerFile() == null || request.getRowsPerFile() <= 0)) {
|
||||
throw new BusinessException("Invalid rowsPerFile value.");
|
||||
throw new BusinessException("每个文件行数不合法。");
|
||||
}
|
||||
if (SPLIT_MODE_PARTS.equals(request.getSplitMode())
|
||||
&& (request.getParts() == null || request.getParts() <= 0)) {
|
||||
throw new BusinessException("Invalid parts value.");
|
||||
throw new BusinessException("拆分份数不合法。");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -446,7 +447,7 @@ public class SplitRunService {
|
||||
zos.closeEntry();
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("拆分结果打包失败:" + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("拆分结果打包失败", ex));
|
||||
}
|
||||
return zipFile;
|
||||
}
|
||||
|
||||
+51
-35
@@ -47,16 +47,25 @@ public class TaskFileJobLocalDispatcher {
|
||||
/**
|
||||
* 调用方已把 job claim 成 RUNNING 时使用:复用同样的背压/去重/异步执行,
|
||||
* 但落到 worker.processClaimed,避免二次 claimRunning 失败导致 job 被静默丢弃。
|
||||
* <p>传的是 claim 那一刻的行快照,执行前不再回读数据库:回读拿到的 {@code updated_at}
|
||||
* 就是当前值,{@code activateRunningClaim} 的 CAS 于是恒真,排队排久了的旧派发会冒充成
|
||||
* 新持有者,撞锁后再用 {@code deferRunning} 把真持有者正在跑的行翻回 PENDING,
|
||||
* 那次执行的 {@code markSuccess} 随即静默 0 行更新、成功状态丢失
|
||||
* (2026-10-09 任务 30456:结果文件可下载,作业行却是 FAILED)。
|
||||
*/
|
||||
public boolean dispatchClaimed(Long jobId, Long taskId, String moduleType) {
|
||||
return submit(jobId, taskId, moduleType, false, true);
|
||||
public boolean dispatchClaimed(TaskFileJobEntity claim) {
|
||||
if (claim == null || claim.getId() == null || claim.getId() <= 0) {
|
||||
return false;
|
||||
}
|
||||
return accept(claim.getId(), claim.getTaskId(), claim.getModuleType(), false,
|
||||
() -> runClaimed(claim));
|
||||
}
|
||||
|
||||
public boolean dispatch(Long jobId, Long taskId, String moduleType, boolean force) {
|
||||
return submit(jobId, taskId, moduleType, force, false);
|
||||
return accept(jobId, taskId, moduleType, force, () -> processLocally(jobId, taskId, moduleType));
|
||||
}
|
||||
|
||||
private boolean submit(Long jobId, Long taskId, String moduleType, boolean force, boolean alreadyClaimed) {
|
||||
private boolean accept(Long jobId, Long taskId, String moduleType, boolean force, Runnable body) {
|
||||
if (jobId == null || jobId <= 0) {
|
||||
return false;
|
||||
}
|
||||
@@ -85,20 +94,28 @@ public class TaskFileJobLocalDispatcher {
|
||||
jobId, taskId, moduleType);
|
||||
return true;
|
||||
}
|
||||
// 守卫只写一处:两条 body(已 claim / 未 claim)共用同一个"记日志 + 放名额"的包装,
|
||||
// 免得拆方法时一人一份 catch,把 catch-静默棘轮的总数悄悄抬上去。
|
||||
Runnable guarded = () -> {
|
||||
try {
|
||||
body.run();
|
||||
} catch (Exception ex) {
|
||||
log.warn("[task-file-job] local dispatch failed jobId={} taskId={} moduleType={} msg={}",
|
||||
jobId, taskId, moduleType, ex.getMessage(), ex);
|
||||
} finally {
|
||||
removeInflight(jobId);
|
||||
}
|
||||
};
|
||||
try {
|
||||
taskFileJobDispatchExecutor.execute(() -> processLocally(jobId, taskId, moduleType, alreadyClaimed));
|
||||
taskFileJobDispatchExecutor.execute(guarded);
|
||||
return true;
|
||||
} catch (RuntimeException ex) {
|
||||
removeInflight(jobId);
|
||||
log.warn("[task-file-job] local dispatch executor rejected jobId={} taskId={} moduleType={} msg={}",
|
||||
jobId, taskId, moduleType, ex.getMessage(), ex);
|
||||
if (force) {
|
||||
try {
|
||||
processLocally(jobId, taskId, moduleType, alreadyClaimed);
|
||||
return true;
|
||||
} finally {
|
||||
removeInflight(jobId);
|
||||
}
|
||||
guarded.run();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -113,30 +130,29 @@ public class TaskFileJobLocalDispatcher {
|
||||
}
|
||||
}
|
||||
|
||||
private void processLocally(Long jobId, Long taskId, String moduleType, boolean alreadyClaimed) {
|
||||
try {
|
||||
TaskFileJobEntity job = taskFileJobMapper.selectById(jobId);
|
||||
if (job == null) {
|
||||
log.warn("[task-file-job] local dispatch ignored, job not found jobId={} taskId={} moduleType={}",
|
||||
jobId, taskId, moduleType);
|
||||
return;
|
||||
}
|
||||
TaskResultFileJobWorker taskResultFileJobWorker = taskResultFileJobWorkerProvider.getIfAvailable();
|
||||
if (taskResultFileJobWorker == null) {
|
||||
log.warn("[task-file-job] local dispatch ignored, worker unavailable jobId={} taskId={} moduleType={}",
|
||||
jobId, taskId, moduleType);
|
||||
return;
|
||||
}
|
||||
if (alreadyClaimed) {
|
||||
taskResultFileJobWorker.processClaimed(job);
|
||||
} else {
|
||||
taskResultFileJobWorker.process(job);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
log.warn("[task-file-job] local dispatch failed jobId={} taskId={} moduleType={} msg={}",
|
||||
jobId, taskId, moduleType, ex.getMessage(), ex);
|
||||
} finally {
|
||||
removeInflight(jobId);
|
||||
private void runClaimed(TaskFileJobEntity claim) {
|
||||
TaskResultFileJobWorker taskResultFileJobWorker = taskResultFileJobWorkerProvider.getIfAvailable();
|
||||
if (taskResultFileJobWorker == null) {
|
||||
log.warn("[task-file-job] local dispatch ignored, worker unavailable jobId={} taskId={} moduleType={}",
|
||||
claim.getId(), claim.getTaskId(), claim.getModuleType());
|
||||
return;
|
||||
}
|
||||
taskResultFileJobWorker.processClaimed(claim);
|
||||
}
|
||||
|
||||
private void processLocally(Long jobId, Long taskId, String moduleType) {
|
||||
TaskFileJobEntity job = taskFileJobMapper.selectById(jobId);
|
||||
if (job == null) {
|
||||
log.warn("[task-file-job] local dispatch ignored, job not found jobId={} taskId={} moduleType={}",
|
||||
jobId, taskId, moduleType);
|
||||
return;
|
||||
}
|
||||
TaskResultFileJobWorker taskResultFileJobWorker = taskResultFileJobWorkerProvider.getIfAvailable();
|
||||
if (taskResultFileJobWorker == null) {
|
||||
log.warn("[task-file-job] local dispatch ignored, worker unavailable jobId={} taskId={} moduleType={}",
|
||||
jobId, taskId, moduleType);
|
||||
return;
|
||||
}
|
||||
taskResultFileJobWorker.process(job);
|
||||
}
|
||||
}
|
||||
|
||||
+11
-4
@@ -638,12 +638,19 @@ public class TaskFileJobService {
|
||||
return true;
|
||||
}
|
||||
|
||||
public void markSuccess(TaskFileJobEntity job, String resultFileUrl) {
|
||||
/**
|
||||
* 只有行还归本次执行(状态仍是 RUNNING)时才落 SUCCESS。
|
||||
*
|
||||
* @return 是否真的写进去了。false 意味着这一行的状态已被别人翻走(见
|
||||
* {@link #deferRunning}),成功状态丢失——调用方必须打日志,否则线上只会看到
|
||||
* "结果文件明明可下载、作业行却是 FAILED"(2026-10-09 任务 30456)。
|
||||
*/
|
||||
public boolean markSuccess(TaskFileJobEntity job, String resultFileUrl) {
|
||||
if (job == null || job.getId() == null) {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
taskFileJobMapper.update(null, new LambdaUpdateWrapper<TaskFileJobEntity>()
|
||||
return taskFileJobMapper.update(null, new LambdaUpdateWrapper<TaskFileJobEntity>()
|
||||
.eq(TaskFileJobEntity::getId, job.getId())
|
||||
.eq(TaskFileJobEntity::getStatus, "RUNNING")
|
||||
.set(TaskFileJobEntity::getStatus, "SUCCESS")
|
||||
@@ -651,7 +658,7 @@ public class TaskFileJobService {
|
||||
.set(TaskFileJobEntity::getResultFileUrl, resultFileUrl)
|
||||
.set(TaskFileJobEntity::getUpdatedAt, now)
|
||||
.set(TaskFileJobEntity::getFinishedAt, now)
|
||||
.set(TaskFileJobEntity::getTerminalCallbackAt, now));
|
||||
.set(TaskFileJobEntity::getTerminalCallbackAt, now)) > 0;
|
||||
}
|
||||
|
||||
public TaskFileJobEntity findById(Long jobId) {
|
||||
|
||||
+13
-9
@@ -81,11 +81,7 @@ public class TaskResultFileJobWorker {
|
||||
// claimRunnableJobsForOwner 已把 job 原子翻转成 RUNNING,这里必须走"已 claim"
|
||||
// 通道:若再走 process() 的 claimRunning,条件 UPDATE 会因状态已是 RUNNING 而
|
||||
// 失败,job 被静默丢弃并挂到 stuck 扫描才回收,定时兜底等于失效。
|
||||
boolean dispatched = taskFileJobLocalDispatcher.dispatchClaimed(
|
||||
job.getId(),
|
||||
job.getTaskId(),
|
||||
job.getModuleType()
|
||||
);
|
||||
boolean dispatched = taskFileJobLocalDispatcher.dispatchClaimed(job);
|
||||
if (!dispatched) {
|
||||
processClaimed(job);
|
||||
}
|
||||
@@ -274,11 +270,19 @@ public class TaskResultFileJobWorker {
|
||||
return;
|
||||
}
|
||||
String resultFileUrl = resolveResultFileUrl(job);
|
||||
taskFileJobService.markSuccess(job, resultFileUrl);
|
||||
boolean successMarked = taskFileJobService.markSuccess(job, resultFileUrl);
|
||||
cleanupAfterSuccess(job);
|
||||
log.info("[task-file-job] process success jobId={} taskId={} moduleType={} resultId={} elapsedMs={} resultFileUrl={} stage=SUCCESS",
|
||||
job.getId(), job.getTaskId(), job.getModuleType(), job.getResultId(),
|
||||
System.currentTimeMillis() - startedAt, resultFileUrl);
|
||||
if (!successMarked) {
|
||||
// 结果文件已经生成、可下载,但作业行不在这次执行手里了(成功状态丢失)。
|
||||
// 不翻 FAILED:那会让界面把一次成功的任务显示成"结果生成失败"。
|
||||
log.warn("[task-file-job] process succeeded but job row is no longer RUNNING for this run jobId={} taskId={} moduleType={} resultId={} elapsedMs={} resultFileUrl={} stage=SUCCESS_LOST",
|
||||
job.getId(), job.getTaskId(), job.getModuleType(), job.getResultId(),
|
||||
System.currentTimeMillis() - startedAt, resultFileUrl);
|
||||
} else {
|
||||
log.info("[task-file-job] process success jobId={} taskId={} moduleType={} resultId={} elapsedMs={} resultFileUrl={} stage=SUCCESS",
|
||||
job.getId(), job.getTaskId(), job.getModuleType(), job.getResultId(),
|
||||
System.currentTimeMillis() - startedAt, resultFileUrl);
|
||||
}
|
||||
}
|
||||
// 成功后回调解耦(原 WITHDRAW 特判):时机与历史一致——锁已释放、markSuccess 之后;
|
||||
// 各模块需要"任务收尾"时实现 ResultFileJobHandler.onSuccess,task 侧不再 import 业务模块
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.taskcenter.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.common.module.TaskModuleRegistry;
|
||||
import com.nanri.aiimage.modules.taskcenter.mapper.TaskCenterQueryMapper;
|
||||
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterCollectStatsRow;
|
||||
@@ -403,7 +404,7 @@ public class TaskCenterQueryService {
|
||||
vo.setProgressSuccess(nullToZero(snapshot.getSuccessCount()));
|
||||
vo.setProgressFailed(nullToZero(snapshot.getFailedCount()));
|
||||
vo.setCurrentScope(snapshot.getCurrentScopeKey());
|
||||
vo.setMessage(snapshot.getMessage());
|
||||
vo.setMessage(UserMessages.orFallback(snapshot.getMessage(), ""));
|
||||
} else {
|
||||
fillFallbackProgress(vo, row, collectStats.get(row.getId()));
|
||||
}
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.usersecret.client;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.util.SecretMasking;
|
||||
@@ -137,7 +138,7 @@ public class JikipProxyClient {
|
||||
} catch (Exception ex) {
|
||||
log.warn("[user-secret][proxy] 余量查询失败 err={}", ex.getMessage());
|
||||
vo.setAvailable(false);
|
||||
vo.setMessage("余量查询失败:" + ex.getMessage());
|
||||
vo.setMessage(UserMessages.with("余量查询失败", ex));
|
||||
}
|
||||
return vo;
|
||||
}
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.withdraw.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.util.SxssfWorkbookWriter;
|
||||
import com.nanri.aiimage.modules.withdraw.model.dto.WithdrawRowDto;
|
||||
@@ -83,7 +84,7 @@ public class WithdrawExcelAssemblyService {
|
||||
writer.write(outputXlsx);
|
||||
} catch (Exception ex) {
|
||||
log.warn("[withdraw] write workbook failed: {}", ex.getMessage());
|
||||
throw new BusinessException("生成取款 Excel 失败: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("生成取款 Excel 失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.withdraw.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCandidateAddRequest;
|
||||
@@ -160,11 +161,11 @@ public class WithdrawResolveService {
|
||||
} catch (BusinessException ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(ex.getMessage());
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "该行匹配失败,请稍后重试"));
|
||||
} catch (Exception ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(Objects.toString(ex.getMessage(), "匹配异常"));
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "匹配异常"));
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.ziniao.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.config.ZiniaoProperties;
|
||||
@@ -427,7 +428,7 @@ public class ZiniaoShopIndexService {
|
||||
whitelistSkippedApiKeyCount, nextOffset);
|
||||
} catch (Exception ex) {
|
||||
cursor.setStatus("FAILED");
|
||||
cursor.setMessage(ex.getMessage());
|
||||
cursor.setMessage(UserMessages.orFallback(ex.getMessage(), "店铺列表获取失败,请稍后重试"));
|
||||
cursor.setLastFinishedAt(now);
|
||||
if (isIpWhitelistRefreshFailure(ex)) {
|
||||
log.warn("[ziniao-index] refresh blocked reason={} existing shop index rows left untouched",
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
-- =============================================================
|
||||
-- 迁移 V156__dedupe_total_data_pioneer_backfill
|
||||
-- 模板:docs/flyway-migration-template.md
|
||||
-- 需求:2026-10-09 控制方截图「admin 代导入的行应该在『先锋』tab 下」牵出的存量归属回填。
|
||||
-- 同批 JAR 把去重库读侧(列表/导出/公司超管)从"按上传账号认公司"切到"按行
|
||||
-- company_id 认公司"——切换前必须把本文件这一批"账号已删、归属兜成公司 1"的行先修对,
|
||||
-- 否则切完它们会整批出现在厦门米椿花 tab 下(比今天"谁都看不见"更坏)。
|
||||
--
|
||||
-- 1. 变更目的:把组 33「先锋」名下、上传账号已被硬删(uid=1188「先峰」)的 1452 行
|
||||
-- biz_dedupe_total_data 的 company_id 从兜底值 1(厦门米椿花)回填到 3(先锋-团队)。
|
||||
--
|
||||
-- 归属判据(2026-10-09 主机A 业务库只读实查,不是推断):
|
||||
-- · 组 33 名为「先锋」,创建于 2026-10-03 16:06(**早于公司 3 开通的 10-05 00:27**,
|
||||
-- 多公司一期前"先锋"团队就在用系统);
|
||||
-- · 上传账号 1188 用户名「先峰」—— V153 头注释(10-08 客户「先锋-团队」定档那单)
|
||||
-- 已把「id=33 那行、其组长账号 uid=1188 已被硬删」与先锋团队绑定为同一语境;
|
||||
-- · 该批行全部由 1188 在 2026-10-05 14:40 ~ 23:23 导入(公司 3 开通当天),
|
||||
-- 组 33 与 1188 在 biz_dedupe_total_data 里严格同一批(双向差集均为 0 行);
|
||||
-- · 该批数据只存在于本表:biz_query_asin / biz_shop_manage / biz_skip_price_asin /
|
||||
-- biz_invalid_asin_data 里挂组 33 的行数全部为 0;
|
||||
-- · 内容为 UK 1427 行 + DE 25 行,与先锋做英/德站点吻合。
|
||||
-- 本文件**不碰** biz_shop_manage_group 的 company_id(组 33/34 保持 NULL):
|
||||
-- V153 第 1 段明文定案「孤儿推不出归属,硬塞一个公司号就是归属失真」——组表那两行
|
||||
-- 不参与任何读写判据(列表按组长收窄、NULL 在唯一索引里不互相挡),保持现状。
|
||||
--
|
||||
-- 为什么现在做(不做会怎样):写侧"五处收口"(39de5035,10-09 17:57)已把去重执行 /
|
||||
-- 导入预检 / 手工新增重名 / 删除导入 / 采集结果过滤统一改按 company_id 收窄——这 1452 行
|
||||
-- 当前正以 company_id=1 参与**厦门米椿花**的去重比对(米椿花采集结果里这些 ASIN 会被
|
||||
-- 误判「已存在」而过滤掉),同时先锋自己去重时拿不到这 1452 个值;本批读侧切换后还会
|
||||
-- 在米椿花 tab 整批可见。回填到 3 一次性解决三面。
|
||||
--
|
||||
-- 2. 影响表与数据量:只有 `biz_dedupe_total_data`,WHERE 命中 **1452 行**(实查)。
|
||||
-- 唯一键预检:这批行迁到 company 3 后与公司 3 现存值(8139 行)**零交集**——
|
||||
-- `JOIN ... ON a.data_value = b.data_value AND b.company_id = 3 WHERE a.group_id = 33`
|
||||
-- 返回 0 行,`uk_company_data_value` 不会撞键。company 1 侧是本行移除、不涉唯一键。
|
||||
-- 表 55 万行,本文件只有这一条 UPDATE,无任何 DDL、无列变更、无索引变更。
|
||||
--
|
||||
-- 3. 锁表风险:低。WHERE 由 `uploader_user_id = 1188`(有 idx_uploader_user_id_id 前缀)
|
||||
-- 落点查,叠 `group_id = 33 AND company_id = 1` 过滤,扫描面是"该账号名下的行",
|
||||
-- 不是全表;命中的 1452 行做一次 UPDATE(行锁,毫秒级)。不 JOIN 大表、不写回其他列
|
||||
-- (updated_at 由 ON UPDATE 自行维护,属预期)。重跑是 no-op(见第 4 段幂等限定)。
|
||||
--
|
||||
-- 4. 幂等:`AND company_id = 1` 重跑零命中。MySQL 的 DML 进事务,失败自动回滚,无需 repair。
|
||||
--
|
||||
-- 5. 验证 SQL(迁移后跑,不许只看启动日志的 Successfully applied):
|
||||
-- SELECT company_id, COUNT(*) FROM biz_dedupe_total_data
|
||||
-- WHERE uploader_user_id = 1188 GROUP BY company_id;
|
||||
-- -> 期望只剩一行:3 | 1452
|
||||
-- SELECT COUNT(*) FROM biz_dedupe_total_data WHERE group_id = 33 AND company_id = 1;
|
||||
-- -> 期望 0(全部迁走)
|
||||
-- SELECT COUNT(*) FROM biz_dedupe_total_data d JOIN users u ON u.id = d.uploader_user_id
|
||||
-- WHERE u.company_id <> d.company_id;
|
||||
-- -> 期望 14(2026-10-09 19:12 admin 代导入那批,company_id=3 正确但 uploader 归属
|
||||
-- 公司 1——那是"上传者≠数据归属"的合法形态,读侧已按公司列收窄,不是脏数据;
|
||||
-- 迁移前该值为 14+1452=1466)
|
||||
--
|
||||
-- 6. 回滚步骤:反向 UPDATE(人工执行,不写成版本化回滚——V145 同款纪律):
|
||||
-- UPDATE biz_dedupe_total_data SET company_id = 1
|
||||
-- WHERE uploader_user_id = 1188 AND group_id = 33 AND company_id = 3;
|
||||
-- 注意:回滚必须与 JAR 回滚同批——读侧按 company_id 的 JAR 在跑时就回滚数据,
|
||||
-- 1452 行会立刻整批出现在米椿花 tab 且参与米椿花的去重比对。
|
||||
--
|
||||
-- 7. 上线窗口:随 V156 所属 JAR 双节点同窗执行(Flyway 只在先到的一台上跑)。
|
||||
-- 业务低峰即可,无长事务等待;与读侧切换的 JAR 必须同批——只上迁移不上 JAR,
|
||||
-- 1452 行在旧读侧(按账号)依旧谁都看不见(无害但不完整);只上 JAR 不上迁移,
|
||||
-- 米椿花 tab 会多出 1452 行别家数据(有害),所以先到的一台跑完迁移、第二台
|
||||
-- 启动前数据已就位,混合窗口内安全。
|
||||
-- =============================================================
|
||||
|
||||
UPDATE `biz_dedupe_total_data`
|
||||
SET `company_id` = 3
|
||||
WHERE `uploader_user_id` = 1188
|
||||
AND `group_id` = 33
|
||||
AND `company_id` = 1;
|
||||
@@ -0,0 +1,137 @@
|
||||
package com.nanri.aiimage;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* 全仓尺子:用户可见文案出口不许把底层异常原文直接拼进去。
|
||||
*
|
||||
* <p>起因是 2026-10-09 那张货源查询截图:卡片上那句英文不是写错的文案,而是
|
||||
* {@code biz_task_file_job.error_message} 里存的异常原文。普查数出 61 处出口
|
||||
* ({@code new BusinessException("中文: " + ex.getMessage())}、
|
||||
* {@code setErrorMessage(ex.getMessage())}、{@code ApiResponse.fail(ex.getMessage())} 这类)
|
||||
* 把 Java 栈名、Coze/MinIO 报错原样交给界面——逐条翻译追不上新增速度,所以把规矩做进代码:
|
||||
* 出口只接受 {@link com.nanri.aiimage.common.util.UserMessages} 把关后的串。
|
||||
*
|
||||
* <p>判据按行匹配(与同目录 {@code UserFacingMessageChineseGuardTest} 的括号配平法互补):
|
||||
* 一行里既有文案出口、又出现 {@code getMessage()/messageOf()},却没有 {@code UserMessages.}
|
||||
* 也没有 {@code log.},就是违例。日志行不算——日志正是留着英文原文查根因的地方。
|
||||
*
|
||||
* <p>分母硬钉:扫到的出口行数低于下限,说明正则或目录树坏了,那时的"零违例"不作数。
|
||||
*/
|
||||
class RawExceptionMessageSinkGuardTest {
|
||||
|
||||
/** 本轮实测 1595 行出口,下限取 1500:明显缩水即判抽取器失效。 */
|
||||
private static final int MIN_SINK_LINES = 1500;
|
||||
|
||||
/**
|
||||
* 逐条点名的豁免:格式 {@code 文件后缀 :: 语句}(空白归一后整句比对,行号会漂所以不进键)。
|
||||
* 数字人任务把 Coze 返回的业务错原文留在 error_message 里,是给支持同学对着
|
||||
* ImageVideoAsyncTaskServiceTest 那三条钉子查根因用的;界面上的中文由前端
|
||||
* {@code userNotice} 兜住,所以这里放行、不再要求写侧把关。
|
||||
*/
|
||||
private static final List<String> EXEMPTIONS = List.of(
|
||||
"modules/imagevideo/service/ImageVideoAsyncTaskService.java::"
|
||||
+ "task.setErrorMessage(truncate(messageOf(ex)));");
|
||||
|
||||
private static final Pattern SINK = Pattern.compile(
|
||||
"new BusinessException\\(|ApiResponse\\.fail\\(|set(?:ErrorMessage|Error|MatchMessage|FileError"
|
||||
+ "|Message|FailureReason)\\(|markFailed|markFailureFinalized|saveBrandProgressSnapshot"
|
||||
+ "|saveFileBuildProgress");
|
||||
|
||||
private static final Pattern RAW_EXCEPTION_TEXT = Pattern.compile("\\.getMessage\\(\\)|messageOf\\(");
|
||||
|
||||
private static final Pattern GUARDED = Pattern.compile("UserMessages\\.|\\blog\\.\\w+\\(");
|
||||
|
||||
@Test
|
||||
void userVisibleSinksNeverEmbedRawExceptionText() throws IOException {
|
||||
List<String> offenders = new ArrayList<>();
|
||||
Set<String> usedExemptions = new LinkedHashSet<>();
|
||||
int sinkLines = 0;
|
||||
for (Path file : mainSources()) {
|
||||
String relative = relativeName(file);
|
||||
List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8);
|
||||
for (int i = 0; i < lines.size(); i++) {
|
||||
String line = lines.get(i).strip();
|
||||
if (line.startsWith("//") || line.startsWith("*") || line.startsWith("/*")) {
|
||||
continue;
|
||||
}
|
||||
if (!SINK.matcher(line).find()) {
|
||||
continue;
|
||||
}
|
||||
sinkLines++;
|
||||
if (RAW_EXCEPTION_TEXT.matcher(line).find() && !GUARDED.matcher(line).find()) {
|
||||
String key = relative + "::" + line;
|
||||
if (EXEMPTIONS.contains(key)) {
|
||||
usedExemptions.add(key);
|
||||
continue;
|
||||
}
|
||||
offenders.add(relative + ":" + (i + 1) + " " + shorten(line));
|
||||
}
|
||||
}
|
||||
}
|
||||
assertTrue(sinkLines >= MIN_SINK_LINES,
|
||||
"只扫到 " + sinkLines + " 行文案出口(下限 " + MIN_SINK_LINES + ")——正则或源码树坏了,"
|
||||
+ "此刻的\"零违例\"不作数");
|
||||
if (!offenders.isEmpty()) {
|
||||
fail("这些出口把底层异常原文交给了界面,必须走 UserMessages.with/orFallback:\n "
|
||||
+ String.join("\n ", offenders));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 自证:把一条违例样本喂给同一套判据,必须被抓住。
|
||||
* 判据抓不到自己造的违例,就说明它是个恒绿的空壳。
|
||||
*/
|
||||
@Test
|
||||
void detectorCatchesAPlantedViolation() {
|
||||
String planted = "throw new BusinessException(\"生成结果失败: \" + ex.getMessage());";
|
||||
assertTrue(SINK.matcher(planted).find(), "样本没被认成文案出口,抽取器对这类写法失明");
|
||||
assertTrue(RAW_EXCEPTION_TEXT.matcher(planted).find(), "样本没被认出异常原文");
|
||||
assertTrue(!GUARDED.matcher(planted).find(), "样本不该算已把关");
|
||||
|
||||
String guarded = "throw new BusinessException(UserMessages.with(\"生成结果失败\", ex));";
|
||||
assertTrue(SINK.matcher(guarded).find());
|
||||
assertTrue(GUARDED.matcher(guarded).find(), "把关写法被误判成违例");
|
||||
|
||||
String logged = "log.warn(\"assemble failed msg={}\", ex.getMessage());";
|
||||
assertTrue(GUARDED.matcher(logged).find(), "日志行不该进违例");
|
||||
}
|
||||
|
||||
private static String shorten(String line) {
|
||||
return line.length() <= 140 ? line : line.substring(0, 140) + "...";
|
||||
}
|
||||
|
||||
private static String relativeName(Path file) {
|
||||
String path = file.toString().replace('\\', '/');
|
||||
int cut = path.indexOf("/com/nanri/aiimage/");
|
||||
return cut < 0 ? path : path.substring(cut + "/com/nanri/aiimage/".length());
|
||||
}
|
||||
|
||||
private static List<Path> mainSources() throws IOException {
|
||||
Path root = moduleRoot().resolve("src/main/java");
|
||||
if (!Files.isDirectory(root)) {
|
||||
fail("找不到源码目录:" + root);
|
||||
}
|
||||
try (Stream<Path> stream = Files.walk(root)) {
|
||||
return stream.filter(p -> p.toString().endsWith(".java")).sorted().toList();
|
||||
}
|
||||
}
|
||||
|
||||
private static Path moduleRoot() {
|
||||
Path here = Path.of("").toAbsolutePath();
|
||||
return here.getFileName().toString().equals("backend-java") ? here : here.getParent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package com.nanri.aiimage;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* 全仓尺子:凡是会进用户界面的文案出口({@code new BusinessException(...)} 与
|
||||
* {@code saveFileBuildProgress(...)}),首段必须是中文。
|
||||
*
|
||||
* <p>起因是 2026-10-09 一张货源查询任务截图:同一个卡片上既有中文"仅完成 102/112 行",
|
||||
* 又有一句英文 "Similar ASIN result rows are empty; please retry result generation"。
|
||||
* 那次拆分只翻译了 legacy 装配路径,bounded 路径的 8 句英文异常原样进了
|
||||
* {@code biz_task_file_job.error_message},前端 {@code pendingResultHint} 又不加转换地渲染。
|
||||
* 全仓普查当时数出 1,213 个带字面量的出口、其中 112 个首段没有中文。
|
||||
*
|
||||
* <p>判据是"首段字面量含中文",不是"每段都含中文":拼接里的单位片段
|
||||
* ({@code " bytes"}、{@code " 分钟)"})本就不该有中文。
|
||||
*
|
||||
* <p>豁免表必须条条被用到——用不到的豁免就是常开的洞,所以 {@link #noDeadExemptions} 专门反查。
|
||||
*/
|
||||
class UserFacingMessageChineseGuardTest {
|
||||
|
||||
/** 扫描到的出口总数下限:低于此值说明抽取器什么都没抓到,那时的"零违规"是假的。 */
|
||||
private static final int MIN_OUTLETS_SCANNED = 1200;
|
||||
|
||||
/**
|
||||
* 逐条点名豁免,格式 {@code 文件后缀 :: 首段字面量}。
|
||||
* 每一条都要在下面写清为什么可以留英文,以及什么时候该摘掉。
|
||||
*/
|
||||
private static final List<String> EXEMPTIONS = List.of(
|
||||
// JSON 键名,不是消息:真正的兜底文案在同一个参数列表的最后一段,已是中文
|
||||
"modules/imagevideo/service/ImageVideoCozeService.java::msg");
|
||||
|
||||
@Test
|
||||
void everyUserFacingMessageOutletStartsWithChinese() throws IOException {
|
||||
List<String> offenders = new ArrayList<>();
|
||||
Set<String> usedExemptions = new LinkedHashSet<>();
|
||||
int scanned = 0;
|
||||
for (Path file : mainSources()) {
|
||||
String source = read(file);
|
||||
String relative = relativeName(file);
|
||||
for (String arguments : messageArguments(source)) {
|
||||
String first = firstLiteral(arguments);
|
||||
if (first.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
scanned++;
|
||||
if (containsChinese(first)) {
|
||||
continue;
|
||||
}
|
||||
String key = relative + "::" + first;
|
||||
if (EXEMPTIONS.contains(key)) {
|
||||
usedExemptions.add(key);
|
||||
continue;
|
||||
}
|
||||
offenders.add(relative + " -> \"" + first + "\"");
|
||||
}
|
||||
}
|
||||
assertThatListIsEmpty(offenders, "这些文案出口的首段不是中文,会原样出现在用户界面上");
|
||||
assertTrue(scanned >= MIN_OUTLETS_SCANNED,
|
||||
"只扫到 " + scanned + " 个带字面量的出口(下限 " + MIN_OUTLETS_SCANNED
|
||||
+ ")——抽取器失效了,此刻的\"零违规\"不作数");
|
||||
}
|
||||
|
||||
/** 用不到的豁免要摘掉,否则它会慢慢变成一个"谁都能往里塞一条"的常开门。 */
|
||||
@Test
|
||||
void noDeadExemptions() throws IOException {
|
||||
Set<String> seen = new LinkedHashSet<>();
|
||||
for (Path file : mainSources()) {
|
||||
String relative = relativeName(file);
|
||||
for (String arguments : messageArguments(read(file))) {
|
||||
String first = firstLiteral(arguments);
|
||||
if (!first.isBlank()) {
|
||||
seen.add(relative + "::" + first);
|
||||
}
|
||||
}
|
||||
}
|
||||
List<String> dead = EXEMPTIONS.stream().filter(key -> !seen.contains(key)).toList();
|
||||
assertThatListIsEmpty(dead, "这些豁免已经没有对应的英文出口了,请从 EXEMPTIONS 里删掉");
|
||||
}
|
||||
|
||||
private static void assertThatListIsEmpty(List<String> items, String message) {
|
||||
if (!items.isEmpty()) {
|
||||
fail(message + ":\n " + String.join("\n ", items));
|
||||
}
|
||||
}
|
||||
|
||||
private static final List<String> MARKERS = List.of("new BusinessException(", "saveFileBuildProgress(");
|
||||
|
||||
/** 每个标记后面那段配平的括号内容,就是文案所在的地方。 */
|
||||
private static List<String> messageArguments(String source) {
|
||||
List<String> arguments = new ArrayList<>();
|
||||
for (String marker : MARKERS) {
|
||||
int from = 0;
|
||||
while (true) {
|
||||
int at = source.indexOf(marker, from);
|
||||
if (at < 0) {
|
||||
break;
|
||||
}
|
||||
from = at + marker.length();
|
||||
int open = source.indexOf('(', at);
|
||||
String body = balancedArguments(source, open);
|
||||
if (body == null) {
|
||||
fail("括号没配平,扫描器会在 " + marker + " 处漏判(offset=" + at + ")");
|
||||
}
|
||||
arguments.add(body);
|
||||
}
|
||||
}
|
||||
return arguments;
|
||||
}
|
||||
|
||||
private static String balancedArguments(String source, int openParen) {
|
||||
int depth = 0;
|
||||
boolean inString = false;
|
||||
for (int i = openParen; i < source.length(); i++) {
|
||||
char c = source.charAt(i);
|
||||
if (inString) {
|
||||
if (c == '\\') {
|
||||
i++;
|
||||
} else if (c == '"') {
|
||||
inString = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (c == '"') {
|
||||
inString = true;
|
||||
} else if (c == '(') {
|
||||
depth++;
|
||||
} else if (c == ')') {
|
||||
depth--;
|
||||
if (depth == 0) {
|
||||
return source.substring(openParen + 1, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String firstLiteral(String arguments) {
|
||||
int start = -1;
|
||||
boolean inString = false;
|
||||
for (int i = 0; i < arguments.length(); i++) {
|
||||
char c = arguments.charAt(i);
|
||||
if (inString) {
|
||||
if (c == '\\') {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (c == '"') {
|
||||
return arguments.substring(start + 1, i);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (c == '"') {
|
||||
inString = true;
|
||||
start = i;
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
private static boolean containsChinese(String text) {
|
||||
for (int i = 0; i < text.length(); i++) {
|
||||
char c = text.charAt(i);
|
||||
if (c >= 0x4E00 && c <= 0x9FFF) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** 相对 src/main/java/com/nanri/aiimage 的路径,豁免表用它点名,行号会漂所以不进键。 */
|
||||
private static String relativeName(Path file) {
|
||||
String path = file.toString().replace('\\', '/');
|
||||
int cut = path.indexOf("/com/nanri/aiimage/");
|
||||
return cut < 0 ? path : path.substring(cut + "/com/nanri/aiimage/".length());
|
||||
}
|
||||
|
||||
private static List<Path> mainSources() throws IOException {
|
||||
Path root = moduleRoot().resolve("src/main/java");
|
||||
if (!Files.isDirectory(root)) {
|
||||
fail("找不到 " + root + " —— 用例依赖以 backend-java 为工作目录运行,别让守卫静默通过");
|
||||
}
|
||||
try (Stream<Path> walk = Files.walk(root)) {
|
||||
return walk.filter(Files::isRegularFile)
|
||||
.filter(p -> p.getFileName().toString().endsWith(".java"))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
|
||||
/** surefire 的工作目录是模块目录;从仓库根或 IDE 跑时退到 backend-java/。 */
|
||||
private static Path moduleRoot() {
|
||||
Path here = Path.of("").toAbsolutePath();
|
||||
if (Files.isDirectory(here.resolve("src/main/java"))) {
|
||||
return here;
|
||||
}
|
||||
Path nested = here.resolve("backend-java");
|
||||
if (Files.isDirectory(nested.resolve("src/main/java"))) {
|
||||
return nested;
|
||||
}
|
||||
throw new IllegalStateException("无法定位 backend-java 模块目录(cwd=" + here + ")");
|
||||
}
|
||||
|
||||
private static String read(Path file) {
|
||||
try {
|
||||
return Files.readString(file, StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("读取 " + file + " 失败", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+79
-8
@@ -113,20 +113,22 @@ import org.junit.jupiter.api.Test;
|
||||
* D 的代价与射程一并交代:非 {@code Long} 型公司参数取不到绑定名,判红并报形状;而"handler 之外的私有
|
||||
* 收口方法里把公司参数硬写成 {@code null}"这一族 D 看不见——块边界止于该 handler 自己的闭括号
|
||||
* (第 7 条),{@code AdminImageVideoTaskController.scopeOf} 正是它,那一处是<b>故意</b>传 null 的。</li>
|
||||
* <li><b>几条正门,一套判据</b>(批次 2/3 新增;10-06 复验后加第二道,批次 6 加第三道,10-07 三期加第四道)。
|
||||
* 出口现在有四个:
|
||||
* {@code readScope(} 按账号集合给范围(去重库、查询 ASIN、最低价 ASIN、历史、视频),
|
||||
* <li><b>几条正门,一套判据</b>(批次 2/3 新增;10-06 复验后加第二道,批次 6 加第三道,10-07 三期加第四道,
|
||||
* 10-09 去重库口径切换加第五道)。出口现在有五个:
|
||||
* {@code readScope(} 按账号集合给范围(查询 ASIN、最低价 ASIN、历史、视频、店铺管理、设备日志等),
|
||||
* {@code readCompanyIdOrOwn(} 给"归属物化成 {@code company_id} 列、可见集又不靠账号/分组"的表
|
||||
* (今天只有店铺密钥,V150 起每公司一套),{@code resolveScopeCompanyId(} 给菜单字典那一棵树一套
|
||||
* (V149 起,读写共用同一判据,见 {@link #RESOLVE_MENU_SCOPE_CALL} 的理由),
|
||||
* {@code superAdminScopedUserIds(} 给看板那一族"只在站点超管身上收窄"的形状
|
||||
* (见 {@link #SUPER_SCOPED_USER_IDS_CALL} 的理由)。
|
||||
* 四道门共用 A/B/C/D 四条判据:
|
||||
* (见 {@link #SUPER_SCOPED_USER_IDS_CALL} 的理由),
|
||||
* {@code superAdminScopedCompanyId(} 给去重库"同样只对超管收窄、但维度是行 company_id"的形状
|
||||
* (见 {@link #SUPER_SCOPED_COMPANY_ID_CALL} 的理由)。
|
||||
* 五道门共用 A/B/C/D 四条判据:
|
||||
* {@link #SCOPE_DOORS} 供 A 与 C 逐条跑,{@link #SCOPE_CALLEE_NAMES} 供 D 认被调名,
|
||||
* <b>名单只写一次</b>(红因消息与自检断言咬的是拼出来的同一个标签,两处各写一遍会随哈希顺序漂红)。
|
||||
* 每条门各自带能红/能绿两向探针(全局约束 15 那把尺子):只在 {@code readScope} 上验过,
|
||||
* 等于第二道门上的返回值与入参没人看守;第三道门(菜单字典)的三枚 {@code MENU_SCOPE_*} 探针同理,
|
||||
* 第四道门的三枚 {@code SUPER_SCOPED_*} 也是照这一条补的。
|
||||
* 第四、五道门的三枚 {@code SUPER_SCOPED_*} 也是照这一条补的。</li>
|
||||
* <p>批次 2 时这里还有<b>中间</b>那道 {@code readCompanyId(},服务品牌库 {@code biz_invalid_asin_data}
|
||||
* 与商品类目 {@code biz_product_category} 两张物化列表。10-06 控制方把这两页定成全平台共享,
|
||||
* 方法随之删除 ⇒ 门也从名单一起摘掉:名单里留一门没有实现者的门,等于给"把公司开关再接回那两张表"
|
||||
@@ -257,8 +259,20 @@ class CompanyIdParamGoesThroughReadScopeTest {
|
||||
* (全局约束 15),所以正/负两向证据在下面各给一遍。</p>
|
||||
*/
|
||||
private static final String SUPER_SCOPED_USER_IDS_CALL = "superAdminScopedUserIds(";
|
||||
/**
|
||||
* 第五道正门(2026-10-09 去重库读侧口径切换):{@code superAdminScopedCompanyId}。与第四道门同形,
|
||||
* 收窄维度从"上传账号集合"换成"行归属的公司 id"——去重库的归属自 V145 起物化在
|
||||
* {@code company_id} 列上(写侧 39de5035 起一律显式落值、V154 摘 DEFAULT),继续按上传账号推导时
|
||||
* 超管代导入的行会整体归错家(控制方截图:admin 在「先锋」tab 导入的行在先锋 tab 看不见)。
|
||||
*
|
||||
* <p>入名单的前提与第二、三、四道门同一条:它只是 {@code DataReadScope} 上的一个方法,
|
||||
* 不是页里自己写的 if。不加它的话 A 会把去重库那两支合规 handler 判红;只加名字不配探针的话,
|
||||
* 这道门上的返回值与入参没人看守(全局约束 15),所以正/负两向证据在下面各给一遍。</p>
|
||||
*/
|
||||
private static final String SUPER_SCOPED_COMPANY_ID_CALL = "superAdminScopedCompanyId(";
|
||||
private static final List<String> SCOPE_DOORS =
|
||||
List.of(READ_SCOPE_CALL, READ_OWN_COMPANY_ID_CALL, RESOLVE_MENU_SCOPE_CALL, SUPER_SCOPED_USER_IDS_CALL);
|
||||
List.of(READ_SCOPE_CALL, READ_OWN_COMPANY_ID_CALL, RESOLVE_MENU_SCOPE_CALL, SUPER_SCOPED_USER_IDS_CALL,
|
||||
SUPER_SCOPED_COMPANY_ID_CALL);
|
||||
private static final String EXPLICIT_PARAM_NAME = "name = \"company_id\"";
|
||||
private static final String SNAKE_PARAM = "company_id";
|
||||
private static final String CAMEL_PARAM = "companyId";
|
||||
@@ -318,7 +332,7 @@ class CompanyIdParamGoesThroughReadScopeTest {
|
||||
*/
|
||||
private static final List<String> SCOPE_CALLEE_NAMES =
|
||||
List.of("readScope", "resolveScope", "readCompanyIdOrOwn", "resolveScopeCompanyId",
|
||||
"superAdminScopedUserIds");
|
||||
"superAdminScopedUserIds", "superAdminScopedCompanyId");
|
||||
private static final Set<String> SCOPE_CALLEES = Set.copyOf(SCOPE_CALLEE_NAMES);
|
||||
private static final String SCOPE_CALLEE_LABEL = String.join("/", SCOPE_CALLEE_NAMES);
|
||||
|
||||
@@ -575,6 +589,38 @@ class CompanyIdParamGoesThroughReadScopeTest {
|
||||
}
|
||||
""";
|
||||
|
||||
/**
|
||||
* 第五道正门的<b>正探针</b>(形状逐字抄现网 {@code DedupeTotalDataController.page}):
|
||||
* 结果接进变量、又作为实参交给 {@code page(…)},公司参数本身进了门 ⇒ C 与 D 都必须判绿。
|
||||
*/
|
||||
private static final String SUPER_SCOPED_COMPANY_CAUGHT_PROBE = """
|
||||
@GetMapping("/probe")
|
||||
public String superScopedCompanyDoor(@RequestParam(name = "company_id", required = false) Long companyId) {
|
||||
AdminUserEntity operator = session.operator();
|
||||
Long scopedCompanyId = dataReadScope.superAdminScopedCompanyId(operator, companyId);
|
||||
return String.valueOf(dedupeTotalDataService.page(1L, 15L, null, null, null, null, null, null, null, operatorId, scopedCompanyId));
|
||||
}
|
||||
""";
|
||||
|
||||
/** 第五道正门的<b>裸语句探针</b>(C 在该门上的"能红"证据):门调了,公司 id 当场丢掉。 */
|
||||
private static final String SUPER_SCOPED_COMPANY_DISCARD_PROBE = """
|
||||
@GetMapping("/probe")
|
||||
public String superScopedCompanyDoorDiscard(@RequestParam(name = "company_id", required = false) Long companyId) {
|
||||
dataReadScope.superAdminScopedCompanyId(operator, companyId);
|
||||
return "ok";
|
||||
}
|
||||
""";
|
||||
|
||||
/** 第五道正门的<b>负探针</b>(D 在该门上的存在理由):切了 tab,传进门里的还是 {@code null}。 */
|
||||
private static final String SUPER_SCOPED_COMPANY_PASSED_NULL_PROBE = """
|
||||
@GetMapping("/probe")
|
||||
public String superScopedCompanyDoorNull(@RequestParam(name = "company_id", required = false) Long companyId) {
|
||||
AdminUserEntity operator = session.operator();
|
||||
Long scopedCompanyId = dataReadScope.superAdminScopedCompanyId(operator, null);
|
||||
return String.valueOf(dedupeTotalDataService.page(1L, 15L, null, null, null, null, null, null, null, operatorId, scopedCompanyId));
|
||||
}
|
||||
""";
|
||||
|
||||
/**
|
||||
* 已摘掉那道门的<b>正样本探针</b>(形状抄退回前的 {@code InvalidAsinDataController.page}:
|
||||
* 收 {@code company_id} 参数、体内调 {@code readCompanyId})。它现在应当被 A/C/D 三条同时判红——
|
||||
@@ -787,6 +833,31 @@ class CompanyIdParamGoesThroughReadScopeTest {
|
||||
.isNotNull()
|
||||
.contains("没进任何 " + SCOPE_CALLEE_LABEL + " 的实参列表");
|
||||
|
||||
// 第五道门(去重库按行 company_id 收窄)同样两向取证:它今天有两个真实消费者
|
||||
// (DedupeTotalDataController 的 page 与 export)。只把名字加进 SCOPE_DOORS 而不验
|
||||
// 返回值与入参,这道门就是"名单里有、没人守"——scopedCompanyId 哪天被丢掉或传成 null,
|
||||
// C 与 D 都不求值,切 tab 又变装饰品。
|
||||
assertThat(scopeProbeReason(SUPER_SCOPED_COMPANY_CAUGHT_PROBE, "SUPER_SCOPED_COMPANY_CAUGHT_PROBE"))
|
||||
.as("断言 C 自检(第五道门·正样本):Long scopedCompanyId = superAdminScopedCompanyId(operator, companyId) "
|
||||
+ "且它进了 page(…) 的实参 ⇒ 判红就是护栏假红")
|
||||
.isNull();
|
||||
assertThat(companyIdArgProbeReason(
|
||||
SUPER_SCOPED_COMPANY_CAUGHT_PROBE, "SUPER_SCOPED_COMPANY_CAUGHT_PROBE", CAMEL_PARAM))
|
||||
.as("断言 D 自检(第五道门·正样本):companyId 真进了 superAdminScopedCompanyId 的实参表 ⇒ 不许红")
|
||||
.isNull();
|
||||
assertThat(scopeProbeReason(SUPER_SCOPED_COMPANY_DISCARD_PROBE, "SUPER_SCOPED_COMPANY_DISCARD_PROBE"))
|
||||
.as("断言 C 自检(第五道门·负样本):superAdminScopedCompanyId( 写成裸语句、公司 id 当场丢掉 ⇒ 必须判红")
|
||||
.isNotNull()
|
||||
.contains("范围算了但没接住");
|
||||
assertThat(scopeProbeReason(SUPER_SCOPED_COMPANY_PASSED_NULL_PROBE, "SUPER_SCOPED_COMPANY_PASSED_NULL_PROBE"))
|
||||
.as("断言 D(第五道门)负样本的前提(断言 C):结果接进 scopedCompanyId 又喂给了 page ⇒ C 判它绿")
|
||||
.isNull();
|
||||
assertThat(companyIdArgProbeReason(
|
||||
SUPER_SCOPED_COMPANY_PASSED_NULL_PROBE, "SUPER_SCOPED_COMPANY_PASSED_NULL_PROBE", CAMEL_PARAM))
|
||||
.as("断言 D 自检(第五道门·负样本):superAdminScopedCompanyId(operator, null) ⇒ 必须判红")
|
||||
.isNotNull()
|
||||
.contains("没进任何 " + SCOPE_CALLEE_LABEL + " 的实参列表");
|
||||
|
||||
// 已摘掉的那道门不许再接回(全局约束 15 的"能红"方向)。这一族 handler(品牌库、商品类目)现在定案
|
||||
// 全平台共享、不再收公司参数 ⇒ 它们已不进 A/C/D 的样本,"哪天有人把 ?company_id= 接回这两张表"
|
||||
// 只剩这条探针还在求值,而今天真正拦它的是断言 A:C 与 D 在主循环里都以"体内有正门调用"为前提
|
||||
|
||||
@@ -161,6 +161,34 @@ class DataReadScopeTest {
|
||||
assertThat(dataReadScope.readCompanyIdOrOwn(user(9L, "company_super_admin", 2L), 7L)).isEqualTo(2L);
|
||||
}
|
||||
|
||||
// ---- 第五道正门 superAdminScopedCompanyId(2026-10-09 去重库读侧口径切换)----
|
||||
// 与第四道门 superAdminScopedUserIds 同形"只在站点超管身上收窄",区别是收窄维度:
|
||||
// 那个给"上传账号集合",这个给"行归属的公司 id"(行把归属物化在 company_id 列上的表用)。
|
||||
// 与非超管相关的关键差异(对照第二道门 readCompanyIdOrOwn):非超管<b>返回 null</b>(不叠),
|
||||
// 绝不 pin own——去重库非超管的可见集锁在账号/分组上,叠一刀公司会把"靠分组可见"的行静默删掉。
|
||||
|
||||
@Test
|
||||
@DisplayName("第五道门:超管按 tab 走,0/负数与非空归一化成「没选公司」")
|
||||
void superScopedCompanyIdFollowsTheTabForSuperAdmin() {
|
||||
assertThat(dataReadScope.superAdminScopedCompanyId(user(1L, "super_admin", 1L), 2L)).isEqualTo(2L);
|
||||
assertThat(dataReadScope.superAdminScopedCompanyId(user(1L, "super_admin", 1L), null)).isNull();
|
||||
assertThat(dataReadScope.superAdminScopedCompanyId(user(1L, "super_admin", 1L), 0L)).isNull();
|
||||
assertThat(dataReadScope.superAdminScopedCompanyId(user(1L, "super_admin", 1L), -3L)).isNull();
|
||||
verifyNoInteractions(companyScope);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("第五道门:非超管一律 null(不叠公司谓词),与第二道门 pin 本公司是两回事")
|
||||
void superScopedCompanyIdLeavesNonSuperAdminUnscoped() {
|
||||
// 传 2(本公司)/ 7(别家)/ null 都必须 null,且不许去查公司归属
|
||||
// (readCompanyIdOrOwn 在老位置会返回 own——那一道门管的是"可见集不靠账号/分组"的表,别抄错门)。
|
||||
assertThat(dataReadScope.superAdminScopedCompanyId(user(5L, "admin", 2L), 2L)).isNull();
|
||||
assertThat(dataReadScope.superAdminScopedCompanyId(user(5L, "admin", 2L), 7L)).isNull();
|
||||
assertThat(dataReadScope.superAdminScopedCompanyId(user(5L, "admin", 2L), null)).isNull();
|
||||
assertThat(dataReadScope.superAdminScopedCompanyId(user(9L, "company_super_admin", 2L), 2L)).isNull();
|
||||
verifyNoInteractions(companyScope);
|
||||
}
|
||||
|
||||
// ---- 写侧闸门 writeCompanyId:读收窄而写不收窄="藏起来的行照样能删" ----
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.nanri.aiimage.common.util;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* 文案把关工具的行为钉子:中文照原样过、英文换兜底句、详情只在中文时才拼接。
|
||||
*/
|
||||
class UserMessagesTest {
|
||||
|
||||
@Test
|
||||
void chineseMessagePassesThroughUntouched() {
|
||||
assertEquals("这份文件没有解析到可导出的行",
|
||||
UserMessages.orFallback("这份文件没有解析到可导出的行", "操作未能完成"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void englishAndBlankFallBackToChinese() {
|
||||
assertEquals("操作未能完成",
|
||||
UserMessages.orFallback("Similar ASIN result rows are empty", "操作未能完成"));
|
||||
assertEquals("操作未能完成", UserMessages.orFallback(null, "操作未能完成"));
|
||||
assertEquals("操作未能完成", UserMessages.orFallback(" ", "操作未能完成"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void chineseDetailIsAppendedAndEnglishDetailIsDropped() {
|
||||
assertEquals("转换结果打包失败:临时目录已满",
|
||||
UserMessages.with("转换结果打包失败", new RuntimeException("临时目录已满")));
|
||||
assertEquals("转换结果打包失败",
|
||||
UserMessages.with("转换结果打包失败", new RuntimeException("No space left on device")));
|
||||
assertEquals("转换结果打包失败", UserMessages.with("转换结果打包失败", (String) null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void headlineKeepsItsOwnColonWhenDetailIsGone() {
|
||||
String text = UserMessages.with("去重结果打包失败: ", new IllegalStateException("boom"));
|
||||
assertEquals("去重结果打包失败", text);
|
||||
assertFalse(text.endsWith(":"), "尾巴被丢掉后不该留下悬空冒号");
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyHanCharactersCountAsChinese() {
|
||||
assertTrue(UserMessages.hasChinese("401 未登录"));
|
||||
assertFalse(UserMessages.hasChinese("TASK_LOCK_BUSY"));
|
||||
assertFalse(UserMessages.hasChinese(":()—"), "全角标点不等于中文文案");
|
||||
assertFalse(UserMessages.hasChinese(null));
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -99,8 +99,9 @@ class TaskResultFileJobWorkerLogAuditTest {
|
||||
assertFalse(l.contains("module="), "不应使用 module= 漂移字段: " + l.trim());
|
||||
}
|
||||
// 阶段字面量来自允许集合(防新增阶段拼写漂移)
|
||||
// SUCCESS_LOST:结果文件已生成但作业行不在本次执行手里(2026-10-09 任务 30456 的静默丢失)
|
||||
List<String> allowed = List.of("SKIP_OWNER", "REQUEUE", "WAIT_LLM", "DEFER", "SUCCESS",
|
||||
"ORPHAN", "FAILED", "FINALIZE", "HEARTBEAT", "FALLBACK");
|
||||
"SUCCESS_LOST", "ORPHAN", "FAILED", "FINALIZE", "HEARTBEAT", "FALLBACK");
|
||||
for (String l : perJob) {
|
||||
if (l.contains("stage=")) {
|
||||
int idx = l.indexOf("stage=");
|
||||
|
||||
+19
-14
@@ -3,7 +3,6 @@ package com.nanri.aiimage.modules.dedupe.controller;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
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.modules.dedupe.service.DedupeTotalDataService;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||
@@ -46,12 +45,13 @@ class DedupeTotalDataControllerTest {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
DedupeTotalDataController controller = new DedupeTotalDataController(
|
||||
service, authSupport, permissionMenuService, dataReadScope);
|
||||
when(dataReadScope.readScope(any(), any())).thenReturn(ReadScope.unfiltered());
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
operator.setId(8L);
|
||||
operator.setRole("super_admin");
|
||||
when(authSupport.requireUser(request)).thenReturn(operator);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
// 未选公司 ⇒ 门给 null(Mockito 对包装 Long 的默认返回值是 0L,必须显式桩)
|
||||
when(dataReadScope.superAdminScopedCompanyId(any(), any())).thenReturn(null);
|
||||
doAnswer(invocation -> {
|
||||
OutputStream outputStream = invocation.getArgument(0);
|
||||
outputStream.write(new byte[]{1, 2, 3});
|
||||
@@ -111,12 +111,13 @@ class DedupeTotalDataControllerTest {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
DedupeTotalDataController controller = new DedupeTotalDataController(
|
||||
service, authSupport, permissionMenuService, dataReadScope);
|
||||
when(dataReadScope.readScope(any(), any())).thenReturn(ReadScope.unfiltered());
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
operator.setId(8L);
|
||||
operator.setRole("super_admin");
|
||||
when(authSupport.requireUser(request)).thenReturn(operator);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
// 未选公司 ⇒ 门给 null(Mockito 对包装 Long 的默认返回值是 0L,必须显式桩)
|
||||
when(dataReadScope.superAdminScopedCompanyId(any(), any())).thenReturn(null);
|
||||
|
||||
ResponseEntity<StreamingResponseBody> response = controller.export(
|
||||
"member",
|
||||
@@ -157,12 +158,13 @@ class DedupeTotalDataControllerTest {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
DedupeTotalDataController controller = new DedupeTotalDataController(
|
||||
service, authSupport, permissionMenuService, dataReadScope);
|
||||
when(dataReadScope.readScope(any(), any())).thenReturn(ReadScope.unfiltered());
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
operator.setId(8L);
|
||||
operator.setRole("super_admin");
|
||||
when(authSupport.requireUser(request)).thenReturn(operator);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
// 未选公司 ⇒ 门给 null(Mockito 对包装 Long 的默认返回值是 0L,必须显式桩)
|
||||
when(dataReadScope.superAdminScopedCompanyId(any(), any())).thenReturn(null);
|
||||
doAnswer(invocation -> {
|
||||
OutputStream outputStream = invocation.getArgument(0);
|
||||
outputStream.write(new byte[]{4, 5});
|
||||
@@ -215,7 +217,6 @@ class DedupeTotalDataControllerTest {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
DedupeTotalDataController controller = new DedupeTotalDataController(
|
||||
service, authSupport, permissionMenuService, dataReadScope);
|
||||
when(dataReadScope.readScope(any(), any())).thenReturn(ReadScope.unfiltered());
|
||||
|
||||
BusinessException exception = assertThrows(BusinessException.class, () -> controller.export(
|
||||
"member",
|
||||
@@ -231,9 +232,10 @@ class DedupeTotalDataControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void companyTabNarrowsSuperAdminToListOfMemberAccounts() {
|
||||
// 超管点公司 tab ⇒ 成员集必须一路传到 service 的最后一个实参。
|
||||
// 这一记盯的是"参数收了、readScope 也调了、结果却喂了 null"那种假接线(tab 恒不动的现网形状)。
|
||||
void companyTabNarrowsSuperAdminToRequestedCompanyId() {
|
||||
// 超管点公司 tab ⇒ 门给出的公司 id 必须一路传到 service 的最后一个实参。
|
||||
// 这一记盯的是"参数收了、门也调了、结果却喂了 null"那种假接线(tab 恒不动的现网形状)。
|
||||
// 2026-10-09 口径切换:尾参从"成员账号集"换成"公司 id"(行按 company_id 列筛)。
|
||||
DedupeTotalDataService service = mock(DedupeTotalDataService.class);
|
||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
||||
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
|
||||
@@ -246,19 +248,19 @@ class DedupeTotalDataControllerTest {
|
||||
operator.setRole("super_admin");
|
||||
when(authSupport.requireUser(request)).thenReturn(operator);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
when(dataReadScope.readScope(operator, 2L)).thenReturn(ReadScope.users(List.of(11L, 12L)));
|
||||
when(dataReadScope.superAdminScopedCompanyId(operator, 2L)).thenReturn(2L);
|
||||
|
||||
controller.page(1L, 15L, null, "member", null, null, null, null, null, 2L, request);
|
||||
|
||||
verify(service).page(eq(1L), eq(15L), isNull(), eq("member"),
|
||||
isNull(), isNull(), isNull(), isNull(), isNull(), eq(8L), eq(List.of(11L, 12L)));
|
||||
isNull(), isNull(), isNull(), isNull(), isNull(), eq(8L), eq(2L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonSuperAdminStaysUnfilteredEvenWhenCompanyTabIsSent() {
|
||||
// 非超管:刻意<b>不</b>按公司收窄。他的可见集里含"靠分组权限可见"的行,
|
||||
// 叠一层账号 IN 会把那批行静默删掉(口径同 ShopManageController)。
|
||||
// 这条是反向钉:哪天有人给非超管也加上成员集,这里必须红。
|
||||
// 非超管:刻意<b>不</b>按公司收窄(门对非超管恒返回 null,规则在 DataReadScope 内)。
|
||||
// 他的可见集里含"靠分组权限可见"的行,叠一层公司谓词会把那批行静默删掉
|
||||
// (口径同 ShopManageController)。这条是反向钉:哪天有人给非超管也加上公司值,这里必须红。
|
||||
DedupeTotalDataService service = mock(DedupeTotalDataService.class);
|
||||
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
|
||||
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
|
||||
@@ -274,11 +276,14 @@ class DedupeTotalDataControllerTest {
|
||||
PermissionMenuItemVo granted = new PermissionMenuItemVo();
|
||||
granted.setColumnKey("admin_dedupe_total_data");
|
||||
when(permissionMenuService.getUserColumnPermissions(9L, "admin")).thenReturn(List.of(granted));
|
||||
// 门对非超管恒返回 null(此处用桩复现该语义;Mockito 对包装 Long 的默认值是 0L)
|
||||
when(dataReadScope.superAdminScopedCompanyId(operator, 2L)).thenReturn(null);
|
||||
|
||||
controller.page(1L, 15L, null, null, null, null, null, null, null, 2L, request);
|
||||
|
||||
// 门被调(tab 值确实交给了唯一出口),但非超管由门内规则折成 null ⇒ service 不叠公司条件
|
||||
verify(dataReadScope).superAdminScopedCompanyId(operator, 2L);
|
||||
verify(service).page(eq(1L), eq(15L), isNull(), isNull(),
|
||||
isNull(), isNull(), isNull(), isNull(), isNull(), eq(9L), isNull());
|
||||
verify(dataReadScope, never()).readScope(any(), any());
|
||||
}
|
||||
}
|
||||
|
||||
+42
@@ -1,5 +1,8 @@
|
||||
package com.nanri.aiimage.modules.dedupe.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.mapper.AdminUserMapper;
|
||||
import com.nanri.aiimage.common.mapper.ShopManageGroupMapper;
|
||||
@@ -7,10 +10,13 @@ import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.model.entity.ShopManageGroupEntity;
|
||||
import com.nanri.aiimage.common.service.CompanyScopeSupport;
|
||||
import com.nanri.aiimage.modules.dedupe.mapper.DedupeTotalDataMapper;
|
||||
import com.nanri.aiimage.modules.dedupe.model.entity.DedupeTotalDataEntity;
|
||||
import com.nanri.aiimage.modules.shopkey.service.ShopManageGroupService;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
@@ -23,6 +29,10 @@ import java.util.Set;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
@@ -130,4 +140,36 @@ class DedupeTotalDataCompanySuperAdminGroupAccessTest {
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessage("请选择分组");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("读列表按行归属收窄:company_id = 本公司,不再叠「成员上传」(代导入/上传者已删两族不再漏)")
|
||||
@SuppressWarnings({"rawtypes", "unchecked"})
|
||||
void pageNarrowsCompanySuperAdminByRowCompanyId() {
|
||||
// 2026-10-09 口径切换(wholeCompany 分支):原条件 uploader_user_id IN (本公司成员)
|
||||
// 会整批漏掉两类行——超管代导入的行(uploader=超管,不属本公司)与上传账号被硬删的行
|
||||
// (JOIN 不上任何成员集)。先锋公司超管(uid=1206)对 admin 代导入的 14 行与组 33 的
|
||||
// 1452 行历史数据一行都看不到,切到行 company_id 后可见。
|
||||
TableInfoHelper.initTableInfo(
|
||||
new MapperBuilderAssistant(new MybatisConfiguration(), ""),
|
||||
DedupeTotalDataEntity.class);
|
||||
stubCompanySuperAdmin();
|
||||
when(shopManageGroupService.listCompanyGroupIds(List.of(OPERATOR_ID)))
|
||||
.thenReturn(Set.of(OWN_COMPANY_GROUP_ID));
|
||||
when(dedupeTotalDataMapper.selectCount(any())).thenReturn(0L);
|
||||
when(dedupeTotalDataMapper.selectList(any())).thenReturn(List.of());
|
||||
|
||||
service.page(1, 15, "", "", null, null, null, null, null, OPERATOR_ID, null);
|
||||
|
||||
ArgumentCaptor<LambdaQueryWrapper<DedupeTotalDataEntity>> captor =
|
||||
ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
|
||||
verify(dedupeTotalDataMapper).selectCount(captor.capture());
|
||||
LambdaQueryWrapper<DedupeTotalDataEntity> query = captor.getValue();
|
||||
query.getSqlSegment();
|
||||
assertTrue(query.getSqlSegment().contains("company_id"),
|
||||
"公司超管必须按行 company_id 看全公司: " + query.getSqlSegment());
|
||||
assertTrue(query.getParamNameValuePairs().containsValue(OWN_COMPANY_ID),
|
||||
"company_id 收窄值必须是本公司: " + query.getParamNameValuePairs());
|
||||
assertFalse(query.getSqlSegment().contains("uploader_user_id"),
|
||||
"不许回退成「成员上传」口径(会漏代导入/上传者已删两族): " + query.getSqlSegment());
|
||||
}
|
||||
}
|
||||
|
||||
+29
-1
@@ -266,6 +266,34 @@ class DedupeTotalDataServiceTest {
|
||||
assertTrue(query.getCustomSqlSegment().contains("FIND_IN_SET"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({"rawtypes", "unchecked"})
|
||||
void pageNarrowsSuperAdminByRowCompanyId() {
|
||||
// 2026-10-09 口径切换:超管切公司 tab 后按行自己的 company_id 筛(原按上传账号集合)。
|
||||
// 这条钉的是 applyCompanyScope 的那一刀:删掉 eq(company_id,…),切 tab 就成装饰品;
|
||||
// 反向(又冒回 uploader_user_id)则 admin 代导入的行会重新归错家。
|
||||
TableInfoHelper.initTableInfo(
|
||||
new MapperBuilderAssistant(new MybatisConfiguration(), ""),
|
||||
DedupeTotalDataEntity.class);
|
||||
when(adminUserMapper.selectById(1L)).thenReturn(user(1L, "super_admin", "root"));
|
||||
when(dedupeTotalDataMapper.selectCount(any())).thenReturn(0L);
|
||||
when(dedupeTotalDataMapper.selectList(any())).thenReturn(List.of());
|
||||
|
||||
service.page(1, 15, "", "", null, null, null, null, null, 1L, 2L);
|
||||
|
||||
ArgumentCaptor<LambdaQueryWrapper<DedupeTotalDataEntity>> queryCaptor =
|
||||
ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
|
||||
verify(dedupeTotalDataMapper).selectCount(queryCaptor.capture());
|
||||
LambdaQueryWrapper<DedupeTotalDataEntity> query = queryCaptor.getValue();
|
||||
query.getSqlSegment();
|
||||
assertTrue(query.getSqlSegment().contains("company_id"),
|
||||
"超管切公司后必须按行 company_id 收窄: " + query.getSqlSegment());
|
||||
assertTrue(query.getParamNameValuePairs().containsValue(2L),
|
||||
"company_id 收窄值必须是 tab 传下来的 2: " + query.getParamNameValuePairs());
|
||||
assertFalse(query.getSqlSegment().contains("uploader_user_id"),
|
||||
"不许再按上传账号收窄: " + query.getSqlSegment());
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentDuplicateDuringImportIsSkipped() throws Exception {
|
||||
when(adminUserMapper.selectById(23L)).thenReturn(user(23L, "normal", "member-a"));
|
||||
@@ -382,7 +410,7 @@ class DedupeTotalDataServiceTest {
|
||||
when(dedupeTotalDataMapper.delete(any())).thenReturn(1);
|
||||
|
||||
service.deleteBatchByDataValues(List.of("B012345678"),
|
||||
new DedupeTotalDataService.AccessScope(true, java.util.Set.of(), java.util.Set.of(), false),
|
||||
new DedupeTotalDataService.AccessScope(true, java.util.Set.of(), java.util.Set.of(), false, null),
|
||||
null, 3L);
|
||||
|
||||
ArgumentCaptor<LambdaQueryWrapper<DedupeTotalDataEntity>> captor =
|
||||
|
||||
+2
-2
@@ -207,7 +207,7 @@ class ImageVideoAsyncTaskServiceTest {
|
||||
ImageVideoAsyncTaskEntity task = waitingWorkflowTask();
|
||||
task.setStatus("FAILED");
|
||||
task.setCozeStatus("RUNNING");
|
||||
task.setErrorMessage("Coze workflow finished with status RUNNING");
|
||||
task.setErrorMessage("Coze 工作流已结束,状态 RUNNING");
|
||||
when(taskMapper.selectOne(any())).thenReturn(task);
|
||||
|
||||
var result = service.getTask(98L, 1L);
|
||||
@@ -367,7 +367,7 @@ class ImageVideoAsyncTaskServiceTest {
|
||||
|
||||
assertEquals("FAILED", task.getStatus());
|
||||
assertEquals("SUCCESS", task.getCozeStatus());
|
||||
assertEquals("Coze workflow succeeded but video_url is empty", task.getErrorMessage());
|
||||
assertEquals("Coze 工作流成功但没有返回视频地址", task.getErrorMessage());
|
||||
assertNotNull(task.getCompletedAt());
|
||||
assertTrue(task.getResultJson().contains("video_url"));
|
||||
verify(archiveService, never()).enrichCompletedTask(any(), any());
|
||||
|
||||
+2
-2
@@ -174,7 +174,7 @@ class SimilarAsinTaskServiceChunkKeysetTest {
|
||||
when(taskChunkMapper.selectList(any())).thenThrow(new IllegalStateException("db down"));
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> SimilarAsinChunkMergeSupport.loadChunksKeyset(taskChunkMapper, 7004L, MODULE, 500));
|
||||
assertTrue(ex.getMessage() != null && ex.getMessage().contains("chunk"),
|
||||
assertTrue(ex.getMessage() != null && ex.getMessage().contains("分片"),
|
||||
"异常消息必须可识别,实际: " + ex.getMessage());
|
||||
}
|
||||
|
||||
@@ -194,7 +194,7 @@ class SimilarAsinTaskServiceChunkKeysetTest {
|
||||
}).when(taskChunkMapper).selectList(any());
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> SimilarAsinChunkMergeSupport.loadChunksKeyset(taskChunkMapper, 7004L, MODULE, 3));
|
||||
assertTrue(ex.getMessage() != null && ex.getMessage().contains("chunk"),
|
||||
assertTrue(ex.getMessage() != null && ex.getMessage().contains("分片"),
|
||||
"异常消息必须可识别,实际: " + ex.getMessage());
|
||||
// 恢复后重试成功:5 个 chunk 全部取回
|
||||
stubKeysetPages(all, 3);
|
||||
|
||||
+1
-1
@@ -357,7 +357,7 @@ class SimilarAsinTaskServiceChunkMergeLimitTest {
|
||||
}
|
||||
});
|
||||
assertNotNull(ex.getMessage());
|
||||
assertTrue(ex.getMessage().contains("chunk"),
|
||||
assertTrue(ex.getMessage().contains("分片"),
|
||||
"chunk 读取失败消息必须可识别,实际: " + ex.getMessage());
|
||||
verify(transientPayloadStorageService, times(0)).storeChunkPayloadVersioned(anyString(), any(), anyString(), any(), anyString());
|
||||
verify(taskScopeStateMapper, times(0)).insert(any(TaskScopeStateEntity.class));
|
||||
|
||||
+1
-1
@@ -309,7 +309,7 @@ class SimilarAsinTaskServiceRowKeyDedupeTest {
|
||||
throw e.getCause();
|
||||
}
|
||||
});
|
||||
assertTrue(ex.getMessage() != null && ex.getMessage().contains("chunk"),
|
||||
assertTrue(ex.getMessage() != null && ex.getMessage().contains("分片"),
|
||||
"chunk 读取失败消息必须可识别,实际: " + ex.getMessage());
|
||||
verify(transientPayloadStorageService, times(0)).storeChunkPayloadVersioned(anyString(), any(), anyString(), any(), anyString());
|
||||
// 恢复后重试成功:只写一次,无重复记录
|
||||
|
||||
+1
-1
@@ -359,7 +359,7 @@ class SimilarAsinTaskServiceRowKeyIndexTest {
|
||||
throw e.getCause();
|
||||
}
|
||||
});
|
||||
assertTrue(ex.getMessage() != null && ex.getMessage().contains("chunk"),
|
||||
assertTrue(ex.getMessage() != null && ex.getMessage().contains("分片"),
|
||||
"chunk 读取失败消息必须可识别,实际: " + ex.getMessage());
|
||||
verify(transientPayloadStorageService, times(0)).storeChunkPayloadVersioned(anyString(), any(), anyString(), any(), anyString());
|
||||
// 恢复后重试成功:行合并到正确 chunk
|
||||
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
package com.nanri.aiimage.modules.similarasin.service.support;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.fail;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* 货源查询(SIMILAR_ASIN)结果出口的提示语必须是中文。
|
||||
*
|
||||
* <p>线上任务 30456 的界面同时出现"仅完成 102/112 行"和一句英文
|
||||
* "Similar ASIN result rows are empty; please retry result generation":前者是 legacy 装配路径写的,
|
||||
* 后者是 bounded 装配路径写的。两条路径是同一次拆分(9d92fb4a)时只翻译了 legacy 那一半,
|
||||
* bounded 那一半的 8 句英文异常原样进了 {@code biz_task_file_job.error_message},
|
||||
* 前端 {@code pendingResultHint} 又把这一列不加转换地渲染出来。
|
||||
*
|
||||
* <p>所以这里钉两件事:
|
||||
* <ol>
|
||||
* <li>那 8 句英文不许回来(排他断言,逐句点名);</li>
|
||||
* <li>两个文件里每个 {@code new BusinessException(...)} / {@code saveFileBuildProgress(...)}
|
||||
* 出口的第一段文案必须含中文——新增出口自动受约束。</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p>第二条的判据是"首段字面量含中文",不是"每段都含中文":拼接里的单位片段
|
||||
* ({@code " bytes"}、{@code " 分钟)"})本就不该有中文,2026-10-09 用两个文件的全部
|
||||
* 62 个出口校准过这个口径。分母自证用例防止扫描器一旦抓不到就恒绿。
|
||||
*/
|
||||
class SimilarAsinChineseMessageGuardTest {
|
||||
|
||||
private static final List<String> SCANNED_FILES = List.of(
|
||||
"modules/similarasin/service/SimilarAsinTaskService.java",
|
||||
"modules/similarasin/service/support/SimilarAsinResultWorkbookAssembler.java");
|
||||
|
||||
/** 2026-10-09 实测:TaskService 42 个出口 + Assembler 20 个出口。新增/删除出口要同步改这里。 */
|
||||
private static final int SCANNED_SITE_COUNT = 62;
|
||||
|
||||
/** 文案来自变量、字面量判据覆盖不到的出口,按构造点名(行号会漂)。 */
|
||||
private static final List<String> VARIABLE_FED_OUTLETS = List.of(
|
||||
"task, job, 1, 1, failureMessage",
|
||||
"FailedStatusRowFilter.noMatchedRowsMessage()",
|
||||
"message");
|
||||
|
||||
private static final List<String> ENGLISH_LEAKS = List.of(
|
||||
"Similar ASIN result rows are empty",
|
||||
"failed to create result directory",
|
||||
"result workbook assembly interrupted",
|
||||
"result workbook assembly timed out",
|
||||
"result workbook assembly cancelled",
|
||||
"result workbook assembly failed",
|
||||
"create Similar ASIN image spool failed",
|
||||
"no valid similar ASIN rows",
|
||||
"Assembling xlsx",
|
||||
"Uploading result file",
|
||||
"Result file generated",
|
||||
"LLM result is still processing");
|
||||
|
||||
@Test
|
||||
void theEnglishMessagesThatReachedTheUiAreGone() throws IOException {
|
||||
for (String fragment : ENGLISH_LEAKS) {
|
||||
for (String file : SCANNED_FILES) {
|
||||
assertThat(readSource(file))
|
||||
.as("%s 里不许出现以 \"%s\" 开头的用户可见文案,改成中文", file, fragment)
|
||||
.doesNotContain(fragment);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyMessageOutletStartsWithChinese() throws IOException {
|
||||
List<String> offenders = new ArrayList<>();
|
||||
List<String> variableFed = new ArrayList<>();
|
||||
int scanned = 0;
|
||||
for (String file : SCANNED_FILES) {
|
||||
String source = readSource(file);
|
||||
for (Outlet outlet : outlets(source)) {
|
||||
scanned++;
|
||||
if (!outlet.hasFirstLiteral()) {
|
||||
variableFed.add(outlet.arguments().trim());
|
||||
continue;
|
||||
}
|
||||
if (!containsChinese(outlet.firstLiteral())) {
|
||||
offenders.add(file + ":" + outlet.line() + " -> \"" + outlet.firstLiteral() + "\"");
|
||||
}
|
||||
}
|
||||
}
|
||||
assertThat(offenders)
|
||||
.as("这些出口的首段文案没有中文,会原样出现在用户界面上")
|
||||
.isEmpty();
|
||||
// 分母自证:扫描器一旦什么都抓不到,上面的断言就恒绿,等于没有护栏。
|
||||
// 新增出口要同时改这个数字;文案来自变量时也要确认变量本身是中文。
|
||||
assertThat(scanned)
|
||||
.as("两个文件里 new BusinessException(...) 与 saveFileBuildProgress(...) 的出口总数")
|
||||
.isEqualTo(SCANNED_SITE_COUNT);
|
||||
assertThat(variableFed)
|
||||
.as("文案来自变量、本用例判不了的出口——改动这几处时要自己确认落到界面上是中文")
|
||||
.containsExactlyInAnyOrderElementsOf(VARIABLE_FED_OUTLETS);
|
||||
}
|
||||
|
||||
private record Outlet(int line, String arguments) {
|
||||
boolean hasFirstLiteral() {
|
||||
return !firstLiteral().isEmpty();
|
||||
}
|
||||
|
||||
String firstLiteral() {
|
||||
int start = -1;
|
||||
boolean inString = false;
|
||||
for (int i = 0; i < arguments.length(); i++) {
|
||||
char c = arguments.charAt(i);
|
||||
if (inString) {
|
||||
if (c == '\\') {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (c == '"') {
|
||||
return arguments.substring(start + 1, i);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (c == '"') {
|
||||
inString = true;
|
||||
start = i;
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Outlet> outlets(String source) {
|
||||
List<Outlet> outlets = new ArrayList<>();
|
||||
for (String marker : List.of("new BusinessException(", "saveFileBuildProgress(")) {
|
||||
int from = 0;
|
||||
while (true) {
|
||||
int at = source.indexOf(marker, from);
|
||||
if (at < 0) {
|
||||
break;
|
||||
}
|
||||
from = at + marker.length();
|
||||
int open = source.indexOf('(', at);
|
||||
String arguments = balancedArguments(source, open);
|
||||
if (arguments == null) {
|
||||
fail("括号没配平,扫描器会在 " + marker + " 处漏判(offset=" + at + ")");
|
||||
}
|
||||
outlets.add(new Outlet(lineOf(source, at), arguments));
|
||||
}
|
||||
}
|
||||
return outlets;
|
||||
}
|
||||
|
||||
private static int lineOf(String source, int offset) {
|
||||
int line = 1;
|
||||
for (int i = 0; i < offset; i++) {
|
||||
if (source.charAt(i) == '\n') {
|
||||
line++;
|
||||
}
|
||||
}
|
||||
return line;
|
||||
}
|
||||
|
||||
private static String balancedArguments(String source, int openParen) {
|
||||
int depth = 0;
|
||||
boolean inString = false;
|
||||
for (int i = openParen; i < source.length(); i++) {
|
||||
char c = source.charAt(i);
|
||||
if (inString) {
|
||||
if (c == '\\') {
|
||||
i++;
|
||||
} else if (c == '"') {
|
||||
inString = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (c == '"') {
|
||||
inString = true;
|
||||
} else if (c == '(') {
|
||||
depth++;
|
||||
} else if (c == ')') {
|
||||
depth--;
|
||||
if (depth == 0) {
|
||||
return source.substring(openParen + 1, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean containsChinese(String text) {
|
||||
for (int i = 0; i < text.length(); i++) {
|
||||
char c = text.charAt(i);
|
||||
if (c >= 0x4E00 && c <= 0x9FFF) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static String readSource(String moduleRelativePath) throws IOException {
|
||||
Path file = mainJavaRoot().resolve("com/nanri/aiimage/" + moduleRelativePath);
|
||||
if (!Files.isRegularFile(file)) {
|
||||
fail("找不到 " + file + " —— 用例依赖以 backend-java 为工作目录运行,别让守卫静默通过");
|
||||
}
|
||||
return Files.readString(file, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/** surefire 的工作目录是模块目录;从仓库根或 IDE 跑时退到 backend-java/。 */
|
||||
private static Path mainJavaRoot() {
|
||||
Path here = Path.of("").toAbsolutePath();
|
||||
if (Files.isDirectory(here.resolve("src/main/java"))) {
|
||||
return here.resolve("src/main/java");
|
||||
}
|
||||
Path nested = here.resolve("backend-java");
|
||||
if (Files.isDirectory(nested.resolve("src/main/java"))) {
|
||||
return nested.resolve("src/main/java");
|
||||
}
|
||||
throw new IllegalStateException("无法定位 backend-java 模块目录(cwd=" + here + ")");
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -370,7 +370,7 @@ class SimilarAsinHistoryAssemblerTest {
|
||||
|
||||
BusinessException thrown = assertThrows(BusinessException.class,
|
||||
() -> assembler.buildHistoryItems(List.of(row), Map.of(10L, task(10L, "RUNNING", null)), jobMap()));
|
||||
assertTrue(thrown.getMessage().contains("chunk=2"), "异常附带 chunk 索引,实际: " + thrown.getMessage());
|
||||
assertTrue(thrown.getMessage().contains("分片=2"), "异常附带分片索引,实际: " + thrown.getMessage());
|
||||
|
||||
ArgumentCaptor<LambdaUpdateWrapper<TaskScopeStateEntity>> captor =
|
||||
ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
|
||||
|
||||
+28
@@ -4,6 +4,7 @@ import com.nanri.aiimage.modules.task.mapper.TaskFileJobMapper;
|
||||
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.core.task.TaskExecutor;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
@@ -13,6 +14,7 @@ import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
@@ -86,6 +88,32 @@ class TaskFileJobLocalDispatcherTest {
|
||||
verify(executor, times(1)).execute(any(Runnable.class));
|
||||
}
|
||||
|
||||
/**
|
||||
* 已 claim 的派发必须把 claim 那一刻的行快照原样带到执行处,且这条路径一次都不回读数据库。
|
||||
*
|
||||
* <p>线上任务 30456(2026-10-09)的反例:执行前 {@code selectById} 重读,读到的
|
||||
* {@code updated_at} 就是当前值,{@code activateRunningClaim} 的 CAS 于是恒真 ——
|
||||
* 排队排久了的旧派发能冒充成新持有者,撞锁后再用 {@code deferRunning} 把真持有者
|
||||
* 正在跑的行翻回 PENDING,那次的 {@code markSuccess} 静默 0 行更新、成功丢失。
|
||||
*/
|
||||
@Test
|
||||
void claimedDispatchCarriesTheSnapshotInsteadOfReReadingTheRow() {
|
||||
TaskFileJobEntity claim = job(7L);
|
||||
claim.setStatus("RUNNING");
|
||||
TaskFileJobEntity rowChangedAfterTheClaim = job(7L);
|
||||
rowChangedAfterTheClaim.setStatus("PENDING");
|
||||
when(taskFileJobMapper.selectById(7L)).thenReturn(rowChangedAfterTheClaim);
|
||||
|
||||
List<Runnable> captured = captureRunnables();
|
||||
assertTrue(dispatcher.dispatchClaimed(claim));
|
||||
captured.forEach(Runnable::run);
|
||||
|
||||
ArgumentCaptor<TaskFileJobEntity> passed = ArgumentCaptor.forClass(TaskFileJobEntity.class);
|
||||
verify(worker).processClaimed(passed.capture());
|
||||
assertSame(claim, passed.getValue(), "必须用 claim 快照,重读就等于没有围栏");
|
||||
verify(taskFileJobMapper, never()).selectById(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void test_task_073_dispatch_normal_multiple_items() throws Exception {
|
||||
// 批量场景:多个不同 jobId 依次 dispatch,互不冲突,全部受理。
|
||||
|
||||
+18
@@ -176,6 +176,24 @@ class TaskFileJobServiceTest {
|
||||
assertTrue(update.getValue().getParamNameValuePairs().containsValue("RUNNING"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 围栏写没命中必须让调用方知道。2026-10-09 任务 30456 就是这里静默 0 行更新:
|
||||
* 结果文件已生成、可下载,作业行却被别人翻回了 PENDING,最后被重试打满判成 FAILED,
|
||||
* 界面上一个成功的任务显示成"结果生成失败"。
|
||||
*/
|
||||
@Test
|
||||
void markSuccessReportsWhetherTheFencedWriteLanded() {
|
||||
TaskFileJobEntity job = runningJob(109L, 1, LocalDateTime.now());
|
||||
TaskFileJobService service = new TaskFileJobService(taskFileJobMapper, applicationEventPublisher);
|
||||
|
||||
when(taskFileJobMapper.update(isNull(), any(LambdaUpdateWrapper.class))).thenReturn(0);
|
||||
assertFalse(service.markSuccess(job, "result.xlsx"),
|
||||
"行已不在本次执行手里时必须报未落库,不能静默");
|
||||
|
||||
when(taskFileJobMapper.update(isNull(), any(LambdaUpdateWrapper.class))).thenReturn(1);
|
||||
assertTrue(service.markSuccess(job, "result.xlsx"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void similarAsinHeartbeatOnlyTouchesStaleRunningAssembleJobs() {
|
||||
TaskFileJobService service = new TaskFileJobService(taskFileJobMapper, applicationEventPublisher);
|
||||
|
||||
+30
@@ -158,6 +158,36 @@ class TaskResultFileJobWorkerOrphanTest {
|
||||
verify(taskFileJobService).markFailedPermanent(job, "result record not found");
|
||||
}
|
||||
|
||||
/**
|
||||
* 2026-10-09 把各模块的"任务不存在/结果记录不存在"从英文换成中文后,孤儿判据必须照样命中:
|
||||
* 这两句是 {@code isOrphanJobFailure} 的匹配串,漏了这些作业就会对着已经不存在的任务白重试 5 次。
|
||||
*/
|
||||
@Test
|
||||
void orphanTaskNotFoundChineseMessage() throws Exception {
|
||||
TaskResultFileJobWorker worker = buildWorker();
|
||||
TaskFileJobEntity job = job("SHOP_MATCH", 3L, 13L);
|
||||
allowClaim(job);
|
||||
allowLock(job.getModuleType(), job.getTaskId());
|
||||
doThrow(new BusinessException("任务不存在")).when(shopMatch).processResultFileJob(job);
|
||||
|
||||
worker.process(job);
|
||||
|
||||
verify(taskFileJobService).markFailedPermanent(job, "任务不存在");
|
||||
}
|
||||
|
||||
@Test
|
||||
void orphanResultRecordNotFoundChineseMessage() throws Exception {
|
||||
TaskResultFileJobWorker worker = buildWorker();
|
||||
TaskFileJobEntity job = job("SHOP_MATCH", 4L, 14L);
|
||||
allowClaim(job);
|
||||
allowLock(job.getModuleType(), job.getTaskId());
|
||||
doThrow(new BusinessException("结果记录不存在")).when(shopMatch).processResultFileJob(job);
|
||||
|
||||
worker.process(job);
|
||||
|
||||
verify(taskFileJobService).markFailedPermanent(job, "结果记录不存在");
|
||||
}
|
||||
|
||||
@Test
|
||||
void orphanChineseMessages() throws Exception {
|
||||
TaskResultFileJobWorker worker = buildWorker();
|
||||
|
||||
+3
-3
@@ -125,7 +125,7 @@ class TaskResultFileJobWorkerOwnerRoutingTest {
|
||||
TaskFileJobEntity claim = claimedJob(PublishTaskService.MODULE_TYPE, 18524L, 26402L, "task:26402:owner:instance-a");
|
||||
when(taskFileJobService.claimRunnableJobsForOwner(20, "instance-a")).thenReturn(List.of(claim));
|
||||
when(taskFileJobService.activateRunningClaim(claim)).thenReturn(true);
|
||||
when(localDispatcher.dispatchClaimed(claim.getId(), claim.getTaskId(), claim.getModuleType())).thenReturn(false);
|
||||
when(localDispatcher.dispatchClaimed(claim)).thenReturn(false);
|
||||
when(taskDistributedLockService.acquire(PublishTaskService.MODULE_TYPE, claim.getTaskId(),
|
||||
TaskDistributedLockService.DEFAULT_WAIT_MILLIS)).thenReturn(lock);
|
||||
|
||||
@@ -142,11 +142,11 @@ class TaskResultFileJobWorkerOwnerRoutingTest {
|
||||
when(instanceMetadata.getInstanceId()).thenReturn("instance-a");
|
||||
TaskFileJobEntity claim = claimedJob(PublishTaskService.MODULE_TYPE, 18525L, 26403L, "task:26403:owner:instance-a");
|
||||
when(taskFileJobService.claimRunnableJobsForOwner(20, "instance-a")).thenReturn(List.of(claim));
|
||||
when(localDispatcher.dispatchClaimed(claim.getId(), claim.getTaskId(), claim.getModuleType())).thenReturn(true);
|
||||
when(localDispatcher.dispatchClaimed(claim)).thenReturn(true);
|
||||
|
||||
worker.runPendingJobs();
|
||||
|
||||
verify(localDispatcher).dispatchClaimed(claim.getId(), claim.getTaskId(), claim.getModuleType());
|
||||
verify(localDispatcher).dispatchClaimed(claim);
|
||||
verify(localDispatcher, never()).dispatch(anyLong(), anyLong(), any());
|
||||
verify(taskFileJobService, never()).claimRunning(anyLong());
|
||||
verify(publish, never()).processResultFileJob(any());
|
||||
|
||||
@@ -69,6 +69,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||
import { userNotice } from '@/shared/utils/user-notice'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
|
||||
import FileUploadZone from '@/shared/components/FileUploadZone.vue'
|
||||
@@ -234,7 +235,7 @@ function toPatentTaskView(item: AppearancePatentHistoryItem): TaskItemView {
|
||||
extraLines: [
|
||||
...(item.rowCount != null ? [`行数:${item.rowCount}`] : []),
|
||||
...(item.resultFilename && !showProgress ? [item.resultFilename] : []),
|
||||
...(item.error ? [`错误:${item.error}`] : []),
|
||||
...(item.error ? [`错误:${userNotice(item.error)}`] : []),
|
||||
],
|
||||
progress: showProgress
|
||||
? {
|
||||
@@ -290,7 +291,7 @@ function isResultBuildFailed(item: AppearancePatentHistoryItem) {
|
||||
|
||||
function pendingResultHint(item: AppearancePatentHistoryItem) {
|
||||
if (isResultBuildFailed(item)) {
|
||||
return item.fileError || '结果文件生成失败,请稍后重试或检查后端日志'
|
||||
return userNotice(item.fileError, '结果文件生成失败,请稍后重试或检查后端日志')
|
||||
}
|
||||
if (board.showFileProgress(item)) {
|
||||
return ''
|
||||
|
||||
@@ -96,6 +96,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import { userNotice } from '@/shared/utils/user-notice'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue'
|
||||
import FileUploadZone from '@/shared/components/FileUploadZone.vue'
|
||||
@@ -335,7 +336,7 @@ function toBrandTaskView(item: BrandTaskItem): TaskItemView {
|
||||
const extraLines = [
|
||||
...(item.file_paths?.length ? [`文件:${item.file_paths.length} 个`] : []),
|
||||
...(lp && lineTotal > 0 ? [`已处理 ${lineCurrent} 行 / 共 ${lineTotal} 行(含查询失败)`] : []),
|
||||
...(errorMessage(item) ? [`错误:${errorMessage(item)}`] : []),
|
||||
...(errorMessage(item) ? [`错误:${userNotice(errorMessage(item))}`] : []),
|
||||
]
|
||||
// 行级进度优先:完成数 = 已处理品牌行(成功或查询失败都计入),进度 = 完成数 / 总数 * 100
|
||||
let progress: TaskItemView['progress'] = null
|
||||
@@ -462,7 +463,7 @@ async function downloadResult(item: BrandTaskItem) {
|
||||
if (res.success) {
|
||||
ElMessage.success(`已保存:${res.path || filename}`)
|
||||
} else if (res.error && res.error !== '用户取消') {
|
||||
ElMessage.error(res.error)
|
||||
ElMessage.error(userNotice(res.error))
|
||||
}
|
||||
return
|
||||
} catch (error) {
|
||||
@@ -489,7 +490,7 @@ async function downloadTemplate(kind: 'xlsx' | 'zip') {
|
||||
if (res?.success) {
|
||||
ElMessage.success(`模板已保存至:${res.path}`)
|
||||
} else if (res?.error) {
|
||||
ElMessage.warning(res.error)
|
||||
ElMessage.warning(userNotice(res.error))
|
||||
} else {
|
||||
ElMessage.warning('当前环境不支持模板下载,请在本机客户端中打开')
|
||||
}
|
||||
|
||||
@@ -136,6 +136,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, reactive, ref, shallowRef, triggerRef } from 'vue'
|
||||
import { userNotice } from '@/shared/utils/user-notice'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
|
||||
import FileUploadZone from '@/shared/components/FileUploadZone.vue'
|
||||
@@ -566,7 +567,7 @@ async function downloadResult(item: CollectDataHistoryItem) {
|
||||
if (result.success) {
|
||||
ElMessage.success(`已保存: ${result.path || filename}`)
|
||||
} else if (result.error && result.error !== '用户取消') {
|
||||
ElMessage.error(result.error)
|
||||
ElMessage.error(userNotice(result.error))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -692,7 +693,7 @@ function toCollectTaskView(item: CollectDataHistoryItem): TaskItemView {
|
||||
`不符合 ASIN 过滤:${item.invalidFilteredCount ?? 0}`,
|
||||
...(item.resultFilename ? [item.resultFilename] : []),
|
||||
...(taskFilterSummary(item) ? [`筛选统计:${taskFilterSummary(item)}`] : []),
|
||||
...(item.error ? [`错误:${item.error}`] : []),
|
||||
...(item.error ? [`错误:${userNotice(item.error)}`] : []),
|
||||
]
|
||||
return {
|
||||
key: `collect-${item.taskId ?? item.resultId ?? item.sourceFilename}`,
|
||||
|
||||
@@ -105,6 +105,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { userNotice } from '@/shared/utils/user-notice'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
|
||||
import FileUploadZone from '@/shared/components/FileUploadZone.vue'
|
||||
@@ -207,7 +208,7 @@ function toConvertTaskView(item: ConvertResultItem): TaskItemView {
|
||||
statusClass: convertTaskStatusClass(item),
|
||||
extraLines: [
|
||||
...(item.outputFilename ? [`压缩包文件:${item.outputFilename}`] : []),
|
||||
...(item.error ? [`错误信息:${item.error}`] : []),
|
||||
...(item.error ? [`错误信息:${userNotice(item.error)}`] : []),
|
||||
],
|
||||
source: item,
|
||||
}
|
||||
@@ -318,7 +319,7 @@ async function downloadConvertResult(item: ConvertResultItem) {
|
||||
if (result.success) {
|
||||
ElMessage.success(`已保存:${result.path || filename}`)
|
||||
} else if (result.error && result.error !== '用户取消') {
|
||||
ElMessage.error(result.error)
|
||||
ElMessage.error(userNotice(result.error))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -122,6 +122,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import { userNotice } from '@/shared/utils/user-notice'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
|
||||
import FileUploadZone from '@/shared/components/FileUploadZone.vue'
|
||||
@@ -231,7 +232,7 @@ function toDedupeTaskView(item: DedupeResultItem): TaskItemView {
|
||||
statusClass: item.success ? 'success' : 'failed',
|
||||
extraLines: [
|
||||
...(item.outputFilename ? [`输出文件:${item.outputFilename}`] : []),
|
||||
...(item.error ? [`错误信息:${item.error}`] : []),
|
||||
...(item.error ? [`错误信息:${userNotice(item.error)}`] : []),
|
||||
],
|
||||
source: item,
|
||||
}
|
||||
@@ -413,7 +414,7 @@ async function downloadCleanResult(item: DedupeResultItem) {
|
||||
if (result.success) {
|
||||
ElMessage.success(`已保存:${result.path || filename}`)
|
||||
} else if (result.error && result.error !== '用户取消') {
|
||||
ElMessage.error(result.error)
|
||||
ElMessage.error(userNotice(result.error))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -101,6 +101,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 AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
|
||||
import FileUploadZone from '@/shared/components/FileUploadZone.vue'
|
||||
@@ -360,7 +361,7 @@ function toDeleteBrandTaskView(item: DeleteBrandResultItem): TaskItemView {
|
||||
...(item.totalRows !== undefined && item.matched ? [`去重后 ${item.totalRows} 条`] : []),
|
||||
...(showProgress && formatProgress(item) ? [formatProgress(item)] : []),
|
||||
...(item.previewRows?.length ? [formatPreview(item.previewRows)] : []),
|
||||
...(getDisplayError(item) ? [`错误信息:${getDisplayError(item)}`] : []),
|
||||
...(getDisplayError(item) ? [`错误信息:${userNotice(getDisplayError(item))}`] : []),
|
||||
]
|
||||
return {
|
||||
key: `delete-brand-${item.taskId ?? ''}-${item.resultId ?? item.fileKey ?? item.sourceFilename}`,
|
||||
@@ -1101,7 +1102,7 @@ async function downloadTaskResult(item: DeleteBrandResultItem) {
|
||||
if (result.success) {
|
||||
ElMessage.success(`已保存:${result.path || filename}`)
|
||||
} else if (result.error && result.error !== '用户取消') {
|
||||
ElMessage.error(result.error)
|
||||
ElMessage.error(userNotice(result.error))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -249,6 +249,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
|
||||
import { userNotice } from '@/shared/utils/user-notice'
|
||||
import { ElMessage } from "element-plus";
|
||||
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
|
||||
import TaskCenterPanel from "@/shared/components/tasks/TaskCenterPanel.vue";
|
||||
@@ -394,7 +395,7 @@ function toPatrolTaskView(item: PatrolDeleteHistoryItem): TaskItemView {
|
||||
...(formatTaskGroupShopIds(item) ? [`店铺 ID: ${formatTaskGroupShopIds(item)}`] : []),
|
||||
...(item.platform ? [`平台: ${item.platform}`] : []),
|
||||
`模板: ${formatTemplateSummary(item)}`,
|
||||
...(formatTaskGroupErrors(item) ? [`错误: ${formatTaskGroupErrors(item)}`] : []),
|
||||
...(formatTaskGroupErrors(item) ? [`错误: ${userNotice(formatTaskGroupErrors(item))}`] : []),
|
||||
],
|
||||
source: item,
|
||||
}
|
||||
@@ -1239,7 +1240,7 @@ async function downloadResult(item: PatrolDeleteHistoryItem) {
|
||||
if (result.success) {
|
||||
ElMessage.success(`已保存: ${result.path || filename}`);
|
||||
} else if (result.error && result.error !== "用户取消") {
|
||||
ElMessage.error(result.error);
|
||||
ElMessage.error(userNotice(result.error));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -220,6 +220,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, onUnmounted, ref, shallowRef, triggerRef, watch } from 'vue'
|
||||
import { userNotice } from '@/shared/utils/user-notice'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import type { TableInstance } from 'element-plus'
|
||||
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
|
||||
@@ -1074,7 +1075,7 @@ async function enqueueCreatedTask(api: PywebviewApi, taskId: number, queuePayloa
|
||||
try {
|
||||
pushResult = await api.enqueue_json(queuePayload)
|
||||
} catch (error) {
|
||||
reason = `任务队列调用异常:${error instanceof Error ? error.message : String(error || '未知错误')}`
|
||||
reason = `任务队列调用异常:${userNotice(error instanceof Error ? error.message : String(error || '未知错误'))}`
|
||||
await compensateDispatchFailure(taskId, reason)
|
||||
throw new Error(reason)
|
||||
}
|
||||
@@ -1571,7 +1572,7 @@ function toPriceTrackTaskView(item: PriceTrackHistoryItem): TaskItemView {
|
||||
...(item.roundIndex ? [`轮次:第 ${item.roundIndex} 轮`] : []),
|
||||
...(item.platform ? [`平台:${item.platform}`] : []),
|
||||
...(item.outputFilename ? [`文件:${item.outputFilename}`] : []),
|
||||
...(item.error ? [`错误:${item.error}`] : []),
|
||||
...(item.error ? [`错误:${userNotice(item.error)}`] : []),
|
||||
],
|
||||
source: item,
|
||||
}
|
||||
@@ -1621,7 +1622,7 @@ async function downloadResult(item: PriceTrackHistoryItem) {
|
||||
if (result.success) {
|
||||
ElMessage.success(`已保存:${result.path || filename}`)
|
||||
} else if (result.error && result.error !== '用户取消') {
|
||||
ElMessage.error(result.error)
|
||||
ElMessage.error(userNotice(result.error))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user