fix(文案出口): 用户可见提示语一律走 UserMessages 把关,并补结果作业租约围栏
两件事同源:2026-10-09 任务 30456 的卡片上同时出现中文进度和一句英文异常原文。 围栏:派发链在执行前重读 job 行,让 activateRunningClaim 的 CAS 恒真,撞锁方 deferRunning 把在跑的行翻回 PENDING,markSuccess 静默写 0 行——成功被判成失败。 claim 快照现在贯穿到 runClaimed 不再回读,markSuccess 返回布尔并补 stage=SUCCESS_LOST 日志,让这次丢失可观测。 文案:普查数出 61 处把 ex.getMessage() 拼进用户可见字段(异常响应、任务 error_message、 结果作业 error_msg、看板 message),逐条翻译追不上新增速度,改为出口把关—— UserMessages.with(中文主干, 异常) 只拼接中文详情、orFallback(原文, 兜底句) 只放行含中文的串, 被换掉的原文进日志;GlobalExceptionHandler 按码分档兜底(401/4011/40902 各说各的话)。 另把 chunk-read-failed[N] 摘要写成"第 N 分片读取失败"、TASK_LOCK_BUSY 换成中文(40902 码不动, 客户端按码分支)。数字人两处与结果作业 worker 故意仍存原文:孤儿判定与三条 preserves raw 用例按 error_message 读它,界面侧由前端 userNotice 兜住,已在新尺子里点名豁免并反查豁免是否还被用到。 尺子:RawExceptionMessageSinkGuardTest(出口行数下限硬钉 1500+内存造违例自证)、UserMessagesTest、 UserFacingMessageChineseGuardTest 豁免表收到只剩 JSON 键 msg 一条。mvn -o test 4205 例 0 失败。
This commit is contained in:
+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)
|
||||
|
||||
+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;
|
||||
}
|
||||
|
||||
+7
-6
@@ -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;
|
||||
@@ -279,7 +280,7 @@ public class DedupeTotalDataService {
|
||||
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);
|
||||
@@ -315,14 +316,14 @@ public class DedupeTotalDataService {
|
||||
Long operatorId,
|
||||
List<Long> companyMemberIds) {
|
||||
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);
|
||||
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();
|
||||
@@ -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("去重库数据导出失败,请稍后重试");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+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",
|
||||
|
||||
Reference in New Issue
Block a user