Compare commits

...

6 Commits

Author SHA1 Message Date
huangzd1997 17cc775176 docs(运维): 上线后性能/逻辑审查报告(外观与货源两条链的批间串行等待是大头)
只读代码审查,每条带 file:line,依赖线上数才能定量化的标了【待测】并附取数 SQL。
四条 P0 的共同形态是「贵的不是 LLM 本身,是夹在批次之间的串行等待」;另记两处
有现成批量接口没接上的系统性浪费与一处调度自相矛盾(PENDING 排队超 5 分钟被 retry
顶到上限,之后一次真实超时直接判死)。
2026-10-02 09:22:48 +08:00
huangzd1997 8c37bcc7e9 fix(货源): LLM 密钥去掉平台公费兜底,任务没带自己的密钥就不检而不代付
`llm-api-key` 这条回落链(配置 → 公费 key)此前是账目对不上的一个来源:用户没配密钥时
货源任务照样跑完 LLM,花费记在平台头上。现在只认任务自带的 api_key,为空即跳过检测、
保留原始行。两台线上都未设置 AIIMAGE_SIMILAR_ASIN_LLM_API_KEY,本批发布对现网行为零变化。
2026-10-02 09:21:40 +08:00
huangzd1997 e90f614962 perf(用户密钥): 探测与告警按密钥值收敛,共用同一把 key 的账号不再各付一次提取费
实测 314 条配置只有 33 种密钥(一把平均挂 9.5 个账号):定时巡检按「模块+密文」分组后一轮只
真实探测一次;后台「立即检测该用户」的 90s 新鲜期缓存键去掉 uid、改为按密钥值指纹共享,
管理员连点 N 个共用 key 的账号只付 1 次费。管理员侧告警按密钥组合并成一条(受众仍按数据权限
过滤,正文不列 uid——同 key 账号常分属不同主管),单账号组保持原文案与原去重键。
2026-10-02 09:21:25 +08:00
huangzd1997 0384d62968 fix(任务判死): 外观/货源判死文案按证据陈述,不再断言 Python 中断
2026-10-01 三条外观任务被心跳判死时一行业务结果都没回传过(Linux worker 一次领 5 条却只有
2 个采集槽,多出来的任务零心跳零分片直到钟面走完),而文案固定写 "Python interrupted before
uploading final result",把「没开跑」说成「跑挂了」,排查方向被带偏过一次。现在按已落库分片数、
最后回传/心跳时间、客户端最后一次上报的位置分述;结果文件作业重试耗尽也不再写成客户端中断。
2026-10-02 09:21:11 +08:00
huangzd1997 517b02485b refactor: 第二批收敛——公共 Excel 写出器 + 任务收尾零件下沉 + 前端上传区/任务面板抽取 2026-10-01 15:00:52 +08:00
huangzd1997 16e2c9a5e7 refactor: 第一批低风险收敛——任务缓存服务泛型化 + 前端死代码清理与状态映射统一 2026-10-01 14:05:30 +08:00
111 changed files with 4108 additions and 6447 deletions
@@ -0,0 +1,54 @@
package com.nanri.aiimage.common.util;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
/**
* 客户端型任务(外观专利 / 货源)心跳判死文案:只写证据支持的话。
*
* <p>历史上这里固定写 "Python interrupted before uploading final result",而 2026-10-01 线上三条
* 外观任务其实一行业务结果都没回传过——Linux worker 一次领 5 条却只有 2 个采集槽,多出来的任务
* 状态是 RUNNING、零心跳零分片,两小时后被写成「Python 中断」。「没开工」被说成「跑挂了」,
* 排查方向被带偏过一次,故文案按证据分述,并把客户端最后一次上报的位置一起带出来
* (排队中的任务会上报「排队等待空闲槽位」,与真在采集是两种成因)。
*
* @param chunkCount 已落库的结果分片数(biz_task_chunk)
* @param lastChunkAt 最后一次结果分片回传时间,从未回传时为 null
* @param lastHeartbeatAt 最后一次客户端心跳时间,Redis 无记录时为 null
* @param lastProgress 客户端最后一次上报的位置/阶段文本,老客户端或无位置信息时为 null
* @param fileJobExhausted 结果文件作业是否已重试耗尽(true 时责任不在客户端回传)
* @param timeoutMinutes 判死阈值(分钟)
*/
public record StaleTaskDeathReason(long chunkCount,
LocalDateTime lastChunkAt,
LocalDateTime lastHeartbeatAt,
String lastProgress,
boolean fileJobExhausted,
int timeoutMinutes) {
private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("MM-dd HH:mm");
public String describe() {
if (chunkCount > 0 && fileJobExhausted) {
return "已收到 " + chunkCount + " 个结果分片,但结果文件生成多次失败,任务已自动结束";
}
String headline = chunkCount <= 0L
? "客户端未回传任何检测结果,超过 " + Math.max(1, timeoutMinutes) + " 分钟无进展"
: "客户端回传中断";
List<String> evidence = new ArrayList<>();
if (chunkCount > 0L) {
evidence.add("已收到 " + chunkCount + " 个分片,最后一次 " + at(lastChunkAt));
}
evidence.add("最后心跳 " + at(lastHeartbeatAt));
if (lastProgress != null && !lastProgress.isBlank()) {
evidence.add("最后上报 " + lastProgress.trim());
}
return headline + ",任务已自动结束(" + String.join(";", evidence) + ")";
}
private static String at(LocalDateTime time) {
return time == null ? "时间未知" : time.format(TIME);
}
}
@@ -0,0 +1,135 @@
package com.nanri.aiimage.common.util;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 公共 SXSSF 流式写出器:统一 {@code new SXSSFWorkbook(200) + setCompressTempFiles(true)}
* + write + try/finally {@code close()+dispose()} 骨架,并提供空值安全的单元格写入与列宽换算。
*
* <p>此前 8 个 {@code *ExcelAssemblyService} 与独立写出实现各自复制这段骨架和
* {@code value == null ? "" : value}、{@code n * 256} 样板;本类把骨架收敛到一处,
* 表头定义与行映射仍保留在各装配类中(调用方持有 Sheet/Row,本类只提供工作簿生命周期
* 与零件方法),因此日期/数字/特殊样式等模块语义不会被偷偷改掉。
*
* <p>用法:
* <pre>{@code
* try (SxssfWorkbookWriter writer = SxssfWorkbookWriter.open()) {
* Sheet sheet = writer.createSheet("结果", HEADER, new int[]{20, 18, 18});
* for (RowDto item : rows) {
* Row row = sheet.createRow(rowIndex++);
* SxssfWorkbookWriter.setText(row, 0, item.getAsin());
* }
* writer.write(outputXlsx);
* }
* }</pre>
*/
public final class SxssfWorkbookWriter implements AutoCloseable {
/** 各模块历史实现统一的滚动窗口大小(ShopDataCrawl 流式路径的自定义窗口除外)。 */
public static final int DEFAULT_ROW_ACCESS_WINDOW = 200;
private final SXSSFWorkbook workbook;
private CellStyle headerStyle;
private SxssfWorkbookWriter(int rowAccessWindow) {
this.workbook = new SXSSFWorkbook(rowAccessWindow);
this.workbook.setCompressTempFiles(true);
}
public static SxssfWorkbookWriter open() {
return new SxssfWorkbookWriter(DEFAULT_ROW_ACCESS_WINDOW);
}
public static SxssfWorkbookWriter open(int rowAccessWindow) {
return new SxssfWorkbookWriter(rowAccessWindow);
}
public SXSSFWorkbook workbook() {
return workbook;
}
/** 建表 + 第 0 行表头 + 列宽(单位:字符,内部换算 n*256)。columnWidthChars 为 null 时不设列宽。 */
public Sheet createSheet(String sheetName, String[] headers, int[] columnWidthChars) {
Sheet sheet = workbook.createSheet(sheetName);
writeHeaderRow(sheet, headers);
if (columnWidthChars != null) {
applyColumnWidths(sheet, columnWidthChars);
}
return sheet;
}
/** 在 sheet 第 0 行写入表头文字(不做样式;需要表头样式的调用方再逐格 setCellStyle)。 */
public void writeHeaderRow(Sheet sheet, String[] headers) {
Row headerRow = sheet.createRow(0);
for (int i = 0; i < headers.length; i++) {
headerRow.createCell(i).setCellValue(headers[i]);
}
}
/** 加粗表头样式(与 Publish/SimilarAsin 历史实现一致:bold Font + 空 CellStyle),惰性创建并复用。 */
public CellStyle headerStyle() {
if (headerStyle == null) {
Font font = workbook.createFont();
font.setBold(true);
CellStyle style = workbook.createCellStyle();
style.setFont(font);
headerStyle = style;
}
return headerStyle;
}
/** 写出文件(内部开 FileOutputStream)。失败时抛 IOException,工作簿由 close() 兜底释放。 */
public void write(File output) throws IOException {
try (FileOutputStream fos = new FileOutputStream(output)) {
workbook.write(fos);
}
}
/** 历史骨架的固定收尾:close() 吞异常 + dispose() 释放 SXSSF 临时文件。 */
@Override
public void close() {
try {
workbook.close();
} catch (Exception ignored) {
}
workbook.dispose();
}
// ------------------------------------------------------------------
// 静态零件:空值安全写入与列宽
// ------------------------------------------------------------------
/** null 写成空字符串,其余原样写入(与各模块 safe()/valueOf() 语义一致)。 */
public static void setText(Row row, int column, String value) {
row.createCell(column).setCellValue(value == null ? "" : value);
}
/** 数值单元格:null 写成空字符串,否则写 doubleValue(与 Withdraw writeMoney/CollectData intOrZero 语义一致)。 */
public static void setNumber(Row row, int column, Number value) {
if (value == null) {
row.createCell(column).setCellValue("");
} else {
row.createCell(column).setCellValue(value.doubleValue());
}
}
/** 列宽换算:字符数 * 256。 */
public static int width(int charCount) {
return charCount * 256;
}
/** 按字符数依次设置第 0..n-1 列宽。 */
public static void applyColumnWidths(Sheet sheet, int[] columnWidthChars) {
for (int i = 0; i < columnWidthChars.length; i++) {
sheet.setColumnWidth(i, columnWidthChars[i] * 256);
}
}
}
@@ -158,9 +158,6 @@ public class SimilarAsinProperties {
/** 直连 LLM 的 base url(OpenAI 兼容 /v1/chat/completions)。 */
private String llmHost = "https://ai.t8star.org";
/** 直连 LLM 的 Bearer token;前端未传 api_key 时兜底使用。 */
private String llmApiKey = "";
/** 类目匹配(一级/二级)使用的小模型。 */
private String llmCategoryModel = "gemini-3.1-flash-lite-preview-thinking-medium";
@@ -28,7 +28,7 @@ public class AppearancePatentHistoryItemVo {
private String taskStatus;
@Schema(description = "结果是否成功。true 表示任务完成并生成结果文件;false 表示失败或未完成。", example = "true")
private Boolean success;
@Schema(description = "错误信息。任务失败时返回,例如 Python 超时、结果文件生成失败等。", example = "Python interrupted before uploading final appearance patent result")
@Schema(description = "错误信息。任务失败时返回,例如客户端未回传任何检测结果、结果文件生成失败等。", example = "客户端未回传任何检测结果,超过 30 分钟无进展,任务已自动结束(最后心跳 10-01 12:34)")
private String error;
@Schema(description = "最终结果行数。包含解析阶段被过滤但最终需要补回的 2_2、2_3 等子行。", example = "716")
private Integer rowCount;
@@ -1,23 +1,23 @@
package com.nanri.aiimage.modules.appearancepatent.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentResultRowDto;
import lombok.RequiredArgsConstructor;
import com.nanri.aiimage.modules.task.service.AbstractPendingRowTaskCacheService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
/**
* 外观专利模块任务缓存服务:待处理行队列 + 心跳复用通用基类
* {@link AbstractPendingRowTaskCacheService};本模块额外的行级两态标记
* (处理中 / 已完成)与轮次计数留在本类。
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class AppearancePatentTaskCacheService {
private static final long TTL_HOURS = 24;
public class AppearancePatentTaskCacheService extends AbstractPendingRowTaskCacheService<AppearancePatentResultRowDto> {
/**
* 处理中标记 TTL。取 15 分钟:合批后单批实测约 30–120 秒(合批前 10 行要 220 秒),
@@ -26,117 +26,16 @@ public class AppearancePatentTaskCacheService {
*/
private static final Duration IN_FLIGHT_TTL = Duration.ofMinutes(15);
private final StringRedisTemplate stringRedisTemplate;
private final ObjectMapper objectMapper;
private static final long TTL_HOURS = 24;
public void appendPendingRow(Long taskId, String scopeHash, Integer chunkIndex, AppearancePatentResultRowDto row) {
if (taskId == null || taskId <= 0 || scopeHash == null || scopeHash.isBlank() || chunkIndex == null || row == null) {
return;
}
try {
stringRedisTemplate.opsForList().rightPush(
pendingRowsKey(taskId),
objectMapper.writeValueAsString(new PendingRow(scopeHash, chunkIndex, row))
);
stringRedisTemplate.expire(pendingRowsKey(taskId), Duration.ofHours(TTL_HOURS));
touchTaskHeartbeat(taskId);
} catch (Exception ignored) {
}
public AppearancePatentTaskCacheService(StringRedisTemplate stringRedisTemplate,
ObjectMapper objectMapper) {
super("appearance-patent", AppearancePatentResultRowDto.class, stringRedisTemplate, objectMapper);
}
public long pendingRowCount(Long taskId) {
Long size;
try {
size = stringRedisTemplate.opsForList().size(pendingRowsKey(taskId));
} catch (Exception ex) {
log.warn("[appearance-patent-cache] pending row count degraded taskId={} msg={}", taskId, ex.getMessage());
return 0L;
}
return size == null ? 0L : size;
}
public List<PendingRow> drainPendingRows(Long taskId, int limit) {
if (taskId == null || taskId <= 0 || limit <= 0) {
return List.of();
}
String key = pendingRowsKey(taskId);
List<String> values;
try {
values = stringRedisTemplate.opsForList().range(key, 0, limit - 1L);
} catch (Exception ex) {
log.warn("[appearance-patent-cache] drain range degraded taskId={} msg={}", taskId, ex.getMessage());
return List.of();
}
if (values == null || values.isEmpty()) {
return List.of();
}
try {
stringRedisTemplate.opsForList().trim(key, values.size(), -1);
} catch (Exception ex) {
log.warn("[appearance-patent-cache] drain trim degraded taskId={} msg={}", taskId, ex.getMessage());
return List.of();
}
List<PendingRow> rows = new ArrayList<>();
for (String value : values) {
if (value == null || value.isBlank()) {
continue;
}
try {
rows.add(objectMapper.readValue(value, PendingRow.class));
} catch (Exception ignored) {
}
}
touchTaskHeartbeat(taskId);
return rows;
}
public void touchTaskHeartbeat(Long taskId) {
if (taskId == null || taskId <= 0) {
return;
}
try {
stringRedisTemplate.opsForValue().set(
heartbeatKey(taskId),
String.valueOf(Instant.now().toEpochMilli()),
Duration.ofHours(TTL_HOURS)
);
} catch (Exception ex) {
log.warn("[appearance-patent-cache] touch heartbeat degraded taskId={} msg={}", taskId, ex.getMessage());
}
}
public long getTaskHeartbeatMillis(Long taskId) {
if (taskId == null || taskId <= 0) {
return 0L;
}
String raw;
try {
raw = stringRedisTemplate.opsForValue().get(heartbeatKey(taskId));
} catch (Exception ex) {
log.warn("[appearance-patent-cache] get heartbeat degraded taskId={} msg={}", taskId, ex.getMessage());
return 0L;
}
if (raw == null || raw.isBlank()) {
return 0L;
}
try {
return Long.parseLong(raw);
} catch (NumberFormatException ignored) {
return 0L;
}
}
public void deleteTaskCache(Long taskId) {
if (taskId == null || taskId <= 0) {
return;
}
try {
stringRedisTemplate.delete(pendingRowsKey(taskId));
stringRedisTemplate.delete(heartbeatKey(taskId));
stringRedisTemplate.delete(processedRowsKey(taskId));
} catch (Exception ex) {
log.warn("[appearance-patent-cache] delete degraded taskId={} msg={}", taskId, ex.getMessage());
}
@Override
protected void deleteExtraTaskCacheKeys(Long taskId) {
stringRedisTemplate.delete(processedRowsKey(taskId));
}
/**
@@ -277,15 +176,4 @@ public class AppearancePatentTaskCacheService {
private String processedRowKey(Long taskId, String rowKey) {
return processedRowsKey(taskId) + ":" + rowKey;
}
private String pendingRowsKey(Long taskId) {
return "appearance-patent:task:pending-rows:" + taskId;
}
private String heartbeatKey(Long taskId) {
return "appearance-patent:task:heartbeat:" + taskId;
}
public record PendingRow(String scopeHash, Integer chunkIndex, AppearancePatentResultRowDto row) {
}
}
@@ -13,6 +13,7 @@ import com.nanri.aiimage.common.exception.TaskOwnerMismatchException;
import com.nanri.aiimage.common.service.DistributedJobLockService;
import com.nanri.aiimage.common.util.GroupResultPropagator;
import com.nanri.aiimage.common.util.FailedStatusRowFilter;
import com.nanri.aiimage.common.util.StaleTaskDeathReason;
import com.nanri.aiimage.config.AppearancePatentProperties;
import com.nanri.aiimage.config.InstanceMetadata;
import com.nanri.aiimage.config.StorageProperties;
@@ -650,7 +651,7 @@ public class AppearancePatentTaskService {
continue;
}
try (lockHandle) {
finalizeStaleTask(task.getId(), "Python interrupted before uploading final appearance patent result");
finalizeStaleTask(task.getId(), describeStaleDeath(task.getId()));
}
}
finalizeNoUploadStaleTasks();
@@ -665,10 +666,44 @@ public class AppearancePatentTaskService {
return;
}
try (lockHandle) {
finalizeStaleTask(taskId, "Python interrupted before uploading final appearance patent result");
finalizeStaleTask(taskId, describeStaleDeath(taskId));
}
}
/**
* 判死文案按证据分述:客户端从未回传(多半是排队等槽位)、回传中断、还是文件生成侧失败。
* 三条路径历史上共用一句 "Python interrupted before uploading final appearance patent result",
* 把「没开跑」说成「跑挂了」。
*/
private String describeStaleDeath(Long taskId) {
long heartbeatMillis = taskCacheService.getTaskHeartbeatMillis(taskId);
return new StaleTaskDeathReason(
persistedResultChunkCount(taskId),
lastResultChunkAt(taskId),
heartbeatMillis > 0L
? LocalDateTime.ofInstant(Instant.ofEpochMilli(heartbeatMillis), ZoneId.systemDefault())
: null,
taskHeartbeatPositionService.describe(taskId),
taskFileJobService.hasExhaustedAssembleJob(taskId, MODULE_TYPE),
properties.getStaleTimeoutMinutes()).describe();
}
private long persistedResultChunkCount(Long taskId) {
if (taskId == null) {
return 0L;
}
Long count = taskChunkMapper.selectCount(new LambdaQueryWrapper<TaskChunkEntity>()
.eq(TaskChunkEntity::getTaskId, taskId)
.eq(TaskChunkEntity::getModuleType, MODULE_TYPE));
return count == null ? 0L : count;
}
/** 最后一次结果分片回传时间;从未回传时为 null。 */
private LocalDateTime lastResultChunkAt(Long taskId) {
List<TaskScopeLastChunkDto> rows = taskScopeStateMapper.selectLastChunkAtByTaskIds(List.of(taskId));
return rows == null || rows.isEmpty() ? null : rows.get(0).lastChunkAt();
}
private List<FileTaskEntity> listStaleFinalizeCandidates() {
// P1-7:不再用 file_task.updated_at 预过滤,由调用方按 Redis heartbeat 判 stale。
// APPEARANCE_PATENT 在线 RUNNING 任务量级有限(限 200),全扫成本可忽略。
@@ -1,16 +1,15 @@
package com.nanri.aiimage.modules.collectdata.service;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.util.SxssfWorkbookWriter;
import com.nanri.aiimage.modules.collectdata.model.dto.CollectDataSummaryRowDto;
import com.nanri.aiimage.modules.collectdata.model.vo.CollectDataResultRowVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
@@ -85,17 +84,14 @@ public class CollectDataExcelAssemblyService {
if (outputXlsx == null) {
throw new BusinessException("生成采集数据 Excel 失败: 输出文件路径为空");
}
SXSSFWorkbook workbook = new SXSSFWorkbook(200);
workbook.setCompressTempFiles(true);
SxssfWorkbookWriter writer = SxssfWorkbookWriter.open();
// 先写目标同目录的临时文件,成功后原子落位:写入或落位失败时目标路径
// 不残留半成品,临时文件由 catch/finally 清理(SXSSF 滚动窗口文件由 dispose 释放)。
File tmpFile = new File(outputXlsx.getAbsolutePath() + ".tmp");
try {
long detailRowCount = writeDetailSheet(workbook, itemsSource);
writeSummarySheet(workbook, summaries, rawItemsSource);
try (FileOutputStream outputStream = new FileOutputStream(tmpFile)) {
workbook.write(outputStream);
}
long detailRowCount = writeDetailSheet(writer, itemsSource);
writeSummarySheet(writer, summaries, rawItemsSource);
writer.write(tmpFile);
Files.move(tmpFile.toPath(), outputXlsx.toPath(),
StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
return detailRowCount;
@@ -104,11 +100,7 @@ public class CollectDataExcelAssemblyService {
deleteQuietly(tmpFile);
throw new BusinessException("生成采集数据 Excel 失败: " + ex.getMessage());
} finally {
try {
workbook.close();
} catch (Exception ignored) {
}
workbook.dispose();
writer.close();
deleteQuietly(tmpFile);
}
}
@@ -130,12 +122,10 @@ public class CollectDataExcelAssemblyService {
}
}
private long writeDetailSheet(SXSSFWorkbook workbook, RowBatchSource itemsSource) {
Sheet sheet = workbook.createSheet(SHEET_DETAIL_NAME);
Row headerRow = sheet.createRow(0);
private long writeDetailSheet(SxssfWorkbookWriter writer, RowBatchSource itemsSource) {
Sheet sheet = writer.createSheet(SHEET_DETAIL_NAME, SHEET_DETAIL_HEADER, null);
for (int i = 0; i < SHEET_DETAIL_HEADER.length; i++) {
headerRow.createCell(i).setCellValue(SHEET_DETAIL_HEADER[i]);
sheet.setColumnWidth(i, (i == 3 ? 24 : 18) * 256);
sheet.setColumnWidth(i, SxssfWorkbookWriter.width(i == 3 ? 24 : 18));
}
// state[0]=下一个写入行号,state[1]=已写明细行数(与原 List 路径 rows.size() 对齐)
long[] state = new long[]{1L, 0L};
@@ -149,12 +139,12 @@ public class CollectDataExcelAssemblyService {
continue;
}
Row row = sheet.createRow((int) state[0]++);
row.createCell(0).setCellValue(safe(item.getBrand()));
row.createCell(1).setCellValue(safe(item.getAsin()));
row.createCell(2).setCellValue(safe(item.getPrice()));
row.createCell(3).setCellValue(safe(item.getSellerName()));
row.createCell(4).setCellValue(safe(item.getKeyword()));
row.createCell(5).setCellValue(safe(item.getDeliveryMethod()));
SxssfWorkbookWriter.setText(row, 0, item.getBrand());
SxssfWorkbookWriter.setText(row, 1, item.getAsin());
SxssfWorkbookWriter.setText(row, 2, item.getPrice());
SxssfWorkbookWriter.setText(row, 3, item.getSellerName());
SxssfWorkbookWriter.setText(row, 4, item.getKeyword());
SxssfWorkbookWriter.setText(row, 5, item.getDeliveryMethod());
state[1]++;
}
});
@@ -168,14 +158,12 @@ public class CollectDataExcelAssemblyService {
* - 当 summaries 为空(Python 端尚未接入或解析失败)时,回退到基于 rawItems 自聚合,
* 保证 Excel 不会因迁移过渡期而出现空表。等 Python 端全部接入并稳定后,可移除 fallback 分支。
*/
private void writeSummarySheet(SXSSFWorkbook workbook,
private void writeSummarySheet(SxssfWorkbookWriter writer,
List<CollectDataSummaryRowDto> summaries,
RowBatchSource rawItemsSource) {
Sheet sheet = workbook.createSheet(SHEET_SUMMARY_NAME);
Row headerRow = sheet.createRow(0);
Sheet sheet = writer.createSheet(SHEET_SUMMARY_NAME, SHEET_SUMMARY_HEADER, null);
for (int i = 0; i < SHEET_SUMMARY_HEADER.length; i++) {
headerRow.createCell(i).setCellValue(SHEET_SUMMARY_HEADER[i]);
sheet.setColumnWidth(i, (i == 0 ? 28 : 12) * 256);
sheet.setColumnWidth(i, SxssfWorkbookWriter.width(i == 0 ? 28 : 12));
}
if (summaries != null && !summaries.isEmpty()) {
@@ -186,18 +174,18 @@ public class CollectDataExcelAssemblyService {
continue;
}
Row row = sheet.createRow(rowIndex++);
row.createCell(0).setCellValue(safe(item.getKeyword()));
row.createCell(1).setCellValue(intOrZero(item.getFba()));
row.createCell(2).setCellValue(intOrZero(item.getFbm()));
row.createCell(3).setCellValue(intOrZero(item.getAmz()));
row.createCell(4).setCellValue(intOrZero(item.getNoneCount()));
SxssfWorkbookWriter.setText(row, 0, item.getKeyword());
SxssfWorkbookWriter.setNumber(row, 1, intOrZero(item.getFba()));
SxssfWorkbookWriter.setNumber(row, 2, intOrZero(item.getFbm()));
SxssfWorkbookWriter.setNumber(row, 3, intOrZero(item.getAmz()));
SxssfWorkbookWriter.setNumber(row, 4, intOrZero(item.getNoneCount()));
Integer totalPage = item.getTotalPage();
if (totalPage != null && totalPage > 0) {
row.createCell(5).setCellValue(totalPage);
SxssfWorkbookWriter.setNumber(row, 5, totalPage);
} else {
row.createCell(5).setCellValue("");
SxssfWorkbookWriter.setText(row, 5, "");
}
row.createCell(6).setCellValue(intOrZero(item.getAsinFilter()));
SxssfWorkbookWriter.setNumber(row, 6, intOrZero(item.getAsinFilter()));
}
return;
}
@@ -40,6 +40,7 @@ import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
import com.nanri.aiimage.modules.task.service.TaskDistributedLockService;
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
import com.nanri.aiimage.modules.task.service.TaskFinalizeSupport;
import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoShopMatchResultVo;
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopIndexService;
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopSwitchService;
@@ -1260,6 +1261,7 @@ public class DeleteBrandRunService {
}
private FileTaskEntity loadTaskForExecution(Long taskId) {
// DeleteBrandTaskCacheService 未继承 AbstractModuleTaskCacheService,保持本地实现
Map<Long, FileTaskEntity> cachedTasks = deleteBrandTaskCacheService.getTaskCacheBatch(List.of(taskId));
FileTaskEntity cached = cachedTasks.get(taskId);
if (cached != null) {
@@ -1273,16 +1275,7 @@ public class DeleteBrandRunService {
}
private List<FileTaskEntity> selectTasksByIdsInBatches(List<Long> taskIds) {
List<FileTaskEntity> tasks = new ArrayList<>();
if (taskIds == null || taskIds.isEmpty()) {
return tasks;
}
int batchSize = Math.max(1, taskPressureProperties.getDbSelectBatchSize());
for (int start = 0; start < taskIds.size(); start += batchSize) {
int end = Math.min(start + batchSize, taskIds.size());
tasks.addAll(fileTaskMapper.selectBatchIds(taskIds.subList(start, end)));
}
return tasks;
return TaskFinalizeSupport.selectTasksByIdsInBatches(fileTaskMapper, taskPressureProperties, taskIds);
}
private List<FileTaskEntity> selectTaskHistoryFieldsByIdsInBatches(List<Long> taskIds) {
@@ -11,6 +11,7 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -73,6 +74,37 @@ public class NotificationDispatchService {
return pushed;
}
/**
* 一条事件发给「能看到任一所列用户」的管理员:同一 dedupeKeyBase 下每个管理员只落一条。
* 用于一把密钥被多个账号共用时的告警收敛——按主体逐个调用 {@code pushToAdmins} 会让同一个
* 管理员收到 N 条同内容通知,这里改成每个管理员最多一条,同时保留数据权限边界。
*/
public int pushToAdminsAnyOf(AdminAudience audience, String scene, String level, String title, String content,
String dedupeKeyBase, Collection<Long> subjectUserIds) {
int pushed = 0;
int filtered = 0;
for (AdminUserEntity admin : audience.admins()) {
boolean visible = false;
for (Long subjectUserId : subjectUserIds) {
if (audience.canReceive(admin.getId(), subjectUserId)) {
visible = true;
break;
}
}
if (!visible) {
filtered++;
continue;
}
if (notificationService.pushOrRefresh(admin.getId(), NotificationService.AUDIENCE_ADMIN,
scene, level, title, content, dedupeKeyBase + ":" + admin.getId())) {
pushed++;
}
}
log.info("[notification] 管理员分发(合并)完成 scene={} 涉及用户数={} 受众={} 权限过滤={} 落库={}",
scene, subjectUserIds.size(), audience.admins().size(), filtered, pushed);
return pushed;
}
/**
* 「任务成功,但有一部分行没跑出来」通知:整任务没失败、铃铛里的 task_failed 只覆盖终态失败,
* 这类部分缺失过去对用户完全不可见(品牌检测的查询失败行只躺在结果文件的一张子表里)。
@@ -14,9 +14,9 @@ import com.nanri.aiimage.modules.patroldelete.service.PatrolDeleteResolveService
import com.nanri.aiimage.modules.patroldelete.service.PatrolDeleteTaskService;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCandidateAddRequest;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskMatchShopsRequest;
import com.nanri.aiimage.common.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.common.model.vo.ProductRiskDashboardVo;
import com.nanri.aiimage.common.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskDashboardVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskMatchShopsVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
@@ -1,6 +1,7 @@
package com.nanri.aiimage.modules.patroldelete.service;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.util.SxssfWorkbookWriter;
import com.nanri.aiimage.modules.patroldelete.model.dto.PatrolDeleteCartRatioDto;
import com.nanri.aiimage.modules.patroldelete.model.dto.PatrolDeleteCountryMetricRowDto;
import com.nanri.aiimage.modules.patroldelete.model.dto.PatrolDeleteCountrySectionDto;
@@ -8,11 +9,9 @@ import com.nanri.aiimage.modules.patroldelete.model.vo.PatrolDeleteResultItemVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
@Service
@@ -38,16 +37,23 @@ public class PatrolDeleteExcelAssemblyService {
"国家", "购物车比例",
"国家", "购物车比例"
};
private static final int[] COLUMN_WIDTHS = {
20,
14, 10, 12, 16,
14, 10, 12, 16,
14, 10, 12, 16,
14, 10, 12, 16,
14, 10, 12, 16,
10, 16,
10, 16,
10, 16,
10, 16,
10, 16
};
public void writeWorkbook(File outputXlsx, List<PatrolDeleteResultItemVo> items) {
SXSSFWorkbook workbook = new SXSSFWorkbook(200);
workbook.setCompressTempFiles(true);
try (FileOutputStream outputStream = new FileOutputStream(outputXlsx)) {
Sheet sheet = workbook.createSheet("巡店删除结果");
Row headerRow = sheet.createRow(0);
for (int columnIndex = 0; columnIndex < HEADER.length; columnIndex++) {
headerRow.createCell(columnIndex).setCellValue(HEADER[columnIndex]);
}
try (SxssfWorkbookWriter writer = SxssfWorkbookWriter.open()) {
Sheet sheet = writer.createSheet("巡店删除结果", HEADER, COLUMN_WIDTHS);
int rowIndex = 1;
for (PatrolDeleteResultItemVo item : items) {
@@ -57,7 +63,7 @@ public class PatrolDeleteExcelAssemblyService {
int shopRowCount = maxCountryRowCount(item.getCountrySections());
for (int shopRowIndex = 0; shopRowIndex < shopRowCount; shopRowIndex++) {
Row row = sheet.createRow(rowIndex++);
row.createCell(0).setCellValue(shopRowIndex == 0 ? safe(item.getShopName()) : "");
SxssfWorkbookWriter.setText(row, 0, shopRowIndex == 0 ? safe(item.getShopName()) : "");
writeCountryColumns(row, 1, findSection(item.getCountrySections(), COUNTRY_DE), shopRowIndex);
writeCountryColumns(row, 5, findSection(item.getCountrySections(), COUNTRY_UK), shopRowIndex);
writeCountryColumns(row, 9, findSection(item.getCountrySections(), COUNTRY_FR), shopRowIndex);
@@ -74,17 +80,10 @@ public class PatrolDeleteExcelAssemblyService {
rowIndex++;
}
applyDefaultColumnWidths(sheet);
workbook.write(outputStream);
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());
} finally {
try {
workbook.close();
} catch (Exception ignored) {
}
workbook.dispose();
}
}
@@ -131,38 +130,19 @@ public class PatrolDeleteExcelAssemblyService {
if (section != null && section.getRows() != null && rowIndex < section.getRows().size()) {
metric = section.getRows().get(rowIndex);
}
row.createCell(startColumn).setCellValue(metric == null ? "" : safe(metric.getStatus()));
row.createCell(startColumn + 1).setCellValue(metric == null ? "" : safe(metric.getQuantity()));
row.createCell(startColumn + 2).setCellValue(metric == null ? "" : safe(metric.getDeleteQuantity()));
row.createCell(startColumn + 3).setCellValue(metric == null ? "" : safe(metric.getProcessStatus()));
SxssfWorkbookWriter.setText(row, startColumn, metric == null ? "" : safe(metric.getStatus()));
SxssfWorkbookWriter.setText(row, startColumn + 1, metric == null ? "" : safe(metric.getQuantity()));
SxssfWorkbookWriter.setText(row, startColumn + 2, metric == null ? "" : safe(metric.getDeleteQuantity()));
SxssfWorkbookWriter.setText(row, startColumn + 3, metric == null ? "" : safe(metric.getProcessStatus()));
}
private void writeCartRatioColumns(Row row, int startColumn, List<PatrolDeleteCartRatioDto> ratios, int ratioIndex) {
PatrolDeleteCartRatioDto ratio = ratios != null && ratioIndex < ratios.size() ? ratios.get(ratioIndex) : null;
row.createCell(startColumn).setCellValue(ratio == null ? "" : safe(ratio.getCountry()));
row.createCell(startColumn + 1).setCellValue(ratio == null ? "" : safe(ratio.getRatio()));
SxssfWorkbookWriter.setText(row, startColumn, ratio == null ? "" : safe(ratio.getCountry()));
SxssfWorkbookWriter.setText(row, startColumn + 1, ratio == null ? "" : safe(ratio.getRatio()));
}
private String safe(String value) {
return value == null ? "" : value;
}
private void applyDefaultColumnWidths(Sheet sheet) {
int[] widths = {
20,
14, 10, 12, 16,
14, 10, 12, 16,
14, 10, 12, 16,
14, 10, 12, 16,
14, 10, 12, 16,
10, 16,
10, 16,
10, 16,
10, 16,
10, 16
};
for (int i = 0; i < widths.length; i++) {
sheet.setColumnWidth(i, widths[i] * 256);
}
}
}
@@ -10,9 +10,9 @@ import com.nanri.aiimage.modules.patroldelete.model.entity.PatrolDeleteShopCandi
import com.nanri.aiimage.modules.patroldelete.model.vo.PatrolDeleteConditionVo;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCandidateAddRequest;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskMatchShopsRequest;
import com.nanri.aiimage.common.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.common.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.common.model.vo.ProductRiskShopQueueItemVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskShopQueueItemVo;
import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoShopMatchResultVo;
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopIndexService;
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopSwitchService;
@@ -1,216 +1,25 @@
package com.nanri.aiimage.modules.patroldelete.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.modules.patroldelete.model.dto.PatrolDeleteShopPayloadDto;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.service.AbstractModuleTaskCacheService;
import com.nanri.aiimage.modules.task.service.TaskScopePayloadStorageService;
import com.nanri.aiimage.modules.task.util.TaskEntityLocalCache;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 巡检删除模块任务缓存服务:通用实现见 {@link AbstractModuleTaskCacheService},
* 本类只声明模块差异(moduleType / Redis key 前缀 / 载荷类型)。
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class PatrolDeleteTaskCacheService {
public class PatrolDeleteTaskCacheService extends AbstractModuleTaskCacheService<PatrolDeleteShopPayloadDto> {
private static final String MODULE_TYPE = "PATROL_DELETE";
private static final long PAYLOAD_TTL_HOURS = 24;
private final StringRedisTemplate stringRedisTemplate;
private final ObjectMapper objectMapper;
private final TaskScopePayloadStorageService taskScopePayloadStorageService;
private final TaskEntityLocalCache taskEntityLocalCache;
public PatrolDeleteShopPayloadDto getShopMergedPayload(Long taskId, String shopKey) {
return taskScopePayloadStorageService.getScopePayload(taskId, MODULE_TYPE, shopKey, PatrolDeleteShopPayloadDto.class);
}
public void saveShopMergedPayload(Long taskId, String shopKey, PatrolDeleteShopPayloadDto payload) {
if (taskId == null || taskId <= 0 || shopKey == null || shopKey.isBlank() || payload == null) {
return;
}
taskScopePayloadStorageService.saveScopePayload(taskId, MODULE_TYPE, shopKey, payload);
touchTaskHeartbeat(taskId);
}
public void removeShopMergedPayload(Long taskId, String shopKey) {
taskScopePayloadStorageService.removeScopePayload(taskId, MODULE_TYPE, shopKey);
}
public Map<String, PatrolDeleteShopPayloadDto> getAllShopMergedPayload(Long taskId) {
return taskScopePayloadStorageService.getAllScopePayload(taskId, MODULE_TYPE, PatrolDeleteShopPayloadDto.class);
}
public boolean hasAnyShopMergedPayload(Long taskId) {
return taskScopePayloadStorageService.hasAnyScopePayload(taskId, MODULE_TYPE);
}
public long countShopMergedPayload(Long taskId) {
return taskScopePayloadStorageService.countScopePayload(taskId, MODULE_TYPE);
}
public long getTaskHeartbeatMillis(Long taskId) {
if (taskId == null || taskId <= 0) {
return 0L;
}
String raw;
try {
raw = stringRedisTemplate.opsForValue().get(buildTaskHeartbeatKey(taskId));
} catch (Exception ex) {
log.warn("[patrol-delete-cache] get heartbeat degraded taskId={} msg={}", taskId, ex.getMessage());
return 0L;
}
if (raw == null || raw.isBlank()) {
return 0L;
}
try {
return Long.parseLong(raw);
} catch (NumberFormatException ignored) {
return 0L;
}
}
public Map<Long, Long> getTaskHeartbeatMillisBatch(List<Long> taskIds) {
Map<Long, Long> result = new LinkedHashMap<>();
if (taskIds == null || taskIds.isEmpty()) {
return result;
}
List<Long> normalized = taskIds.stream()
.filter(id -> id != null && id > 0)
.distinct()
.toList();
if (normalized.isEmpty()) {
return result;
}
List<String> keys = normalized.stream().map(this::buildTaskHeartbeatKey).toList();
List<String> values;
try {
values = stringRedisTemplate.opsForValue().multiGet(keys);
} catch (Exception ex) {
log.warn("[patrol-delete-cache] batch get heartbeat degraded taskIds={} msg={}", normalized, ex.getMessage());
return result;
}
for (int i = 0; i < normalized.size(); i++) {
String raw = values != null && i < values.size() ? values.get(i) : null;
if (raw == null || raw.isBlank()) {
result.put(normalized.get(i), 0L);
continue;
}
try {
result.put(normalized.get(i), Long.parseLong(raw));
} catch (NumberFormatException ignored) {
result.put(normalized.get(i), 0L);
}
}
return result;
}
public void touchTaskHeartbeat(Long taskId) {
try {
stringRedisTemplate.opsForValue().set(
buildTaskHeartbeatKey(taskId),
String.valueOf(Instant.now().toEpochMilli()),
Duration.ofHours(PAYLOAD_TTL_HOURS));
} catch (Exception ex) {
log.warn("[patrol-delete-cache] touch heartbeat degraded taskId={} msg={}", taskId, ex.getMessage());
}
}
public void deleteTaskCache(Long taskId) {
evictTaskCacheOnly(taskId);
taskScopePayloadStorageService.deleteTaskScopePayloads(taskId, MODULE_TYPE);
}
public void evictTaskCacheOnly(Long taskId) {
if (taskId == null || taskId <= 0) {
return;
}
taskEntityLocalCache.evict(taskId);
try {
stringRedisTemplate.delete(buildTaskHeartbeatKey(taskId));
stringRedisTemplate.delete(buildTaskEntityKey(taskId));
} catch (Exception ex) {
log.warn("[patrol-delete-cache] delete cache degraded taskId={} msg={}", taskId, ex.getMessage());
}
}
public void saveTaskCache(FileTaskEntity task) {
if (task == null || task.getId() == null) {
return;
}
taskEntityLocalCache.put(task.getId(), task);
try {
stringRedisTemplate.opsForValue().set(
buildTaskEntityKey(task.getId()),
objectMapper.writeValueAsString(task),
Duration.ofHours(PAYLOAD_TTL_HOURS)
);
} catch (Exception ignored) {
}
}
public Map<Long, FileTaskEntity> getTaskCacheBatch(java.util.List<Long> taskIds) {
Map<Long, FileTaskEntity> result = new LinkedHashMap<>();
if (taskIds == null || taskIds.isEmpty()) {
return result;
}
java.util.List<Long> normalized = taskIds.stream()
.filter(id -> id != null && id > 0)
.distinct()
.toList();
if (normalized.isEmpty()) {
return result;
}
long now = System.currentTimeMillis();
java.util.List<Long> missingIds = new ArrayList<>();
for (Long taskId : normalized) {
TaskEntityLocalCache.Entry cached = taskEntityLocalCache.get(taskId, now);
if (cached != null) {
result.put(taskId, cached.task());
} else {
missingIds.add(taskId);
}
}
if (missingIds.isEmpty()) {
return result;
}
java.util.List<String> keys = missingIds.stream().map(this::buildTaskEntityKey).toList();
java.util.List<String> values;
try {
values = stringRedisTemplate.opsForValue().multiGet(keys);
} catch (Exception ex) {
log.warn("[patrol-delete-cache] batch get task cache degraded taskIds={} msg={}", missingIds, ex.getMessage());
return result;
}
for (int i = 0; i < missingIds.size(); i++) {
Long taskId = missingIds.get(i);
String val = values != null && i < values.size() ? values.get(i) : null;
if (val == null || val.isBlank()) {
continue;
}
try {
FileTaskEntity task = objectMapper.readValue(val, FileTaskEntity.class);
result.put(taskId, task);
taskEntityLocalCache.put(taskId, task);
} catch (Exception ignored) {
}
}
return result;
}
private String buildTaskHeartbeatKey(Long taskId) {
return "patrol-delete:task:heartbeat:" + taskId;
}
private String buildTaskEntityKey(Long taskId) {
return "patrol-delete:task:entity:" + taskId;
public PatrolDeleteTaskCacheService(StringRedisTemplate stringRedisTemplate,
ObjectMapper objectMapper,
TaskScopePayloadStorageService taskScopePayloadStorageService,
TaskEntityLocalCache taskEntityLocalCache) {
super("PATROL_DELETE", "patrol-delete", PatrolDeleteShopPayloadDto.class,
stringRedisTemplate, objectMapper, taskScopePayloadStorageService, taskEntityLocalCache);
}
}
@@ -6,7 +6,6 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessCodes;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.config.TaskPressureProperties;
@@ -22,7 +21,7 @@ import com.nanri.aiimage.modules.patroldelete.model.vo.PatrolDeleteTaskBatchVo;
import com.nanri.aiimage.modules.patroldelete.model.vo.PatrolDeleteCreateTaskVo;
import com.nanri.aiimage.modules.patroldelete.model.vo.PatrolDeleteHistoryVo;
import com.nanri.aiimage.modules.patroldelete.model.vo.PatrolDeleteResultItemVo;
import com.nanri.aiimage.common.model.vo.ProductRiskDashboardVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskDashboardVo;
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.model.entity.FileResultEntity;
@@ -30,6 +29,7 @@ import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
import com.nanri.aiimage.modules.task.service.TaskDistributedLockService;
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
import com.nanri.aiimage.modules.task.service.TaskFinalizeSupport;
import com.nanri.aiimage.modules.task.service.TaskProgressSnapshotService;
import com.nanri.aiimage.modules.task.service.TaskResultItemService;
import com.nanri.aiimage.modules.task.service.TaskScopePayloadStorageService;
@@ -90,60 +90,15 @@ public class PatrolDeleteTaskService {
private final org.springframework.transaction.PlatformTransactionManager transactionManager;
private FileTaskEntity loadTaskForExecution(Long taskId) {
Map<Long, FileTaskEntity> cachedTasks = taskCacheService.getTaskCacheBatch(List.of(taskId));
FileTaskEntity cached = cachedTasks.get(taskId);
if (cached != null) {
return cached;
}
FileTaskEntity dbTask = fileTaskMapper.selectById(taskId);
if (dbTask != null && MODULE_TYPE.equals(dbTask.getModuleType())) {
taskCacheService.saveTaskCache(dbTask);
}
return dbTask;
return TaskFinalizeSupport.loadTaskForExecution(fileTaskMapper, taskCacheService, MODULE_TYPE, taskId);
}
private Map<Long, FileTaskEntity> loadTaskMapByIds(List<Long> taskIds) {
Map<Long, FileTaskEntity> result = new LinkedHashMap<>();
if (taskIds == null || taskIds.isEmpty()) {
return result;
}
List<Long> normalizedTaskIds = taskIds.stream()
.filter(taskId -> taskId != null && taskId > 0)
.distinct()
.toList();
if (normalizedTaskIds.isEmpty()) {
return result;
}
Map<Long, FileTaskEntity> cachedTasks = taskCacheService.getTaskCacheBatch(normalizedTaskIds);
result.putAll(cachedTasks);
List<Long> missingTaskIds = normalizedTaskIds.stream()
.filter(taskId -> !cachedTasks.containsKey(taskId))
.toList();
if (!missingTaskIds.isEmpty()) {
for (FileTaskEntity dbTask : selectTasksByIdsInBatches(missingTaskIds)) {
if (dbTask == null || !MODULE_TYPE.equals(dbTask.getModuleType())) {
continue;
}
result.put(dbTask.getId(), dbTask);
if ("RUNNING".equals(dbTask.getStatus())) {
taskCacheService.saveTaskCache(dbTask);
}
}
}
return result;
return TaskFinalizeSupport.loadTaskMapByIds(fileTaskMapper, taskPressureProperties, taskCacheService, MODULE_TYPE, taskIds);
}
private List<FileTaskEntity> selectTasksByIdsInBatches(List<Long> taskIds) {
List<FileTaskEntity> tasks = new ArrayList<>();
if (taskIds == null || taskIds.isEmpty()) {
return tasks;
}
int batchSize = Math.max(1, taskPressureProperties.getDbSelectBatchSize());
for (int start = 0; start < taskIds.size(); start += batchSize) {
int end = Math.min(start + batchSize, taskIds.size());
tasks.addAll(fileTaskMapper.selectBatchIds(taskIds.subList(start, end)));
}
return tasks;
return TaskFinalizeSupport.selectTasksByIdsInBatches(fileTaskMapper, taskPressureProperties, taskIds);
}
public ProductRiskDashboardVo dashboard(Long userId) {
@@ -1099,19 +1054,11 @@ public class PatrolDeleteTaskService {
}
private TaskDistributedLockService.LockHandle acquireTaskLockOrThrow(Long taskId) {
TaskDistributedLockService.LockHandle lockHandle = acquireTaskLock(taskId);
if (lockHandle == null) {
log.warn("[patrol-delete] 任务锁竞争,拒绝本次提交 taskId={}", taskId);
throw new BusinessException(BusinessCodes.TASK_BUSY, "任务正在处理中,请稍后再试");
}
return lockHandle;
return TaskFinalizeSupport.acquireTaskLockOrThrow(taskDistributedLockService, MODULE_TYPE, taskId, "patrol-delete");
}
private TaskDistributedLockService.LockHandle acquireTaskLock(Long taskId) {
if (taskId == null || taskId <= 0) {
return null;
}
return taskDistributedLockService.acquire(MODULE_TYPE, taskId);
return TaskFinalizeSupport.acquireTaskLock(taskDistributedLockService, MODULE_TYPE, taskId);
}
/**
@@ -1134,14 +1081,7 @@ public class PatrolDeleteTaskService {
}
private void markResultFailed(FileResultEntity row, String message) {
row.setSuccess(RESULT_FAILED);
row.setErrorMessage(blankToNull(message));
row.setResultFilename(null);
row.setResultFileUrl(null);
row.setResultFileSize(0L);
row.setResultContentType(null);
row.setRowCount(0);
fileResultMapper.updateById(row);
TaskFinalizeSupport.markResultFailed(fileResultMapper, row, blankToNull(message));
}
private boolean isResultFinished(FileResultEntity row) {
@@ -1,16 +1,15 @@
package com.nanri.aiimage.modules.pricetrack.service;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.util.SxssfWorkbookWriter;
import com.nanri.aiimage.modules.pricetrack.model.dto.PriceTrackSubmitResultRequest;
import com.nanri.aiimage.modules.productrisk.model.enums.ProductRiskCountryCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.FileOutputStream;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -36,20 +35,15 @@ public class PriceTrackExcelAssemblyService {
"修改次数",
"状态"
};
private static final int[] RESULT_COLUMN_WIDTHS = {22, 18, 12, 12, 12, 12, 20, 22, 20, 22, 22, 14, 18, 12, 12};
public void writeWorkbook(File outputXlsx, Map<String, List<PriceTrackSubmitResultRequest.AsinResult>> countries) {
Map<String, List<PriceTrackSubmitResultRequest.AsinResult>> safe = countries == null ? Map.of() : countries;
SXSSFWorkbook workbook = new SXSSFWorkbook(200);
workbook.setCompressTempFiles(true);
try (FileOutputStream fos = new FileOutputStream(outputXlsx)) {
try (SxssfWorkbookWriter writer = SxssfWorkbookWriter.open()) {
for (ProductRiskCountryCode code : ProductRiskCountryCode.values()) {
String countryCode = code.name();
String sheetName = sheetNameOf(code);
Sheet sheet = workbook.createSheet(sheetName);
Row headerRow = sheet.createRow(0);
for (int i = 0; i < RESULT_HEADER.length; i++) {
headerRow.createCell(i).setCellValue(RESULT_HEADER[i]);
}
Sheet sheet = writer.createSheet(sheetName, RESULT_HEADER, RESULT_COLUMN_WIDTHS);
List<PriceTrackSubmitResultRequest.AsinResult> rows = safe.getOrDefault(countryCode, List.of());
int rowIdx = 1;
for (PriceTrackSubmitResultRequest.AsinResult item : rows) {
@@ -57,34 +51,27 @@ public class PriceTrackExcelAssemblyService {
continue;
}
Row row = sheet.createRow(rowIdx++);
row.createCell(0).setCellValue(valueOf(item.getShopMallName()));
row.createCell(1).setCellValue(valueOf(item.getAsin()));
row.createCell(2).setCellValue(valueOf(item.getPrice()));
row.createCell(3).setCellValue(valueOf(item.getRecommendedPrice()));
row.createCell(4).setCellValue(valueOf(item.getShippingFee()));
row.createCell(5).setCellValue(valueOf(item.getMinimumPrice()));
row.createCell(6).setCellValue(valueOf(item.getFirstPlace()));
row.createCell(7).setCellValue(valueOf(item.getFirstShop()));
row.createCell(8).setCellValue(valueOf(item.getSecondPlace()));
row.createCell(9).setCellValue(valueOf(item.getSecondShop()));
row.createCell(10).setCellValue(valueOf(item.getCartShopName()));
row.createCell(11).setCellValue(valueOf(item.getPriceChangePrice()));
row.createCell(12).setCellValue(valueOf(item.getPriceChangeStatus()));
row.createCell(13).setCellValue(valueOf(item.getModifyCount()));
row.createCell(14).setCellValue(valueOf(item.getStatus()));
SxssfWorkbookWriter.setText(row, 0, item.getShopMallName());
SxssfWorkbookWriter.setText(row, 1, item.getAsin());
SxssfWorkbookWriter.setText(row, 2, item.getPrice());
SxssfWorkbookWriter.setText(row, 3, item.getRecommendedPrice());
SxssfWorkbookWriter.setText(row, 4, item.getShippingFee());
SxssfWorkbookWriter.setText(row, 5, item.getMinimumPrice());
SxssfWorkbookWriter.setText(row, 6, item.getFirstPlace());
SxssfWorkbookWriter.setText(row, 7, item.getFirstShop());
SxssfWorkbookWriter.setText(row, 8, item.getSecondPlace());
SxssfWorkbookWriter.setText(row, 9, item.getSecondShop());
SxssfWorkbookWriter.setText(row, 10, item.getCartShopName());
SxssfWorkbookWriter.setText(row, 11, item.getPriceChangePrice());
SxssfWorkbookWriter.setText(row, 12, item.getPriceChangeStatus());
SxssfWorkbookWriter.setText(row, 13, item.getModifyCount());
SxssfWorkbookWriter.setText(row, 14, item.getStatus());
}
applyDefaultColumnWidths(sheet);
}
workbook.write(fos);
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());
} finally {
try {
workbook.close();
} catch (Exception ignored) {
}
workbook.dispose();
}
}
@@ -116,10 +103,6 @@ public class PriceTrackExcelAssemblyService {
return out;
}
private static String valueOf(String value) {
return value == null ? "" : value;
}
private static String sheetNameOf(ProductRiskCountryCode code) {
return switch (code) {
case DE -> "德国";
@@ -129,11 +112,4 @@ public class PriceTrackExcelAssemblyService {
case UK -> "英国";
};
}
private void applyDefaultColumnWidths(Sheet sheet) {
int[] widths = {22, 18, 12, 12, 12, 12, 20, 22, 20, 22, 22, 14, 18, 12, 12};
for (int i = 0; i < widths.length; i++) {
sheet.setColumnWidth(i, widths[i] * 256);
}
}
}
@@ -1,211 +1,25 @@
package com.nanri.aiimage.modules.pricetrack.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.modules.pricetrack.model.dto.PriceTrackSubmitResultRequest;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.service.AbstractModuleTaskCacheService;
import com.nanri.aiimage.modules.task.service.TaskScopePayloadStorageService;
import com.nanri.aiimage.modules.task.util.TaskEntityLocalCache;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 跟价模块任务缓存服务:通用实现见 {@link AbstractModuleTaskCacheService},
* 本类只声明模块差异(moduleType / Redis key 前缀 / 载荷类型)。
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class PriceTrackTaskCacheService {
public class PriceTrackTaskCacheService extends AbstractModuleTaskCacheService<PriceTrackSubmitResultRequest.ShopResult> {
private static final String MODULE_TYPE = "PRICE_TRACK";
private static final long HEARTBEAT_TTL_HOURS = 24;
private final StringRedisTemplate stringRedisTemplate;
private final ObjectMapper objectMapper;
private final TaskScopePayloadStorageService taskScopePayloadStorageService;
private final TaskEntityLocalCache taskEntityLocalCache;
public void touchTaskHeartbeat(Long taskId) {
if (taskId == null || taskId <= 0) {
return;
}
try {
stringRedisTemplate.opsForValue().set(
buildTaskHeartbeatKey(taskId),
String.valueOf(Instant.now().toEpochMilli()),
Duration.ofHours(HEARTBEAT_TTL_HOURS));
} catch (Exception ex) {
log.warn("[price-track-cache] touch heartbeat degraded taskId={} msg={}", taskId, ex.getMessage());
}
}
public long getTaskHeartbeatMillis(Long taskId) {
if (taskId == null || taskId <= 0) {
return 0L;
}
String raw;
try {
raw = stringRedisTemplate.opsForValue().get(buildTaskHeartbeatKey(taskId));
} catch (Exception ex) {
log.warn("[price-track-cache] get heartbeat degraded taskId={} msg={}", taskId, ex.getMessage());
return 0L;
}
if (raw == null || raw.isBlank()) {
return 0L;
}
try {
return Long.parseLong(raw);
} catch (NumberFormatException ignored) {
return 0L;
}
}
public Map<Long, Long> getTaskHeartbeatMillisBatch(List<Long> taskIds) {
Map<Long, Long> result = new LinkedHashMap<>();
if (taskIds == null || taskIds.isEmpty()) {
return result;
}
List<Long> normalized = taskIds.stream()
.filter(id -> id != null && id > 0)
.distinct()
.toList();
if (normalized.isEmpty()) {
return result;
}
List<String> keys = normalized.stream().map(this::buildTaskHeartbeatKey).toList();
List<String> values;
try {
values = stringRedisTemplate.opsForValue().multiGet(keys);
} catch (Exception ex) {
log.warn("[price-track-cache] batch get heartbeat degraded taskIds={} msg={}", normalized, ex.getMessage());
return result;
}
for (int i = 0; i < normalized.size(); i++) {
String raw = values != null && i < values.size() ? values.get(i) : null;
if (raw == null || raw.isBlank()) {
result.put(normalized.get(i), 0L);
continue;
}
try {
result.put(normalized.get(i), Long.parseLong(raw));
} catch (NumberFormatException ignored) {
result.put(normalized.get(i), 0L);
}
}
return result;
}
public PriceTrackSubmitResultRequest.ShopResult getShopMergedPayload(Long taskId, String shopKey) {
return taskScopePayloadStorageService.getScopePayload(taskId, MODULE_TYPE, shopKey, PriceTrackSubmitResultRequest.ShopResult.class);
}
public void saveShopMergedPayload(Long taskId, String shopKey, PriceTrackSubmitResultRequest.ShopResult payload) {
if (taskId == null || taskId <= 0 || shopKey == null || shopKey.isBlank() || payload == null) {
return;
}
taskScopePayloadStorageService.saveScopePayload(taskId, MODULE_TYPE, shopKey, payload);
touchTaskHeartbeat(taskId);
}
public void removeShopMergedPayload(Long taskId, String shopKey) {
taskScopePayloadStorageService.removeScopePayload(taskId, MODULE_TYPE, shopKey);
}
public Map<String, PriceTrackSubmitResultRequest.ShopResult> getAllShopMergedPayload(Long taskId) {
return taskScopePayloadStorageService.getAllScopePayload(taskId, MODULE_TYPE, PriceTrackSubmitResultRequest.ShopResult.class);
}
public boolean hasAnyShopMergedPayload(Long taskId) {
return taskScopePayloadStorageService.hasAnyScopePayload(taskId, MODULE_TYPE);
}
public void deleteTaskCache(Long taskId) {
if (taskId == null || taskId <= 0) {
return;
}
taskEntityLocalCache.evict(taskId);
try {
stringRedisTemplate.delete(buildTaskHeartbeatKey(taskId));
stringRedisTemplate.delete(buildTaskEntityKey(taskId));
} catch (Exception ex) {
log.warn("[price-track-cache] delete cache degraded taskId={} msg={}", taskId, ex.getMessage());
}
taskScopePayloadStorageService.deleteTaskScopePayloads(taskId, MODULE_TYPE);
}
public void saveTaskCache(FileTaskEntity task) {
if (task == null || task.getId() == null) {
return;
}
taskEntityLocalCache.put(task.getId(), task);
try {
stringRedisTemplate.opsForValue().set(
buildTaskEntityKey(task.getId()),
objectMapper.writeValueAsString(task),
Duration.ofHours(HEARTBEAT_TTL_HOURS)
);
} catch (Exception ignored) {
}
}
public Map<Long, FileTaskEntity> getTaskCacheBatch(java.util.List<Long> taskIds) {
Map<Long, FileTaskEntity> result = new LinkedHashMap<>();
if (taskIds == null || taskIds.isEmpty()) {
return result;
}
java.util.List<Long> normalized = taskIds.stream()
.filter(id -> id != null && id > 0)
.distinct()
.toList();
if (normalized.isEmpty()) {
return result;
}
long now = System.currentTimeMillis();
java.util.List<Long> missingIds = new ArrayList<>();
for (Long taskId : normalized) {
TaskEntityLocalCache.Entry cached = taskEntityLocalCache.get(taskId, now);
if (cached != null) {
result.put(taskId, cached.task());
} else {
missingIds.add(taskId);
}
}
if (missingIds.isEmpty()) {
return result;
}
java.util.List<String> keys = missingIds.stream().map(this::buildTaskEntityKey).toList();
java.util.List<String> values;
try {
values = stringRedisTemplate.opsForValue().multiGet(keys);
} catch (Exception ex) {
log.warn("[price-track-cache] batch get task cache degraded taskIds={} msg={}", missingIds, ex.getMessage());
return result;
}
for (int i = 0; i < missingIds.size(); i++) {
Long taskId = missingIds.get(i);
String val = values != null && i < values.size() ? values.get(i) : null;
if (val == null || val.isBlank()) {
continue;
}
try {
FileTaskEntity task = objectMapper.readValue(val, FileTaskEntity.class);
result.put(taskId, task);
taskEntityLocalCache.put(taskId, task);
} catch (Exception ignored) {
}
}
return result;
}
private String buildTaskHeartbeatKey(Long taskId) {
return "price-track:task:heartbeat:" + taskId;
}
private String buildTaskEntityKey(Long taskId) {
return "price-track:task:entity:" + taskId;
public PriceTrackTaskCacheService(StringRedisTemplate stringRedisTemplate,
ObjectMapper objectMapper,
TaskScopePayloadStorageService taskScopePayloadStorageService,
TaskEntityLocalCache taskEntityLocalCache) {
super("PRICE_TRACK", "price-track", PriceTrackSubmitResultRequest.ShopResult.class,
stringRedisTemplate, objectMapper, taskScopePayloadStorageService, taskEntityLocalCache);
}
}
@@ -3,7 +3,6 @@ package com.nanri.aiimage.modules.pricetrack.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessCodes;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.util.ExcelStreamReader;
@@ -33,6 +32,7 @@ import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
import com.nanri.aiimage.modules.task.service.TaskDistributedLockService;
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
import com.nanri.aiimage.modules.task.service.TaskFinalizeSupport;
import com.nanri.aiimage.modules.task.service.TaskResultPayloadService;
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopSwitchService;
import cn.hutool.core.util.IdUtil;
@@ -103,58 +103,17 @@ public class PriceTrackTaskService {
private final org.springframework.transaction.PlatformTransactionManager transactionManager;
private FileTaskEntity loadTaskForExecution(Long taskId) {
Map<Long, FileTaskEntity> cachedTasks = priceTrackTaskCacheService.getTaskCacheBatch(List.of(taskId));
FileTaskEntity cached = cachedTasks.get(taskId);
if (cached != null && hasText(cached.getRequestJson())) {
return cached;
}
FileTaskEntity dbTask = fileTaskMapper.selectById(taskId);
if (dbTask != null && MODULE_TYPE.equals(dbTask.getModuleType())) {
priceTrackTaskCacheService.saveTaskCache(dbTask);
}
return dbTask;
// 缓存行仅当 requestJson 非空时视为可用(历史语义),否则回落 DB
return TaskFinalizeSupport.loadTaskForExecution(fileTaskMapper, priceTrackTaskCacheService, MODULE_TYPE, taskId,
cached -> cached != null && hasText(cached.getRequestJson()));
}
private Map<Long, FileTaskEntity> loadTaskMapByIds(List<Long> taskIds) {
Map<Long, FileTaskEntity> result = new LinkedHashMap<>();
if (taskIds == null || taskIds.isEmpty()) {
return result;
}
List<Long> normalizedTaskIds = taskIds.stream()
.filter(taskId -> taskId != null && taskId > 0)
.distinct()
.toList();
if (normalizedTaskIds.isEmpty()) {
return result;
}
Map<Long, FileTaskEntity> cachedTasks = priceTrackTaskCacheService.getTaskCacheBatch(normalizedTaskIds);
result.putAll(cachedTasks);
List<Long> missingTaskIds = normalizedTaskIds.stream()
.filter(taskId -> !cachedTasks.containsKey(taskId))
.toList();
for (FileTaskEntity dbTask : selectTasksByIdsInBatches(missingTaskIds)) {
if (dbTask == null || !MODULE_TYPE.equals(dbTask.getModuleType())) {
continue;
}
result.put(dbTask.getId(), dbTask);
if ("RUNNING".equals(dbTask.getStatus())) {
priceTrackTaskCacheService.saveTaskCache(dbTask);
}
}
return result;
return TaskFinalizeSupport.loadTaskMapByIds(fileTaskMapper, taskPressureProperties, priceTrackTaskCacheService, MODULE_TYPE, taskIds);
}
private List<FileTaskEntity> selectTasksByIdsInBatches(List<Long> taskIds) {
List<FileTaskEntity> tasks = new ArrayList<>();
if (taskIds == null || taskIds.isEmpty()) {
return tasks;
}
int batchSize = Math.max(1, taskPressureProperties.getDbSelectBatchSize());
for (int start = 0; start < taskIds.size(); start += batchSize) {
int end = Math.min(start + batchSize, taskIds.size());
tasks.addAll(fileTaskMapper.selectBatchIds(taskIds.subList(start, end)));
}
return tasks;
return TaskFinalizeSupport.selectTasksByIdsInBatches(fileTaskMapper, taskPressureProperties, taskIds);
}
private List<FileTaskEntity> selectTaskHistoryFieldsByIdsInBatches(List<Long> taskIds) {
@@ -849,14 +808,7 @@ public class PriceTrackTaskService {
}
private void markResultFailed(FileResultEntity fr, String message) {
fr.setSuccess(0);
fr.setErrorMessage(message);
fr.setResultFilename(null);
fr.setResultFileUrl(null);
fr.setResultFileSize(0L);
fr.setRowCount(0);
fr.setResultContentType(null);
fileResultMapper.updateById(fr);
TaskFinalizeSupport.markResultFailed(fileResultMapper, fr, message);
}
private void assembleShopResult(FileResultEntity result,
@@ -2294,12 +2246,7 @@ public class PriceTrackTaskService {
}
private TaskDistributedLockService.LockHandle acquireTaskLockOrThrow(Long taskId) {
TaskDistributedLockService.LockHandle lockHandle = acquireTaskLock(taskId);
if (lockHandle == null) {
log.warn("[price-track] 任务锁竞争,拒绝本次提交 taskId={}", taskId);
throw new BusinessException(BusinessCodes.TASK_BUSY, "任务正在处理中,请稍后再试");
}
return lockHandle;
return TaskFinalizeSupport.acquireTaskLockOrThrow(taskDistributedLockService, MODULE_TYPE, taskId, "price-track");
}
/**
@@ -2317,10 +2264,7 @@ public class PriceTrackTaskService {
}
private TaskDistributedLockService.LockHandle acquireTaskLock(Long taskId) {
if (taskId == null || taskId <= 0) {
return null;
}
return taskDistributedLockService.acquire(MODULE_TYPE, taskId);
return TaskFinalizeSupport.acquireTaskLock(taskDistributedLockService, MODULE_TYPE, taskId);
}
private static boolean hasText(String value) {
@@ -9,14 +9,14 @@ import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCreateTaskRequ
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskMatchShopsRequest;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskSubmitResultRequest;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskTaskBatchRequest;
import com.nanri.aiimage.common.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.common.model.vo.ProductRiskCountryPreferenceVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCountryPreferenceVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCreateTaskVo;
import com.nanri.aiimage.common.model.vo.ProductRiskDashboardVo;
import com.nanri.aiimage.common.model.vo.ProductRiskHistoryVo;
import com.nanri.aiimage.common.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskDashboardVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskHistoryVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskPendingDeleteVo;
import com.nanri.aiimage.common.model.vo.ProductRiskTaskBatchVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskTaskBatchVo;
import com.nanri.aiimage.modules.productrisk.service.ProductRiskResolveService;
import com.nanri.aiimage.modules.productrisk.service.ProductRiskTaskService;
import io.swagger.v3.oas.annotations.Operation;
@@ -1,7 +1,7 @@
package com.nanri.aiimage.modules.productrisk.model.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.nanri.aiimage.common.model.vo.ProductRiskShopQueueItemVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskShopQueueItemVo;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
@@ -1,4 +1,4 @@
package com.nanri.aiimage.common.model.vo;
package com.nanri.aiimage.modules.productrisk.model.vo;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
@@ -1,4 +1,4 @@
package com.nanri.aiimage.common.model.vo;
package com.nanri.aiimage.modules.productrisk.model.vo;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
@@ -5,7 +5,7 @@ import lombok.Data;
import java.util.ArrayList;
import java.util.List;
import com.nanri.aiimage.common.model.vo.ProductRiskResultItemVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskResultItemVo;
@Data
@Schema(description = "创建任务响应:含任务 id 与各店初始快照(含 resultId),用于推队列与前端展示")
@@ -1,4 +1,4 @@
package com.nanri.aiimage.common.model.vo;
package com.nanri.aiimage.modules.productrisk.model.vo;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
@@ -1,4 +1,4 @@
package com.nanri.aiimage.common.model.vo;
package com.nanri.aiimage.modules.productrisk.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@@ -1,4 +1,4 @@
package com.nanri.aiimage.common.model.vo;
package com.nanri.aiimage.modules.productrisk.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@@ -1,4 +1,4 @@
package com.nanri.aiimage.common.model.vo;
package com.nanri.aiimage.modules.productrisk.model.vo;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -1,4 +1,4 @@
package com.nanri.aiimage.common.model.vo;
package com.nanri.aiimage.modules.productrisk.model.vo;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonProperty;
@@ -1,4 +1,4 @@
package com.nanri.aiimage.common.model.vo;
package com.nanri.aiimage.modules.productrisk.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@@ -1,4 +1,4 @@
package com.nanri.aiimage.common.model.vo;
package com.nanri.aiimage.modules.productrisk.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@@ -1,4 +1,4 @@
package com.nanri.aiimage.common.model.vo;
package com.nanri.aiimage.modules.productrisk.model.vo;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.nanri.aiimage.modules.shopmatch.model.vo.ShopMatchTaskStageVo;
@@ -1,6 +1,7 @@
package com.nanri.aiimage.modules.productrisk.service;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.util.SxssfWorkbookWriter;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskRowDto;
import com.nanri.aiimage.modules.productrisk.model.enums.ProductRiskCountryCode;
import lombok.extern.slf4j.Slf4j;
@@ -16,7 +17,6 @@ import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.FileOutputStream;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -44,15 +44,10 @@ public class ProductRiskExcelAssemblyService {
public void writeWorkbook(File outputXlsx, String shopDisplayName, Map<String, List<ProductRiskRowDto>> countries) {
Map<String, List<ProductRiskRowDto>> safe = countries == null ? Map.of() : countries;
SXSSFWorkbook workbook = new SXSSFWorkbook(200);
workbook.setCompressTempFiles(true);
try (FileOutputStream fos = new FileOutputStream(outputXlsx)) {
try (SxssfWorkbookWriter writer = SxssfWorkbookWriter.open()) {
SXSSFWorkbook workbook = writer.workbook();
for (String sheetName : SHEET_ORDER) {
Sheet sheet = workbook.createSheet(sheetName);
Row headerRow = sheet.createRow(0);
for (int c = 0; c < HEADER.length; c++) {
headerRow.createCell(c).setCellValue(HEADER[c]);
}
Sheet sheet = writer.createSheet(sheetName, HEADER, null);
List<ProductRiskRowDto> rows = safe.getOrDefault(sheetName, List.of());
CellStyle detailStyle = createDetailStyle(workbook);
CellStyle detailAsinStyle = createDetailAsinStyle(workbook);
@@ -66,12 +61,12 @@ public class ProductRiskExcelAssemblyService {
for (int offset = 0; offset < groupSize; offset++) {
Row row = sheet.createRow(rowIdx + offset);
if (offset == 0) {
createTextCell(row, 0, firstNonBlank(dto == null ? null : dto.getShopName(), shopDisplayName));
createTextCell(row, 1, dto == null ? null : dto.getProductAsinSku());
createTextCell(row, 2, dto == null ? null : dto.getStatus());
createTextCell(row, 3, completionDisplayValue(dto));
createTextCell(row, 4, dto == null ? null : dto.getRemoveAsin());
createTextCell(row, 5, dto == null ? null : dto.getRemoveStatus());
SxssfWorkbookWriter.setText(row, 0, firstNonBlank(dto == null ? null : dto.getShopName(), shopDisplayName));
SxssfWorkbookWriter.setText(row, 1, dto == null ? null : dto.getProductAsinSku());
SxssfWorkbookWriter.setText(row, 2, dto == null ? null : dto.getStatus());
SxssfWorkbookWriter.setText(row, 3, completionDisplayValue(dto));
SxssfWorkbookWriter.setText(row, 4, dto == null ? null : dto.getRemoveAsin());
SxssfWorkbookWriter.setText(row, 5, dto == null ? null : dto.getRemoveStatus());
}
if (offset < details.size()) {
ProductRiskRowDto.ViolationDetail detail = details.get(offset);
@@ -85,21 +80,15 @@ public class ProductRiskExcelAssemblyService {
}
rowIdx += groupSize;
}
applyDetailHeaderStyle(headerRow, detailStyle);
applyDetailHeaderStyle(sheet.getRow(0), detailStyle);
applyDefaultColumnWidths(sheet);
}
workbook.write(fos);
writer.write(outputXlsx);
} catch (BusinessException ex) {
throw ex;
} catch (Exception ex) {
log.warn("[product-risk] write workbook failed: {}", ex.getMessage());
throw new BusinessException("generate product-risk excel failed: " + ex.getMessage());
} finally {
try {
workbook.close();
} catch (Exception ignored) {
}
workbook.dispose();
}
}
@@ -130,11 +119,6 @@ public class ProductRiskExcelAssemblyService {
return out;
}
private static void createTextCell(Row row, int index, String value) {
Cell cell = row.createCell(index);
cell.setCellValue(value == null ? "" : value);
}
private static void createStyledTextCell(Row row, int index, String value, CellStyle style) {
Cell cell = row.createCell(index);
cell.setCellValue(value == null ? "" : value);
@@ -12,10 +12,10 @@ import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskMatchShopsRequ
import com.nanri.aiimage.modules.productrisk.model.entity.ProductRiskCountryPrefEntity;
import com.nanri.aiimage.modules.productrisk.model.entity.ProductRiskShopCandidateEntity;
import com.nanri.aiimage.modules.productrisk.model.enums.ProductRiskCountryCode;
import com.nanri.aiimage.common.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.common.model.vo.ProductRiskCountryPreferenceVo;
import com.nanri.aiimage.common.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.common.model.vo.ProductRiskShopQueueItemVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCountryPreferenceVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskShopQueueItemVo;
import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoShopMatchResultVo;
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopIndexService;
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopSwitchService;
@@ -1,212 +1,25 @@
package com.nanri.aiimage.modules.productrisk.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskShopPayloadDto;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.service.AbstractModuleTaskCacheService;
import com.nanri.aiimage.modules.task.service.TaskScopePayloadStorageService;
import com.nanri.aiimage.modules.task.util.TaskEntityLocalCache;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 品牌风险模块任务缓存服务:通用实现见 {@link AbstractModuleTaskCacheService},
* 本类只声明模块差异(moduleType / Redis key 前缀 / 载荷类型)。
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class ProductRiskTaskCacheService {
public class ProductRiskTaskCacheService extends AbstractModuleTaskCacheService<ProductRiskShopPayloadDto> {
private static final String MODULE_TYPE = "PRODUCT_RISK_RESOLVE";
private static final long PAYLOAD_TTL_HOURS = 24;
private final StringRedisTemplate stringRedisTemplate;
private final ObjectMapper objectMapper;
private final TaskScopePayloadStorageService taskScopePayloadStorageService;
private final TaskEntityLocalCache taskEntityLocalCache;
public ProductRiskShopPayloadDto getShopMergedPayload(Long taskId, String shopKey) {
return taskScopePayloadStorageService.getScopePayload(taskId, MODULE_TYPE, shopKey, ProductRiskShopPayloadDto.class);
}
public void saveShopMergedPayload(Long taskId, String shopKey, ProductRiskShopPayloadDto payload) {
if (taskId == null || taskId <= 0 || shopKey == null || shopKey.isBlank() || payload == null) {
return;
}
taskScopePayloadStorageService.saveScopePayload(taskId, MODULE_TYPE, shopKey, payload);
touchTaskHeartbeat(taskId);
}
public void removeShopMergedPayload(Long taskId, String shopKey) {
taskScopePayloadStorageService.removeScopePayload(taskId, MODULE_TYPE, shopKey);
}
public Map<String, ProductRiskShopPayloadDto> getAllShopMergedPayload(Long taskId) {
return taskScopePayloadStorageService.getAllScopePayload(taskId, MODULE_TYPE, ProductRiskShopPayloadDto.class);
}
public boolean hasAnyShopMergedPayload(Long taskId) {
return taskScopePayloadStorageService.hasAnyScopePayload(taskId, MODULE_TYPE);
}
public long countShopMergedPayload(Long taskId) {
return taskScopePayloadStorageService.countScopePayload(taskId, MODULE_TYPE);
}
public long getTaskHeartbeatMillis(Long taskId) {
if (taskId == null || taskId <= 0) {
return 0L;
}
String raw;
try {
raw = stringRedisTemplate.opsForValue().get(buildTaskHeartbeatKey(taskId));
} catch (Exception ex) {
log.warn("[product-risk-cache] get heartbeat degraded taskId={} msg={}", taskId, ex.getMessage());
return 0L;
}
if (raw == null || raw.isBlank()) {
return 0L;
}
try {
return Long.parseLong(raw);
} catch (NumberFormatException ignored) {
return 0L;
}
}
public Map<Long, Long> getTaskHeartbeatMillisBatch(List<Long> taskIds) {
Map<Long, Long> result = new LinkedHashMap<>();
if (taskIds == null || taskIds.isEmpty()) {
return result;
}
List<Long> normalized = taskIds.stream()
.filter(id -> id != null && id > 0)
.distinct()
.toList();
if (normalized.isEmpty()) {
return result;
}
List<String> keys = normalized.stream().map(this::buildTaskHeartbeatKey).toList();
List<String> values;
try {
values = stringRedisTemplate.opsForValue().multiGet(keys);
} catch (Exception ex) {
log.warn("[product-risk-cache] batch get heartbeat degraded taskIds={} msg={}", normalized, ex.getMessage());
return result;
}
for (int i = 0; i < normalized.size(); i++) {
String raw = values != null && i < values.size() ? values.get(i) : null;
if (raw == null || raw.isBlank()) {
result.put(normalized.get(i), 0L);
continue;
}
try {
result.put(normalized.get(i), Long.parseLong(raw));
} catch (NumberFormatException ignored) {
result.put(normalized.get(i), 0L);
}
}
return result;
}
public void deleteTaskCache(Long taskId) {
if (taskId == null || taskId <= 0) {
return;
}
taskEntityLocalCache.evict(taskId);
try {
stringRedisTemplate.delete(buildTaskHeartbeatKey(taskId));
stringRedisTemplate.delete(buildTaskEntityKey(taskId));
} catch (Exception ex) {
log.warn("[product-risk-cache] delete cache degraded taskId={} msg={}", taskId, ex.getMessage());
}
taskScopePayloadStorageService.deleteTaskScopePayloads(taskId, MODULE_TYPE);
}
public void saveTaskCache(FileTaskEntity task) {
if (task == null || task.getId() == null) {
return;
}
taskEntityLocalCache.put(task.getId(), task);
try {
stringRedisTemplate.opsForValue().set(
buildTaskEntityKey(task.getId()),
objectMapper.writeValueAsString(task),
Duration.ofHours(PAYLOAD_TTL_HOURS)
);
} catch (Exception ignored) {
}
}
public Map<Long, FileTaskEntity> getTaskCacheBatch(java.util.List<Long> taskIds) {
Map<Long, FileTaskEntity> result = new LinkedHashMap<>();
if (taskIds == null || taskIds.isEmpty()) {
return result;
}
java.util.List<Long> normalized = taskIds.stream()
.filter(id -> id != null && id > 0)
.distinct()
.toList();
if (normalized.isEmpty()) {
return result;
}
long now = System.currentTimeMillis();
java.util.List<Long> missingIds = new ArrayList<>();
for (Long taskId : normalized) {
TaskEntityLocalCache.Entry cached = taskEntityLocalCache.get(taskId, now);
if (cached != null) {
result.put(taskId, cached.task());
} else {
missingIds.add(taskId);
}
}
if (missingIds.isEmpty()) {
return result;
}
java.util.List<String> keys = missingIds.stream().map(this::buildTaskEntityKey).toList();
java.util.List<String> values;
try {
values = stringRedisTemplate.opsForValue().multiGet(keys);
} catch (Exception ex) {
log.warn("[product-risk-cache] batch get task cache degraded taskIds={} msg={}", missingIds, ex.getMessage());
return result;
}
for (int i = 0; i < missingIds.size(); i++) {
Long taskId = missingIds.get(i);
String val = values != null && i < values.size() ? values.get(i) : null;
if (val == null || val.isBlank()) {
continue;
}
try {
FileTaskEntity task = objectMapper.readValue(val, FileTaskEntity.class);
result.put(taskId, task);
taskEntityLocalCache.put(taskId, task);
} catch (Exception ignored) {
}
}
return result;
}
public void touchTaskHeartbeat(Long taskId) {
try {
stringRedisTemplate.opsForValue().set(
buildTaskHeartbeatKey(taskId),
String.valueOf(Instant.now().toEpochMilli()),
Duration.ofHours(PAYLOAD_TTL_HOURS));
} catch (Exception ex) {
log.warn("[product-risk-cache] touch heartbeat degraded taskId={} msg={}", taskId, ex.getMessage());
}
}
private String buildTaskHeartbeatKey(Long taskId) {
return "product-risk:task:heartbeat:" + taskId;
}
private String buildTaskEntityKey(Long taskId) {
return "product-risk:task:entity:" + taskId;
public ProductRiskTaskCacheService(StringRedisTemplate stringRedisTemplate,
ObjectMapper objectMapper,
TaskScopePayloadStorageService taskScopePayloadStorageService,
TaskEntityLocalCache taskEntityLocalCache) {
super("PRODUCT_RISK_RESOLVE", "product-risk", ProductRiskShopPayloadDto.class,
stringRedisTemplate, objectMapper, taskScopePayloadStorageService, taskEntityLocalCache);
}
}
@@ -2,7 +2,6 @@ package com.nanri.aiimage.modules.productrisk.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessCodes;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.config.TaskPressureProperties;
@@ -14,14 +13,14 @@ import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskShopPayloadDto
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskSubmitResultRequest;
import com.nanri.aiimage.modules.productrisk.model.entity.ProductRiskShopCandidateEntity;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCreateTaskVo;
import com.nanri.aiimage.common.model.vo.ProductRiskDashboardVo;
import com.nanri.aiimage.common.model.vo.ProductRiskHistoryVo;
import com.nanri.aiimage.common.model.vo.ProductRiskResultItemVo;
import com.nanri.aiimage.common.model.vo.ProductRiskTaskBatchVo;
import com.nanri.aiimage.common.model.vo.ProductRiskTaskDetailVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskDashboardVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskHistoryVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskResultItemVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskTaskBatchVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskTaskDetailVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskPendingDeleteVo;
import com.nanri.aiimage.common.model.vo.ProductRiskTaskItemVo;
import com.nanri.aiimage.common.model.vo.ProductRiskShopQueueItemVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskTaskItemVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskShopQueueItemVo;
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.model.entity.FileResultEntity;
@@ -29,6 +28,7 @@ import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
import com.nanri.aiimage.modules.task.service.TaskDistributedLockService;
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
import com.nanri.aiimage.modules.task.service.TaskFinalizeSupport;
import com.nanri.aiimage.modules.task.service.TaskProgressSnapshotService;
import com.nanri.aiimage.modules.task.service.TaskResultItemService;
import com.nanri.aiimage.modules.task.service.TaskResultPayloadService;
@@ -91,58 +91,15 @@ public class ProductRiskTaskService {
private final org.springframework.transaction.PlatformTransactionManager transactionManager;
private FileTaskEntity loadTaskForExecution(Long taskId) {
Map<Long, FileTaskEntity> cachedTasks = productRiskTaskCacheService.getTaskCacheBatch(List.of(taskId));
FileTaskEntity cached = cachedTasks.get(taskId);
if (cached != null) {
return cached;
}
FileTaskEntity dbTask = fileTaskMapper.selectById(taskId);
if (dbTask != null && MODULE_TYPE.equals(dbTask.getModuleType())) {
productRiskTaskCacheService.saveTaskCache(dbTask);
}
return dbTask;
return TaskFinalizeSupport.loadTaskForExecution(fileTaskMapper, productRiskTaskCacheService, MODULE_TYPE, taskId);
}
private Map<Long, FileTaskEntity> loadTaskMapByIds(List<Long> taskIds) {
Map<Long, FileTaskEntity> result = new LinkedHashMap<>();
if (taskIds == null || taskIds.isEmpty()) {
return result;
}
List<Long> normalizedTaskIds = taskIds.stream()
.filter(taskId -> taskId != null && taskId > 0)
.distinct()
.toList();
if (normalizedTaskIds.isEmpty()) {
return result;
}
Map<Long, FileTaskEntity> cachedTasks = productRiskTaskCacheService.getTaskCacheBatch(normalizedTaskIds);
result.putAll(cachedTasks);
List<Long> missingTaskIds = normalizedTaskIds.stream()
.filter(taskId -> !cachedTasks.containsKey(taskId))
.toList();
for (FileTaskEntity dbTask : selectTasksByIdsInBatches(missingTaskIds)) {
if (dbTask == null || !MODULE_TYPE.equals(dbTask.getModuleType())) {
continue;
}
result.put(dbTask.getId(), dbTask);
if ("RUNNING".equals(dbTask.getStatus())) {
productRiskTaskCacheService.saveTaskCache(dbTask);
}
}
return result;
return TaskFinalizeSupport.loadTaskMapByIds(fileTaskMapper, taskPressureProperties, productRiskTaskCacheService, MODULE_TYPE, taskIds);
}
private List<FileTaskEntity> selectTasksByIdsInBatches(List<Long> taskIds) {
List<FileTaskEntity> tasks = new ArrayList<>();
if (taskIds == null || taskIds.isEmpty()) {
return tasks;
}
int batchSize = Math.max(1, taskPressureProperties.getDbSelectBatchSize());
for (int start = 0; start < taskIds.size(); start += batchSize) {
int end = Math.min(start + batchSize, taskIds.size());
tasks.addAll(fileTaskMapper.selectBatchIds(taskIds.subList(start, end)));
}
return tasks;
return TaskFinalizeSupport.selectTasksByIdsInBatches(fileTaskMapper, taskPressureProperties, taskIds);
}
private List<FileTaskEntity> selectTaskHistoryFieldsByIdsInBatches(List<Long> taskIds) {
@@ -839,14 +796,7 @@ public class ProductRiskTaskService {
}
private void markResultFailed(FileResultEntity fr, String message) {
fr.setSuccess(0);
fr.setErrorMessage(message);
fr.setResultFilename(null);
fr.setResultFileUrl(null);
fr.setResultFileSize(0L);
fr.setRowCount(0);
fr.setResultContentType(null);
fileResultMapper.updateById(fr);
TaskFinalizeSupport.markResultFailed(fileResultMapper, fr, message);
}
private void markResultNoData(FileResultEntity fr, String message) {
@@ -1100,19 +1050,11 @@ public class ProductRiskTaskService {
}
private TaskDistributedLockService.LockHandle acquireTaskLockOrThrow(Long taskId) {
TaskDistributedLockService.LockHandle lockHandle = acquireTaskLock(taskId);
if (lockHandle == null) {
log.warn("[product-risk] 任务锁竞争,拒绝本次提交 taskId={}", taskId);
throw new BusinessException(BusinessCodes.TASK_BUSY, "任务正在处理中,请稍后再试");
}
return lockHandle;
return TaskFinalizeSupport.acquireTaskLockOrThrow(taskDistributedLockService, MODULE_TYPE, taskId, "product-risk");
}
private TaskDistributedLockService.LockHandle acquireTaskLock(Long taskId) {
if (taskId == null || taskId <= 0) {
return null;
}
return taskDistributedLockService.acquire(MODULE_TYPE, taskId);
return TaskFinalizeSupport.acquireTaskLock(taskDistributedLockService, MODULE_TYPE, taskId);
}
/**
@@ -2,15 +2,13 @@ package com.nanri.aiimage.modules.publish.service;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.util.ExcelStreamReader;
import com.nanri.aiimage.common.util.SxssfWorkbookWriter;
import com.nanri.aiimage.modules.publish.model.dto.PublishRowDto;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.WorkbookUtil;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.stereotype.Service;
import java.io.File;
@@ -96,27 +94,19 @@ public class PublishWorkbookService {
if (parent != null) {
parent.mkdirs();
}
SXSSFWorkbook workbook = new SXSSFWorkbook(200);
workbook.setCompressTempFiles(true);
try (FileOutputStream output = new FileOutputStream(outputFile)) {
CellStyle headerStyle = createHeaderStyle(workbook);
try (SxssfWorkbookWriter writer = SxssfWorkbookWriter.open()) {
CellStyle headerStyle = writer.headerStyle();
String country = countrySheetName(publishCountry);
// 工作表名必须是 Excel 合法名(≤31 字符、不含 []:*?/\ ),而 country 来自接口参数,
// 用户填了长文本/特殊字符时直接 createSheet 会抛异常导致"生成上架结果 Excel 失败"。
// uniqueSheetName 是项目内已有的净化样板(dedupe 同款 WorkbookUtil.createSafeSheetName),
// 此处只净化工作表名;单元格里的国家值仍按原口径写入。
Sheet sheet = workbook.createSheet(uniqueSheetName(country, new LinkedHashSet<>()));
Sheet sheet = writer.workbook().createSheet(uniqueSheetName(country, new LinkedHashSet<>()));
writeSheet(sheet, rows, headerStyle, country);
workbook.write(output);
writer.write(outputFile);
return outputFile;
} catch (Exception ex) {
throw new BusinessException("生成上架结果 Excel 失败: " + safeMessage(ex));
} finally {
workbook.dispose();
try {
workbook.close();
} catch (Exception ignored) {
}
}
}
@@ -228,20 +218,10 @@ public class PublishWorkbookService {
setText(row, 7, value.getSyncCountries());
}
int[] widths = {14, 18, 12, 24, 12, 14, 14, 28};
for (int index = 0; index < widths.length; index++) {
sheet.setColumnWidth(index, widths[index] * 256);
}
SxssfWorkbookWriter.applyColumnWidths(sheet, widths);
sheet.createFreezePane(0, 1);
}
private CellStyle createHeaderStyle(Workbook workbook) {
Font font = workbook.createFont();
font.setBold(true);
CellStyle style = workbook.createCellStyle();
style.setFont(font);
return style;
}
private void setText(Row row, int columnIndex, String value) {
row.createCell(columnIndex).setCellValue(value == null ? "" : value);
}
@@ -4,9 +4,9 @@ import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCandidateAddRequest;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskMatchShopsRequest;
import com.nanri.aiimage.common.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.common.model.vo.ProductRiskDashboardVo;
import com.nanri.aiimage.common.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskDashboardVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.modules.queryasin.model.dto.QueryAsinCreateTaskRequest;
import com.nanri.aiimage.modules.queryasin.model.dto.QueryAsinSubmitResultRequest;
import com.nanri.aiimage.modules.queryasin.model.dto.QueryAsinTaskBatchRequest;
@@ -1,6 +1,7 @@
package com.nanri.aiimage.modules.queryasin.service;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.util.SxssfWorkbookWriter;
import com.nanri.aiimage.modules.queryasin.model.dto.QueryAsinAsinStatusDto;
import com.nanri.aiimage.modules.queryasin.model.dto.QueryAsinCountryAsinsDto;
import com.nanri.aiimage.modules.queryasin.model.dto.QueryAsinCountryResultDto;
@@ -8,11 +9,9 @@ import com.nanri.aiimage.modules.queryasin.model.vo.QueryAsinResultItemVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
@@ -40,14 +39,10 @@ public class QueryAsinExcelAssemblyService {
};
public void writeWorkbook(File outputXlsx, List<QueryAsinResultItemVo> items) {
SXSSFWorkbook workbook = new SXSSFWorkbook(200);
workbook.setCompressTempFiles(true);
try (FileOutputStream outputStream = new FileOutputStream(outputXlsx)) {
Sheet sheet = workbook.createSheet("查询ASIN结果");
Row headerRow = sheet.createRow(0);
try (SxssfWorkbookWriter writer = SxssfWorkbookWriter.open()) {
Sheet sheet = writer.createSheet("查询ASIN结果", HEADER, null);
for (int columnIndex = 0; columnIndex < HEADER.length; columnIndex++) {
headerRow.createCell(columnIndex).setCellValue(HEADER[columnIndex]);
sheet.setColumnWidth(columnIndex, (columnIndex == 0 ? 22 : 18) * 256);
sheet.setColumnWidth(columnIndex, SxssfWorkbookWriter.width(columnIndex == 0 ? 22 : 18));
}
int rowIndex = 1;
@@ -59,27 +54,21 @@ public class QueryAsinExcelAssemblyService {
int maxRows = maxRows(resultsByCountry);
for (int i = 0; i < maxRows; i++) {
Row row = sheet.createRow(rowIndex++);
row.createCell(0).setCellValue(i == 0 ? safe(item.getShopName()) : "");
SxssfWorkbookWriter.setText(row, 0, i == 0 ? safe(item.getShopName()) : "");
for (int c = 0; c < COUNTRIES.size(); c++) {
List<QueryAsinAsinStatusDto> rows = resultsByCountry.get(COUNTRIES.get(c));
QueryAsinAsinStatusDto result = rows != null && i < rows.size() ? rows.get(i) : null;
int asinColumn = 1 + c * 2;
row.createCell(asinColumn).setCellValue(result == null ? "" : safe(result.getAsin()));
row.createCell(asinColumn + 1).setCellValue(result == null ? "" : safe(result.getStatus()));
SxssfWorkbookWriter.setText(row, asinColumn, result == null ? "" : safe(result.getAsin()));
SxssfWorkbookWriter.setText(row, asinColumn + 1, result == null ? "" : safe(result.getStatus()));
}
}
rowIndex++;
}
workbook.write(outputStream);
writer.write(outputXlsx);
} catch (Exception ex) {
log.warn("[query-asin] write workbook failed: {}", ex.getMessage());
throw new BusinessException("生成查询 ASIN Excel 失败: " + ex.getMessage());
} finally {
try {
workbook.close();
} catch (Exception ignored) {
}
workbook.dispose();
}
}
@@ -4,9 +4,9 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCandidateAddRequest;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskMatchShopsRequest;
import com.nanri.aiimage.common.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.common.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.common.model.vo.ProductRiskShopQueueItemVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskShopQueueItemVo;
import com.nanri.aiimage.modules.queryasin.mapper.QueryAsinShopCandidateMapper;
import com.nanri.aiimage.modules.queryasin.model.dto.QueryAsinCountryAsinsDto;
import com.nanri.aiimage.modules.queryasin.model.entity.QueryAsinShopCandidateEntity;
@@ -1,213 +1,25 @@
package com.nanri.aiimage.modules.queryasin.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.modules.queryasin.model.dto.QueryAsinShopPayloadDto;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.service.AbstractModuleTaskCacheService;
import com.nanri.aiimage.modules.task.service.TaskScopePayloadStorageService;
import com.nanri.aiimage.modules.task.util.TaskEntityLocalCache;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 查询ASIN 模块任务缓存服务:通用实现见 {@link AbstractModuleTaskCacheService},
* 本类只声明模块差异(moduleType / Redis key 前缀 / 载荷类型)。
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class QueryAsinTaskCacheService {
public class QueryAsinTaskCacheService extends AbstractModuleTaskCacheService<QueryAsinShopPayloadDto> {
private static final String MODULE_TYPE = "QUERY_ASIN";
private static final long PAYLOAD_TTL_HOURS = 24;
private final StringRedisTemplate stringRedisTemplate;
private final ObjectMapper objectMapper;
private final TaskScopePayloadStorageService taskScopePayloadStorageService;
private final TaskEntityLocalCache taskEntityLocalCache;
public QueryAsinShopPayloadDto getShopMergedPayload(Long taskId, String shopKey) {
return taskScopePayloadStorageService.getScopePayload(taskId, MODULE_TYPE, shopKey, QueryAsinShopPayloadDto.class);
}
public void saveShopMergedPayload(Long taskId, String shopKey, QueryAsinShopPayloadDto payload) {
if (taskId == null || taskId <= 0 || shopKey == null || shopKey.isBlank() || payload == null) {
return;
}
taskScopePayloadStorageService.saveScopePayload(taskId, MODULE_TYPE, shopKey, payload);
touchTaskHeartbeat(taskId);
}
public void removeShopMergedPayload(Long taskId, String shopKey) {
taskScopePayloadStorageService.removeScopePayload(taskId, MODULE_TYPE, shopKey);
}
public Map<String, QueryAsinShopPayloadDto> getAllShopMergedPayload(Long taskId) {
return taskScopePayloadStorageService.getAllScopePayload(taskId, MODULE_TYPE, QueryAsinShopPayloadDto.class);
}
public boolean hasAnyShopMergedPayload(Long taskId) {
return taskScopePayloadStorageService.hasAnyScopePayload(taskId, MODULE_TYPE);
}
public long countShopMergedPayload(Long taskId) {
return taskScopePayloadStorageService.countScopePayload(taskId, MODULE_TYPE);
}
public long getTaskHeartbeatMillis(Long taskId) {
if (taskId == null || taskId <= 0) {
return 0L;
}
String raw;
try {
raw = stringRedisTemplate.opsForValue().get(buildTaskHeartbeatKey(taskId));
} catch (Exception ex) {
log.warn("[query-asin-cache] get heartbeat degraded taskId={} msg={}", taskId, ex.getMessage());
return 0L;
}
if (raw == null || raw.isBlank()) {
return 0L;
}
try {
return Long.parseLong(raw);
} catch (NumberFormatException ignored) {
return 0L;
}
}
public Map<Long, Long> getTaskHeartbeatMillisBatch(List<Long> taskIds) {
Map<Long, Long> result = new LinkedHashMap<>();
if (taskIds == null || taskIds.isEmpty()) {
return result;
}
List<Long> normalized = taskIds.stream()
.filter(id -> id != null && id > 0)
.distinct()
.toList();
if (normalized.isEmpty()) {
return result;
}
List<String> keys = normalized.stream().map(this::buildTaskHeartbeatKey).toList();
List<String> values;
try {
values = stringRedisTemplate.opsForValue().multiGet(keys);
} catch (Exception ex) {
log.warn("[query-asin-cache] batch get heartbeat degraded taskIds={} msg={}", normalized, ex.getMessage());
return result;
}
for (int i = 0; i < normalized.size(); i++) {
String raw = values != null && i < values.size() ? values.get(i) : null;
if (raw == null || raw.isBlank()) {
result.put(normalized.get(i), 0L);
continue;
}
try {
result.put(normalized.get(i), Long.parseLong(raw));
} catch (NumberFormatException ignored) {
result.put(normalized.get(i), 0L);
}
}
return result;
}
public void touchTaskHeartbeat(Long taskId) {
try {
stringRedisTemplate.opsForValue().set(
buildTaskHeartbeatKey(taskId),
String.valueOf(Instant.now().toEpochMilli()),
Duration.ofHours(PAYLOAD_TTL_HOURS));
} catch (Exception ex) {
log.warn("[query-asin-cache] touch heartbeat degraded taskId={} msg={}", taskId, ex.getMessage());
}
}
public void deleteTaskCache(Long taskId) {
if (taskId == null || taskId <= 0) {
return;
}
taskEntityLocalCache.evict(taskId);
try {
stringRedisTemplate.delete(buildTaskHeartbeatKey(taskId));
stringRedisTemplate.delete(buildTaskEntityKey(taskId));
} catch (Exception ex) {
log.warn("[query-asin-cache] delete cache degraded taskId={} msg={}", taskId, ex.getMessage());
}
taskScopePayloadStorageService.deleteTaskScopePayloads(taskId, MODULE_TYPE);
}
public void saveTaskCache(FileTaskEntity task) {
if (task == null || task.getId() == null) {
return;
}
taskEntityLocalCache.put(task.getId(), task);
try {
stringRedisTemplate.opsForValue().set(
buildTaskEntityKey(task.getId()),
objectMapper.writeValueAsString(task),
Duration.ofHours(PAYLOAD_TTL_HOURS)
);
} catch (Exception ignored) {
}
}
public Map<Long, FileTaskEntity> getTaskCacheBatch(java.util.List<Long> taskIds) {
Map<Long, FileTaskEntity> result = new LinkedHashMap<>();
if (taskIds == null || taskIds.isEmpty()) {
return result;
}
java.util.List<Long> normalized = taskIds.stream()
.filter(id -> id != null && id > 0)
.distinct()
.toList();
if (normalized.isEmpty()) {
return result;
}
long now = System.currentTimeMillis();
java.util.List<Long> missingIds = new ArrayList<>();
for (Long taskId : normalized) {
TaskEntityLocalCache.Entry cached = taskEntityLocalCache.get(taskId, now);
if (cached != null) {
result.put(taskId, cached.task());
} else {
missingIds.add(taskId);
}
}
if (missingIds.isEmpty()) {
return result;
}
java.util.List<String> keys = missingIds.stream().map(this::buildTaskEntityKey).toList();
java.util.List<String> values;
try {
values = stringRedisTemplate.opsForValue().multiGet(keys);
} catch (Exception ex) {
log.warn("[query-asin-cache] batch get task cache degraded taskIds={} msg={}", missingIds, ex.getMessage());
return result;
}
for (int i = 0; i < missingIds.size(); i++) {
Long taskId = missingIds.get(i);
String val = values != null && i < values.size() ? values.get(i) : null;
if (val == null || val.isBlank()) {
continue;
}
try {
FileTaskEntity task = objectMapper.readValue(val, FileTaskEntity.class);
result.put(taskId, task);
taskEntityLocalCache.put(taskId, task);
} catch (Exception ignored) {
}
}
return result;
}
private String buildTaskHeartbeatKey(Long taskId) {
return "query-asin:task:heartbeat:" + taskId;
}
private String buildTaskEntityKey(Long taskId) {
return "query-asin:task:entity:" + taskId;
public QueryAsinTaskCacheService(StringRedisTemplate stringRedisTemplate,
ObjectMapper objectMapper,
TaskScopePayloadStorageService taskScopePayloadStorageService,
TaskEntityLocalCache taskEntityLocalCache) {
super("QUERY_ASIN", "query-asin", QueryAsinShopPayloadDto.class,
stringRedisTemplate, objectMapper, taskScopePayloadStorageService, taskEntityLocalCache);
}
}
@@ -6,7 +6,6 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessCodes;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.config.TaskPressureProperties;
@@ -22,7 +21,7 @@ import com.nanri.aiimage.modules.queryasin.model.vo.QueryAsinTaskBatchVo;
import com.nanri.aiimage.modules.queryasin.model.vo.QueryAsinCreateTaskVo;
import com.nanri.aiimage.modules.queryasin.model.vo.QueryAsinHistoryVo;
import com.nanri.aiimage.modules.queryasin.model.vo.QueryAsinResultItemVo;
import com.nanri.aiimage.common.model.vo.ProductRiskDashboardVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskDashboardVo;
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.model.entity.FileResultEntity;
@@ -30,6 +29,7 @@ import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
import com.nanri.aiimage.modules.task.service.TaskDistributedLockService;
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
import com.nanri.aiimage.modules.task.service.TaskFinalizeSupport;
import com.nanri.aiimage.modules.task.service.TaskProgressSnapshotService;
import com.nanri.aiimage.modules.task.service.TaskResultItemService;
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopSwitchService;
@@ -101,60 +101,15 @@ public class QueryAsinTaskService {
private final org.springframework.transaction.PlatformTransactionManager transactionManager;
private FileTaskEntity loadTaskForExecution(Long taskId) {
Map<Long, FileTaskEntity> cachedTasks = taskCacheService.getTaskCacheBatch(List.of(taskId));
FileTaskEntity cached = cachedTasks.get(taskId);
if (cached != null) {
return cached;
}
FileTaskEntity dbTask = fileTaskMapper.selectById(taskId);
if (dbTask != null && MODULE_TYPE.equals(dbTask.getModuleType())) {
taskCacheService.saveTaskCache(dbTask);
}
return dbTask;
return TaskFinalizeSupport.loadTaskForExecution(fileTaskMapper, taskCacheService, MODULE_TYPE, taskId);
}
private Map<Long, FileTaskEntity> loadTaskMapByIds(List<Long> taskIds) {
Map<Long, FileTaskEntity> result = new LinkedHashMap<>();
if (taskIds == null || taskIds.isEmpty()) {
return result;
}
List<Long> normalizedTaskIds = taskIds.stream()
.filter(taskId -> taskId != null && taskId > 0)
.distinct()
.toList();
if (normalizedTaskIds.isEmpty()) {
return result;
}
Map<Long, FileTaskEntity> cachedTasks = taskCacheService.getTaskCacheBatch(normalizedTaskIds);
result.putAll(cachedTasks);
List<Long> missingTaskIds = normalizedTaskIds.stream()
.filter(taskId -> !cachedTasks.containsKey(taskId))
.toList();
if (!missingTaskIds.isEmpty()) {
for (FileTaskEntity dbTask : selectTasksByIdsInBatches(missingTaskIds)) {
if (dbTask == null || !MODULE_TYPE.equals(dbTask.getModuleType())) {
continue;
}
result.put(dbTask.getId(), dbTask);
if ("RUNNING".equals(dbTask.getStatus())) {
taskCacheService.saveTaskCache(dbTask);
}
}
}
return result;
return TaskFinalizeSupport.loadTaskMapByIds(fileTaskMapper, taskPressureProperties, taskCacheService, MODULE_TYPE, taskIds);
}
private List<FileTaskEntity> selectTasksByIdsInBatches(List<Long> taskIds) {
List<FileTaskEntity> tasks = new ArrayList<>();
if (taskIds == null || taskIds.isEmpty()) {
return tasks;
}
int batchSize = Math.max(1, taskPressureProperties.getDbSelectBatchSize());
for (int start = 0; start < taskIds.size(); start += batchSize) {
int end = Math.min(start + batchSize, taskIds.size());
tasks.addAll(fileTaskMapper.selectBatchIds(taskIds.subList(start, end)));
}
return tasks;
return TaskFinalizeSupport.selectTasksByIdsInBatches(fileTaskMapper, taskPressureProperties, taskIds);
}
public ProductRiskDashboardVo dashboard(Long userId) {
@@ -1075,19 +1030,11 @@ public class QueryAsinTaskService {
}
private TaskDistributedLockService.LockHandle acquireTaskLockOrThrow(Long taskId) {
TaskDistributedLockService.LockHandle lockHandle = acquireTaskLock(taskId);
if (lockHandle == null) {
log.warn("[query-asin] 任务锁竞争,拒绝本次提交 taskId={}", taskId);
throw new BusinessException(BusinessCodes.TASK_BUSY, "任务正在处理中,请稍后再试");
}
return lockHandle;
return TaskFinalizeSupport.acquireTaskLockOrThrow(taskDistributedLockService, MODULE_TYPE, taskId, "query-asin");
}
private TaskDistributedLockService.LockHandle acquireTaskLock(Long taskId) {
if (taskId == null || taskId <= 0) {
return null;
}
return taskDistributedLockService.acquire(MODULE_TYPE, taskId);
return TaskFinalizeSupport.acquireTaskLock(taskDistributedLockService, MODULE_TYPE, taskId);
}
/**
@@ -1110,14 +1057,7 @@ public class QueryAsinTaskService {
}
private void markResultFailed(FileResultEntity row, String message) {
row.setSuccess(RESULT_FAILED);
row.setErrorMessage(blankToNull(message));
row.setResultFilename(null);
row.setResultFileUrl(null);
row.setResultFileSize(0L);
row.setResultContentType(null);
row.setRowCount(0);
fileResultMapper.updateById(row);
TaskFinalizeSupport.markResultFailed(fileResultMapper, row, blankToNull(message));
}
private boolean isResultFinished(FileResultEntity row) {
@@ -5,10 +5,10 @@ import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCandidateAddRequest;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCountryPreferenceSaveRequest;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskMatchShopsRequest;
import com.nanri.aiimage.common.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.common.model.vo.ProductRiskCountryPreferenceVo;
import com.nanri.aiimage.common.model.vo.ProductRiskDashboardVo;
import com.nanri.aiimage.common.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCountryPreferenceVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskDashboardVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.modules.shopdatacrawl.model.dto.ShopDataCrawlCreateTaskRequest;
import com.nanri.aiimage.modules.shopdatacrawl.model.dto.ShopDataCrawlSubmitResultRequest;
import com.nanri.aiimage.modules.shopdatacrawl.model.dto.ShopDataCrawlTaskBatchRequest;
@@ -12,10 +12,10 @@ import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskMatchShopsRequ
import com.nanri.aiimage.modules.shopdatacrawl.model.entity.ShopDataCrawlCountryPrefEntity;
import com.nanri.aiimage.modules.shopdatacrawl.model.entity.ShopDataCrawlShopCandidateEntity;
import com.nanri.aiimage.modules.productrisk.model.enums.ProductRiskCountryCode;
import com.nanri.aiimage.common.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.common.model.vo.ProductRiskCountryPreferenceVo;
import com.nanri.aiimage.common.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.common.model.vo.ProductRiskShopQueueItemVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCountryPreferenceVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskShopQueueItemVo;
import com.nanri.aiimage.modules.shopkey.service.ShopManageService;
import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoShopMatchResultVo;
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopIndexService;
@@ -1,215 +1,35 @@
package com.nanri.aiimage.modules.shopdatacrawl.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.config.TaskPressureProperties;
import com.nanri.aiimage.modules.shopdatacrawl.model.dto.ShopDataCrawlShopPayloadDto;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.service.AbstractModuleTaskCacheService;
import com.nanri.aiimage.modules.task.service.TaskScopePayloadStorageService;
import com.nanri.aiimage.modules.task.util.TaskEntityLocalCache;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 店铺数据采集模块任务缓存服务:通用实现见 {@link AbstractModuleTaskCacheService},
* 本类只声明模块差异(moduleType / Redis key 前缀 / 载荷类型)与本地缓存监控入口。
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class ShopDataCrawlTaskCacheService {
public class ShopDataCrawlTaskCacheService extends AbstractModuleTaskCacheService<ShopDataCrawlShopPayloadDto> {
private static final String MODULE_TYPE = "SHOP_DATA_CRAWL";
private static final long PAYLOAD_TTL_HOURS = 24;
private final StringRedisTemplate stringRedisTemplate;
private final ObjectMapper objectMapper;
private final TaskPressureProperties taskPressureProperties;
private final TaskScopePayloadStorageService taskScopePayloadStorageService;
private final TaskEntityLocalCache taskEntityLocalCache;
public ShopDataCrawlShopPayloadDto getShopMergedPayload(Long taskId, String shopKey) {
return taskScopePayloadStorageService.getScopePayload(taskId, MODULE_TYPE, shopKey, ShopDataCrawlShopPayloadDto.class);
}
public void saveShopMergedPayload(Long taskId, String shopKey, ShopDataCrawlShopPayloadDto payload) {
if (taskId == null || taskId <= 0 || shopKey == null || shopKey.isBlank() || payload == null) {
return;
}
taskScopePayloadStorageService.saveScopePayload(taskId, MODULE_TYPE, shopKey, payload);
touchTaskHeartbeat(taskId);
}
public void removeShopMergedPayload(Long taskId, String shopKey) {
taskScopePayloadStorageService.removeScopePayload(taskId, MODULE_TYPE, shopKey);
}
public Map<String, ShopDataCrawlShopPayloadDto> getAllShopMergedPayload(Long taskId) {
return taskScopePayloadStorageService.getAllScopePayload(taskId, MODULE_TYPE, ShopDataCrawlShopPayloadDto.class);
}
public boolean hasAnyShopMergedPayload(Long taskId) {
return taskScopePayloadStorageService.hasAnyScopePayload(taskId, MODULE_TYPE);
}
public long countShopMergedPayload(Long taskId) {
return taskScopePayloadStorageService.countScopePayload(taskId, MODULE_TYPE);
}
public long getTaskHeartbeatMillis(Long taskId) {
if (taskId == null || taskId <= 0) {
return 0L;
}
String raw;
try {
raw = stringRedisTemplate.opsForValue().get(buildTaskHeartbeatKey(taskId));
} catch (Exception ex) {
log.warn("[shop-data-crawl-cache] get heartbeat degraded taskId={} msg={}", taskId, ex.getMessage());
return 0L;
}
if (raw == null || raw.isBlank()) {
return 0L;
}
try {
return Long.parseLong(raw);
} catch (NumberFormatException ignored) {
return 0L;
}
}
public Map<Long, Long> getTaskHeartbeatMillisBatch(List<Long> taskIds) {
Map<Long, Long> result = new LinkedHashMap<>();
if (taskIds == null || taskIds.isEmpty()) {
return result;
}
List<Long> normalized = taskIds.stream()
.filter(id -> id != null && id > 0)
.distinct()
.toList();
if (normalized.isEmpty()) {
return result;
}
List<String> keys = normalized.stream().map(this::buildTaskHeartbeatKey).toList();
List<String> values;
try {
values = stringRedisTemplate.opsForValue().multiGet(keys);
} catch (Exception ex) {
log.warn("[shop-data-crawl-cache] batch get heartbeat degraded taskIds={} msg={}", normalized, ex.getMessage());
return result;
}
for (int i = 0; i < normalized.size(); i++) {
String raw = values != null && i < values.size() ? values.get(i) : null;
if (raw == null || raw.isBlank()) {
result.put(normalized.get(i), 0L);
continue;
}
try {
result.put(normalized.get(i), Long.parseLong(raw));
} catch (NumberFormatException ignored) {
result.put(normalized.get(i), 0L);
}
}
return result;
}
public void touchTaskHeartbeat(Long taskId) {
try {
stringRedisTemplate.opsForValue().set(
buildTaskHeartbeatKey(taskId),
String.valueOf(Instant.now().toEpochMilli()),
Duration.ofHours(PAYLOAD_TTL_HOURS));
} catch (Exception ex) {
log.warn("[shop-data-crawl-cache] touch heartbeat degraded taskId={} msg={}", taskId, ex.getMessage());
}
}
public void deleteTaskCache(Long taskId) {
if (taskId == null || taskId <= 0) {
return;
}
taskEntityLocalCache.evict(taskId);
try {
stringRedisTemplate.delete(buildTaskHeartbeatKey(taskId));
stringRedisTemplate.delete(buildTaskEntityKey(taskId));
} catch (Exception ex) {
log.warn("[shop-data-crawl-cache] delete cache degraded taskId={} msg={}", taskId, ex.getMessage());
}
taskScopePayloadStorageService.deleteTaskScopePayloads(taskId, MODULE_TYPE);
}
public void saveTaskCache(FileTaskEntity task) {
if (task == null || task.getId() == null) {
return;
}
taskEntityLocalCache.put(task.getId(), task);
try {
stringRedisTemplate.opsForValue().set(
buildTaskEntityKey(task.getId()),
objectMapper.writeValueAsString(task),
Duration.ofHours(PAYLOAD_TTL_HOURS)
);
} catch (Exception ignored) {
}
}
public Map<Long, FileTaskEntity> getTaskCacheBatch(java.util.List<Long> taskIds) {
Map<Long, FileTaskEntity> result = new LinkedHashMap<>();
if (taskIds == null || taskIds.isEmpty()) {
return result;
}
java.util.List<Long> normalized = taskIds.stream()
.filter(id -> id != null && id > 0)
.distinct()
.toList();
if (normalized.isEmpty()) {
return result;
}
long now = System.currentTimeMillis();
java.util.List<Long> missingIds = new ArrayList<>();
for (Long taskId : normalized) {
TaskEntityLocalCache.Entry cached = taskEntityLocalCache.get(taskId, now);
if (cached != null) {
result.put(taskId, cached.task());
} else {
missingIds.add(taskId);
}
}
if (missingIds.isEmpty()) {
return result;
}
java.util.List<String> keys = missingIds.stream().map(this::buildTaskEntityKey).toList();
java.util.List<String> values;
try {
values = stringRedisTemplate.opsForValue().multiGet(keys);
} catch (Exception ex) {
log.warn("[shop-data-crawl-cache] batch get task cache degraded taskIds={} msg={}", missingIds, ex.getMessage());
return result;
}
for (int i = 0; i < missingIds.size(); i++) {
Long taskId = missingIds.get(i);
String val = values != null && i < values.size() ? values.get(i) : null;
if (val == null || val.isBlank()) {
continue;
}
try {
FileTaskEntity task = objectMapper.readValue(val, FileTaskEntity.class);
result.put(taskId, task);
taskEntityLocalCache.put(taskId, task);
} catch (Exception ignored) {
}
}
return result;
}
private String buildTaskHeartbeatKey(Long taskId) {
return "shop-data-crawl:task:heartbeat:" + taskId;
}
private String buildTaskEntityKey(Long taskId) {
return "shop-data-crawl:task:entity:" + taskId;
public ShopDataCrawlTaskCacheService(StringRedisTemplate stringRedisTemplate,
ObjectMapper objectMapper,
TaskPressureProperties taskPressureProperties,
TaskScopePayloadStorageService taskScopePayloadStorageService,
TaskEntityLocalCache taskEntityLocalCache) {
super("SHOP_DATA_CRAWL", "shop-data-crawl", ShopDataCrawlShopPayloadDto.class,
stringRedisTemplate, objectMapper, taskScopePayloadStorageService, taskEntityLocalCache);
this.taskPressureProperties = taskPressureProperties;
}
/** 本地缓存当前条目数(测试与监控用)。 */
@@ -217,4 +37,3 @@ public class ShopDataCrawlTaskCacheService {
return taskEntityLocalCache.size();
}
}
@@ -29,7 +29,7 @@ import com.nanri.aiimage.modules.shopdatacrawl.model.vo.ShopDataCrawlCreateTaskV
import com.nanri.aiimage.modules.shopdatacrawl.model.vo.ShopDataCrawlHistoryVo;
import com.nanri.aiimage.modules.shopdatacrawl.model.vo.ShopDataCrawlResultItemVo;
import com.nanri.aiimage.modules.shopdatacrawl.spi.DuplicateCheckRefreshPort;
import com.nanri.aiimage.common.model.vo.ProductRiskDashboardVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskDashboardVo;
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.mapper.TaskChunkMapper;
@@ -42,6 +42,7 @@ import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
import com.nanri.aiimage.modules.task.model.entity.TaskScopeStateEntity;
import com.nanri.aiimage.modules.task.service.TaskDistributedLockService;
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
import com.nanri.aiimage.modules.task.service.TaskFinalizeSupport;
import com.nanri.aiimage.modules.task.service.TaskProgressSnapshotService;
import com.nanri.aiimage.modules.task.service.TaskResultItemService;
import com.nanri.aiimage.modules.task.service.TransientPayloadStorageService;
@@ -288,60 +289,15 @@ public class ShopDataCrawlTaskService {
}
private FileTaskEntity loadTaskForExecution(Long taskId) {
Map<Long, FileTaskEntity> cachedTasks = taskCacheService.getTaskCacheBatch(List.of(taskId));
FileTaskEntity cached = cachedTasks.get(taskId);
if (cached != null) {
return cached;
}
FileTaskEntity dbTask = fileTaskMapper.selectById(taskId);
if (dbTask != null && MODULE_TYPE.equals(dbTask.getModuleType())) {
taskCacheService.saveTaskCache(dbTask);
}
return dbTask;
return TaskFinalizeSupport.loadTaskForExecution(fileTaskMapper, taskCacheService, MODULE_TYPE, taskId);
}
private Map<Long, FileTaskEntity> loadTaskMapByIds(List<Long> taskIds) {
Map<Long, FileTaskEntity> result = new LinkedHashMap<>();
if (taskIds == null || taskIds.isEmpty()) {
return result;
}
List<Long> normalizedTaskIds = taskIds.stream()
.filter(taskId -> taskId != null && taskId > 0)
.distinct()
.toList();
if (normalizedTaskIds.isEmpty()) {
return result;
}
Map<Long, FileTaskEntity> cachedTasks = taskCacheService.getTaskCacheBatch(normalizedTaskIds);
result.putAll(cachedTasks);
List<Long> missingTaskIds = normalizedTaskIds.stream()
.filter(taskId -> !cachedTasks.containsKey(taskId))
.toList();
if (!missingTaskIds.isEmpty()) {
for (FileTaskEntity dbTask : selectTasksByIdsInBatches(missingTaskIds)) {
if (dbTask == null || !MODULE_TYPE.equals(dbTask.getModuleType())) {
continue;
}
result.put(dbTask.getId(), dbTask);
if ("RUNNING".equals(dbTask.getStatus())) {
taskCacheService.saveTaskCache(dbTask);
}
}
}
return result;
return TaskFinalizeSupport.loadTaskMapByIds(fileTaskMapper, taskPressureProperties, taskCacheService, MODULE_TYPE, taskIds);
}
private List<FileTaskEntity> selectTasksByIdsInBatches(List<Long> taskIds) {
List<FileTaskEntity> tasks = new ArrayList<>();
if (taskIds == null || taskIds.isEmpty()) {
return tasks;
}
int batchSize = Math.max(1, taskPressureProperties.getDbSelectBatchSize());
for (int start = 0; start < taskIds.size(); start += batchSize) {
int end = Math.min(start + batchSize, taskIds.size());
tasks.addAll(fileTaskMapper.selectBatchIds(taskIds.subList(start, end)));
}
return tasks;
return TaskFinalizeSupport.selectTasksByIdsInBatches(fileTaskMapper, taskPressureProperties, taskIds);
}
public ProductRiskDashboardVo dashboard(Long userId) {
@@ -2866,26 +2822,15 @@ public class ShopDataCrawlTaskService {
}
private TaskDistributedLockService.LockHandle acquireTaskLockOrThrow(Long taskId) {
TaskDistributedLockService.LockHandle lockHandle = acquireTaskLock(taskId);
if (lockHandle == null) {
log.warn("[shop-data-crawl] 任务锁竞争,拒绝本次提交 taskId={}", taskId);
throw new BusinessException(BusinessCodes.TASK_BUSY, "任务正在处理中,请稍后再试");
}
return lockHandle;
return TaskFinalizeSupport.acquireTaskLockOrThrow(taskDistributedLockService, MODULE_TYPE, taskId, "shop-data-crawl");
}
private TaskDistributedLockService.LockHandle acquireTaskLock(Long taskId) {
if (taskId == null || taskId <= 0) {
return null;
}
return taskDistributedLockService.acquire(MODULE_TYPE, taskId);
return TaskFinalizeSupport.acquireTaskLock(taskDistributedLockService, MODULE_TYPE, taskId);
}
private TaskDistributedLockService.LockHandle acquireTaskLock(Long taskId, long waitMillis) {
if (taskId == null || taskId <= 0) {
return null;
}
return taskDistributedLockService.acquire(MODULE_TYPE, taskId, waitMillis);
return TaskFinalizeSupport.acquireTaskLock(taskDistributedLockService, MODULE_TYPE, taskId, waitMillis);
}
private void markResultSuccess(FileResultEntity row) {
@@ -2901,14 +2846,7 @@ public class ShopDataCrawlTaskService {
}
private void markResultFailed(FileResultEntity row, String message) {
row.setSuccess(RESULT_FAILED);
row.setErrorMessage(blankToNull(message));
row.setResultFilename(null);
row.setResultFileUrl(null);
row.setResultFileSize(0L);
row.setResultContentType(null);
row.setRowCount(0);
fileResultMapper.updateById(row);
TaskFinalizeSupport.markResultFailed(fileResultMapper, row, blankToNull(message));
}
private boolean isResultFinished(FileResultEntity row) {
@@ -6,12 +6,12 @@ import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCandidateAddRe
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCountryPreferenceSaveRequest;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskMatchShopsRequest;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskTaskBatchRequest;
import com.nanri.aiimage.common.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.common.model.vo.ProductRiskCountryPreferenceVo;
import com.nanri.aiimage.common.model.vo.ProductRiskDashboardVo;
import com.nanri.aiimage.common.model.vo.ProductRiskHistoryVo;
import com.nanri.aiimage.common.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.common.model.vo.ProductRiskTaskBatchVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCountryPreferenceVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskDashboardVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskHistoryVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskTaskBatchVo;
import com.nanri.aiimage.modules.shopmatch.model.dto.ShopMatchCreateTaskRequest;
import com.nanri.aiimage.modules.shopmatch.model.dto.ShopMatchStageCompleteRequest;
import com.nanri.aiimage.modules.shopmatch.model.dto.ShopMatchSubmitResultRequest;
@@ -1,16 +1,15 @@
package com.nanri.aiimage.modules.shopmatch.service;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.util.SxssfWorkbookWriter;
import com.nanri.aiimage.modules.productrisk.model.enums.ProductRiskCountryCode;
import com.nanri.aiimage.modules.shopmatch.model.dto.ShopMatchRowDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.FileOutputStream;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -19,20 +18,12 @@ import java.util.Map;
@Slf4j
public class ShopMatchExcelAssemblyService {
private static final String[] HEADER = {"ASIN", "状态"};
public void writeWorkbook(File outputXlsx, Map<String, List<ShopMatchRowDto>> countries) {
Map<String, List<ShopMatchRowDto>> safe = countries == null ? Map.of() : countries;
SXSSFWorkbook workbook = new SXSSFWorkbook(200);
workbook.setCompressTempFiles(true);
try (FileOutputStream fos = new FileOutputStream(outputXlsx)) {
try (SxssfWorkbookWriter writer = SxssfWorkbookWriter.open()) {
for (ProductRiskCountryCode code : ProductRiskCountryCode.values()) {
String sheetName = code.getSheetName();
Sheet sheet = workbook.createSheet(sheetName);
Row header = sheet.createRow(0);
header.createCell(0).setCellValue("ASIN");
header.createCell(1).setCellValue("最低价");
header.createCell(2).setCellValue("状态");
Sheet sheet = writer.createSheet(sheetName, new String[]{"ASIN", "最低价", "状态"}, new int[]{20, 18, 18});
List<ShopMatchRowDto> rows = safe.getOrDefault(sheetName, List.of());
int rowIndex = 1;
for (ShopMatchRowDto item : rows) {
@@ -40,24 +31,15 @@ public class ShopMatchExcelAssemblyService {
continue;
}
Row row = sheet.createRow(rowIndex++);
row.createCell(0).setCellValue(item.getAsin() == null ? "" : item.getAsin());
row.createCell(1).setCellValue(item.getMinimumPrice() == null ? "" : item.getMinimumPrice());
row.createCell(2).setCellValue(item.getStatus() == null ? "" : item.getStatus());
SxssfWorkbookWriter.setText(row, 0, item.getAsin());
SxssfWorkbookWriter.setText(row, 1, item.getMinimumPrice());
SxssfWorkbookWriter.setText(row, 2, item.getStatus());
}
sheet.setColumnWidth(0, 20 * 256);
sheet.setColumnWidth(1, 18 * 256);
sheet.setColumnWidth(2, 18 * 256);
}
workbook.write(fos);
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());
} finally {
try {
workbook.close();
} catch (Exception ignored) {
}
workbook.dispose();
}
}
@@ -8,10 +8,10 @@ import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCandidateAddRe
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCountryPreferenceSaveRequest;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskMatchShopsRequest;
import com.nanri.aiimage.modules.productrisk.model.enums.ProductRiskCountryCode;
import com.nanri.aiimage.common.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.common.model.vo.ProductRiskCountryPreferenceVo;
import com.nanri.aiimage.common.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.common.model.vo.ProductRiskShopQueueItemVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCountryPreferenceVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskShopQueueItemVo;
import com.nanri.aiimage.modules.shopmatch.mapper.ShopMatchCountryPrefMapper;
import com.nanri.aiimage.modules.shopmatch.mapper.ShopMatchShopCandidateMapper;
import com.nanri.aiimage.modules.shopmatch.model.entity.ShopMatchCountryPrefEntity;
@@ -1,12 +1,12 @@
package com.nanri.aiimage.modules.shopmatch.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.config.TaskPressureProperties;
import com.nanri.aiimage.modules.shopmatch.model.dto.ShopMatchShopPayloadDto;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.service.AbstractModuleTaskCacheService;
import com.nanri.aiimage.modules.task.service.TaskScopePayloadStorageService;
import com.nanri.aiimage.modules.task.util.TaskEntityLocalCache;
import com.nanri.aiimage.config.TaskPressureProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
@@ -16,130 +16,41 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 店铺匹配模块任务缓存服务:心跳与店铺维度载荷复用通用基类
* {@link AbstractModuleTaskCacheService};任务实体不走 Redis,而是落本地临时文件
* (重启后仍可续跑),因此覆写 saveTaskCache / getTaskCacheBatch / deleteTaskCache。
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class ShopMatchTaskCacheService {
public class ShopMatchTaskCacheService extends AbstractModuleTaskCacheService<ShopMatchShopPayloadDto> {
private static final String MODULE_TYPE = "SHOP_MATCH";
private static final long PAYLOAD_TTL_HOURS = 24;
private final StringRedisTemplate stringRedisTemplate;
private final ObjectMapper objectMapper;
private final TaskPressureProperties taskPressureProperties;
private final TaskScopePayloadStorageService taskScopePayloadStorageService;
private final TaskEntityLocalCache taskEntityLocalCache;
public void touchTaskHeartbeat(Long taskId) {
if (taskId == null || taskId <= 0) {
return;
}
try {
stringRedisTemplate.opsForValue().set(
buildTaskHeartbeatKey(taskId),
String.valueOf(Instant.now().toEpochMilli()),
Duration.ofHours(PAYLOAD_TTL_HOURS));
} catch (Exception ex) {
log.warn("[shop-match-cache] touch heartbeat degraded taskId={} msg={}", taskId, ex.getMessage());
}
}
public long getTaskHeartbeatMillis(Long taskId) {
if (taskId == null || taskId <= 0) {
return 0L;
}
String raw;
try {
raw = stringRedisTemplate.opsForValue().get(buildTaskHeartbeatKey(taskId));
} catch (Exception ex) {
log.warn("[shop-match-cache] get heartbeat degraded taskId={} msg={}", taskId, ex.getMessage());
return 0L;
}
if (raw == null || raw.isBlank()) {
return 0L;
}
try {
return Long.parseLong(raw);
} catch (NumberFormatException ignored) {
return 0L;
}
}
public Map<Long, Long> getTaskHeartbeatMillisBatch(List<Long> taskIds) {
Map<Long, Long> result = new LinkedHashMap<>();
if (taskIds == null || taskIds.isEmpty()) {
return result;
}
List<Long> normalized = taskIds.stream()
.filter(id -> id != null && id > 0)
.distinct()
.toList();
if (normalized.isEmpty()) {
return result;
}
List<String> keys = normalized.stream().map(this::buildTaskHeartbeatKey).toList();
List<String> values;
try {
values = stringRedisTemplate.opsForValue().multiGet(keys);
} catch (Exception ex) {
log.warn("[shop-match-cache] batch get heartbeat degraded taskIds={} msg={}", normalized, ex.getMessage());
return result;
}
for (int i = 0; i < normalized.size(); i++) {
String raw = values != null && i < values.size() ? values.get(i) : null;
if (raw == null || raw.isBlank()) {
result.put(normalized.get(i), 0L);
continue;
}
try {
result.put(normalized.get(i), Long.parseLong(raw));
} catch (NumberFormatException ignored) {
result.put(normalized.get(i), 0L);
}
}
return result;
}
public ShopMatchShopPayloadDto getShopMergedPayload(Long taskId, String shopKey) {
return taskScopePayloadStorageService.getScopePayload(taskId, MODULE_TYPE, shopKey, ShopMatchShopPayloadDto.class);
}
public void saveShopMergedPayload(Long taskId, String shopKey, ShopMatchShopPayloadDto payload) {
if (taskId == null || taskId <= 0 || shopKey == null || shopKey.isBlank() || payload == null) {
return;
}
taskScopePayloadStorageService.saveScopePayload(taskId, MODULE_TYPE, shopKey, payload);
touchTaskHeartbeat(taskId);
}
public void removeShopMergedPayload(Long taskId, String shopKey) {
taskScopePayloadStorageService.removeScopePayload(taskId, MODULE_TYPE, shopKey);
}
public Map<String, ShopMatchShopPayloadDto> getAllShopMergedPayload(Long taskId) {
return taskScopePayloadStorageService.getAllScopePayload(taskId, MODULE_TYPE, ShopMatchShopPayloadDto.class);
}
public boolean hasAnyShopMergedPayload(Long taskId) {
return taskScopePayloadStorageService.hasAnyScopePayload(taskId, MODULE_TYPE);
public ShopMatchTaskCacheService(StringRedisTemplate stringRedisTemplate,
ObjectMapper objectMapper,
TaskPressureProperties taskPressureProperties,
TaskScopePayloadStorageService taskScopePayloadStorageService,
TaskEntityLocalCache taskEntityLocalCache) {
super("SHOP_MATCH", "shop-match", ShopMatchShopPayloadDto.class,
stringRedisTemplate, objectMapper, taskScopePayloadStorageService, taskEntityLocalCache);
this.taskPressureProperties = taskPressureProperties;
}
@Override
public void deleteTaskCache(Long taskId) {
if (taskId == null || taskId <= 0) {
return;
}
taskEntityLocalCache.evict(taskId);
try {
stringRedisTemplate.delete(buildTaskHeartbeatKey(taskId));
} catch (Exception ex) {
log.warn("[shop-match-cache] delete heartbeat degraded taskId={} msg={}", taskId, ex.getMessage());
}
taskScopePayloadStorageService.deleteTaskScopePayloads(taskId, MODULE_TYPE);
evictTaskCacheOnly(taskId);
taskScopePayloadStorageService.deleteTaskScopePayloads(taskId, moduleType());
try {
Path taskDir = buildTaskDir(taskId);
if (!Files.exists(taskDir)) {
@@ -165,6 +76,7 @@ public class ShopMatchTaskCacheService {
}
}
@Override
public void saveTaskCache(FileTaskEntity task) {
if (task == null || task.getId() == null) {
return;
@@ -183,7 +95,8 @@ public class ShopMatchTaskCacheService {
}
}
public Map<Long, FileTaskEntity> getTaskCacheBatch(java.util.List<Long> taskIds) {
@Override
public Map<Long, FileTaskEntity> getTaskCacheBatch(List<Long> taskIds) {
Map<Long, FileTaskEntity> result = new LinkedHashMap<>();
if (taskIds == null || taskIds.isEmpty()) {
return result;
@@ -240,10 +153,6 @@ public class ShopMatchTaskCacheService {
return buildTaskDir(taskId).resolve("_task-entity.json");
}
private String buildTaskHeartbeatKey(Long taskId) {
return "shop-match:task:heartbeat:" + taskId;
}
/**
* 文件缓存新鲜度判断:超过 {@code localTaskEntityFileCacheMillis} 视为过期。
* 通过文件 mtime 判断,避免在 finalize 与 poll 线程的竞态下把陈旧的 RUNNING 写回后被永久信任。
@@ -4,19 +4,18 @@ import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessCodes;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.config.TaskPressureProperties;
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
import com.nanri.aiimage.modules.productrisk.model.enums.ProductRiskCountryCode;
import com.nanri.aiimage.common.model.vo.ProductRiskDashboardVo;
import com.nanri.aiimage.common.model.vo.ProductRiskHistoryVo;
import com.nanri.aiimage.common.model.vo.ProductRiskResultItemVo;
import com.nanri.aiimage.common.model.vo.ProductRiskShopQueueItemVo;
import com.nanri.aiimage.common.model.vo.ProductRiskTaskBatchVo;
import com.nanri.aiimage.common.model.vo.ProductRiskTaskDetailVo;
import com.nanri.aiimage.common.model.vo.ProductRiskTaskItemVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskDashboardVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskHistoryVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskResultItemVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskShopQueueItemVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskTaskBatchVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskTaskDetailVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskTaskItemVo;
import com.nanri.aiimage.modules.pricetrack.model.vo.SkipPriceAsinPageVo;
import com.nanri.aiimage.modules.queryasin.model.dto.QueryAsinCountryAsinsDto;
import com.nanri.aiimage.modules.shopmatch.mapper.ShopMatchShopCandidateMapper;
@@ -41,6 +40,7 @@ import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
import com.nanri.aiimage.modules.task.service.TaskDistributedLockService;
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
import com.nanri.aiimage.modules.task.service.TaskFinalizeSupport;
import com.nanri.aiimage.modules.task.service.TaskResultPayloadService;
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopSwitchService;
import lombok.RequiredArgsConstructor;
@@ -939,14 +939,7 @@ public class ShopMatchTaskService {
}
private void markResultFailed(FileResultEntity result, String message) {
result.setSuccess(0);
result.setErrorMessage(message);
result.setResultFilename(null);
result.setResultFileUrl(null);
result.setResultFileSize(0L);
result.setRowCount(0);
result.setResultContentType(null);
fileResultMapper.updateById(result);
TaskFinalizeSupport.markResultFailed(fileResultMapper, result, message);
}
private void updateTaskStatusFromLatestRows(FileTaskEntity task, List<FileResultEntity> latest) {
@@ -1040,19 +1033,11 @@ public class ShopMatchTaskService {
}
private TaskDistributedLockService.LockHandle acquireTaskLockOrThrow(Long taskId) {
TaskDistributedLockService.LockHandle lockHandle = acquireTaskLock(taskId);
if (lockHandle == null) {
log.warn("[shop-match] 任务锁竞争,拒绝本次提交 taskId={}", taskId);
throw new BusinessException(BusinessCodes.TASK_BUSY, "任务正在处理中,请稍后再试");
}
return lockHandle;
return TaskFinalizeSupport.acquireTaskLockOrThrow(taskDistributedLockService, MODULE_TYPE, taskId, "shop-match");
}
private TaskDistributedLockService.LockHandle acquireTaskLock(Long taskId) {
if (taskId == null || taskId <= 0) {
return null;
}
return taskDistributedLockService.acquire(MODULE_TYPE, taskId);
return TaskFinalizeSupport.acquireTaskLock(taskDistributedLockService, MODULE_TYPE, taskId);
}
/**
@@ -97,12 +97,10 @@ public class SimilarAsinLlmClient {
: new IllegalStateException(lastFailure.getMessage(), lastFailure);
}
/** 前端 api_key 为空时兜底走服务端配置(工作流里 api_key 为必填项)。 */
/** 只认任务/用户自己的 api_key(payload → 按 uid 的服务端密钥表已在 readApiKey 兜过);
* 为空即空、跳过 LLM,绝不回落平台公费密钥 —— 各用户的任务只能烧各自的密钥。 */
public String resolveApiKey(String apiKey) {
if (apiKey != null && !apiKey.isBlank()) {
return apiKey.trim();
}
return normalize(properties.getLlmApiKey());
return apiKey == null ? "" : apiKey.trim();
}
public boolean hasApiKey(String apiKey) {
@@ -28,7 +28,7 @@ public class SimilarAsinHistoryItemVo {
private String taskStatus;
@Schema(description = "结果是否成功。true 表示任务完成并生成结果文件;false 表示失败或未完成。", example = "true")
private Boolean success;
@Schema(description = "错误信息。任务失败时返回,例如 Python 超时、结果文件生成失败等。", example = "Python interrupted before uploading final similar ASIN result")
@Schema(description = "错误信息。任务失败时返回,例如客户端未回传任何检测结果、结果文件生成失败等。", example = "客户端回传中断,任务已自动结束(已收到 3 个分片,最后一次 10-01 12:34)")
private String error;
@Schema(description = "最终结果行数。包含解析阶段被过滤但最终需要补回的 2_2、2_3 等子行。", example = "716")
private Integer rowCount;
@@ -1,144 +1,20 @@
package com.nanri.aiimage.modules.similarasin.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.modules.similarasin.model.dto.SimilarAsinResultRowDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.nanri.aiimage.modules.task.service.AbstractPendingRowTaskCacheService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
/**
* 相似ASIN 模块任务缓存服务:待处理行队列 + 心跳,通用实现见
* {@link AbstractPendingRowTaskCacheService},本类只声明模块差异。
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class SimilarAsinTaskCacheService {
public class SimilarAsinTaskCacheService extends AbstractPendingRowTaskCacheService<SimilarAsinResultRowDto> {
private static final long TTL_HOURS = 24;
private final StringRedisTemplate stringRedisTemplate;
private final ObjectMapper objectMapper;
public void appendPendingRow(Long taskId, String scopeHash, Integer chunkIndex, SimilarAsinResultRowDto row) {
if (taskId == null || taskId <= 0 || scopeHash == null || scopeHash.isBlank() || chunkIndex == null || row == null) {
return;
}
try {
stringRedisTemplate.opsForList().rightPush(
pendingRowsKey(taskId),
objectMapper.writeValueAsString(new PendingRow(scopeHash, chunkIndex, row))
);
stringRedisTemplate.expire(pendingRowsKey(taskId), Duration.ofHours(TTL_HOURS));
touchTaskHeartbeat(taskId);
} catch (Exception ignored) {
}
}
public long pendingRowCount(Long taskId) {
Long size;
try {
size = stringRedisTemplate.opsForList().size(pendingRowsKey(taskId));
} catch (Exception ex) {
log.warn("[similar-asin-cache] pending row count degraded taskId={} msg={}", taskId, ex.getMessage());
return 0L;
}
return size == null ? 0L : size;
}
public List<PendingRow> drainPendingRows(Long taskId, int limit) {
if (taskId == null || taskId <= 0 || limit <= 0) {
return List.of();
}
String key = pendingRowsKey(taskId);
List<String> values;
try {
values = stringRedisTemplate.opsForList().range(key, 0, limit - 1L);
} catch (Exception ex) {
log.warn("[similar-asin-cache] drain range degraded taskId={} msg={}", taskId, ex.getMessage());
return List.of();
}
if (values == null || values.isEmpty()) {
return List.of();
}
try {
stringRedisTemplate.opsForList().trim(key, values.size(), -1);
} catch (Exception ex) {
log.warn("[similar-asin-cache] drain trim degraded taskId={} msg={}", taskId, ex.getMessage());
return List.of();
}
List<PendingRow> rows = new ArrayList<>();
for (String value : values) {
if (value == null || value.isBlank()) {
continue;
}
try {
rows.add(objectMapper.readValue(value, PendingRow.class));
} catch (Exception ignored) {
}
}
touchTaskHeartbeat(taskId);
return rows;
}
public void touchTaskHeartbeat(Long taskId) {
if (taskId == null || taskId <= 0) {
return;
}
try {
stringRedisTemplate.opsForValue().set(
heartbeatKey(taskId),
String.valueOf(Instant.now().toEpochMilli()),
Duration.ofHours(TTL_HOURS)
);
} catch (Exception ex) {
log.warn("[similar-asin-cache] touch heartbeat degraded taskId={} msg={}", taskId, ex.getMessage());
}
}
public long getTaskHeartbeatMillis(Long taskId) {
if (taskId == null || taskId <= 0) {
return 0L;
}
String raw;
try {
raw = stringRedisTemplate.opsForValue().get(heartbeatKey(taskId));
} catch (Exception ex) {
log.warn("[similar-asin-cache] get heartbeat degraded taskId={} msg={}", taskId, ex.getMessage());
return 0L;
}
if (raw == null || raw.isBlank()) {
return 0L;
}
try {
return Long.parseLong(raw);
} catch (NumberFormatException ignored) {
return 0L;
}
}
public void deleteTaskCache(Long taskId) {
if (taskId == null || taskId <= 0) {
return;
}
try {
stringRedisTemplate.delete(pendingRowsKey(taskId));
stringRedisTemplate.delete(heartbeatKey(taskId));
} catch (Exception ex) {
log.warn("[similar-asin-cache] delete degraded taskId={} msg={}", taskId, ex.getMessage());
}
}
private String pendingRowsKey(Long taskId) {
return "similar-asin:task:pending-rows:" + taskId;
}
private String heartbeatKey(Long taskId) {
return "similar-asin:task:heartbeat:" + taskId;
}
public record PendingRow(String scopeHash, Integer chunkIndex, SimilarAsinResultRowDto row) {
public SimilarAsinTaskCacheService(StringRedisTemplate stringRedisTemplate,
ObjectMapper objectMapper) {
super("similar-asin", SimilarAsinResultRowDto.class, stringRedisTemplate, objectMapper);
}
}
@@ -13,6 +13,7 @@ import com.nanri.aiimage.common.exception.TaskOwnerMismatchException;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.service.DistributedJobLockService;
import com.nanri.aiimage.common.util.FailedStatusRowFilter;
import com.nanri.aiimage.common.util.StaleTaskDeathReason;
import com.nanri.aiimage.config.InstanceMetadata;
import com.nanri.aiimage.config.SimilarAsinProperties;
import com.nanri.aiimage.config.StorageProperties;
@@ -94,6 +95,7 @@ import org.springframework.transaction.support.TransactionTemplate;
import java.io.File;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.nio.charset.StandardCharsets;
@@ -867,7 +869,7 @@ public class SimilarAsinTaskService implements SimilarAsinPipelineHost {
continue;
}
try (taskLockHandle) {
finalizeStaleTask(task.getId(), "Python interrupted before uploading final similar ASIN result");
finalizeStaleTask(task.getId(), describeStaleDeath(task.getId()));
}
}
finalizeNoUploadStaleTasks();
@@ -882,10 +884,44 @@ public class SimilarAsinTaskService implements SimilarAsinPipelineHost {
return;
}
try (taskLockHandle) {
finalizeStaleTask(taskId, "Python interrupted before uploading final similar ASIN result");
finalizeStaleTask(taskId, describeStaleDeath(taskId));
}
}
/**
* 判死文案按证据分述:客户端从未回传(多半是排队等槽位)、回传中断、还是文件生成侧失败。
* 与 {@code AppearancePatentTaskService#describeStaleDeath} 同型,共用
* {@link StaleTaskDeathReason} 的措辞。
*/
private String describeStaleDeath(Long taskId) {
long heartbeatMillis = taskCacheService.getTaskHeartbeatMillis(taskId);
return new StaleTaskDeathReason(
persistedResultChunkCount(taskId),
lastResultChunkAt(taskId),
heartbeatMillis > 0L
? LocalDateTime.ofInstant(Instant.ofEpochMilli(heartbeatMillis), ZoneId.systemDefault())
: null,
taskHeartbeatPositionService.describe(taskId),
taskFileJobService.hasExhaustedAssembleJob(taskId, MODULE_TYPE),
properties.getStaleTimeoutMinutes()).describe();
}
private long persistedResultChunkCount(Long taskId) {
if (taskId == null) {
return 0L;
}
Long count = taskChunkMapper.selectCount(new LambdaQueryWrapper<TaskChunkEntity>()
.eq(TaskChunkEntity::getTaskId, taskId)
.eq(TaskChunkEntity::getModuleType, MODULE_TYPE));
return count == null ? 0L : count;
}
/** 最后一次结果分片回传时间;从未回传时为 null。 */
private LocalDateTime lastResultChunkAt(Long taskId) {
List<TaskScopeLastChunkDto> rows = taskScopeStateMapper.selectLastChunkAtByTaskIds(List.of(taskId));
return rows == null || rows.isEmpty() ? null : rows.get(0).lastChunkAt();
}
private List<FileTaskEntity> listStaleFinalizeCandidates() {
// P1-7:不再用 file_task.updated_at 预过滤,由调用方按 Redis heartbeat 判 stale。
// SIMILAR_ASIN 在线 RUNNING 任务量级有限(限 200),全扫成本可忽略。
@@ -0,0 +1,282 @@
package com.nanri.aiimage.modules.task.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.util.TaskEntityLocalCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 业务模块「任务缓存服务」泛型基类:心跳键 + 任务实体缓存(本地 LRU + Redis)+ 店铺维度载荷存取。
*
* <p><b>新增任务模块请继承本类,不要复制粘贴再改前缀。</b>各模块此前是逐行复制的
* XxxTaskCacheService(约 200 行 × N 份),除以下三点外完全一致,现统一收敛到这里:
* <ul>
* <li>{@code moduleType}:店铺维度载荷在 task_scope 存储里的隔离键;</li>
* <li>{@code keyPrefix}:Redis 键前缀(心跳 {@code <keyPrefix>:task:heartbeat:*}、
* 实体 {@code <keyPrefix>:task:entity:*})与降级日志标签 {@code [<keyPrefix>-cache]};</li>
* <li>{@code payloadType}:店铺合并载荷的具体类型。必须传 {@code Class<T>},
* 不能用 {@code (Class<T>) T.class} 之类的擦除技巧,否则 JSON 反序列化会得到 LinkedHashMap。</li>
* </ul>
*
* <p>子类只需提供构造器把三个差异常量传给 {@code super};模块独有的缓存形态
* (如 ShopMatch 的文件实体缓存、PatrolDelete 的分段清理)在子类覆写对应方法即可。
* 公共实现统一为「taskId 非法直接返回」的守卫版:此前个别模块的 touch/delete 缺守卫,
* 但全量调用方传入的都是已校验的任务 id,且被跳过的底层操作本身也有 null 守卫,行为等价。
*
* @param <T> 该模块店铺维度合并载荷的类型(taskScopePayloadStorageService 的反序列化目标)
*/
@Slf4j
public abstract class AbstractModuleTaskCacheService<T> {
/** 心跳与任务实体缓存的 Redis TTL(与历史各模块实现一致的 24 小时)。 */
private static final long PAYLOAD_TTL_HOURS = 24;
private final String moduleType;
private final String keyPrefix;
private final Class<T> payloadType;
private final String logTag;
protected final StringRedisTemplate stringRedisTemplate;
protected final ObjectMapper objectMapper;
protected final TaskScopePayloadStorageService taskScopePayloadStorageService;
protected final TaskEntityLocalCache taskEntityLocalCache;
protected AbstractModuleTaskCacheService(String moduleType,
String keyPrefix,
Class<T> payloadType,
StringRedisTemplate stringRedisTemplate,
ObjectMapper objectMapper,
TaskScopePayloadStorageService taskScopePayloadStorageService,
TaskEntityLocalCache taskEntityLocalCache) {
this.moduleType = moduleType;
this.keyPrefix = keyPrefix;
this.payloadType = payloadType;
this.logTag = keyPrefix + "-cache";
this.stringRedisTemplate = stringRedisTemplate;
this.objectMapper = objectMapper;
this.taskScopePayloadStorageService = taskScopePayloadStorageService;
this.taskEntityLocalCache = taskEntityLocalCache;
}
// ------------------------------------------------------------------
// 心跳
// ------------------------------------------------------------------
public void touchTaskHeartbeat(Long taskId) {
if (taskId == null || taskId <= 0) {
return;
}
try {
stringRedisTemplate.opsForValue().set(
buildTaskHeartbeatKey(taskId),
String.valueOf(Instant.now().toEpochMilli()),
Duration.ofHours(PAYLOAD_TTL_HOURS));
} catch (Exception ex) {
log.warn("[{}] touch heartbeat degraded taskId={} msg={}", logTag, taskId, ex.getMessage());
}
}
public long getTaskHeartbeatMillis(Long taskId) {
if (taskId == null || taskId <= 0) {
return 0L;
}
String raw;
try {
raw = stringRedisTemplate.opsForValue().get(buildTaskHeartbeatKey(taskId));
} catch (Exception ex) {
log.warn("[{}] get heartbeat degraded taskId={} msg={}", logTag, taskId, ex.getMessage());
return 0L;
}
if (raw == null || raw.isBlank()) {
return 0L;
}
try {
return Long.parseLong(raw);
} catch (NumberFormatException ignored) {
return 0L;
}
}
public Map<Long, Long> getTaskHeartbeatMillisBatch(List<Long> taskIds) {
Map<Long, Long> result = new LinkedHashMap<>();
if (taskIds == null || taskIds.isEmpty()) {
return result;
}
List<Long> normalized = taskIds.stream()
.filter(id -> id != null && id > 0)
.distinct()
.toList();
if (normalized.isEmpty()) {
return result;
}
List<String> keys = normalized.stream().map(this::buildTaskHeartbeatKey).toList();
List<String> values;
try {
values = stringRedisTemplate.opsForValue().multiGet(keys);
} catch (Exception ex) {
log.warn("[{}] batch get heartbeat degraded taskIds={} msg={}", logTag, normalized, ex.getMessage());
return result;
}
for (int i = 0; i < normalized.size(); i++) {
String raw = values != null && i < values.size() ? values.get(i) : null;
if (raw == null || raw.isBlank()) {
result.put(normalized.get(i), 0L);
continue;
}
try {
result.put(normalized.get(i), Long.parseLong(raw));
} catch (NumberFormatException ignored) {
result.put(normalized.get(i), 0L);
}
}
return result;
}
// ------------------------------------------------------------------
// 店铺维度合并载荷
// ------------------------------------------------------------------
public T getShopMergedPayload(Long taskId, String shopKey) {
return taskScopePayloadStorageService.getScopePayload(taskId, moduleType, shopKey, payloadType);
}
public void saveShopMergedPayload(Long taskId, String shopKey, T payload) {
if (taskId == null || taskId <= 0 || shopKey == null || shopKey.isBlank() || payload == null) {
return;
}
taskScopePayloadStorageService.saveScopePayload(taskId, moduleType, shopKey, payload);
touchTaskHeartbeat(taskId);
}
public void removeShopMergedPayload(Long taskId, String shopKey) {
taskScopePayloadStorageService.removeScopePayload(taskId, moduleType, shopKey);
}
public Map<String, T> getAllShopMergedPayload(Long taskId) {
return taskScopePayloadStorageService.getAllScopePayload(taskId, moduleType, payloadType);
}
public boolean hasAnyShopMergedPayload(Long taskId) {
return taskScopePayloadStorageService.hasAnyScopePayload(taskId, moduleType);
}
public long countShopMergedPayload(Long taskId) {
return taskScopePayloadStorageService.countScopePayload(taskId, moduleType);
}
// ------------------------------------------------------------------
// 任务实体缓存(本地 LRU + Redis)
// ------------------------------------------------------------------
/**
* 只清理心跳/实体缓存,不动店铺维度载荷。删除整任务用 {@link #deleteTaskCache(Long)}。
*/
public void evictTaskCacheOnly(Long taskId) {
if (taskId == null || taskId <= 0) {
return;
}
taskEntityLocalCache.evict(taskId);
try {
stringRedisTemplate.delete(buildTaskHeartbeatKey(taskId));
stringRedisTemplate.delete(buildTaskEntityKey(taskId));
} catch (Exception ex) {
log.warn("[{}] delete cache degraded taskId={} msg={}", logTag, taskId, ex.getMessage());
}
}
public void deleteTaskCache(Long taskId) {
if (taskId == null || taskId <= 0) {
return;
}
evictTaskCacheOnly(taskId);
taskScopePayloadStorageService.deleteTaskScopePayloads(taskId, moduleType);
}
public void saveTaskCache(FileTaskEntity task) {
if (task == null || task.getId() == null) {
return;
}
taskEntityLocalCache.put(task.getId(), task);
try {
stringRedisTemplate.opsForValue().set(
buildTaskEntityKey(task.getId()),
objectMapper.writeValueAsString(task),
Duration.ofHours(PAYLOAD_TTL_HOURS)
);
} catch (Exception ignored) {
}
}
public Map<Long, FileTaskEntity> getTaskCacheBatch(List<Long> taskIds) {
Map<Long, FileTaskEntity> result = new LinkedHashMap<>();
if (taskIds == null || taskIds.isEmpty()) {
return result;
}
List<Long> normalized = taskIds.stream()
.filter(id -> id != null && id > 0)
.distinct()
.toList();
if (normalized.isEmpty()) {
return result;
}
long now = System.currentTimeMillis();
List<Long> missingIds = new ArrayList<>();
for (Long taskId : normalized) {
TaskEntityLocalCache.Entry cached = taskEntityLocalCache.get(taskId, now);
if (cached != null) {
result.put(taskId, cached.task());
} else {
missingIds.add(taskId);
}
}
if (missingIds.isEmpty()) {
return result;
}
List<String> keys = missingIds.stream().map(this::buildTaskEntityKey).toList();
List<String> values;
try {
values = stringRedisTemplate.opsForValue().multiGet(keys);
} catch (Exception ex) {
log.warn("[{}] batch get task cache degraded taskIds={} msg={}", logTag, missingIds, ex.getMessage());
return result;
}
for (int i = 0; i < missingIds.size(); i++) {
Long taskId = missingIds.get(i);
String val = values != null && i < values.size() ? values.get(i) : null;
if (val == null || val.isBlank()) {
continue;
}
try {
FileTaskEntity task = objectMapper.readValue(val, FileTaskEntity.class);
result.put(taskId, task);
taskEntityLocalCache.put(taskId, task);
} catch (Exception ignored) {
}
}
return result;
}
// ------------------------------------------------------------------
// 键构造(子类如需自定义键形可覆写)
// ------------------------------------------------------------------
protected String moduleType() {
return moduleType;
}
protected String buildTaskHeartbeatKey(Long taskId) {
return keyPrefix + ":task:heartbeat:" + taskId;
}
protected String buildTaskEntityKey(Long taskId) {
return keyPrefix + ":task:entity:" + taskId;
}
}
@@ -0,0 +1,182 @@
package com.nanri.aiimage.modules.task.service;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
/**
* 「待处理行」型任务缓存服务泛型基类:Redis list 暂存待 LLM 检测的行 + 心跳键。
*
* <p><b>新增同类任务模块请继承本类,不要复制粘贴再改前缀。</b>此类形态与
* {@link AbstractModuleTaskCacheService}(心跳 + 实体缓存 + 店铺维度载荷)不同:
* 它没有任务实体缓存,也没有按店铺聚合的载荷,只有按任务组织的「待处理行」队列
* (此前 AppearancePatentTaskCacheService / SimilarAsinTaskCacheService 逐行复制)。
* 模块级差异只有三点:
* <ul>
* <li>{@code keyPrefix}:Redis 键前缀({@code <keyPrefix>:task:pending-rows:*}、
* {@code <keyPrefix>:task:heartbeat:*})与降级日志标签 {@code [<keyPrefix>-cache]};</li>
* <li>{@code rowType}:行 DTO 的具体类型。必须传 {@code Class<R>}——Redis list 里每条
* JSON 反序列化目标形如 {@code PendingRow<R>},泛型擦除后必须显式给出行类型,
* 否则 row 字段会退化成 LinkedHashMap;</li>
* <li>任务级附加键:子类覆写 {@link #deleteExtraTaskCacheKeys(Long)} 清理自己的行级标记键。</li>
* </ul>
*
* @param <R> 待处理行 DTO 类型
*/
@Slf4j
public abstract class AbstractPendingRowTaskCacheService<R> {
/** Redis list 中一条待处理行:所属店铺、来源分块、行内容。 */
public record PendingRow<ROW>(String scopeHash, Integer chunkIndex, ROW row) {
}
/** pending-rows list、心跳与完成标记的 Redis TTL(与历史实现一致的 24 小时)。 */
private static final long TTL_HOURS = 24;
protected final StringRedisTemplate stringRedisTemplate;
protected final ObjectMapper objectMapper;
private final String keyPrefix;
private final String logTag;
private final JavaType pendingRowJavaType;
protected AbstractPendingRowTaskCacheService(String keyPrefix,
Class<R> rowType,
StringRedisTemplate stringRedisTemplate,
ObjectMapper objectMapper) {
this.keyPrefix = keyPrefix;
this.logTag = keyPrefix + "-cache";
this.pendingRowJavaType = objectMapper.getTypeFactory()
.constructParametricType(PendingRow.class, rowType);
this.stringRedisTemplate = stringRedisTemplate;
this.objectMapper = objectMapper;
}
public void appendPendingRow(Long taskId, String scopeHash, Integer chunkIndex, R row) {
if (taskId == null || taskId <= 0 || scopeHash == null || scopeHash.isBlank() || chunkIndex == null || row == null) {
return;
}
try {
stringRedisTemplate.opsForList().rightPush(
pendingRowsKey(taskId),
objectMapper.writeValueAsString(new PendingRow<>(scopeHash, chunkIndex, row))
);
stringRedisTemplate.expire(pendingRowsKey(taskId), Duration.ofHours(TTL_HOURS));
touchTaskHeartbeat(taskId);
} catch (Exception ignored) {
}
}
public long pendingRowCount(Long taskId) {
Long size;
try {
size = stringRedisTemplate.opsForList().size(pendingRowsKey(taskId));
} catch (Exception ex) {
log.warn("[{}] pending row count degraded taskId={} msg={}", logTag, taskId, ex.getMessage());
return 0L;
}
return size == null ? 0L : size;
}
public List<PendingRow<R>> drainPendingRows(Long taskId, int limit) {
if (taskId == null || taskId <= 0 || limit <= 0) {
return List.of();
}
String key = pendingRowsKey(taskId);
List<String> values;
try {
values = stringRedisTemplate.opsForList().range(key, 0, limit - 1L);
} catch (Exception ex) {
log.warn("[{}] drain range degraded taskId={} msg={}", logTag, taskId, ex.getMessage());
return List.of();
}
if (values == null || values.isEmpty()) {
return List.of();
}
try {
stringRedisTemplate.opsForList().trim(key, values.size(), -1);
} catch (Exception ex) {
log.warn("[{}] drain trim degraded taskId={} msg={}", logTag, taskId, ex.getMessage());
return List.of();
}
List<PendingRow<R>> rows = new ArrayList<>();
for (String value : values) {
if (value == null || value.isBlank()) {
continue;
}
try {
rows.add(objectMapper.readValue(value, pendingRowJavaType));
} catch (Exception ignored) {
}
}
touchTaskHeartbeat(taskId);
return rows;
}
public void touchTaskHeartbeat(Long taskId) {
if (taskId == null || taskId <= 0) {
return;
}
try {
stringRedisTemplate.opsForValue().set(
heartbeatKey(taskId),
String.valueOf(Instant.now().toEpochMilli()),
Duration.ofHours(TTL_HOURS)
);
} catch (Exception ex) {
log.warn("[{}] touch heartbeat degraded taskId={} msg={}", logTag, taskId, ex.getMessage());
}
}
public long getTaskHeartbeatMillis(Long taskId) {
if (taskId == null || taskId <= 0) {
return 0L;
}
String raw;
try {
raw = stringRedisTemplate.opsForValue().get(heartbeatKey(taskId));
} catch (Exception ex) {
log.warn("[{}] get heartbeat degraded taskId={} msg={}", logTag, taskId, ex.getMessage());
return 0L;
}
if (raw == null || raw.isBlank()) {
return 0L;
}
try {
return Long.parseLong(raw);
} catch (NumberFormatException ignored) {
return 0L;
}
}
public void deleteTaskCache(Long taskId) {
if (taskId == null || taskId <= 0) {
return;
}
try {
stringRedisTemplate.delete(pendingRowsKey(taskId));
stringRedisTemplate.delete(heartbeatKey(taskId));
deleteExtraTaskCacheKeys(taskId);
} catch (Exception ex) {
log.warn("[{}] delete degraded taskId={} msg={}", logTag, taskId, ex.getMessage());
}
}
/** 任务级附加键清理钩子(如外观专利的行级完成标记),默认无。 */
protected void deleteExtraTaskCacheKeys(Long taskId) {
}
protected String pendingRowsKey(Long taskId) {
return keyPrefix + ":task:pending-rows:" + taskId;
}
protected String heartbeatKey(Long taskId) {
return keyPrefix + ":task:heartbeat:" + taskId;
}
}
@@ -0,0 +1,190 @@
package com.nanri.aiimage.modules.task.service;
import com.nanri.aiimage.common.exception.BusinessCodes;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.config.TaskPressureProperties;
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.model.entity.FileResultEntity;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
/**
* 业务模块 *TaskService 收尾/执行骨架的公共零件(无状态静态工具):
* 任务实体加载(模块缓存优先、DB 兜底)、分批任务加载、结果行失败落库、任务分布式锁获取。
*
* <p>此前这些零件在 8 个业务模块的 *TaskService 里逐行同构复制(loadTaskForExecution /
* loadTaskMapByIds / markResultFailed / acquireTaskLock / acquireTaskLockOrThrow /
* selectTasksByIdsInBatches),差异点只有三类,均已参数化:
* <ul>
* <li>模块标识 {@code moduleType}(数据隔离与锁键);</li>
* <li>模块任务缓存服务 {@link AbstractModuleTaskCacheService};</li>
* <li>锁竞争日志标签 {@code logTag}(如 {@code [price-track]})。</li>
* </ul>
*
* <p>已知的非同构变体不强制收敛,调用方保留本地实现:
* PriceTrack 的 loadTaskForExecution 要求缓存行 requestJson 非空(用带 Predicate 的重载);
* ShopMatch 的 loadTaskMapByIds 带缓存/DB 新旧复活防护且缓存 RUNNING+SCHEDULED;
* Withdraw 的 loadTaskMapByIds 先按 {@code limit(50)} 归一化任务 id(本地先归一化再传入即可);
* Brand/AppearancePatent/CollectData/DeleteBrand 等的锁方法带自定义 TTL、等待或日志语义。
*
* <p>依赖仅限 task 模块内部(mapper/entity/锁服务)与 config 包(TaskPressureProperties),
* 不触碰任何业务模块,符合 ArchUnit 边界(task→业务 依赖保持为 0)。
*/
@Slf4j
public final class TaskFinalizeSupport {
private TaskFinalizeSupport() {
}
// ------------------------------------------------------------------
// 任务实体加载(执行前)
// ------------------------------------------------------------------
/** 标准变体:模块缓存命中即直接返回,否则读 DB 并按 moduleType 匹配回填缓存。 */
public static FileTaskEntity loadTaskForExecution(FileTaskMapper fileTaskMapper,
AbstractModuleTaskCacheService<?> cacheService,
String moduleType,
Long taskId) {
return loadTaskForExecution(fileTaskMapper, cacheService, moduleType, taskId, cached -> cached != null);
}
/**
* 带「缓存行可用性」判定的变体:缓存命中但 cachedUsable 判定不可用(如 requestJson 为空)
* 时继续走 DB。cachedUsable 收到的入参可能为 null。
*/
public static FileTaskEntity loadTaskForExecution(FileTaskMapper fileTaskMapper,
AbstractModuleTaskCacheService<?> cacheService,
String moduleType,
Long taskId,
Predicate<FileTaskEntity> cachedUsable) {
Map<Long, FileTaskEntity> cachedTasks = cacheService.getTaskCacheBatch(List.of(taskId));
FileTaskEntity cached = cachedTasks.get(taskId);
if (cachedUsable.test(cached)) {
return cached;
}
FileTaskEntity dbTask = fileTaskMapper.selectById(taskId);
if (dbTask != null && moduleType.equals(dbTask.getModuleType())) {
cacheService.saveTaskCache(dbTask);
}
return dbTask;
}
// ------------------------------------------------------------------
// 批量任务加载
// ------------------------------------------------------------------
/** 标准变体:归一化任务 id → 缓存批量查 → 缺失的按批读 DB(moduleType 匹配),RUNNING 行回填缓存。 */
public static Map<Long, FileTaskEntity> loadTaskMapByIds(FileTaskMapper fileTaskMapper,
TaskPressureProperties taskPressureProperties,
AbstractModuleTaskCacheService<?> cacheService,
String moduleType,
List<Long> taskIds) {
Map<Long, FileTaskEntity> result = new LinkedHashMap<>();
List<Long> normalizedTaskIds = taskIds == null ? List.of() : taskIds.stream()
.filter(taskId -> taskId != null && taskId > 0)
.distinct()
.toList();
if (normalizedTaskIds.isEmpty()) {
return result;
}
Map<Long, FileTaskEntity> cachedTasks = cacheService.getTaskCacheBatch(normalizedTaskIds);
result.putAll(cachedTasks);
List<Long> missingTaskIds = normalizedTaskIds.stream()
.filter(taskId -> !cachedTasks.containsKey(taskId))
.toList();
for (FileTaskEntity dbTask : selectTasksByIdsInBatches(fileTaskMapper, taskPressureProperties, missingTaskIds)) {
if (dbTask == null || !moduleType.equals(dbTask.getModuleType())) {
continue;
}
result.put(dbTask.getId(), dbTask);
if ("RUNNING".equals(dbTask.getStatus())) {
cacheService.saveTaskCache(dbTask);
}
}
return result;
}
/** 按任务压力配置的批量大小分批 selectBatchIds(各模块历史实现逐行一致)。 */
public static List<FileTaskEntity> selectTasksByIdsInBatches(FileTaskMapper fileTaskMapper,
TaskPressureProperties taskPressureProperties,
List<Long> taskIds) {
List<FileTaskEntity> tasks = new ArrayList<>();
if (taskIds == null || taskIds.isEmpty()) {
return tasks;
}
int batchSize = Math.max(1, taskPressureProperties.getDbSelectBatchSize());
for (int start = 0; start < taskIds.size(); start += batchSize) {
int end = Math.min(start + batchSize, taskIds.size());
tasks.addAll(fileTaskMapper.selectBatchIds(taskIds.subList(start, end)));
}
return tasks;
}
// ------------------------------------------------------------------
// 结果行失败落库
// ------------------------------------------------------------------
/**
* 结果行置为失败并清空文件字段后落库(success=0、rowSize=0、文件名/URL/ContentType 置空)。
* errorMessage 原样写入;历史上先把空串归一化为 null 的模块(PatrolDelete/ShopDataCrawl/
* QueryAsin/Withdraw)在调用前自行 {@code blankToNull(message)},保持原行为。
*/
public static void markResultFailed(FileResultMapper fileResultMapper, FileResultEntity row, String message) {
row.setSuccess(0);
row.setErrorMessage(message);
row.setResultFilename(null);
row.setResultFileUrl(null);
row.setResultFileSize(0L);
row.setRowCount(0);
row.setResultContentType(null);
fileResultMapper.updateById(row);
}
// ------------------------------------------------------------------
// 任务分布式锁
// ------------------------------------------------------------------
/** 标准变体:taskId 非法返回 null;否则按模块标识获取锁(默认等待时长)。 */
public static TaskDistributedLockService.LockHandle acquireTaskLock(TaskDistributedLockService taskDistributedLockService,
String moduleType,
Long taskId) {
if (taskId == null || taskId <= 0) {
return null;
}
return taskDistributedLockService.acquire(moduleType, taskId);
}
/** 带 waitMillis 的变体(ShopDataCrawl 等使用)。 */
public static TaskDistributedLockService.LockHandle acquireTaskLock(TaskDistributedLockService taskDistributedLockService,
String moduleType,
Long taskId,
long waitMillis) {
if (taskId == null || taskId <= 0) {
return null;
}
return taskDistributedLockService.acquire(moduleType, taskId, waitMillis);
}
/**
* 锁竞争即拒绝提交并抛 TASK_BUSY(提交路径用)。logTag 传模块标签(如 {@code price-track}),
* 仅用于 warn 日志文案,不影响行为。
*/
public static TaskDistributedLockService.LockHandle acquireTaskLockOrThrow(TaskDistributedLockService taskDistributedLockService,
String moduleType,
Long taskId,
String logTag) {
TaskDistributedLockService.LockHandle lockHandle = acquireTaskLock(taskDistributedLockService, moduleType, taskId);
if (lockHandle == null) {
log.warn("[{}] 任务锁竞争,拒绝本次提交 taskId={}", logTag, taskId);
throw new BusinessException(BusinessCodes.TASK_BUSY, "任务正在处理中,请稍后再试");
}
return lockHandle;
}
}
@@ -114,6 +114,7 @@ public class AdminUserApiSecretController {
userSecretProperties.getCheckMaxRows(), userSecretProperties.getCheckBudgetMinutes());
return ApiResponse.success("巡检完成", Map.of(
"checked", summary.checked(),
"probed", summary.probed(),
"passed", summary.passed(),
"failed", summary.failed(),
"errors", summary.errors(),
@@ -11,9 +11,9 @@ import java.time.Duration;
/**
* 用户密钥连通性巡检:默认每隔一天 04:30(Asia/Shanghai)跑一轮
* (代理模块每次巡检真实提取一次,按次计费;2026-09-14 成本审查后由
* 每日降为隔日),双实例经 Redis 分布式锁互斥;单轮受条数与时间预算
* 约束,超出顺延下一轮。
* (代理模块每次探测都是真实提取、按次计费,故同一把密钥被多个账号配置时一轮只探测一次;
* 2026-09-14 成本审查后巡检频次由每日降为隔日),双实例经 Redis 分布式锁互斥;
* 单轮受条数与时间预算约束,超出顺延下一轮。
*/
@Service
@Slf4j
@@ -42,8 +42,9 @@ public class UserApiSecretCheckScheduler {
properties.getCheckMaxRows(), properties.getCheckBudgetMinutes());
UserApiSecretService.CheckSummary summary = userApiSecretService.checkAllForScheduler(
properties.getCheckMaxRows(), properties.getCheckBudgetMinutes());
log.info("[user-secret] 每日巡检完成 checked={} passed={} failed={} errors={} skipped={}",
summary.checked(), summary.passed(), summary.failed(), summary.errors(), summary.skipped());
log.info("[user-secret] 每日巡检完成 checked={} probed={} passed={} failed={} errors={} skipped={}",
summary.checked(), summary.probed(), summary.passed(), summary.failed(),
summary.errors(), summary.skipped());
} catch (Exception ex) {
log.warn("[user-secret] 每日巡检异常终止 err={}", ex.getMessage(), ex);
}
@@ -282,14 +282,14 @@ public class UserApiSecretService implements UserSecretCleanupPort {
} else if (module == UserSecretModule.PROXY) {
validateProxyValue(plainKey);
}
UserApiSecretCheckService.CheckOutcome outcome = reuseFreshOutcome(userId, module, plainKey);
UserApiSecretCheckService.CheckOutcome outcome = reuseFreshOutcome(module, plainKey);
if (outcome != null) {
log.info("[user-secret] 新鲜期内重复检测相同配置,复用上次结果(代理按次计费,避免连点重复提取)userId={} module={}",
userId, module.key());
} else {
outcome = checkService.probe(module, plainKey);
if (UserApiSecretCheckService.STATUS_PASSED.equals(outcome.status())) {
rememberFreshOutcome(userId, module, plainKey, outcome);
rememberFreshOutcome(module, plainKey, outcome);
}
}
UserApiSecretCheckResultVo vo = toCheckResult(module, outcome);
@@ -522,17 +522,24 @@ public class UserApiSecretService implements UserSecretCleanupPort {
}
/**
* 定时巡检:遍历全部密钥逐条探测并更新状态。
* 单轮受 maxRows 与时间预算约束,超出部分顺延下一轮;单条异常不影响整轮。
* 定时巡检:按「模块 + 密文」分组探测,同一把密钥被多个账号配置时一轮只真实探测一次,
* 结论回写组内全部配置行。代理探测每次都是真实提取(按次计费)、LLM 检测每次都在烧用户额度,
* 逐账号重复探测同一把密钥纯属浪费(2026-10-01 实测:314 条配置实为 33 种密钥)。
* 单轮受 maxRows(按配置行计)与时间预算约束,超出部分顺延下一轮;单条异常不影响整轮。
*/
public CheckSummary checkAllForScheduler(int maxRows, int budgetMinutes) {
long deadline = System.currentTimeMillis() + Duration.ofMinutes(Math.max(1, budgetMinutes)).toMillis();
int checked = 0;
int probed = 0;
int passed = 0;
int failed = 0;
int errors = 0;
int skipped = 0;
int notifySent = 0;
// 密文可作分组键的前提:ShopCredentialCryptoService 用 AES/ECB 无 IV,同明文必同密文
Map<String, UserApiSecretCheckService.CheckOutcome> outcomeBySecret = new HashMap<>();
// 管理员告警按密钥分组收敛:一把 key 挂了,组内 N 个账号只推一条(用户侧仍逐账号通知)
Map<String, SecretAlertGroup> adminAlertGroups = new LinkedHashMap<>();
// 管理员受众整轮复用:轮内管理员/分组几乎不变,避免每条异常都重新解析
NotificationDispatchService.AdminAudience adminAudience =
userSecretProperties.isNotifyEnabled() ? notificationDispatchService.prepareAdminAudience() : null;
@@ -557,20 +564,25 @@ public class UserApiSecretService implements UserSecretCleanupPort {
continue;
}
try {
UserApiSecretCheckService.CheckOutcome outcome;
String plainKey = normalize(cryptoService.decrypt(row.getSecretValue()));
if (plainKey.isEmpty()) {
outcome = new UserApiSecretCheckService.CheckOutcome(
UserApiSecretCheckService.STATUS_FAILED,
UserApiSecretCheckService.CODE_INVALID_KEY,
"配置内容为空,请重新配置", null, false);
} else {
outcome = checkService.probe(module.get(), plainKey);
String groupKey = inspectionGroupKey(row);
UserApiSecretCheckService.CheckOutcome outcome = outcomeBySecret.get(groupKey);
if (outcome == null) {
String plainKey = normalize(cryptoService.decrypt(row.getSecretValue()));
outcome = plainKey.isEmpty()
? new UserApiSecretCheckService.CheckOutcome(
UserApiSecretCheckService.STATUS_FAILED,
UserApiSecretCheckService.CODE_INVALID_KEY,
"配置内容为空,请重新配置", null, false)
: checkService.probe(module.get(), plainKey);
outcomeBySecret.put(groupKey, outcome);
probed++;
sleepQuietly(200L);
}
applyCheckOutcome(row.getUserId(), module.get().key(), outcome);
checked++;
if (adminAudience != null) {
notifySent += notifySecretAlert(adminAudience, row.getUserId(), module.get(), outcome);
notifySent += notifySecretUserAlert(row.getUserId(), module.get(), outcome);
collectAdminAlert(adminAlertGroups, groupKey, row.getUserId(), module.get(), outcome);
}
if (UserApiSecretCheckService.STATUS_PASSED.equals(outcome.status())) {
passed++;
@@ -584,7 +596,6 @@ public class UserApiSecretService implements UserSecretCleanupPort {
log.warn("[user-secret] 巡检单条失败 id={} userId={} module={} err={}",
row.getId(), row.getUserId(), row.getModuleKey(), ex.getMessage());
}
sleepQuietly(200L);
}
if (checked >= maxRows || System.currentTimeMillis() >= deadline) {
Long remaining = userApiSecretMapper.selectCount(new LambdaQueryWrapper<UserApiSecretEntity>()
@@ -593,12 +604,21 @@ public class UserApiSecretService implements UserSecretCleanupPort {
break;
}
}
CheckSummary summary = new CheckSummary(checked, passed, failed, errors, skipped);
log.info("[user-secret] 巡检结束 checked={} passed={} failed={} errors={} skipped={} 通知={}",
summary.checked(), summary.passed(), summary.failed(), summary.errors(), summary.skipped(), notifySent);
int adminNotifySent = dispatchAdminAlerts(adminAudience, adminAlertGroups);
CheckSummary summary = new CheckSummary(checked, probed, passed, failed, errors, skipped);
log.info("[user-secret] 巡检结束 checked={} 真实探测={} 复用={} passed={} failed={} errors={} skipped={} "
+ "用户通知={} 管理员告警组={} 管理员通知={}",
summary.checked(), summary.probed(), summary.checked() - summary.probed(),
summary.passed(), summary.failed(), summary.errors(), summary.skipped(),
notifySent, adminAlertGroups.size(), adminNotifySent);
return summary;
}
/** 巡检分组键:同模块 + 同密文视为同一把密钥。密文确定性加密,无需解密即可分组。 */
private String inspectionGroupKey(UserApiSecretEntity row) {
return row.getModuleKey() + '|' + row.getSecretValue();
}
/**
* 巡检告警判定:欠费(insufficient_balance)→ error 级 secret_balance;
* 密钥无效/被拒(invalid_key/forbidden)→ warning 级 secret_invalid;
@@ -619,10 +639,12 @@ public class UserApiSecretService implements UserSecretCleanupPort {
return null;
}
/** 巡检发现欠费/失效:推用户通知 + 按数据权限推管理员通知;同一模块每天最多各一条。返回落库条数。 */
private int notifySecretAlert(NotificationDispatchService.AdminAudience adminAudience,
Long userId, UserSecretModule module,
UserApiSecretCheckService.CheckOutcome outcome) {
/**
* 巡检发现欠费/失效:推该账号的用户通知(同一模块每天最多一条)。
* 管理员侧不在此逐条推,由 {@link #collectAdminAlert} + {@link #dispatchAdminAlerts} 按密钥合并后一次发。
*/
private int notifySecretUserAlert(Long userId, UserSecretModule module,
UserApiSecretCheckService.CheckOutcome outcome) {
SecretAlertDecision decision = decideSecretAlert(outcome);
if (decision == null) {
return 0;
@@ -639,19 +661,80 @@ public class UserApiSecretService implements UserSecretCleanupPort {
int pushed = notificationDispatchService.pushToUser(userId, decision.scene(), decision.level(),
userTitle, userContent,
decision.scene() + ":" + userId + ":" + module.key() + ":" + day) ? 1 : 0;
String username = notificationDispatchService.displayNameOf(userId);
String adminContent = "用户 " + username + "(uid=" + userId + ")的" + moduleLabel
+ (balance ? "对应服务商余额不足" : "检测失败")
+ (reason.isEmpty() ? "" : ":" + reason);
pushed += notificationDispatchService.pushToAdmins(adminAudience, decision.scene(), decision.level(),
"用户密钥异常:" + username, adminContent,
decision.scene() + "_admin:" + userId + ":" + module.key() + ":" + day, userId);
log.info("[user-secret] 巡检通知已发 userId={} module={} scene={} level={} 条数={}",
log.info("[user-secret] 巡检用户通知已发 userId={} module={} scene={} level={} 条数={}",
userId, module.key(), decision.scene(), decision.level(), pushed);
return pushed;
}
/** 把本条异常按密钥归组:同「模块 + 密文」的 N 个账号只留一条待发管理员通知。 */
private void collectAdminAlert(Map<String, SecretAlertGroup> groups, String groupKey, Long userId,
UserSecretModule module, UserApiSecretCheckService.CheckOutcome outcome) {
SecretAlertDecision decision = decideSecretAlert(outcome);
if (decision == null || userId == null) {
return;
}
groups.computeIfAbsent(groupKey, key -> new SecretAlertGroup(module, decision, outcome)).userIds.add(userId);
}
/**
* 管理员告警下发:一把密钥一条。多账号共用时正文只报「受影响账号数 + 原因」,不逐个点名——
* 同一把 key 的账号往往分属不同主管,列出他人 uid 等于把归属关系泄露给对方,
* 具体账号可在后台「用户密钥」页按状态筛出;单账号组保持原来的点名文案。
* 受众仍按数据权限过滤:只看得到组内任一号的管理员才收得到。
*/
private int dispatchAdminAlerts(NotificationDispatchService.AdminAudience audience,
Map<String, SecretAlertGroup> groups) {
if (audience == null || groups.isEmpty()) {
return 0;
}
String day = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);
int pushed = 0;
for (Map.Entry<String, SecretAlertGroup> entry : groups.entrySet()) {
SecretAlertGroup group = entry.getValue();
boolean balance = NotificationService.SCENE_SECRET_BALANCE.equals(group.decision.scene());
String reason = group.outcome.message() == null ? "" : group.outcome.message().trim();
String what = group.module.label() + (balance ? "对应服务商余额不足" : "检测失败");
String title;
String content;
String dedupeBase;
if (group.userIds.size() == 1) {
Long userId = group.userIds.iterator().next();
String username = notificationDispatchService.displayNameOf(userId);
title = "用户密钥异常:" + username;
content = "用户 " + username + "(uid=" + userId + ")的" + what
+ (reason.isEmpty() ? "" : ":" + reason);
dedupeBase = group.decision.scene() + "_admin:" + userId + ":" + group.module.key();
} else {
int affected = group.userIds.size();
title = "用户密钥异常:" + what + "(" + affected + " 个账号共用同一把)";
content = group.module.label() + "有 " + affected + " 个账号共用同一把配置,"
+ (balance ? "对应服务商余额不足" : "检测失败")
+ (reason.isEmpty() ? "" : ":" + reason)
+ "。具体账号请到后台「用户密钥」页按状态筛选。";
dedupeBase = group.decision.scene() + "_admin:group:" + sha256Hex(entry.getKey())
+ ":" + group.module.key();
}
pushed += notificationDispatchService.pushToAdminsAnyOf(audience, group.decision.scene(),
group.decision.level(), title, content, dedupeBase + ":" + day, group.userIds);
}
return pushed;
}
/** 一把密钥(同模块同密文)的管理员告警分组。 */
private static final class SecretAlertGroup {
private final UserSecretModule module;
private final SecretAlertDecision decision;
private final UserApiSecretCheckService.CheckOutcome outcome;
private final Set<Long> userIds = new LinkedHashSet<>();
private SecretAlertGroup(UserSecretModule module, SecretAlertDecision decision,
UserApiSecretCheckService.CheckOutcome outcome) {
this.module = module;
this.decision = decision;
this.outcome = outcome;
}
}
/** 巡检告警判定结果(场景 + 级别)。 */
record SecretAlertDecision(String scene, String level) {
}
@@ -801,16 +884,28 @@ public class UserApiSecretService implements UserSecretCleanupPort {
* 只在 Redis 暂存里做比对,不落库、不下发。
*/
private String fingerprint(Long userId, UserSecretModule module, String plainValue) {
String hash = sha256Hex(userId + "|" + module.key() + "|" + plainValue);
if (hash.isEmpty()) {
log.warn("[user-secret] 生成检测指纹失败 userId={} module={}", userId, module.key());
}
return hash;
}
/** 新鲜期指纹:只按「模块 + 明文」,不含 uid —— 同一把密钥在任意账号上的检测结论是同一个。 */
private String sharedFingerprint(UserSecretModule module, String plainValue) {
return sha256Hex(module.key() + "|" + plainValue);
}
private String sha256Hex(String raw) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] bytes = digest.digest((userId + "|" + module.key() + "|" + plainValue).getBytes(StandardCharsets.UTF_8));
byte[] bytes = digest.digest(raw.getBytes(StandardCharsets.UTF_8));
StringBuilder hex = new StringBuilder(bytes.length * 2);
for (byte value : bytes) {
hex.append(Character.forDigit((value >> 4) & 0xF, 16)).append(Character.forDigit(value & 0xF, 16));
}
return hex.toString();
} catch (Exception ex) {
log.warn("[user-secret] 生成检测指纹失败 userId={} module={} err={}", userId, module.key(), ex.getMessage());
return "";
}
}
@@ -835,19 +930,23 @@ public class UserApiSecretService implements UserSecretCleanupPort {
}
}
/** 「重复检测」新鲜期键:按登录用户 + 模块隔离。 */
private String freshCheckKey(Long userId, UserSecretModule module) {
return FRESH_CHECK_KEY_PREFIX + ":" + userId + ":" + module.key();
/**
* 「重复检测」新鲜期键:按「模块 + 配置值指纹」隔离,不按 uid。
* 一把密钥平均被 9.5 个账号共用(2026-10-01 实测 314 条配置=33 种密钥),而代理探测每次都是真实提取计费,
* 按 uid 隔离时管理员连点 N 个共用同 key 的账号就要付 N 次;结论本身只取决于密钥,跨账号复用才不重复扣费。
*/
private String freshCheckKey(UserSecretModule module, String sharedHash) {
return FRESH_CHECK_KEY_PREFIX + ":" + module.key() + ":" + sharedHash;
}
/** 读取新鲜期结果:同值且窗口内返回上次 outcome,否则 null(走真实探测)。 */
private UserApiSecretCheckService.CheckOutcome reuseFreshOutcome(Long userId, UserSecretModule module, String plainValue) {
String hash = fingerprint(userId, module, plainValue);
private UserApiSecretCheckService.CheckOutcome reuseFreshOutcome(UserSecretModule module, String plainValue) {
String hash = sharedFingerprint(module, plainValue);
if (hash.isEmpty()) {
return null;
}
try {
String raw = stringRedisTemplate.opsForValue().get(freshCheckKey(userId, module));
String raw = stringRedisTemplate.opsForValue().get(freshCheckKey(module, hash));
if (raw == null || raw.isBlank()) {
return null;
}
@@ -858,16 +957,16 @@ public class UserApiSecretService implements UserSecretCleanupPort {
return new UserApiSecretCheckService.CheckOutcome(
record.status(), record.code(), record.message(), record.latencyMs(), false);
} catch (Exception ex) {
log.warn("[user-secret] 读取检测新鲜期结果失败(按未命中处理)userId={} module={} err={}",
userId, module.key(), ex.getMessage());
log.warn("[user-secret] 读取检测新鲜期结果失败(按未命中处理)module={} err={}",
module.key(), ex.getMessage());
return null;
}
}
/** 暂存「通过」的检测结果供新鲜期内重复检测复用;失败不暂存(允许立即重试)。 */
private void rememberFreshOutcome(Long userId, UserSecretModule module, String plainValue,
private void rememberFreshOutcome(UserSecretModule module, String plainValue,
UserApiSecretCheckService.CheckOutcome outcome) {
String hash = fingerprint(userId, module, plainValue);
String hash = sharedFingerprint(module, plainValue);
if (hash.isEmpty()) {
return;
}
@@ -875,10 +974,10 @@ public class UserApiSecretService implements UserSecretCleanupPort {
String payload = objectMapper.writeValueAsString(new PendingVerification(
hash, outcome.status(), outcome.code(),
truncate(outcome.message(), MESSAGE_MAX_LENGTH), outcome.latencyMs()));
stringRedisTemplate.opsForValue().set(freshCheckKey(userId, module), payload, FRESH_CHECK_TTL);
stringRedisTemplate.opsForValue().set(freshCheckKey(module, hash), payload, FRESH_CHECK_TTL);
} catch (Exception ex) {
log.warn("[user-secret] 暂存检测新鲜期结果失败(不影响本次检测)userId={} module={} err={}",
userId, module.key(), ex.getMessage());
log.warn("[user-secret] 暂存检测新鲜期结果失败(不影响本次检测)module={} err={}",
module.key(), ex.getMessage());
}
}
@@ -1136,6 +1235,10 @@ public class UserApiSecretService implements UserSecretCleanupPort {
}
/** 巡检统计。 */
public record CheckSummary(int checked, int passed, int failed, int errors, int skipped) {
/**
* 巡检汇总:checked 为更新过状态的配置条数,probed 为真实对外探测次数
* (同一把密钥被多个账号共用时 probed &lt; checked)。
*/
public record CheckSummary(int checked, int probed, int passed, int failed, int errors, int skipped) {
}
}
@@ -4,9 +4,9 @@ import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCandidateAddRequest;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskMatchShopsRequest;
import com.nanri.aiimage.common.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.common.model.vo.ProductRiskDashboardVo;
import com.nanri.aiimage.common.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskDashboardVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.modules.withdraw.model.dto.WithdrawCandidateClearRequest;
import com.nanri.aiimage.modules.withdraw.model.dto.WithdrawCreateTaskRequest;
import com.nanri.aiimage.modules.withdraw.model.dto.WithdrawSubmitResultRequest;
@@ -1,18 +1,16 @@
package com.nanri.aiimage.modules.withdraw.service;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.util.SxssfWorkbookWriter;
import com.nanri.aiimage.modules.withdraw.model.dto.WithdrawRowDto;
import com.nanri.aiimage.modules.withdraw.model.enums.WithdrawStatus;
import com.nanri.aiimage.modules.withdraw.model.vo.WithdrawResultItemVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
@@ -35,11 +33,11 @@ public class WithdrawExcelAssemblyService {
);
public void writeWorkbook(File outputXlsx, List<WithdrawResultItemVo> items) {
SXSSFWorkbook workbook = new SXSSFWorkbook(200);
workbook.setCompressTempFiles(true);
try (FileOutputStream outputStream = new FileOutputStream(outputXlsx)) {
Sheet sheet = workbook.createSheet("Sheet1");
writeHeader(sheet);
try (SxssfWorkbookWriter writer = SxssfWorkbookWriter.open()) {
Sheet sheet = writer.createSheet("Sheet1", HEADER, null);
for (int columnIndex = 0; columnIndex < HEADER.length; columnIndex++) {
sheet.setColumnWidth(columnIndex, SxssfWorkbookWriter.width(columnIndex == 0 ? 24 : 18));
}
BigDecimal totalShopAmount = totalShopAmount(items);
BigDecimal totalWithdrawAmount = totalWithdrawAmount(items);
@@ -52,7 +50,7 @@ public class WithdrawExcelAssemblyService {
List<WithdrawRowDto> rows = item.getRows() == null ? List.of() : item.getRows();
if (rows.isEmpty()) {
Row row = sheet.createRow(rowIndex++);
row.createCell(0).setCellValue(safe(item.getShopName()));
SxssfWorkbookWriter.setText(row, 0, safe(item.getShopName()));
if (!totalsWritten) {
writeTotals(row, totalShopAmount, totalWithdrawAmount);
totalsWritten = true;
@@ -61,15 +59,15 @@ public class WithdrawExcelAssemblyService {
for (int i = 0; i < rows.size(); i++) {
WithdrawRowDto data = rows.get(i);
Row row = sheet.createRow(rowIndex++);
row.createCell(0).setCellValue(i == 0 ? safe(item.getShopName()) : "");
row.createCell(1).setCellValue(formatCountry(data == null ? null : data.getCountry()));
writeMoney(row.createCell(2), data == null ? null : data.getShopAmount());
SxssfWorkbookWriter.setText(row, 0, i == 0 ? safe(item.getShopName()) : "");
SxssfWorkbookWriter.setText(row, 1, formatCountry(data == null ? null : data.getCountry()));
SxssfWorkbookWriter.setNumber(row, 2, data == null ? null : data.getShopAmount());
if (!isNegativeWithdraw(data)) {
writeMoney(row.createCell(3), data == null ? null : data.getWithdrawAmount());
SxssfWorkbookWriter.setNumber(row, 3, data == null ? null : data.getWithdrawAmount());
} else {
row.createCell(3).setCellValue("");
SxssfWorkbookWriter.setText(row, 3, "");
}
row.createCell(4).setCellValue(formatStatus(data));
SxssfWorkbookWriter.setText(row, 4, formatStatus(data));
if (!totalsWritten) {
writeTotals(row, totalShopAmount, totalWithdrawAmount);
totalsWritten = true;
@@ -78,20 +76,14 @@ public class WithdrawExcelAssemblyService {
}
Row subtotal = sheet.createRow(rowIndex++);
writeMoney(subtotal.createCell(2), shopSubtotal(rows));
writeMoney(subtotal.createCell(3), withdrawSubtotal(rows));
SxssfWorkbookWriter.setNumber(subtotal, 2, shopSubtotal(rows));
SxssfWorkbookWriter.setNumber(subtotal, 3, withdrawSubtotal(rows));
rowIndex++;
}
workbook.write(outputStream);
writer.write(outputXlsx);
} catch (Exception ex) {
log.warn("[withdraw] write workbook failed: {}", ex.getMessage());
throw new BusinessException("生成取款 Excel 失败: " + ex.getMessage());
} finally {
try {
workbook.close();
} catch (Exception ignored) {
}
workbook.dispose();
}
}
@@ -107,17 +99,9 @@ public class WithdrawExcelAssemblyService {
return count;
}
private void writeHeader(Sheet sheet) {
Row headerRow = sheet.createRow(0);
for (int columnIndex = 0; columnIndex < HEADER.length; columnIndex++) {
headerRow.createCell(columnIndex).setCellValue(HEADER[columnIndex]);
sheet.setColumnWidth(columnIndex, (columnIndex == 0 ? 24 : 18) * 256);
}
}
private void writeTotals(Row row, BigDecimal totalShopAmount, BigDecimal totalWithdrawAmount) {
writeMoney(row.createCell(6), totalShopAmount);
writeMoney(row.createCell(7), totalWithdrawAmount);
SxssfWorkbookWriter.setNumber(row, 6, totalShopAmount);
SxssfWorkbookWriter.setNumber(row, 7, totalWithdrawAmount);
}
private BigDecimal totalShopAmount(List<WithdrawResultItemVo> items) {
@@ -186,14 +170,6 @@ public class WithdrawExcelAssemblyService {
return COUNTRY_NAMES.getOrDefault(value.toUpperCase(), value);
}
private void writeMoney(Cell cell, BigDecimal value) {
if (value == null) {
cell.setCellValue("");
return;
}
cell.setCellValue(value.doubleValue());
}
private String safe(String value) {
return value == null ? "" : value;
}
@@ -4,9 +4,9 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCandidateAddRequest;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskMatchShopsRequest;
import com.nanri.aiimage.common.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.common.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.common.model.vo.ProductRiskShopQueueItemVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskShopQueueItemVo;
import com.nanri.aiimage.modules.withdraw.mapper.WithdrawShopCandidateMapper;
import com.nanri.aiimage.modules.withdraw.model.entity.WithdrawShopCandidateEntity;
import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoShopMatchResultVo;
@@ -1,177 +1,25 @@
package com.nanri.aiimage.modules.withdraw.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.service.AbstractModuleTaskCacheService;
import com.nanri.aiimage.modules.task.service.TaskScopePayloadStorageService;
import com.nanri.aiimage.modules.task.util.TaskEntityLocalCache;
import com.nanri.aiimage.modules.withdraw.model.dto.WithdrawShopPayloadDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 提现模块任务缓存服务:通用实现见 {@link AbstractModuleTaskCacheService},
* 本类只声明模块差异(moduleType / Redis key 前缀 / 载荷类型)。
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class WithdrawTaskCacheService {
public class WithdrawTaskCacheService extends AbstractModuleTaskCacheService<WithdrawShopPayloadDto> {
private static final String MODULE_TYPE = "WITHDRAW";
private static final long PAYLOAD_TTL_HOURS = 24;
private final StringRedisTemplate stringRedisTemplate;
private final ObjectMapper objectMapper;
private final TaskScopePayloadStorageService taskScopePayloadStorageService;
private final TaskEntityLocalCache taskEntityLocalCache;
public WithdrawShopPayloadDto getShopMergedPayload(Long taskId, String shopKey) {
return taskScopePayloadStorageService.getScopePayload(taskId, MODULE_TYPE, shopKey, WithdrawShopPayloadDto.class);
}
public void saveShopMergedPayload(Long taskId, String shopKey, WithdrawShopPayloadDto payload) {
if (taskId == null || taskId <= 0 || shopKey == null || shopKey.isBlank() || payload == null) {
return;
}
taskScopePayloadStorageService.saveScopePayload(taskId, MODULE_TYPE, shopKey, payload);
touchTaskHeartbeat(taskId);
}
public void removeShopMergedPayload(Long taskId, String shopKey) {
taskScopePayloadStorageService.removeScopePayload(taskId, MODULE_TYPE, shopKey);
}
public Map<String, WithdrawShopPayloadDto> getAllShopMergedPayload(Long taskId) {
return taskScopePayloadStorageService.getAllScopePayload(taskId, MODULE_TYPE, WithdrawShopPayloadDto.class);
}
public boolean hasAnyShopMergedPayload(Long taskId) {
return taskScopePayloadStorageService.hasAnyScopePayload(taskId, MODULE_TYPE);
}
public Map<Long, Long> getTaskHeartbeatMillisBatch(List<Long> taskIds) {
Map<Long, Long> result = new LinkedHashMap<>();
if (taskIds == null || taskIds.isEmpty()) {
return result;
}
List<Long> normalized = taskIds.stream().filter(id -> id != null && id > 0).distinct().toList();
if (normalized.isEmpty()) {
return result;
}
List<String> keys = normalized.stream().map(this::buildTaskHeartbeatKey).toList();
List<String> values;
try {
values = stringRedisTemplate.opsForValue().multiGet(keys);
} catch (Exception ex) {
log.warn("[withdraw-cache] batch get heartbeat degraded taskIds={} msg={}", normalized, ex.getMessage());
return result;
}
for (int i = 0; i < normalized.size(); i++) {
String raw = values != null && i < values.size() ? values.get(i) : null;
try {
result.put(normalized.get(i), raw == null || raw.isBlank() ? 0L : Long.parseLong(raw));
} catch (NumberFormatException ignored) {
result.put(normalized.get(i), 0L);
}
}
return result;
}
public void touchTaskHeartbeat(Long taskId) {
if (taskId == null || taskId <= 0) {
return;
}
try {
stringRedisTemplate.opsForValue().set(
buildTaskHeartbeatKey(taskId),
String.valueOf(Instant.now().toEpochMilli()),
Duration.ofHours(PAYLOAD_TTL_HOURS));
} catch (Exception ex) {
log.warn("[withdraw-cache] touch heartbeat degraded taskId={} msg={}", taskId, ex.getMessage());
}
}
public void deleteTaskCache(Long taskId) {
if (taskId == null || taskId <= 0) {
return;
}
taskEntityLocalCache.evict(taskId);
try {
stringRedisTemplate.delete(buildTaskHeartbeatKey(taskId));
stringRedisTemplate.delete(buildTaskEntityKey(taskId));
} catch (Exception ex) {
log.warn("[withdraw-cache] delete cache degraded taskId={} msg={}", taskId, ex.getMessage());
}
taskScopePayloadStorageService.deleteTaskScopePayloads(taskId, MODULE_TYPE);
}
public void saveTaskCache(FileTaskEntity task) {
if (task == null || task.getId() == null) {
return;
}
taskEntityLocalCache.put(task.getId(), task);
try {
stringRedisTemplate.opsForValue().set(
buildTaskEntityKey(task.getId()),
objectMapper.writeValueAsString(task),
Duration.ofHours(PAYLOAD_TTL_HOURS));
} catch (Exception ignored) {
}
}
public Map<Long, FileTaskEntity> getTaskCacheBatch(List<Long> taskIds) {
Map<Long, FileTaskEntity> result = new LinkedHashMap<>();
if (taskIds == null || taskIds.isEmpty()) {
return result;
}
List<Long> normalized = taskIds.stream().filter(id -> id != null && id > 0).distinct().toList();
long now = System.currentTimeMillis();
List<Long> missingIds = new ArrayList<>();
for (Long taskId : normalized) {
TaskEntityLocalCache.Entry cached = taskEntityLocalCache.get(taskId, now);
if (cached != null) {
result.put(taskId, cached.task());
} else {
missingIds.add(taskId);
}
}
if (missingIds.isEmpty()) {
return result;
}
List<String> keys = missingIds.stream().map(this::buildTaskEntityKey).toList();
List<String> values;
try {
values = stringRedisTemplate.opsForValue().multiGet(keys);
} catch (Exception ex) {
log.warn("[withdraw-cache] batch get task cache degraded taskIds={} msg={}", missingIds, ex.getMessage());
return result;
}
for (int i = 0; i < missingIds.size(); i++) {
Long taskId = missingIds.get(i);
String raw = values != null && i < values.size() ? values.get(i) : null;
if (raw == null || raw.isBlank()) {
continue;
}
try {
FileTaskEntity task = objectMapper.readValue(raw, FileTaskEntity.class);
result.put(taskId, task);
taskEntityLocalCache.put(taskId, task);
} catch (Exception ignored) {
}
}
return result;
}
private String buildTaskHeartbeatKey(Long taskId) {
return "withdraw:task:heartbeat:" + taskId;
}
private String buildTaskEntityKey(Long taskId) {
return "withdraw:task:entity:" + taskId;
public WithdrawTaskCacheService(StringRedisTemplate stringRedisTemplate,
ObjectMapper objectMapper,
TaskScopePayloadStorageService taskScopePayloadStorageService,
TaskEntityLocalCache taskEntityLocalCache) {
super("WITHDRAW", "withdraw", WithdrawShopPayloadDto.class,
stringRedisTemplate, objectMapper, taskScopePayloadStorageService, taskEntityLocalCache);
}
}
@@ -6,12 +6,11 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessCodes;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.config.TaskPressureProperties;
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
import com.nanri.aiimage.common.model.vo.ProductRiskDashboardVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskDashboardVo;
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.model.entity.FileResultEntity;
@@ -19,6 +18,7 @@ import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
import com.nanri.aiimage.modules.task.service.TaskDistributedLockService;
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
import com.nanri.aiimage.modules.task.service.TaskFinalizeSupport;
import com.nanri.aiimage.modules.task.service.TaskProgressSnapshotService;
import com.nanri.aiimage.modules.task.service.TaskResultItemService;
import com.nanri.aiimage.modules.withdraw.model.dto.WithdrawCreateTaskRequest;
@@ -529,49 +529,16 @@ public class WithdrawTaskService {
}
private FileTaskEntity loadTaskForExecution(Long taskId) {
Map<Long, FileTaskEntity> cachedTasks = taskCacheService.getTaskCacheBatch(List.of(taskId));
FileTaskEntity cached = cachedTasks.get(taskId);
if (cached != null) {
return cached;
}
FileTaskEntity dbTask = fileTaskMapper.selectById(taskId);
if (dbTask != null && MODULE_TYPE.equals(dbTask.getModuleType())) {
taskCacheService.saveTaskCache(dbTask);
}
return dbTask;
return TaskFinalizeSupport.loadTaskForExecution(fileTaskMapper, taskCacheService, MODULE_TYPE, taskId);
}
private Map<Long, FileTaskEntity> loadTaskMapByIds(List<Long> taskIds) {
Map<Long, FileTaskEntity> result = new LinkedHashMap<>();
List<Long> normalizedTaskIds = normalizeTaskIds(taskIds);
if (normalizedTaskIds.isEmpty()) {
return result;
}
Map<Long, FileTaskEntity> cachedTasks = taskCacheService.getTaskCacheBatch(normalizedTaskIds);
result.putAll(cachedTasks);
List<Long> missingTaskIds = normalizedTaskIds.stream().filter(taskId -> !cachedTasks.containsKey(taskId)).toList();
for (FileTaskEntity dbTask : selectTasksByIdsInBatches(missingTaskIds)) {
if (dbTask != null && MODULE_TYPE.equals(dbTask.getModuleType())) {
result.put(dbTask.getId(), dbTask);
if ("RUNNING".equals(dbTask.getStatus())) {
taskCacheService.saveTaskCache(dbTask);
}
}
}
return result;
// Withdraw 特有:任务 id 归一化带 limit(50) 上限,保留在本地后传入公共加载
return TaskFinalizeSupport.loadTaskMapByIds(fileTaskMapper, taskPressureProperties, taskCacheService, MODULE_TYPE, normalizeTaskIds(taskIds));
}
private List<FileTaskEntity> selectTasksByIdsInBatches(List<Long> taskIds) {
List<FileTaskEntity> tasks = new ArrayList<>();
if (taskIds == null || taskIds.isEmpty()) {
return tasks;
}
int batchSize = Math.max(1, taskPressureProperties.getDbSelectBatchSize());
for (int start = 0; start < taskIds.size(); start += batchSize) {
int end = Math.min(start + batchSize, taskIds.size());
tasks.addAll(fileTaskMapper.selectBatchIds(taskIds.subList(start, end)));
}
return tasks;
return TaskFinalizeSupport.selectTasksByIdsInBatches(fileTaskMapper, taskPressureProperties, taskIds);
}
private Map<Long, FileTaskEntity> loadHistoryTaskMap(List<FileResultEntity> entities) {
@@ -1013,14 +980,7 @@ public class WithdrawTaskService {
}
private void markResultFailed(FileResultEntity row, String message) {
row.setSuccess(RESULT_FAILED);
row.setErrorMessage(blankToNull(message));
row.setResultFilename(null);
row.setResultFileUrl(null);
row.setResultFileSize(0L);
row.setResultContentType(null);
row.setRowCount(0);
fileResultMapper.updateById(row);
TaskFinalizeSupport.markResultFailed(fileResultMapper, row, blankToNull(message));
}
private boolean isResultFinished(FileResultEntity row) {
@@ -1055,19 +1015,11 @@ public class WithdrawTaskService {
}
private TaskDistributedLockService.LockHandle acquireTaskLockOrThrow(Long taskId) {
TaskDistributedLockService.LockHandle lockHandle = acquireTaskLock(taskId);
if (lockHandle == null) {
log.warn("[withdraw] 任务锁竞争,拒绝本次提交 taskId={}", taskId);
throw new BusinessException(BusinessCodes.TASK_BUSY, "任务正在处理中,请稍后再试");
}
return lockHandle;
return TaskFinalizeSupport.acquireTaskLockOrThrow(taskDistributedLockService, MODULE_TYPE, taskId, "withdraw");
}
private TaskDistributedLockService.LockHandle acquireTaskLock(Long taskId) {
if (taskId == null || taskId <= 0) {
return null;
}
return taskDistributedLockService.acquire(MODULE_TYPE, taskId);
return TaskFinalizeSupport.acquireTaskLock(taskDistributedLockService, MODULE_TYPE, taskId);
}
/**
@@ -372,7 +372,6 @@ aiimage:
llm-result-buffer-enabled: ${AIIMAGE_SIMILAR_ASIN_LLM_RESULT_BUFFER_ENABLED:true}
direct-llm-enabled: ${AIIMAGE_SIMILAR_ASIN_DIRECT_LLM_ENABLED:true}
llm-host: ${AIIMAGE_SIMILAR_ASIN_LLM_HOST:https://ai.t8star.org}
llm-api-key: ${AIIMAGE_SIMILAR_ASIN_LLM_API_KEY:}
llm-category-model: ${AIIMAGE_SIMILAR_ASIN_LLM_CATEGORY_MODEL:gemini-3.1-flash-lite-preview-thinking-medium}
llm-conform-model: ${AIIMAGE_SIMILAR_ASIN_LLM_CONFORM_MODEL:gemini-3.1-flash-lite-preview-thinking-medium}
llm-image-compare-model: ${AIIMAGE_SIMILAR_ASIN_LLM_IMAGE_COMPARE_MODEL:gemini-3.1-flash-lite-preview-thinking-medium}
@@ -0,0 +1,66 @@
package com.nanri.aiimage.common.util;
import org.junit.jupiter.api.Test;
import java.time.LocalDateTime;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class StaleTaskDeathReasonTest {
private static final LocalDateTime T = LocalDateTime.of(2026, 10, 1, 12, 34, 5);
@Test
void neverUploadedSaysNoResultUploadedNotThatPythonCrashed() {
String reason = new StaleTaskDeathReason(0L, null, T, null, false, 30).describe();
assertTrue(reason.contains("未回传任何检测结果"), reason);
assertTrue(reason.contains("超过 30 分钟无进展"), reason);
assertTrue(reason.contains("最后心跳 10-01 12:34"), reason);
assertFalse(reason.contains("Python"), reason);
assertFalse(reason.contains("最后上报"), reason);
}
@Test
void queuedTaskIsToldApartFromACrashedOneByTheReportedPhase() {
String reason = new StaleTaskDeathReason(0L, null, T, "排队等待空闲槽位", false, 30).describe();
assertTrue(reason.contains("最后上报 排队等待空闲槽位"), reason);
assertFalse(reason.contains("已收到"), reason);
}
@Test
void missingHeartbeatAndBlankPhaseDegradeQuietly() {
String reason = new StaleTaskDeathReason(0L, null, null, " ", false, 30).describe();
assertTrue(reason.contains("最后心跳 时间未知"), reason);
assertFalse(reason.contains("最后上报"), reason);
}
@Test
void interruptedUploadReportsChunksAndLastChunkTime() {
String reason = new StaleTaskDeathReason(7L, T, T, "第 120/500 组", false, 30).describe();
assertTrue(reason.contains("客户端回传中断"), reason);
assertTrue(reason.contains("已收到 7 个分片,最后一次 10-01 12:34"), reason);
assertTrue(reason.contains("最后上报 第 120/500 组"), reason);
assertFalse(reason.contains("结果文件生成"), reason);
}
@Test
void exhaustedFileJobBlamesFileGenerationInsteadOfTheClient() {
String reason = new StaleTaskDeathReason(7L, T, T, "第 120/500 组", true, 30).describe();
assertTrue(reason.contains("结果文件生成多次失败"), reason);
assertFalse(reason.contains("回传中断"), reason);
}
@Test
void exhaustedFileJobWithoutAnyChunkStillReportsClientSilence() {
String reason = new StaleTaskDeathReason(0L, null, T, null, true, 30).describe();
assertTrue(reason.contains("未回传任何检测结果"), reason);
assertFalse(reason.contains("结果文件生成"), reason);
}
@Test
void nonPositiveTimeoutNeverPrintsZeroMinutes() {
assertTrue(new StaleTaskDeathReason(0L, null, null, null, false, 0)
.describe().contains("超过 1 分钟"));
}
}
@@ -4,8 +4,8 @@ import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.common.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.modules.patroldelete.mapper.PatrolDeleteConditionMapper;
import com.nanri.aiimage.modules.patroldelete.mapper.PatrolDeleteShopCandidateMapper;
import com.nanri.aiimage.modules.patroldelete.model.entity.PatrolDeleteShopCandidateEntity;
@@ -4,8 +4,8 @@ import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.common.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCandidateAddRequest;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskMatchShopsRequest;
import com.nanri.aiimage.modules.queryasin.mapper.QueryAsinShopCandidateMapper;
@@ -5,9 +5,9 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.common.model.vo.ProductRiskCountryPreferenceVo;
import com.nanri.aiimage.common.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCountryPreferenceVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCandidateAddRequest;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCountryPreferenceSaveRequest;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskMatchShopsRequest;
@@ -58,7 +58,7 @@ public class SimilarAsinLlmLocalVerify {
}
SimilarAsinProperties props = new SimilarAsinProperties();
props.setLlmApiKey(apiKey);
// 密钥经 inspectRows 参数显式传入(平台公费 llm-api-key 已废除)
props.setLlmRowConcurrency(2);
props.setLlmImageDownloadTimeoutSeconds(10);
@@ -53,9 +53,8 @@ class SimilarAsinLlmServiceTest {
}
private SimilarAsinProperties properties() {
SimilarAsinProperties props = new SimilarAsinProperties();
props.setLlmApiKey("test-key");
return props;
// 平台公费 llm-api-key 已废除:密钥只来自任务 payload / 用户密钥表(测试里 llmClient 都是 mock)
return new SimilarAsinProperties();
}
private SimilarAsinLlmService service(SimilarAsinLlmClient llmClient) {
@@ -28,9 +28,12 @@ import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import java.time.Duration;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
@@ -60,6 +63,8 @@ class UserApiSecretServiceTest {
private final ObjectMapper objectMapper = new ObjectMapper();
/** 内存版 Redis 值操作:让「检测暂存 → 保存读取」的 JSON 往返在单测里真实走一遍。 */
private final Map<String, String> redisValues = new HashMap<>();
/** 巡检测试用:记录 updateById 写入的 userId → checkStatus 快照。 */
private final Map<Long, String> inspectionWrites = new LinkedHashMap<>();
private ValueOperations<String, String> valueOps;
private UserApiSecretService newService() {
@@ -226,6 +231,47 @@ class UserApiSecretServiceTest {
verify(checkService, times(2)).probe(any(), anyString());
}
/**
* 新鲜期按「配置值」共享而非按账号:一把密钥平均挂 9.5 个账号(2026-10-01 实测 314 条配置=33 种),
* 后台连点两个共用同 key 的账号若各探一次就是付两次提取费;结论只取决于密钥,跨账号复用才不重复扣费。
*/
@Test
void freshCheckIsSharedAcrossAccountsUsingTheSameSecret() {
UserApiSecretService service = newService();
when(checkService.probe(any(), anyString())).thenReturn(outcome("passed", "ok", "代理可用", 120));
var first = service.check(7L, "proxy", "https://api.jikip.com/ip-get?num=1&key=abc");
var second = service.check(8L, "proxy", "https://api.jikip.com/ip-get?num=1&key=abc");
verify(checkService, times(1)).probe(any(), anyString());
assertThat(second.getCheckStatus()).isEqualTo("passed");
assertThat(second.getCheckStatus()).isEqualTo(first.getCheckStatus());
}
/** 共享的边界是「同一个值」:换了 key 必须真实探测,否则新鲜期退化成全局缓存一份结论。 */
@Test
void freshCheckDoesNotLeakAcrossDifferentSecretValues() {
UserApiSecretService service = newService();
when(checkService.probe(any(), anyString())).thenReturn(outcome("passed", "ok", "正常", 100));
service.check(7L, "proxy", "https://api.jikip.com/ip-get?num=1&key=aaa");
service.check(8L, "proxy", "https://api.jikip.com/ip-get?num=1&key=bbb");
verify(checkService, times(2)).probe(any(), anyString());
}
/** 同一串值在不同模块下结论可能不同(货源/外观各自独立的检测端点),新鲜期按模块隔离。 */
@Test
void freshCheckIsScopedPerModule() {
UserApiSecretService service = newService();
when(checkService.probe(any(), anyString())).thenReturn(outcome("passed", "ok", "连通正常", 100));
service.check(7L, "similar-asin", "sk-shared");
service.check(8L, "appearance-patent", "sk-shared");
verify(checkService, times(2)).probe(any(), anyString());
}
private UserApiSecretEntity existingRow(String cipher) {
UserApiSecretEntity existing = new UserApiSecretEntity();
existing.setId(5L);
@@ -730,6 +776,189 @@ class UserApiSecretServiceTest {
assertThat(bundle.getProxy().getMasked()).isEqualTo("https://api.jikip.com");
}
/** 巡检去重:同一把代理密钥被 3 个账号共用,一轮只真实提取一次,结论回写 3 行。 */
@Test
void schedulerProbesSharedSecretOnceForAllAccounts() {
UserApiSecretService service = newService();
String sharedCipher = "enc:https://api.jikip.com/ip-get?num=1&key=abc";
stubInspectionStore(Map.of(
11L, storedRow(11L, "proxy", sharedCipher),
12L, storedRow(12L, "proxy", sharedCipher),
13L, storedRow(13L, "proxy", sharedCipher)));
when(checkService.probe(any(), anyString())).thenReturn(outcome("passed", "ok", "代理可用", 120));
when(mapper.selectList(any())).thenReturn(List.of(
inspectionRow(1L, 11L, "proxy", sharedCipher),
inspectionRow(2L, 12L, "proxy", sharedCipher),
inspectionRow(3L, 13L, "proxy", sharedCipher)), List.of());
var summary = service.checkAllForScheduler(500, 20);
verify(checkService, times(1)).probe(any(), anyString());
assertThat(summary.checked()).isEqualTo(3);
assertThat(summary.probed()).isEqualTo(1);
assertThat(inspectionWrites.keySet()).containsExactlyInAnyOrder(11L, 12L, 13L);
assertThat(inspectionWrites.values()).containsOnly("passed");
}
/** 失败结论同样整组复用:否则一把欠费的 key 会按账号数重复付费提取。 */
@Test
void schedulerReusesFailedOutcomeAcrossSharedSecretGroup() {
UserApiSecretService service = newService();
String sharedCipher = "enc:https://api.jikip.com/ip-get?num=1&key=abc";
stubInspectionStore(Map.of(
11L, storedRow(11L, "proxy", sharedCipher),
12L, storedRow(12L, "proxy", sharedCipher)));
when(checkService.probe(any(), anyString())).thenReturn(
outcome("failed", "insufficient_balance", "代理服务商余额不足,请充值后重试", 80));
when(mapper.selectList(any())).thenReturn(List.of(
inspectionRow(1L, 11L, "proxy", sharedCipher),
inspectionRow(2L, 12L, "proxy", sharedCipher)), List.of());
var summary = service.checkAllForScheduler(500, 20);
verify(checkService, times(1)).probe(any(), anyString());
assertThat(summary.probed()).isEqualTo(1);
assertThat(summary.failed()).isEqualTo(2);
assertThat(inspectionWrites.values()).containsOnly("failed");
}
/** 分组只在同模块内生效:同一串值在货源/外观两个模块下各探一次(两模块的检测主机可独立配置)。 */
@Test
void schedulerProbesSameValueOncePerModule() {
UserApiSecretService service = newService();
String sharedCipher = "enc:sk-shared";
stubInspectionStore(Map.of(
11L, storedRow(11L, "similar-asin", sharedCipher),
12L, storedRow(12L, "appearance-patent", sharedCipher)));
when(checkService.probe(any(), anyString())).thenReturn(outcome("passed", "ok", "连通正常", 100));
when(mapper.selectList(any())).thenReturn(List.of(
inspectionRow(1L, 11L, "similar-asin", sharedCipher),
inspectionRow(2L, 12L, "appearance-patent", sharedCipher)), List.of());
var summary = service.checkAllForScheduler(500, 20);
verify(checkService, times(2)).probe(any(), anyString());
assertThat(summary.checked()).isEqualTo(2);
assertThat(summary.probed()).isEqualTo(2);
}
/**
* 一把欠费密钥被 3 个账号共用:用户通知逐个发(各自的余额问题各自得知道),
* 管理员侧收敛成一条 —— 过去是 3 条同内容告警,33 种密钥×平均 9.5 账号时后台铃铛会被刷屏。
*/
@Test
void schedulerGroupsAdminAlertForAccountsSharingOneSecret() {
UserApiSecretService service = newService();
String sharedCipher = "enc:https://api.jikip.com/ip-get?num=1&key=abc";
stubInspectionStore(Map.of(
11L, storedRow(11L, "proxy", sharedCipher),
12L, storedRow(12L, "proxy", sharedCipher),
13L, storedRow(13L, "proxy", sharedCipher)));
when(checkService.probe(any(), anyString())).thenReturn(
outcome("failed", "insufficient_balance", "代理服务商余额不足,请充值后重试", 80));
when(mapper.selectList(any())).thenReturn(List.of(
inspectionRow(1L, 11L, "proxy", sharedCipher),
inspectionRow(2L, 12L, "proxy", sharedCipher),
inspectionRow(3L, 13L, "proxy", sharedCipher)), List.of());
stubAdminNotificationPath();
var summary = service.checkAllForScheduler(500, 20);
assertThat(summary.failed()).isEqualTo(3);
verify(notificationDispatchService, times(3)).pushToUser(any(), any(), any(), any(), any(), any());
ArgumentCaptor<String> title = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> content = ArgumentCaptor.forClass(String.class);
@SuppressWarnings("unchecked")
ArgumentCaptor<Collection<Long>> subjects = ArgumentCaptor.forClass(Collection.class);
verify(notificationDispatchService, times(1)).pushToAdminsAnyOf(any(), anyString(), anyString(),
title.capture(), content.capture(), anyString(), subjects.capture());
assertThat(title.getValue()).contains("3 个账号共用同一把");
assertThat(subjects.getValue()).containsExactlyInAnyOrder(11L, 12L, 13L);
// 合并告警不点名具体账号:同 key 的账号往往分属不同主管,列 uid 等于泄露归属
assertThat(content.getValue()).doesNotContain("uid=");
verify(notificationDispatchService, never()).pushToAdmins(any(), anyString(), anyString(),
anyString(), anyString(), anyString(), any());
}
/** 只有一个账号在用的密钥保持原口径:仍然点名「用户密钥异常:{用户名}」,去重键与改动前一致。 */
@Test
void schedulerKeepsNamedAdminAlertWhenSecretIsUsedByOneAccount() {
UserApiSecretService service = newService();
String cipher = "enc:sk-solo";
stubInspectionStore(Map.of(11L, storedRow(11L, "similar-asin", cipher)));
when(checkService.probe(any(), anyString())).thenReturn(
outcome("failed", "invalid_key", "密钥无效或已被拒绝", 90));
when(mapper.selectList(any())).thenReturn(List.of(
inspectionRow(1L, 11L, "similar-asin", cipher)), List.of());
stubAdminNotificationPath();
service.checkAllForScheduler(500, 20);
ArgumentCaptor<String> title = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> content = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> dedupeBase = ArgumentCaptor.forClass(String.class);
verify(notificationDispatchService, times(1)).pushToAdminsAnyOf(any(), anyString(), anyString(),
title.capture(), content.capture(), dedupeBase.capture(), any());
assertThat(title.getAllValues()).containsExactly("用户密钥异常:shop-a");
assertThat(content.getValue()).contains("用户 shop-a(uid=11)的货源查询密钥检测失败");
assertThat(dedupeBase.getValue())
.isEqualTo("secret_invalid_admin:11:similar-asin:" + today());
}
/** 管理员受众与推送出口打桩:只关心「发几条、发给谁、什么文案」,受众解析本身有专测。 */
private void stubAdminNotificationPath() {
when(notificationDispatchService.prepareAdminAudience()).thenReturn(
new NotificationDispatchService.AdminAudience(List.of(), Set.of(), Map.of()));
when(notificationDispatchService.pushToUser(any(), any(), any(), any(), any(), any())).thenReturn(true);
when(notificationDispatchService.pushToAdminsAnyOf(any(), any(), any(), any(), any(), any(), any()))
.thenReturn(1);
when(notificationDispatchService.displayNameOf(any())).thenReturn("shop-a");
}
private String today() {
return java.time.LocalDate.now().format(java.time.format.DateTimeFormatter.BASIC_ISO_DATE);
}
/**
* 巡检落库打桩:selectOne 按 wrapper 里的 userId 取库内行,updateById 记录写入状态。
* 条件值要构建 SQL 段才写入参数表,而 mock 不会建 SQL,故 stub 内手动触发一次。
*/
private void stubInspectionStore(Map<Long, UserApiSecretEntity> storedByUser) {
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
UserApiSecretEntity.class);
inspectionWrites.clear();
when(mapper.selectOne(any())).thenAnswer(inv -> {
LambdaQueryWrapper<UserApiSecretEntity> wrapper = inv.getArgument(0);
wrapper.getSqlSegment();
Long userId = wrapper.getParamNameValuePairs().values().stream()
.filter(value -> value instanceof Long)
.map(value -> (Long) value)
.findFirst().orElse(null);
return storedByUser.get(userId);
});
doAnswer(inv -> {
UserApiSecretEntity entity = inv.getArgument(0);
inspectionWrites.put(entity.getUserId(), entity.getCheckStatus());
return 1;
}).when(mapper).updateById(any(UserApiSecretEntity.class));
}
private UserApiSecretEntity inspectionRow(long id, long userId, String moduleKey, String cipher) {
UserApiSecretEntity entity = storedRow(userId, moduleKey, cipher);
entity.setId(id);
entity.setCheckStatus("unknown");
return entity;
}
private UserApiSecretEntity storedRow(long userId, String moduleKey, String cipher) {
UserApiSecretEntity entity = new UserApiSecretEntity();
entity.setId(userId * 100);
entity.setUserId(userId);
entity.setModuleKey(moduleKey);
entity.setSecretValue(cipher);
return entity;
}
private AdminUserSecretModuleVo moduleVo(boolean exists, String status) {
AdminUserSecretModuleVo vo = new AdminUserSecretModuleVo();
vo.setExists(exists);
@@ -4,8 +4,8 @@ import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.common.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskCandidateVo;
import com.nanri.aiimage.modules.productrisk.model.vo.ProductRiskMatchShopsVo;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCandidateAddRequest;
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskMatchShopsRequest;
import com.nanri.aiimage.modules.withdraw.mapper.WithdrawShopCandidateMapper;
+163
View File
@@ -0,0 +1,163 @@
# 上线后性能 / 逻辑优化建议(2026-10-02)
审查方式:只读代码,未连生产、未压测。所有 file:line 均已逐行回读确认;凡依赖线上数据才能定量化的,标了 `【待测】` 并给出取数语句。
本报告按「能缩短多少单任务时长」排序,不按改动难度排序。
---
## 一、结论摘要
外观专利与货源是任务时长的大头(外观占 LLM 花费 95%)。这两条链上**最贵的不是 LLM 本身,而是夹在 LLM 批次之间的串行等待**:
| # | 问题 | 位置 | 每任务额外代价 |
|---|---|---|---|
| A1 | 每个 LLM 批次之间把全部分片从对象存储重读重解析一遍 | `AppearancePatentTaskService.java:1926`→`:3126` | 轮数 × 分片数 次远程 GET,全在批间空档,期内并发槽闲置 |
| A2 | 品牌校验逐行发、每行各带一个 90 秒预算;同项目已有的批量+缓存过滤器没用 | `AppearancePatentLlmClient.java:916` | 一批 10 行 = 10 个独立 90s 预算串行 |
| A3 | 货源采集链仍逐行回传 + 逐行查终态,没吃到变体链已上线的攒批 | `func/collect_data_run/handler.py:338-350` | 每行 2 次公网 HTTP |
| A4 | 每次开页取 cookie 都让 Redis 全键空间 SCAN 一遍 | `maixiang_task_api/main.py:315` | 与开页次数等量(实测口径 10 万+ 次开页 = 10 万+ 次扫描) |
B 组是 DB / 对象存储的往返浪费(心跳整行读、删除路径的全表 COUNT、结果文件作业的调度自相矛盾),C 组是吞吐上限(要先测再改),D 组是交付层低成本项。
---
## 二、A 组:直接缩短单任务时长
### A1 外观专利:批间全量重读分片 `[P0]`
**证据链**
- `modules/appearancepatent/service/AppearancePatentTaskService.java:902-904` 注释自陈「同步检测:按批次串行调用 LLM」;`:915` 取 `llm-batch-size`(yml:336 默认 **10**);`:949` 外层 `for (i += batchSize)` 串行推进。
- 每轮批内 `:970 mergeLlmRowsIntoChunks` → `:1047` 定义 → `mergeLlmRowsIntoSubmittedChunks`:`:1926 loadSubmittedChunks(task.getId())` 取回**该任务全部分片**,`:1934` 对每一片调 `readChunkRows(chunk)`。
- `:3126 readChunkRows` = `transientPayloadStorageService.resolvePayload(...)`(RustFS/OSS GET)+ 整片 JSON 反序列化。
**代价**:N 行任务 = ⌈N/10⌉ 轮,每轮 C 次载荷 GET + 全量解析(C = 分片数)。5000 行、C=25 → 500 轮 × 25 = **1.25 万次 GET、约 250 万行对象解析**,全部串在批与批之间。这段时间 `llm-row-concurrency:5`(yml:343)的槽是空着的。
`【待测】C 的真实分布`:`SELECT task_id, COUNT(*) c FROM biz_task_chunk WHERE module_type='APPEARANCE_PATENT' GROUP BY task_id ORDER BY c DESC LIMIT 20;`
**改法**(纯读,不动写回)
1. 把 `Map<chunkKey, Map<rowKey,row>>` 提成批循环的局部状态,在 `:1058 collectPendingLlmCandidates` 首次读片时就建好,批内 merge 只更新真正被写回的那几片;
2. 参照 similarasin 侧已有的 `indexRowsByChunkKey` 思路建 `rowKey→chunkKey` 索引,去掉 `:1910` 对全部分片的线性试探。
**风险**:分片在批中被别的入口改写时读到旧态。现状靠 `mergeChunkPayload` 的 CAS 兜住,改后仍要走同一 CAS,只省读不省写。行数与判定结果不变。
### A2 外观专利:品牌校验合批 + 复用已有缓存 `[P0]`
**证据链**
- `modules/appearancepatent/client/AppearancePatentLlmClient.java:187-200` 是行循环,`:197 applyResult(...)`;`applyResult` 内 `:916` 调 `brandCheckClient.checkTitleText(result.title(), "Terms")`。
- `modules/brand/client/BrandCheckClient.java:201-203 checkTitleText` → `checkAll(splitTitleText(title), strategy)`;`:100-101` 预算 `total-timeout-millis` **每次调用重算**(yml:320-325:`retry-times:10 / total-timeout-millis:90000 / read-timeout-millis:60000`)。
- 同项目 `modules/collectdata/util/CollectDataBrandBatchFilter.java:26-31` 注释与 `:44-62` 实现已经做过这件事:按 10 行一批去重后一次 `checkAll`(整批共享预算)+ 512 条 LRU 判定缓存 + 远程抛错不写缓存。**外观侧完全没走它**。
**代价**:一批 10 行 = 10 个独立 90s 预算串行;上游 16890 劣化时批间隔被拉到分钟级。跨行同品牌(nike/adidas 这类高频词)零复用。
**这一条的量级取决于 16890 现在的状态**:9-28 实测 jikip 套餐彻底失效那轮,`distinct 品牌 291 / 最终判失败 290`(99.7%),A 机 45 分钟内 `整批耗时预算用尽` 290 次,当时的结论是"10 次重试纯放大时延、零收益"(`docs/ops/prod-decisions-2026-09-28.md` §八)。
- 上游**正常**时:合批+缓存省的是 10 次往返 → 1 次,收益是个常数因子;
- 上游**再次劣化**时:`每行一个 90s 预算` 意味着 10 行/批最坏 900s,改成整批共享预算后最坏仍是 90s/批 —— **这条真正的价值是把爆炸半径从"行"收回"批",和外观合批那次同样的思路**。所以下手前先看一眼 16890 现在的成功率,它决定 A2 排在 A1 前还是后。
**改法**:`applyResult` 拆两段——先收齐全批 keywords,`distinct` 后一次 `checkAll`,再按行取结论;缓存口径照抄 `CollectDataBrandBatchFilter.checkAndCache`。**不要新建类**,把该过滤器提到可被外观复用的位置即可。
**风险(必须拍)**:合并后同品牌在同批内共享一次结论。上游抖动时「第 1 行 OK、第 2 行 QUERY_FAILED」会变成两行同结论 → **判定集合可能变化**,属于本项目在意的静默错判族(参见外观 id 塌陷那次)。行数不变、LLM 输出不变。
### A3 货源采集链:套用变体链已上线的攒批 `[P0]`
**证据链**
- `maixiang_run_task/func/collect_data_run/handler.py:338-350 _emit`:每产出一条就 `feed(pending, False)`,紧跟 `:345 self._is_task_terminal(task_id)`。
- `func/amazon_base.py:460-471 _is_task_terminal`:每次调 `api_client.get_batch_status(task_id)`,**无节流**。
- 对照组 `func/variant-collection/handler.py:235-257`:攒批 flush + `TERMINAL_CHECK_INTERVAL` 节流 + 失败批留缓冲重发。变体链已改完,货源链没跟上。
**代价**:每行 2 次公网 HTTP(`API_BASE_URL` 走公网 121.196.149.225:18960),另加 `:343` 每行把整条 payload 打进日志。一次往返失败被 `tools/api_client.py:33-43`(timeout 30×3 + sleep 2)卡住最长约 94s。
**改法**:把变体链的缓冲与终态节流提到 `amazon_base` 的公共方法,`_emit` 走同一缓冲。
**风险**:不改行数。**需采集机跑一次 `更新并重启.bat` 才生效**(与变体那条同一批次,不额外增加发布动作)。
### A4 取 cookie 的全键空间 SCAN `[P0]`
**证据链**:`maixiang_task_api/main.py:300 /api/cookie/get` → `:315 async for k in redis_client.scan_iter(match=f"{country}:*", count=100)`。
**代价**:SCAN 的 `match` 是**扫完再过滤**,成本取决于键空间大小而非命中数。每一次开页要一个 cookie 就扫一遍全库,与队列 `LMOVE`、心跳抢同一条 Redis 连接池。
**改法**:`/cookie/add` 时 `SADD cookie:{country}`、失效时 `SREM`,`get_cookie` 改 `SRANDMEMBER cookie:{country} 3`,保留 `:301-305` 注释写明的"随机打散取用"意图(那注释是为了避免所有并发任务抢同一个 cookie 被风控拉黑)。
**风险**:存量 cookie 必须一次性回填 Set,漏回填=取不到 cookie=整链失败。这是本组唯一硬风险,上线判据要写"取空计数为 0"。
---
## 三、B 组:DB 与对象存储往返浪费
### B1 心跳每 60 秒整行读任务 + 全实体序列化进 Redis `[P1]`
- 频率:`app_client/amazon/main.py:311 HEARTBEAT_INTERVAL = 60`,每个在跑任务一次 POST `/api/tasks/{id}/heartbeat`。
- 服务端 `modules/task/service/TaskHeartbeatService.java:101-106 selectFileTask` 只有 `eq(id).last("limit 1")`,**没有 `.select()` 投影** ⇒ 把 `biz_file_task` 的 `request_json`、`result_json` 整列读回来(`FileTaskEntity.java:23-24`)。
- `:198-202` 无条件 `handler.saveTaskCache(task)`;`AbstractModuleTaskCacheService.java:203-216` 把**整个实体** `writeValueAsString` 后 `SET` 进 Redis(24h TTL)。
- 节流只有 similar-asin 实现了(`SimilarAsinTaskHeartbeatSpi.java:46 checkpointInterval()` 是全仓唯一覆盖点),其余模块每轮心跳都写。
- 同项目已有裁剪惯例,属漏改:`TaskProgressLightAssembler.java:49`、`StaleTaskRepairService.java:70`。
**改法**:`selectFileTask` 加 `.select(id, status, moduleType, userId, updatedAt)`;新增轻字段版缓存写入(或让心跳只写进度键,任务实体交给状态变更点)。
**风险**:PriceTrack 的 `loadTaskForExecution` 依赖缓存行里的 `requestJson` 非空(`TaskFinalizeSupport.java:32-33` 已注明),必须保留 DB 兜底路径。
`【待测】result_json 字节分布`:`SELECT id, LENGTH(result_json) FROM biz_file_task WHERE module_type IN ('QUERY_ASIN','PATROL_DELETE','SHOP_DATA_CRAWL') ORDER BY 2 DESC LIMIT 20;` —— 决定这一条值不值得动。
### B2 载荷物理删除每次跑两条无 task_id 的 JSON 全表 COUNT `[P1]`
- `TransientPayloadStorageService.java:329-340` 与 `:343-358`:先按 task_id 收敛查一次,**查不到就回退全表** `IN(payload_json, values)`;`:275` 的注释自己写明「调用方正常路径下引用数必然为 0」⇒ 正常删除路径**必然**走到全表回退。合计每次删除 4 条 COUNT,其中 2 条在 JSON/TEXT 列上无索引可走(V121 已删相关索引)。
- 调用面广:全仓 50+ 个 `deletePayloadIfPresent` / `deleteReplacedPayloadIfNeeded` 生产调用点(chunk 回传、scope state 覆盖、结果项升级旧对象等)。
- 已有的批量版 `TransientPayloadDeleteOrchestrator.batchReferencedPointers`(`:235`)目前只有 `ModuleHistoryCleanupService.java:339` 一个调用方在用;`TaskResultItemService.java:184` 注释显示结果项那条热路径已经改走编排器了。
**改法**:把剩余高频调用点改投 `submitDeletes(List.of(v))` + 周期 flush(编排器已带 journal 与去重);或让全局回退只在 `extractTaskId(pointer)` 解析失败时才执行(`:311` 已解析成功却仍全局查,等于把收敛当预筛而不是当边界)。
**风险**:去掉回退会重演 28459 误删——所以**只对"指针能解析出 task_id"的路径**取消全局回退,解析不出仍按现口径。
### B3 结果文件作业:三个调度参数互相打架 `[P1]`
- 每 10s claim 20 条并全部翻成 RUNNING(`TaskResultFileJobWorker.java:70-84` + yml:279 `local-worker-delay-ms:10000`、:285 `batch-size:20`);
- 本地派发池只有 2 线程、in-flight 满 64 就直接回落**在调度线程内联执行**(yml:276、`TaskFileJobLocalDispatcher.java:36-37,74-78`);
- 卡死线 5 分钟、每 60s 扫一次(yml:280、:283)⇒ 排队超 5 分钟的 RUNNING 被翻回 PENDING,真正开跑时 `activateRunningClaim` 的 CAS 失败,整轮白跑。
- 更实的问题:`:352-368` 对 PENDING 超阈值每轮 `retry_count++`(封顶 `MAX_RETRY_COUNT-1`=4,`MAX_RETRY_COUNT=5` 在 `:29`)⇒ **排队时间吃掉重试预算**,作业之后只要遇到一次真实 RUNNING 超时就直接判 FAILED,拿不到设计意图里的 5 次机会。
**改法**:`runPendingJobs` 的 limit 改 `min(batchSize, 本地剩余容量)`;PENDING 分支只补发 dispatch 事件、不递增 retry_count(`TaskFileJobService.java:352-368`)。
**风险**:47 个 `@Scheduled` 共用 pool-size 16(`SchedulingConfig.java:31`),内联回落会挤占其他定时任务;改完要回看 `requeued because task lock is busy` 计数有没有回升。
### B4 其余四条已定位的重复读 / 串行下载 `[P1-P2]`
| 位置 | 问题 | 量级 | 改法 |
|---|---|---|---|
| `SimilarAsinResultWorkbookAssembler.java:576-595`(+`:646-658`)、`AppearancePatentTaskService.java:2466-2485` | 导出时逐分片 `LIMIT 1` 分页取片,且每个源文件都全量重扫 | 源文件数 × 分片数 次单行 SELECT + 载荷 GET | 一次 `selectList` 取回片列表,按片自带 `scopeHash` 过滤(外观 `:517` 已按 submissionId 生成) |
| `SimilarAsinPayloadSupport.java:210/219/238` → `:244-259` | `prompt/apiKey/imgSwitch/categorySwitch` 各读一次全量 parsed payload(下载+反序列化+行对象复制 2-3 份),调用点 `SimilarAsinPipelineSupport.java:1018-1021` | 每轮回传 × 4-6 次全量读 | 合并成一个 `readTaskSettings(task)` 一次读完返回 record |
| `PuzzleImageMerger.java:97-106`(`:211-231` 重试) | 一行 16 张 1688/alibaba 图仍串行下载,单张 10s(yml:363 池是 8 但这里没用) | 每行最多 16 次串行往返,最坏 320s | 复用 `SimilarAsinImageEmbedder` 已有的 `CompletionService + downloadPool(8) + 全局 deadline` 取字节,按 index 落回原顺序 |
| `SimilarAsinLlmService.java:201`(`ProductCategoryService.java:43-50` 无缓存全表读)、`:359 tree.formatTwoLevels()` 每行重算 | 类目树每批全表 SELECT、两层清单每行重拼 | 图模式 `llm-batch-size:3` ⇒ 5000 行 ≈ 1667 次全表读 | `formatTwoLevels()` memoize;树按 `max(id)/updated_at` 做秒级 TTL |
`SimilarAsinImagePrefetchService.java:319 lookupBatch(...)` 已经写好但**全仓无调用方**,实际走 `:387 lookup(url)` 被 `SimilarAsinResultWorkbookAssembler.java:793-810` 在 URL 循环里逐条调;预热侧 `PREFETCH_POOL_SIZE=2` 且每 task 单 worker。属于"批量接口写了没接上"。
---
## 四、C 组:吞吐上限,先测再改
- **C1 单任务实际并发 ≈ 2,而闸给到 12。** 外观一轮批内:文本 10 行合 1 次调用、图片 10 行按 `llm-appearance-batch-size:5` 分 2 块并发(`AppearancePatentLlmClient.java:291-292` 的 `Semaphore(llmRowConcurrency=5)` 只在块数 >1 时才起作用),批与批之间串行(A1)。`task-queue.max-concurrent:12`(yml:314)远没用满。**先做 A1,再谈抬并发**——顺序反过来只会把等待搬个地方。
- **C2 代理上游有没有账号级并发/RPM 上限,仍未归因。** 没测之前,抬并发、补消费者、MQ 化三条路都只能算猜测(外观一批 10 行线上实测 `costMs` 已到 214869/249250,慢在上游不在本机)。取数:同一任务把 `llm-row-concurrency` 从 5 抬到 8,观察 429/超时率与 `costMs` 分位;有 429 就说明上限在代理。
- **C3 按负载选机(主机B 目前基本闲着)比 MQ 化便宜一个数量级。** `owner_instance_id` + `aiimage.instance-routing` 已保证"任务在哪台就由那台跑完",只需把**新任务落地机器**从"客户端解析到谁"改成按在飞作业数选机,不碰批次语义。
- **C4 风控降级是进程全局的**:`func/amazon_base.py:163-168` 每页 401/403/503 都进同一个闸门,`config.py:51-54`(300s 窗口 / 阈值 8 / HOLD 600s)触发后把 4 槽压到 1 至少 10 分钟 ≈ 少产出 440 行(按单槽 880 行/h),且一个坏 cookie 池或一国风控会拖垮全部任务类型。改法:闸门按 `(task_type, country)` 分桶。**阈值要先看线上信号频次再动**,放宽等于真多烧代理费。
---
## 五、D 组:交付层低成本项
- **D1 管理后台首屏比用户端大 5.2 倍。** 实测产物:`admin-frontend-vue/dist/assets/index-CAmaFJ39.js` **1,127,603 B** + `index-CSE0eCeX.css` 383,318 B;用户端 `frontend-vue/new_web_source/assets/index-BwjSp_ZA.js` 217,568 B。根因:`admin-frontend-vue/src/main.ts:3-5` 全量 `import ElementPlus` + `element-plus/dist/index.css`,`vite.config.ts:32-35` 的 build 块没有 `manualChunks`。改法照用户端(`frontend-vue/vite.config.ts:5-7` 用 ElementPlusResolver),命令式组件样式按用户端 `main.ts:7-8` 补两行。**这是纯前端构建改动,风险最低、见效最快。**
- **D2 轻量进度端点已就绪但只接了 5/12。** `frontend-vue/src/shared/api/progress-light.ts:19-32` 白名单 12 个模块、`endpoints.ts` 12 个 `progressLight` 都在;实际只有 appearancePatent / patrolDelete / queryAsin / shopDataCrawl / withdraw 五个 tab 调 `getModuleProgressLight`。`BrandSimilarAsinTab.vue:206` 仍传重型 `getSimilarAsinTaskProgressBatch`(同类还有 publish / priceTrack / collectData / deleteBrand / productRisk / shopMatch)。`useLiveTaskBoard.ts:430` 无条件调 `fetchProgressBatch`,所以每个 tab 的收益取决于它自己传的是哪个函数——照 `BrandAppearancePatentTab.vue:159` 的 `beforeBatch` + 行版本门控写法迁移即可。轮询节奏:可见 10s / 隐藏 60s(`task-progress-config.ts:16-17`)。
- **D3 后台列表拉 LONGTEXT。** `modules/imagevideo/mapper/ImageVideoAdminTaskMapper.java:19` 列表 SELECT 了 `request_json/submit_response_json/result_json/video_urls_json/archived_videos_json`(V71 为 LONGTEXT),但列表只用 `request_json` 里一个标量(`ImageVideoAdminTaskService.java:226 modeOf`),另两列只有详情 `:238-245` 用。同类:`ShopDataCrawlDailyFileService.java:138-142` 无投影读 `row_payload`(MEDIUMTEXT, V93)却只用于判空(`ShopDataCrawlTaskService.java:849`)/取 resultId(`ShopDataCrawlAdminTasksService.java:96`)。改法:列表用 `JSON_UNQUOTE(JSON_EXTRACT(...))` 取标量,大列留给详情查询。
- **D4 任务中心看板每 30s 全量 UNION COUNT + OFFSET 分页。** `TaskCenterBoardPage.vue:43,242` 每 30s 三接口;`TaskCenterQueryService.java:137` 对 `biz_file_task ∪ brand_crawl_tasks` 无时间界计数、`:144` OFFSET 无页上限;`TaskCenterQueryMapper.java:258-274` 的 UNION-ALL 每页被执行两遍,`:220-229` 含 4 个相关子查询 `EXISTS … LIKE '%…%'`。改法:总数短 TTL 缓存 + `last_id` 游标(范式见 `DedupeTotalDataService.java:194-201`)。
- **D5 gzip 需要取证再定。** 仓库里的网关模板 `scripts/deploy_nginx_gateway.py:70-84` 只有 sendfile/tcp_nopush,全仓 grep 无 `gzip on`;但线上真正生效的是主机B `/opt/1panel/www/conf.d/api.aishufu.top.conf`(不在仓库),1Panel 可能已在全局开 gzip。**先 `curl -H 'Accept-Encoding: gzip' -sI <json接口>` 看有没有 `Content-Encoding`**,有就别动。
- **D6 无依赖的串行 await**:`BrandPriceTrackTab.vue:1652-1653`、`BrandProductRiskTab.vue:495-496,805-806` 先 `await loadHistory()` 再 `await loadDashboard()`,两者互不依赖;`GroupEditorDialog.vue:58`、`pages/records/history-api.ts:17` 用 `page_size=999` 一次拉全量用户。
---
## 六、口径已知的遗留杠杆(不是新发现,列出来免得重复讨论)
1. **外观专利图片按内容寻址缓存** —— 唯一攻图片输入 token 的一条,也是合批之后剩余最大的成本杠杆,仍未做。
2. **ASIN 跨任务缓存命中率低的真实原因(本次查清)**:键设计是干净的 `(country, asin)` 唯一键(`AsinResultCacheMapper.java:49-72`),TTL 按采集端真实开页时间 `observed_at`(`AsinResultCacheService.java:232`)——**不是键坏了**。0.1% 命中来自覆盖面与截断:服务端唯一写入口在 `CollectDataService.java:1855` 且硬编码 `AVAILABILITY_OK`(`AsinResultCacheService.java:187`);多选国家直接不写(`CollectDataService.java:1867-1874` → `AsinResultCacheService.java:175-178`);空价不写(`:181-183`);单次查询/写入各 500 行截断且不补查(`:95-98`、`:134-137`,默认值 yml:404-405);表没有保留期清理任务。要提命中率,动"多国家不写"和 500 截断这两处,别动 TTL。
3. `FOR UPDATE SKIP LOCKED` 路线仍未实施。
4. `biz_file_task.result_json` 存明文 apiKey 的泄露面仍未处理。
## 七、已经排除、不必再查的
加索引方向(瓶颈是行锁与大 JSON 列);清 `/app/java` 的 jar 备份;缩短 `DEFAULT_WAIT_MILLIS`;进一步合并 LLM 调用次数 / 词典替提词 / 拼图合并 / 家族页一次取价;空价格行的 KKBrowser 兜底耗时(只占 3.3%~3.9%);结果文件作业"纯轮询驱动"(`TaskFileJobDispatchCoordinator.java:25-45` 有事件点火);前端 `setInterval` 泄漏(两侧 8 个调用点,卸载清理与模块级单例都核过);Excel 导出(写出统一 `SXSSFWorkbook(200)` 流式,读入已改流式);`TaskObservabilityMetrics` 确认未接生产(无 `@Component`、无生产调用方、pom 无 prometheus registry),要做告警走日志字段或补 registry。
## 八、建议执行顺序
1. **A1 + B3**(外观批间重读 + 结果作业调度)——都在 jar 里,可同批发;A1 单条就能把 5000 行任务的批间空档基本抹掉。
2. **A2**——需要一次判定口径的确认(同批同品牌共享结论),拍完就改。
3. **A4**(18960)+ **A3**(采集机 `更新并重启.bat`,与变体攒批同一次更新)——与既欠的 18960 / 4.0.42 发版并批,不额外开窗口。
4. **D1**(后台分包按需)——纯前端,随时可做。
5. **B1/B2/B4** 一批发,收益是 DB 与对象存储往返,不改语义。
6. **C2 的归因测量**与 C1/C3 的实施穿插做;不要在测出代理上限之前抬并发。
@@ -5,17 +5,12 @@
<div class="main-content">
<aside class="left-panel left-panel--with-template">
<div class="section-title">上传文件</div>
<div class="upload-zone">
<div class="hint">选择 Excel 后点击解析,系统会识别表格里的 ID、ASIN、国家信息;同一 ID 有多行时只保留第一行。</div>
<div class="btns">
<button type="button" class="opt-btn" @click="selectFiles">选择 Excel</button>
<button type="button" class="opt-btn" @click="selectFolder">选择文件夹</button>
</div>
<div class="selected-files">
<span v-if="!selectedFileNames.length">暂未选择文件</span>
<span v-for="name in selectedFileNames" v-else :key="name">{{ name }}</span>
</div>
</div>
<FileUploadZone
hint="选择 Excel 后点击解析,系统会识别表格里的 ID、ASIN、国家信息;同一 ID 有多行时只保留第一行。"
:names="selectedFileNames"
@select-files="selectFiles"
@select-folder="selectFolder"
/>
<div class="prompt-card">
<div class="section-title">新增条件要求</div>
@@ -76,6 +71,7 @@
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
import FileUploadZone from '@/shared/components/FileUploadZone.vue'
import ModuleTemplateDownload from '@/shared/components/ModuleTemplateDownload.vue'
import TaskCenterPanel from '@/shared/components/tasks/TaskCenterPanel.vue'
import type { TaskItemView, TaskStatCard } from '@/shared/components/tasks/types'
@@ -87,33 +83,47 @@ import {
getAppearancePatentResultDownloadUrl,
getAppearancePatentTaskProgressBatch,
parseAppearancePatent,
type AppearancePatentDashboardVo,
type AppearancePatentHistoryItem,
type AppearancePatentParseVo,
type UploadedFileRef,
type UploadFileVo,
} from '@/shared/api/java-modules'
import { expandBrandFolderRecursive } from '@/shared/api/brand'
import { getPywebviewApi } from '@/shared/bridges/pywebview'
import { getTaskPollIntervalMs } from '@/shared/task-progress-config'
import { getStoredApiSecret } from '@/shared/utils/api-secret-store'
import { createCategorizedTimers } from '@/shared/utils/categorized-timers'
import { saveUrlWithProgress } from '@/shared/utils/download-progress'
import { useExcelFileUpload } from '@/shared/composables/useExcelFileUpload'
import {
EXCEL_EXTENSIONS,
checkParseResult,
checkSelectedFiles,
} from '@/shared/dispatch-guard'
import { passGuard } from '@/shared/dispatch-guard-ui'
import { formatDateTime } from '@/shared/utils/datetime'
import { uploadPathsToJava } from '@/shared/utils/upload-to-java'
import { runBatchDelete } from '@/shared/utils/batch-delete'
useLiveTaskBoard,
activeFileJobStatus,
hasActiveFileJob,
shouldShowFallbackJobProgress,
} from '@/shared/composables/useLiveTaskBoard'
import { getModuleProgressLight } from '@/shared/api/progress-light.ts'
import { createRowsVersionTracker } from '@/shared/api/task-progress-polling.ts'
import { confirmTaskDeletion } from '@/shared/task-delete-confirm'
import { checkParseResult } from '@/shared/dispatch-guard'
import { passGuard } from '@/shared/dispatch-guard-ui'
import { formatDateTime } from '@/shared/utils/datetime'
import { taskStatusClass, taskStatusText } from '@/shared/utils/task-status-text'
import { getStoredApiSecret } from '@/shared/utils/api-secret-store'
// ---- 文件选择 / 上传(公共组合式函数)----
const {
files: uploadedFiles,
selectedPaths: selectedFileNames,
selectFiles,
selectFolder,
} = useExcelFileUpload({
requireUploadCapability: true,
pickFilesUnavailableWarning: '当前环境不支持文件选择或上传',
folderUnavailableWarning: '当前环境不支持文件夹选择,请在本地客户端中打开',
errorFallbackMessage: (action) => (action === 'files' ? '文件上传失败' : '选择失败'),
onUploaded: () => {
parseResult.value = null
queuedTaskSummary.value = null
},
onFailed: () => {
parseResult.value = null
queuedTaskSummary.value = null
},
})
const selectedFileNames = ref<string[]>([])
const uploadedFiles = ref<UploadFileVo[]>([])
const parseResult = ref<AppearancePatentParseVo | null>(null)
type TaskSummary = Pick<AppearancePatentParseVo, 'taskId' | 'totalRows' | 'acceptedRows' | 'groupCount' | 'droppedRows'>
const queuedTaskSummary = ref<TaskSummary | null>(null)
@@ -121,30 +131,66 @@ const queuedTaskSummary = ref<TaskSummary | null>(null)
const aiPrompt = ref('')
const parsing = ref(false)
const pushing = ref(false)
const pollingTaskIds = ref<number[]>([])
const pendingFileTaskIds = ref<number[]>([])
const pollTimer = ref<number | null>(null)
const pollingInFlight = ref(false)
const HISTORY_CACHE_TTL_MS = 3000
let historyInFlight: Promise<void> | null = null
let lastHistoryLoadedAt = 0
let disposed = false
const timers = createCategorizedTimers('appearance-patent')
const dashboard = ref<AppearancePatentDashboardVo>({
pendingTaskCount: 0,
processedTaskCount: 0,
successTaskCount: 0,
failedTaskCount: 0,
/** 结果行版本跟踪(审查 F5 后续):版本未变的任务跳过行明细拉取 */
const rowsVersionTracker = createRowsVersionTracker()
function uidForStorage() {
return typeof window !== 'undefined' ? window.localStorage.getItem('uid') || '0' : '0'
}
// ---- 实时任务面板(与货源查询 Tab 的公共骨架抽到 useLiveTaskBoard)----
const board = useLiveTaskBoard<AppearancePatentHistoryItem>({
scope: 'appearance-patent',
pollingStorageKey: () => `appearance-patent:tasks:${uidForStorage()}`,
fetchHistory: getAppearancePatentHistory,
fetchProgressBatch: getAppearancePatentTaskProgressBatch,
fetchDashboard: getAppearancePatentDashboard,
normalizeTaskStatus,
isResultPreparing,
addPendingAfterFinalStatus: (_task, item) => Boolean(item && isResultPreparing(item)),
keepPendingFileTask: (_item, taskStatus) => taskStatus === 'SUCCESS' || taskStatus === 'FAILED',
settleOnTaskStatuses: ['SUCCESS', 'FAILED'],
beforeBatch: async (taskIds, pendingIds) => {
// 行数据按需拉取(审查 F5 后续):等结果文件(pending)时必须强刷;其余情况版本未变的任务跳过
const mustForce = pendingIds.length > 0
if (!mustForce) {
try {
const light = await getModuleProgressLight('appearancePatent', taskIds)
const heavyIds = rowsVersionTracker.selectTasksNeedingRows(light.items || [], taskIds)
if (!heavyIds.length && !(light.missingTaskIds || []).length) {
// 行数据与状态都没变:本轮不拉行明细,直接结束
return null
}
return { taskIds: heavyIds, force: false }
} catch {
// 轻量端点不可用(老后端/网络)→ 照旧全量拉取,行为与原来一致
return { taskIds, force: false }
}
}
return { taskIds, force: true }
},
// 轮询回调抛错时上抛、轮询停止(与原实现一致)
pollErrorMode: 'propagate',
getPendingParseItem: () => pendingParseItem.value,
download: {
buildUrl: (resultId) => getAppearancePatentResultDownloadUrl(resultId),
fallbackFilename: 'appearance-patent',
progressKeyPrefix: 'appearance-patent',
},
deleteTask: {
shouldDeleteTask: (item) => item.taskStatus === 'RUNNING' && item.taskId != null,
deleteTask: (taskId) => deleteAppearancePatentTask(taskId),
deleteHistory: (resultId) => deleteAppearancePatentHistory(resultId),
onTaskDeleted: (item) => board.removePollingTask(item.taskId as number),
},
})
const historyItems = ref<AppearancePatentHistoryItem[]>([])
const liveProgressItems = ref<Record<number, AppearancePatentHistoryItem>>({})
const visibleTaskSummary = computed(() => parseResult.value || queuedTaskSummary.value)
const pendingParseItem = computed<AppearancePatentHistoryItem | null>(() => {
const result = parseResult.value
if (!result?.taskId) return null
const exists = historyItems.value.some((item) => item.taskId === result.taskId)
const exists = board.historyItems.value.some((item) => item.taskId === result.taskId)
if (exists) return null
return {
taskId: result.taskId,
@@ -154,47 +200,20 @@ const pendingParseItem = computed<AppearancePatentHistoryItem | null>(() => {
success: false,
}
})
const currentItems = computed(() => {
const activeIds = new Set([...pollingTaskIds.value, ...pendingFileTaskIds.value])
const activeItems = historyItems.value
.filter((item) => {
const status = normalizeTaskStatus(item)
return item.taskId != null && (activeIds.has(item.taskId) || status === 'RUNNING' || status === 'PENDING')
})
.map((item) => mergeCurrentTaskItem(item))
for (const [taskIdText, liveItem] of Object.entries(liveProgressItems.value)) {
const taskId = Number(taskIdText)
if (!Number.isFinite(taskId) || taskId <= 0) continue
if (!activeIds.has(taskId) && normalizeTaskStatus(liveItem) !== 'RUNNING' && normalizeTaskStatus(liveItem) !== 'PENDING') {
continue
}
if (activeItems.some((item) => item.taskId === taskId)) continue
activeItems.push(mergeCurrentTaskItem(liveItem))
}
if (!pendingParseItem.value) return activeItems
const exists = activeItems.some((item) => item.taskId === pendingParseItem.value?.taskId)
return exists ? activeItems : [pendingParseItem.value, ...activeItems]
})
const historyOnlyItems = computed(() =>
historyItems.value.filter((i) => {
const status = normalizeTaskStatus(i)
return status !== 'RUNNING' && status !== 'PENDING'
}),
)
const patentCards = computed<TaskStatCard[]>(() => [
{ label: '运行中任务', value: dashboard.value.pendingTaskCount },
{ label: '已结束任务', value: dashboard.value.processedTaskCount },
{ label: '成功任务', value: dashboard.value.successTaskCount },
{ label: '失败任务', value: dashboard.value.failedTaskCount },
{ label: '运行中任务', value: board.dashboard.value.pendingTaskCount },
{ label: '已结束任务', value: board.dashboard.value.processedTaskCount },
{ label: '成功任务', value: board.dashboard.value.successTaskCount },
{ label: '失败任务', value: board.dashboard.value.failedTaskCount },
])
const currentTaskViews = computed<TaskItemView[]>(() =>
currentItems.value.map(toPatentTaskView),
board.currentItems.value.map(toPatentTaskView),
)
const historyTaskViews = computed<TaskItemView[]>(() =>
historyOnlyItems.value.map(toPatentTaskView),
board.historyOnlyItems.value.map(toPatentTaskView),
)
function itemSource(item: TaskItemView) {
@@ -202,7 +221,7 @@ function itemSource(item: TaskItemView) {
}
function toPatentTaskView(item: AppearancePatentHistoryItem): TaskItemView {
const showProgress = showFileProgress(item)
const showProgress = board.showFileProgress(item)
const progressPercent = fileProgressPercent(item)
return {
key: `patent-${item.taskId ?? item.resultId ?? item.sourceFilename}`,
@@ -227,20 +246,113 @@ function toPatentTaskView(item: AppearancePatentHistoryItem): TaskItemView {
}
}
function mergeCurrentTaskItem(item: AppearancePatentHistoryItem) {
if (item.taskId == null) return item
const liveItem = liveProgressItems.value[item.taskId]
if (!liveItem) return item
return {
...item,
...liveItem,
sourceFilename: liveItem.sourceFilename || item.sourceFilename,
resultFilename: liveItem.resultFilename || item.resultFilename,
rowCount: liveItem.rowCount ?? item.rowCount,
createdAt: liveItem.createdAt || item.createdAt,
}
// ---- 本模块的状态语义(与货源查询 Tab 不同,保留在 Tab 内)----
function statusText(item: AppearancePatentHistoryItem) {
const status = normalizeTaskStatus(item)
if (status === 'RUNNING') return taskStatusText(status)
if (status === 'PENDING') return taskStatusText(status, { text: { PENDING: '已解析,等待后台执行' } })
// 已判死(含心跳超时)的任务始终显示失败:后台检测可能仍在跑、文件生成后下载按钮会自动出现,
// 但状态文案不能是"结果生成中",否则用户会以为任务还在执行(2026-09-28 29473/29479)
if (status === 'FAILED') return isResultBuildFailed(item) ? '结果生成失败' : taskStatusText('FAILED')
if (isResultPreparing(item)) return '结果生成中'
if (isResultBuildFailed(item)) return '结果生成失败'
if (hasDownloadableResult(item)) return taskStatusText('SUCCESS')
if (status === 'SUCCESS' || item.success) return taskStatusText('SUCCESS')
return '等待中'
}
function statusClass(item: AppearancePatentHistoryItem) {
const status = normalizeTaskStatus(item)
if (status === 'FAILED' || isResultBuildFailed(item)) return taskStatusClass('FAILED')
if (status === 'RUNNING' || isResultPreparing(item)) return taskStatusClass('RUNNING')
if (hasDownloadableResult(item)) return taskStatusClass('SUCCESS')
if (status === 'SUCCESS' || item.success) return taskStatusClass('SUCCESS')
return 'pending'
}
function isResultPreparing(item: AppearancePatentHistoryItem) {
const status = normalizeTaskStatus(item)
const fileStatus = (item.fileStatus || '').toUpperCase()
if (status !== 'SUCCESS' && status !== 'FAILED') return false
if (canDownload(item)) return false
if (fileStatus === 'FAILED' || fileStatus === 'SUCCESS') return false
return status === 'SUCCESS' || hasActiveFileJob(item)
}
function normalizeTaskStatus(item: AppearancePatentHistoryItem) {
return (item.taskStatus || '').toUpperCase()
}
function isResultBuildFailed(item: AppearancePatentHistoryItem) {
return (item.fileStatus || '').toUpperCase() === 'FAILED'
}
function pendingResultHint(item: AppearancePatentHistoryItem) {
if (isResultBuildFailed(item)) {
return item.fileError || '结果文件生成失败,请稍后重试或检查后端日志'
}
if (board.showFileProgress(item)) {
return ''
}
if (!isResultPreparing(item)) return ''
const doneLabel = normalizeTaskStatus(item) === 'FAILED' ? '任务已失败' : '任务已完成'
const fileStatus = (item.fileStatus || '').toUpperCase()
if (fileStatus === 'PENDING') {
return `${doneLabel},结果文件排队中,请稍候`
}
return `${doneLabel},正在生成结果文件,下载按钮稍后出现`
}
function canDownload(item: AppearancePatentHistoryItem) {
return Boolean(item.resultId && (item.fileReady || item.downloadUrl))
}
function hasDownloadableResult(item: AppearancePatentHistoryItem) {
return canDownload(item)
}
function fileProgressPercent(item: AppearancePatentHistoryItem) {
const percent = Number(item.fileProgressPercent || 0)
if (Number.isFinite(percent) && percent > 0) {
return Math.max(0, Math.min(100, Math.round(percent)))
}
if (shouldShowFallbackJobProgress(item)) {
return activeFileJobStatus(item) === 'PENDING' ? 6 : 10
}
return 0
}
function displayFileProgressMessage(item: AppearancePatentHistoryItem, fallback: string) {
const message = (item.fileProgressMessage || '').trim()
if (!message) return fallback
return translateFileProgressMessage(message)
}
function translateFileProgressMessage(message: string) {
const submittedMatch = message.match(/^LLM submitted (\d+) batches, completed (\d+), waiting for results$/)
if (submittedMatch) {
return `已提交 ${submittedMatch[1]} 批,已完成 ${submittedMatch[2]} 批,等待结果`
}
const completedMatch = message.match(/^LLM completed (\d+) batches, waiting for remaining Python data$/)
if (completedMatch) {
return `已完成 ${completedMatch[1]} 批,等待后续数据`
}
const translations: Record<string, string> = {
'Receiving Python data, waiting for 50 rows before LLM': '正在接收检测数据,累计 50 条后提交检测',
'Submitting LLM': '正在提交检测',
'LLM submitted, waiting for result': '已提交检测,等待结果',
'Waiting for Python upload': '等待后续数据',
'LLM results ready, assembling xlsx': '检测结果已返回,正在生成结果文件',
'Assembling xlsx': '正在生成结果文件',
'Uploading result file': '正在上传结果文件',
'Result file generated': '结果文件已生成',
}
return translations[message] || message
}
// ---- 解析与提交(本模块特有)----
function effectiveAiPrompt() {
// 用户没在文本框填东西就送空字符串,后端会跳过 prompt 字段。
return aiPrompt.value.trim()
@@ -250,15 +362,6 @@ function effectiveLlmApiKey() {
return getStoredApiSecret('appearance-patent').trim()
}
function uidForStorage() {
return typeof window !== 'undefined' ? window.localStorage.getItem('uid') || '0' : '0'
}
function pollingKey() {
return `appearance-patent:tasks:${uidForStorage()}`
}
function toTaskSummary(result: AppearancePatentParseVo): TaskSummary {
return {
taskId: result.taskId,
@@ -269,80 +372,6 @@ function toTaskSummary(result: AppearancePatentParseVo): TaskSummary {
}
}
function savePollingIds() {
if (typeof window === 'undefined') return
const ids = Array.from(new Set([...pollingTaskIds.value, ...pendingFileTaskIds.value]))
if (!ids.length) window.localStorage.removeItem(pollingKey())
else window.localStorage.setItem(pollingKey(), JSON.stringify(ids))
}
function loadPollingIds() {
if (typeof window === 'undefined') return
try {
const raw = window.localStorage.getItem(pollingKey())
const ids = raw ? JSON.parse(raw) : []
pollingTaskIds.value = Array.isArray(ids)
? ids.filter((id): id is number => typeof id === 'number' && id > 0)
: []
} catch {
pollingTaskIds.value = []
}
}
async function selectFiles() {
const api = getPywebviewApi()
if (!api?.select_brand_xlsx_files || !api.upload_file_to_java) {
ElMessage.warning('当前环境不支持文件选择或上传')
return
}
const paths = await api.select_brand_xlsx_files()
if (!paths?.length) return
if (!(await passGuard(checkSelectedFiles(paths, { allowedExtensions: EXCEL_EXTENSIONS })))) return
try {
const files = await uploadPathsToJava(getPywebviewApi(), paths)
uploadedFiles.value = files
selectedFileNames.value = files.map((f) => f.relativePath || f.originalFilename || f.fileKey)
parseResult.value = null
queuedTaskSummary.value = null
} catch (error) {
// 上传失败时清空选择,避免残留上一批文件让用户误以为新文件已就绪
uploadedFiles.value = []
selectedFileNames.value = []
parseResult.value = null
queuedTaskSummary.value = null
ElMessage.error(error instanceof Error ? error.message : '文件上传失败')
}
}
async function selectFolder() {
const api = getPywebviewApi()
if (!api?.select_brand_folder) {
ElMessage.warning('当前环境不支持文件夹选择,请在本地客户端中打开')
return
}
try {
const folder = await api.select_brand_folder()
if (!folder) return
const result = await expandBrandFolderRecursive(folder)
if (!result.success || !result.items?.length) {
ElMessage.warning(result.error || '该文件夹下没有可用的 xlsx 文件')
return
}
if (!(await passGuard(checkSelectedFiles(result.items, { allowedExtensions: EXCEL_EXTENSIONS })))) return
const files = await uploadPathsToJava(getPywebviewApi(), result.items)
uploadedFiles.value = files
selectedFileNames.value = result.items.map((item) => item.relativePath || item.absolutePath)
parseResult.value = null
queuedTaskSummary.value = null
ElMessage.success(`已选择文件夹内 ${result.items.length} 个 Excel 文件`)
} catch (error) {
uploadedFiles.value = []
selectedFileNames.value = []
parseResult.value = null
ElMessage.error(error instanceof Error ? error.message : '选择失败')
}
}
/**
* 本模块按 id 列分组,同组只检测 1 次并把结论复制给组内其它行。
* 生产事故(任务 28805):源表 id 列 904 行全填 "1",整表塌成 1 组,105 秒就"完成"了。
@@ -423,10 +452,10 @@ async function pushToPythonQueue() {
pushing.value = true
try {
queuedTaskSummary.value = toTaskSummary(currentParseResult)
addPollingTask(taskId)
board.addPollingTask(taskId)
clearParsedTask()
await loadDashboard()
await loadHistory({ force: true })
await board.loadDashboard()
await board.loadHistory({ force: true })
ElMessage.success('已提交,后台自动执行中(无需打开浏览器)')
} finally {
pushing.value = false
@@ -437,476 +466,22 @@ function clearParsedTask() {
parseResult.value = null
}
function addPollingTask(taskId: number) {
if (!pollingTaskIds.value.includes(taskId)) {
pollingTaskIds.value = [...pollingTaskIds.value, taskId]
savePollingIds()
}
ensurePolling()
}
function removePollingTask(taskId: number) {
pollingTaskIds.value = pollingTaskIds.value.filter((id) => id !== taskId)
if (!pendingFileTaskIds.value.includes(taskId)) {
const next = { ...liveProgressItems.value }
delete next[taskId]
liveProgressItems.value = next
}
savePollingIds()
}
function addPendingFileTask(taskId: number) {
if (!pendingFileTaskIds.value.includes(taskId)) {
pendingFileTaskIds.value = [...pendingFileTaskIds.value, taskId]
savePollingIds()
}
ensurePolling()
}
function removePendingFileTask(taskId: number) {
pendingFileTaskIds.value = pendingFileTaskIds.value.filter((id) => id !== taskId)
if (!pollingTaskIds.value.includes(taskId)) {
const next = { ...liveProgressItems.value }
delete next[taskId]
liveProgressItems.value = next
}
savePollingIds()
}
function ensurePolling() {
if (disposed) return
if (pollTimer.value != null) return
scheduleNextPoll(true)
}
function stopPolling() {
if (pollTimer.value != null) {
timers.clearTimer('task-poll', pollTimer.value)
pollTimer.value = null
}
}
function scheduleNextPoll(immediate = false) {
if (disposed) return
if (pollTimer.value != null) {
if (!immediate) return
timers.clearTimer('task-poll', pollTimer.value)
pollTimer.value = null
}
const run = async () => {
pollTimer.value = null
if (disposed) return
if (!pollingTaskIds.value.length && !pendingFileTaskIds.value.length) return
await refreshTaskProgress()
if (!disposed && pollTimer.value == null && (pollingTaskIds.value.length || pendingFileTaskIds.value.length)) {
pollTimer.value = timers.setTimeout('task-poll', run, getTaskPollIntervalMs())
}
}
if (immediate) void run()
else pollTimer.value = timers.setTimeout('task-poll', run, getTaskPollIntervalMs())
}
/** 结果行版本跟踪(审查 F5 后续):版本未变的任务跳过行明细拉取 */
const rowsVersionTracker = createRowsVersionTracker()
async function refreshTaskProgress() {
if (pollingInFlight.value || (!pollingTaskIds.value.length && !pendingFileTaskIds.value.length)) {
if (!pollingTaskIds.value.length && !pendingFileTaskIds.value.length) stopPolling()
return
}
pollingInFlight.value = true
try {
let shouldRefreshDashboard = false
let shouldRefreshHistory = false
const taskIds = Array.from(new Set([...pollingTaskIds.value, ...pendingFileTaskIds.value]))
if (taskIds.length) {
// 行数据按需拉取(审查 F5 后续):等结果文件(pending)时必须强刷;其余情况版本未变的任务跳过
let heavyIds = taskIds
const mustForce = pendingFileTaskIds.value.length > 0
if (!mustForce) {
try {
const light = await getModuleProgressLight('appearancePatent', taskIds)
heavyIds = rowsVersionTracker.selectTasksNeedingRows(light.items || [], taskIds)
if (!heavyIds.length && !(light.missingTaskIds || []).length) {
// 行数据与状态都没变:本轮不拉行明细,直接结束
return
}
} catch {
// 轻量端点不可用(老后端/网络)→ 照旧全量拉取,行为与原来一致
heavyIds = taskIds
}
}
const batch = await getAppearancePatentTaskProgressBatch(heavyIds, { force: mustForce })
for (const detail of batch.items || []) {
const task = detail.task
if (!task?.id) continue
const item = detail.items?.[0]
if (item) {
liveProgressItems.value = {
...liveProgressItems.value,
[task.id]: item,
}
mergeHistoryItem(item)
}
if (task.status === 'SUCCESS' || task.status === 'FAILED') {
removePollingTask(task.id)
shouldRefreshDashboard = true
if (item && isResultPreparing(item)) addPendingFileTask(task.id)
else removePendingFileTask(task.id)
}
if (item && (task.status === 'SUCCESS' || task.status === 'FAILED') && pendingFileTaskIds.value.includes(task.id)) {
const fileStatus = (item.fileStatus || '').toUpperCase()
if (item.fileReady || fileStatus === 'SUCCESS' || fileStatus === 'FAILED') {
removePendingFileTask(task.id)
shouldRefreshDashboard = true
shouldRefreshHistory = true
}
}
}
if (batch.missingTaskIds?.length) {
batch.missingTaskIds.forEach((taskId) => {
removePollingTask(taskId)
removePendingFileTask(taskId)
})
shouldRefreshHistory = true
shouldRefreshDashboard = true
}
}
if (shouldRefreshDashboard) {
await loadDashboard()
}
if (shouldRefreshHistory) {
await loadHistory()
}
settlePendingFileTasks()
} finally {
pollingInFlight.value = false
}
}
function mergeHistoryItem(item: AppearancePatentHistoryItem) {
if (!item.taskId && !item.resultId) return
const index = historyItems.value.findIndex((row) =>
(item.resultId != null && row.resultId === item.resultId)
|| (item.taskId != null && row.taskId === item.taskId),
)
if (index >= 0) {
historyItems.value[index] = { ...historyItems.value[index], ...item }
} else {
historyItems.value = [item, ...historyItems.value]
}
}
function settlePendingFileTasks() {
if (!pendingFileTaskIds.value.length) return
const remaining: number[] = []
for (const taskId of pendingFileTaskIds.value) {
const item = historyItems.value.find((row) => row.taskId === taskId)
if (!item) {
remaining.push(taskId)
continue
}
const taskStatus = (item.taskStatus || '').toUpperCase()
const fileStatus = (item.fileStatus || '').toUpperCase()
if (item.fileReady || fileStatus === 'SUCCESS' || fileStatus === 'FAILED') {
continue
}
if (taskStatus === 'SUCCESS' || taskStatus === 'FAILED') {
remaining.push(taskId)
}
}
pendingFileTaskIds.value = remaining
savePollingIds()
if (pendingFileTaskIds.value.length) ensurePolling()
}
function seedPendingFileTasksFromHistory() {
const ids = historyItems.value
.filter((item) => item.taskId != null && isResultPreparing(item))
.map((item) => item.taskId as number)
pendingFileTaskIds.value = Array.from(new Set(ids))
savePollingIds()
if (pendingFileTaskIds.value.length) ensurePolling()
}
function seedRunningTasksFromHistory() {
const ids = historyItems.value
.filter((item) => item.taskId != null && normalizeTaskStatus(item) === 'RUNNING')
.map((item) => item.taskId as number)
if (!ids.length) return
pollingTaskIds.value = Array.from(new Set([...pollingTaskIds.value, ...ids]))
savePollingIds()
ensurePolling()
}
async function loadDashboard() {
dashboard.value = await getAppearancePatentDashboard()
}
async function loadHistory(options: { force?: boolean } = {}) {
const now = Date.now()
if (!options.force && historyItems.value.length && now - lastHistoryLoadedAt < HISTORY_CACHE_TTL_MS) return
if (historyInFlight) return historyInFlight
historyInFlight = getAppearancePatentHistory()
.then((res) => {
historyItems.value = mergeHistoryItemsPreservingLiveProgress(historyItems.value, res.items || [])
lastHistoryLoadedAt = Date.now()
})
.finally(() => {
historyInFlight = null
})
return historyInFlight
}
function mergeHistoryItemsPreservingLiveProgress(
previousItems: AppearancePatentHistoryItem[],
incomingItems: AppearancePatentHistoryItem[],
) {
const previousByTaskId = new Map<number, AppearancePatentHistoryItem>()
const previousByResultId = new Map<number, AppearancePatentHistoryItem>()
for (const item of previousItems || []) {
if (item.taskId != null) previousByTaskId.set(item.taskId, item)
if (item.resultId != null) previousByResultId.set(item.resultId, item)
}
return (incomingItems || []).map((incoming) => {
const previous = incoming.resultId != null
? previousByResultId.get(incoming.resultId)
: incoming.taskId != null
? previousByTaskId.get(incoming.taskId)
: undefined
return mergeHistoryItemPreservingLiveProgress(previous, incoming)
})
}
function mergeHistoryItemPreservingLiveProgress(
previous: AppearancePatentHistoryItem | undefined,
incoming: AppearancePatentHistoryItem,
) {
if (!previous) return incoming
const shouldPreserveLiveProgress =
(normalizeTaskStatus(previous) === 'RUNNING' || isResultPreparing(previous) || showFileProgress(previous))
&& !showFileProgress(incoming)
&& !canDownload(incoming)
if (!shouldPreserveLiveProgress) {
return incoming
}
return {
...incoming,
fileJobId: incoming.fileJobId ?? previous.fileJobId,
fileStatus: incoming.fileStatus || previous.fileStatus,
fileError: incoming.fileError || previous.fileError,
fileReady: incoming.fileReady || previous.fileReady,
fileProgressPercent: hasMeaningfulProgressValue(incoming.fileProgressPercent)
? incoming.fileProgressPercent
: previous.fileProgressPercent,
fileProgressCurrent: hasMeaningfulProgressValue(incoming.fileProgressCurrent)
? incoming.fileProgressCurrent
: previous.fileProgressCurrent,
fileProgressTotal: hasMeaningfulProgressValue(incoming.fileProgressTotal)
? incoming.fileProgressTotal
: previous.fileProgressTotal,
fileProgressMessage: (incoming.fileProgressMessage || '').trim()
? incoming.fileProgressMessage
: previous.fileProgressMessage,
}
}
function hasMeaningfulProgressValue(value: unknown) {
const num = Number(value)
return Number.isFinite(num) && num > 0
}
function statusText(item: AppearancePatentHistoryItem) {
const status = normalizeTaskStatus(item)
if (status === 'RUNNING') return '执行中'
if (status === 'PENDING') return '已解析,等待后台执行'
// 已判死(含心跳超时)的任务始终显示失败:后台检测可能仍在跑、文件生成后下载按钮会自动出现,
// 但状态文案不能是"结果生成中",否则用户会以为任务还在执行(2026-09-28 29473/29479)
if (status === 'FAILED') return isResultBuildFailed(item) ? '结果生成失败' : '失败'
if (isResultPreparing(item)) return '结果生成中'
if (isResultBuildFailed(item)) return '结果生成失败'
if (hasDownloadableResult(item)) return '已完成'
if (status === 'SUCCESS' || item.success) return '已完成'
return '等待中'
}
function statusClass(item: AppearancePatentHistoryItem) {
const status = normalizeTaskStatus(item)
if (status === 'FAILED' || isResultBuildFailed(item)) return 'failed'
if (status === 'RUNNING' || isResultPreparing(item)) return 'running'
if (hasDownloadableResult(item)) return 'success'
if (status === 'SUCCESS' || item.success) return 'success'
return 'pending'
}
function isResultPreparing(item: AppearancePatentHistoryItem) {
const status = normalizeTaskStatus(item)
const fileStatus = (item.fileStatus || '').toUpperCase()
if (status !== 'SUCCESS' && status !== 'FAILED') return false
if (canDownload(item)) return false
if (fileStatus === 'FAILED' || fileStatus === 'SUCCESS') return false
return status === 'SUCCESS' || hasActiveFileJob(item)
}
function normalizeTaskStatus(item: AppearancePatentHistoryItem) {
return (item.taskStatus || '').toUpperCase()
}
function isResultBuildFailed(item: AppearancePatentHistoryItem) {
return (item.fileStatus || '').toUpperCase() === 'FAILED'
}
function pendingResultHint(item: AppearancePatentHistoryItem) {
if (isResultBuildFailed(item)) {
return item.fileError || '结果文件生成失败,请稍后重试或检查后端日志'
}
if (showFileProgress(item)) {
return ''
}
if (!isResultPreparing(item)) return ''
const doneLabel = normalizeTaskStatus(item) === 'FAILED' ? '任务已失败' : '任务已完成'
const fileStatus = (item.fileStatus || '').toUpperCase()
if (fileStatus === 'PENDING') {
return `${doneLabel},结果文件排队中,请稍候`
}
return `${doneLabel},正在生成结果文件,下载按钮稍后出现`
}
function canDownload(item: AppearancePatentHistoryItem) {
return Boolean(item.resultId && (item.fileReady || item.downloadUrl))
}
function hasDownloadableResult(item: AppearancePatentHistoryItem) {
return canDownload(item)
}
function fileProgressPercent(item: AppearancePatentHistoryItem) {
const percent = Number(item.fileProgressPercent || 0)
if (Number.isFinite(percent) && percent > 0) {
return Math.max(0, Math.min(100, Math.round(percent)))
}
if (shouldShowFallbackJobProgress(item)) {
return activeFileJobStatus(item) === 'PENDING' ? 6 : 10
}
return 0
}
function displayFileProgressMessage(item: AppearancePatentHistoryItem, fallback: string) {
const message = (item.fileProgressMessage || '').trim()
if (!message) return fallback
return translateFileProgressMessage(message)
}
function translateFileProgressMessage(message: string) {
const submittedMatch = message.match(/^LLM submitted (\d+) batches, completed (\d+), waiting for results$/)
if (submittedMatch) {
return `已提交 ${submittedMatch[1]} 批,已完成 ${submittedMatch[2]} 批,等待结果`
}
const completedMatch = message.match(/^LLM completed (\d+) batches, waiting for remaining Python data$/)
if (completedMatch) {
return `已完成 ${completedMatch[1]} 批,等待后续数据`
}
const translations: Record<string, string> = {
'Receiving Python data, waiting for 50 rows before LLM': '正在接收检测数据,累计 50 条后提交检测',
'Submitting LLM': '正在提交检测',
'LLM submitted, waiting for result': '已提交检测,等待结果',
'Waiting for Python upload': '等待后续数据',
'LLM results ready, assembling xlsx': '检测结果已返回,正在生成结果文件',
'Assembling xlsx': '正在生成结果文件',
'Uploading result file': '正在上传结果文件',
'Result file generated': '结果文件已生成',
}
return translations[message] || message
}
function showFileProgress(item: AppearancePatentHistoryItem) {
const status = normalizeTaskStatus(item)
return (status === 'RUNNING' || isResultPreparing(item)) && (hasExplicitFileProgress(item) || shouldShowFallbackJobProgress(item))
}
function hasExplicitFileProgress(item: AppearancePatentHistoryItem) {
return hasFileProgressCount(item)
|| Number(item.fileProgressPercent || 0) > 0
|| Boolean((item.fileProgressMessage || '').trim())
}
function hasFileProgressCount(item: AppearancePatentHistoryItem) {
return (item.fileProgressTotal || 0) > 0
}
function activeFileJobStatus(item: AppearancePatentHistoryItem) {
return (item.fileStatus || '').toUpperCase()
}
function hasActiveFileJob(item: AppearancePatentHistoryItem) {
const fileStatus = activeFileJobStatus(item)
return item.fileJobId != null || fileStatus === 'PENDING' || fileStatus === 'RUNNING'
}
function shouldShowFallbackJobProgress(item: AppearancePatentHistoryItem) {
return hasActiveFileJob(item) && !hasExplicitFileProgress(item)
}
async function downloadResult(item: AppearancePatentHistoryItem) {
if (!item.resultId) return
const url = item.downloadUrl || getAppearancePatentResultDownloadUrl(item.resultId)
const filename = item.resultFilename || `${item.sourceFilename || 'appearance-patent'}.xlsx`
const result = await saveUrlWithProgress(url, filename, `appearance-patent:${item.resultId}`)
if (result.success) {
ElMessage.success(`已保存: ${result.path || filename}`)
} else if (result.error && result.error !== '用户取消') {
ElMessage.error(result.error)
}
}
async function deleteTaskRecord(item: AppearancePatentHistoryItem) {
if (!(await confirmTaskDeletion(item))) return
try {
if (item.taskStatus === 'RUNNING' && item.taskId) {
await deleteAppearancePatentTask(item.taskId)
removePollingTask(item.taskId)
} else if (item.resultId) {
await deleteAppearancePatentHistory(item.resultId)
}
await loadDashboard()
await loadHistory({ force: true })
ElMessage.success('已删除')
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '删除失败')
}
}
const { batchDeleteHistory, deleteTaskRecord, downloadResult } = board
onMounted(async () => {
loadPollingIds()
board.loadPollingIds()
await Promise.all([
loadDashboard().catch(() => undefined),
loadHistory().catch(() => undefined),
board.loadDashboard().catch(() => undefined),
board.loadHistory().catch(() => undefined),
])
seedRunningTasksFromHistory()
seedPendingFileTasksFromHistory()
if (pollingTaskIds.value.length || pendingFileTaskIds.value.length) ensurePolling()
board.seedRunningTasksFromHistory()
board.seedPendingFileTasksFromHistory()
board.ensurePollingIfAny()
})
onUnmounted(() => {
disposed = true
stopPolling()
timers.clearScope()
board.dispose()
})
/**
* 历史记录批量删除:复用单条删除逻辑(删除后原函数各自刷新列表)
*/
async function batchDeleteHistory(views: TaskItemView[]) {
const { total, failed } = await runBatchDelete(views, (view) => deleteTaskRecord(itemSource(view)))
if (!total) return
if (failed > 0) {
ElMessage.warning(`删除完成,${failed} 条失败`)
} else {
ElMessage.success(`已删除 ${total} 条历史记录`)
}
}
</script>
<style scoped>
@@ -915,18 +490,14 @@ async function batchDeleteHistory(views: TaskItemView[]) {
.left-panel { width: 400px; background: #242424; padding: 20px; overflow-y: auto; border-right: 1px solid #2e3a52; }
.right-panel { flex: 1; min-width: 0; background: #242424; display: flex; flex-direction: column; }
.section-title, .subsection-title { font-size: 13px; color: #a0acbe; margin-bottom: 10px; }
.upload-zone { border: 1px dashed #3e4a62; border-radius: 10px; padding: 18px; background: #242424; margin-bottom: 18px; }
.hint, .loading-msg, .files, .muted { color: #5e6878; font-size: 12px; line-height: 1.5; }
.link { color: #6ea8fe; text-decoration: none; }
.link:hover { color: #9fc5ff; }
.btns, .run-row { display: flex; gap: 10px; flex-wrap: wrap; }
.opt-btn, .btn-run, .btn-delete, .download { border: none; cursor: pointer; border-radius: 7px; }
.opt-btn { padding: 8px 14px; color: #c8d2e2; background: #242424; border: 1px solid #3e4a62; }
.run-row { display: flex; gap: 10px; flex-wrap: wrap; }
.btn-run, .btn-delete, .download { border: none; cursor: pointer; border-radius: 7px; }
.btn-run { padding: 10px 18px; color: #f5f8fc; background: #3498db; font-weight: 600; }
.btn-queue { background: #27ae60; }
.btn-run:disabled { opacity: .55; cursor: not-allowed; }
.selected-files { margin-top: 14px; color: #a0acbe; font-size: 12px; word-break: break-all; }
.selected-files span { display: block; margin: 4px 0; }
.prompt-card, .secret-card { margin-bottom: 18px; }
.secret-card { display: none; }
.prompt-input { width: 100%; box-sizing: border-box; resize: vertical; min-height: 180px; padding: 10px 12px; border: 1px solid #333; border-radius: 8px; background: #222b3d; color: #c8d2e2; font-size: 12px; line-height: 1.6; outline: none; }
@@ -5,25 +5,16 @@
<div class="main-content">
<aside class="left-panel">
<div class="section-title">待检品牌文件</div>
<div class="upload-zone">
<div class="hint">
Excel 每行含「品牌」列即会加入检测。可多选文件或选择整个文件夹(.xlsx)。检测由本机客户端执行,请在桌面客户端中打开本页面。
</div>
<div class="btns">
<button type="button" class="opt-btn" :disabled="!hasBridge" @click="selectFiles">选择 Excel</button>
<button type="button" class="opt-btn" :disabled="!hasBridge" @click="selectFolder">选择文件夹</button>
</div>
<div class="selected-files">
<template v-if="selectedPaths.length">
<span v-for="name in displayPaths" :key="name" :title="name">{{ baseName(name) }}</span>
<span v-if="selectedPaths.length > displayPaths.length" class="more-line">
还有 {{ selectedPaths.length - displayPaths.length }} 个文件未展开显示
</span>
</template>
<span v-else>暂未选择文件</span>
</div>
<div v-if="!hasBridge" class="bridge-tip">当前浏览器环境无桌面客户端桥接,仅可预览页面;请用本机客户端打开。</div>
</div>
<FileUploadZone
hint="Excel 每行含「品牌」列即会加入检测。可多选文件或选择整个文件夹(.xlsx)。检测由本机客户端执行,请在桌面客户端中打开本页面。"
:names="selectedPaths"
:max-display="8"
:disabled="!hasBridge"
name-title
:footer-tip="hasBridge ? '' : '当前浏览器环境无桌面客户端桥接,仅可预览页面;请用本机客户端打开。'"
@select-files="selectFiles"
@select-folder="selectFolder"
/>
<div class="section-title">匹配策略</div>
<div class="radio-cards">
@@ -107,6 +98,7 @@
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue'
import FileUploadZone from '@/shared/components/FileUploadZone.vue'
import TaskCenterPanel from '@/shared/components/tasks/TaskCenterPanel.vue'
import type { TaskItemView, TaskStatCard } from '@/shared/components/tasks/types'
import { getPywebviewApi } from '@/shared/bridges/pywebview'
@@ -119,17 +111,42 @@ import {
runBrandNow,
type BrandTaskItem,
} from '@/shared/api/brand'
import { checkSelectedFiles, EXCEL_EXTENSIONS } from '@/shared/dispatch-guard.ts'
import { passGuard } from '@/shared/dispatch-guard-ui'
import { useExcelFileUpload } from '@/shared/composables/useExcelFileUpload'
import { getTaskPollIntervalMs } from '@/shared/task-progress-config'
import { createCategorizedTimers } from '@/shared/utils/categorized-timers'
import type { UploadFileVo } from '@/shared/api/upload.ts'
import type { UploadedFileRef } from '@/shared/api/types/upload.ts'
import { formatDateTime } from '@/shared/utils/datetime'
import { uploadPathsToJava } from '@/shared/utils/upload-to-java'
import { taskStatusClass, taskStatusText } from '@/shared/utils/task-status-text'
import { runBatchDelete } from '@/shared/utils/batch-delete'
const uploadedFiles = ref<UploadFileVo[]>([])
const {
files: uploadedFiles,
selectedPaths,
selectFiles,
selectFolder,
} = useExcelFileUpload({
pickFilesUnavailableWarning: '当前环境不支持文件选择,请在本机客户端中打开',
folderUnavailableWarning: '当前环境不支持文件夹选择,请在本机客户端中打开',
folderEmptyWarning: (error) => error || '该文件夹下没有 xlsx 文件',
filesSuccessMessage: (files) => `已选择并上传 ${files.length} 个 Excel 文件`,
folderSuccessMessage: (files) => `已选择并上传文件夹内 ${files.length} 个 Excel 文件`,
errorFallbackMessage: (action) => (action === 'files' ? '文件上传失败' : '文件夹选择失败'),
uploadOptions: { uploadOss: true },
// 展示名与原实现一致:始终取上传结果的相对路径/文件名(文件、文件夹两个动作都一样)
filePathsMode: 'uploaded',
folderPathsMode: 'uploaded',
// 原实现上传失败时保留上一批已上传文件,仅提示错误
clearOnError: false,
// 新版桌面客户端桥在本机展开文件夹(服务器无法访问用户本机目录)
expandFolder: async (folder) => {
const bridge = getPywebviewApi()
if (!bridge?.expand_brand_folder) {
ElMessage.warning('当前桌面客户端版本不支持文件夹展开,请使用"选择文件"(可多选)')
return { success: false }
}
return await bridge.expand_brand_folder(folder)
},
})
const strategy = ref<'Terms' | 'Simple'>('Simple')
const submitting = ref(false)
const tasks = ref<BrandTaskItem[]>([])
@@ -142,15 +159,6 @@ const hasUid = computed(() => {
const numeric = Number(raw.trim())
return Number.isFinite(numeric) && numeric > 0
})
// 展示用:已上传文件列表的展示名(优先相对路径,其次原文件名)
const selectedPaths = computed(() =>
uploadedFiles.value.map((f) => f.relativePath || f.originalFilename || f.fileKey),
)
const displayPaths = computed(() => selectedPaths.value.slice(0, 8))
function baseName(path: string) {
return path.split(/[\\/]/).pop() || path
}
const timers = createCategorizedTimers('brand-brand-task')
let pollTimer: number | null = null
@@ -270,23 +278,30 @@ function errorMessage(item: BrandTaskItem) {
}
function statusText(status?: BrandTaskItem['status']) {
const value = (status || '').toLowerCase()
const map: Record<string, string> = {
pending: '排队中',
running: '执行中',
success: '已完成',
failed: '失败',
cancelled: '已取消',
}
return map[value] || String(status ?? '未知')
// 与原实现一致:小写映射 + 未知状态原样展示(完全替换默认表)
return taskStatusText(status, {
replace: true,
text: {
PENDING: '排队中',
RUNNING: '执行中',
SUCCESS: '已完成',
FAILED: '失败',
CANCELLED: '已取消',
},
textFallback: String(status ?? '未知'),
})
}
function statusClass(status?: BrandTaskItem['status']) {
const value = (status || '').toLowerCase()
if (value === 'running') return 'running'
if (value === 'success') return 'success'
if (value === 'failed') return 'failed'
return 'pending'
return taskStatusClass(status, {
replace: true,
classMap: {
RUNNING: 'running',
SUCCESS: 'success',
FAILED: 'failed',
},
classFallback: 'pending',
})
}
// ---- 右侧任务面板统一视图(TaskCenterPanel)----
@@ -353,53 +368,6 @@ function toBrandTaskView(item: BrandTaskItem): TaskItemView {
}
}
/** 上传本地 xlsx 到 Java 临时目录,成功后回填 fileUrl(服务器本地路径,Java 直接读取) */
async function selectFiles() {
const bridge = getPywebviewApi()
if (!bridge?.select_brand_xlsx_files) {
ElMessage.warning('当前环境不支持文件选择,请在本机客户端中打开')
return
}
const paths = await bridge.select_brand_xlsx_files()
if (!paths?.length) return
if (!(await passGuard(checkSelectedFiles(paths, { allowedExtensions: EXCEL_EXTENSIONS })))) return
try {
const files = await uploadPathsToJava(getPywebviewApi(), paths, { uploadOss: true })
uploadedFiles.value = files
ElMessage.success(`已选择并上传 ${files.length} 个 Excel 文件`)
} catch (error) {
ElMessage.error(error instanceof Error ? error.message : '文件上传失败')
}
}
async function selectFolder() {
const bridge = getPywebviewApi()
if (!bridge?.select_brand_folder) {
ElMessage.warning('当前环境不支持文件夹选择,请在本机客户端中打开')
return
}
const folder = await bridge.select_brand_folder()
if (!folder) return
// 新版桌面客户端桥在本机展开文件夹(服务器无法访问用户本机目录)
if (!bridge.expand_brand_folder) {
ElMessage.warning('当前桌面客户端版本不支持文件夹展开,请使用"选择文件"(可多选)')
return
}
try {
const res = await bridge.expand_brand_folder(folder)
if (!res.success || !res.items?.length) {
ElMessage.warning(res.error || '该文件夹下没有 xlsx 文件')
return
}
if (!(await passGuard(checkSelectedFiles(res.items.map((i) => i.absolutePath), { allowedExtensions: EXCEL_EXTENSIONS })))) return
const files = await uploadPathsToJava(getPywebviewApi(), res.items, { uploadOss: true })
uploadedFiles.value = files
ElMessage.success(`已选择并上传文件夹内 ${files.length} 个 Excel 文件`)
} catch (error) {
ElMessage.error(error instanceof Error ? error.message : '文件夹选择失败')
}
}
async function submitRun() {
if (!hasBridge.value) {
ElMessage.warning('请在桌面客户端中打开本页面执行品牌检测')
@@ -560,16 +528,20 @@ async function batchDeleteHistory(views: TaskItemView[]) {
.section-title { font-size: 13px; color: #a0acbe; margin: 12px 0 10px; }
.hint, .loading-msg, .files, .muted { color: #5e6878; font-size: 12px; line-height: 1.5; }
.hint { margin-bottom: 12px; }
.upload-zone { border: 1px dashed #3e4a62; border-radius: 10px; padding: 16px; background: #242424; margin-bottom: 6px; }
/* upload-zone 已抽到 FileUploadZone 组件;这里只保留本 Tab 的差异样式 */
:deep(.upload-zone) { padding: 16px; margin-bottom: 6px; }
:deep(.upload-zone .hint) { margin-bottom: 12px; }
:deep(.upload-zone .opt-btn) { font-size: 12px; }
:deep(.upload-zone .opt-btn:hover:not(:disabled)) { color: #3498db; border-color: #3498db; }
:deep(.upload-zone .opt-btn:disabled) { opacity: 0.5; cursor: not-allowed; }
:deep(.selected-files) { margin-top: 12px; }
:deep(.selected-files span) { margin: 3px 0; }
:deep(.bridge-tip) { margin-top: 10px; color: #e6a23c; font-size: 11px; }
.btns, .run-row { display: flex; gap: 10px; flex-wrap: wrap; }
.run-row { margin-top: 14px; }
.opt-btn { padding: 8px 14px; color: #c8d2e2; background: #242424; border: 1px solid #3e4a62; border-radius: 7px; cursor: pointer; font-size: 12px; }
.opt-btn:hover:not(:disabled) { color: #3498db; border-color: #3498db; }
.opt-btn:disabled { opacity: 0.5; cursor: not-allowed; }
.selected-files { margin-top: 12px; color: #a0acbe; font-size: 12px; word-break: break-all; }
.selected-files span { display: block; margin: 3px 0; }
.selected-files .more-line { color: #5e6878; }
.bridge-tip { margin-top: 10px; color: #e6a23c; font-size: 11px; }
.env-tip { margin-top: 10px; padding: 8px 10px; border-radius: 8px; background: rgba(230, 162, 60, 0.1); color: #e6a23c; font-size: 12px; line-height: 1.6; }
.radio-cards { display: flex; flex-direction: column; gap: 8px; margin-bottom: 6px; }
.radio-card { display: flex; flex-direction: column; gap: 3px; padding: 10px 12px; border: 1px solid #333; border-radius: 8px; background: #242424; cursor: pointer; }
@@ -5,22 +5,13 @@
<div class="main-content">
<aside class="left-panel left-panel--with-template">
<div class="section-title">上传文件</div>
<div class="upload-zone">
<div class="hint">选择需要采集的 Excel 文件或文件夹(默认根目录:采集前数据.xlsx),系统将按下方筛选条件自动采集数据。</div>
<div class="btns">
<button type="button" class="opt-btn" @click="selectFiles">选择 Excel</button>
<button type="button" class="opt-btn" @click="selectFolder">选择文件夹</button>
</div>
<div class="selected-files">
<template v-if="selectedFileNames.length">
<span v-for="name in displayFileNames" :key="name">{{ name }}</span>
<span v-if="selectedFileNames.length > displayFileNames.length" class="more-line">
还有 {{ selectedFileNames.length - displayFileNames.length }} 个文件未展开显示
</span>
</template>
<span v-else>暂未选择文件</span>
</div>
</div>
<FileUploadZone
hint="选择需要采集的 Excel 文件或文件夹(默认根目录:采集前数据.xlsx),系统将按下方筛选条件自动采集数据。"
:names="selectedFileNames"
:max-display="8"
@select-files="selectFiles"
@select-folder="selectFolder"
/>
<div class="section-title">筛选条件</div>
<div class="filter-zone">
@@ -147,19 +138,18 @@
import { computed, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
import FileUploadZone from '@/shared/components/FileUploadZone.vue'
import ModuleTemplateDownload from '@/shared/components/ModuleTemplateDownload.vue'
import TaskCenterPanel from '@/shared/components/tasks/TaskCenterPanel.vue'
import type { TaskItemView, TaskStatCard } from '@/shared/components/tasks/types'
import { expandBrandFolderRecursive } from '@/shared/api/brand'
import { getPywebviewApi } from '@/shared/bridges/pywebview'
import { useExcelFileUpload } from '@/shared/composables/useExcelFileUpload'
import { useTaskProgressLoop } from '@/shared/composables/useTaskProgressLoop'
import { createCategorizedTimers } from '@/shared/utils/categorized-timers'
import { saveUrlWithProgress } from '@/shared/utils/download-progress'
import {
EXCEL_EXTENSIONS,
checkParseResult,
checkQueuePayload,
checkSelectedFiles,
} from '@/shared/dispatch-guard'
import { passGuard } from '@/shared/dispatch-guard-ui'
import {
@@ -177,11 +167,10 @@ import {
type CollectDataHistoryItem,
type CollectDataParseVo,
type CollectDataTaskDetailVo,
type UploadFileVo,
} from '@/shared/api/java-modules'
import { getPollingProgressBatch } from '@/shared/api/task-progress-polling.ts'
import { formatDateTime } from '@/shared/utils/datetime'
import { uploadPathsToJava } from '@/shared/utils/upload-to-java'
import { taskStatusClass, taskStatusText } from '@/shared/utils/task-status-text'
import { runBatchDelete } from '@/shared/utils/batch-delete'
import { confirmTaskDeletion } from '@/shared/task-delete-confirm'
@@ -193,10 +182,27 @@ const COUNTRY_OPTIONS = [
{ code: 'ES', label: '西班牙' },
] as const
const selectedFileNames = ref<string[]>([])
const uploadedFiles = ref<UploadFileVo[]>([])
const submitting = ref(false)
const pushing = ref(false)
const {
files: uploadedFiles,
selectedPaths: selectedFileNames,
selectFiles,
selectFolder,
} = useExcelFileUpload({
requireUploadCapability: true,
pickFilesUnavailableWarning: '当前环境不支持文件选择或上传',
folderUnavailableWarning: '当前环境不支持文件夹选择,请在本地客户端中打开',
errorFallbackMessage: (action) => (action === 'files' ? '文件选择失败' : '选择失败'),
onUploaded: () => {
lastTaskId.value = null
lastParseVo.value = null
},
onFailed: () => {
lastTaskId.value = null
lastParseVo.value = null
},
})
const filters = reactive<{
minAmount: number | null
@@ -313,8 +319,6 @@ const progressLoop = useTaskProgressLoop<CollectDataTaskDetailVo>({
},
})
const displayFileNames = computed(() => selectedFileNames.value.slice(0, 8))
function selectCountry(code: string) {
if (!COUNTRY_OPTIONS.some((row) => row.code === code)) return
if (selectedCountryCode.value === code) return
@@ -358,61 +362,6 @@ async function loadCountryPreference() {
}
}
async function selectFiles() {
const api = getPywebviewApi()
if (!api?.select_brand_xlsx_files || !api.upload_file_to_java) {
ElMessage.warning('当前环境不支持文件选择或上传')
return
}
try {
const paths = await api.select_brand_xlsx_files()
if (!paths?.length) return
if (!(await passGuard(checkSelectedFiles(paths, { allowedExtensions: EXCEL_EXTENSIONS })))) return
const files = await uploadPathsToJava(getPywebviewApi(), paths)
uploadedFiles.value = files
selectedFileNames.value = files.map((f) => f.relativePath || f.originalFilename || f.fileKey)
lastTaskId.value = null
lastParseVo.value = null
} catch (error) {
// 上传失败时清空选择,避免残留上一批文件让用户误以为新文件已就绪
uploadedFiles.value = []
selectedFileNames.value = []
lastTaskId.value = null
lastParseVo.value = null
ElMessage.error(error instanceof Error ? error.message : '文件选择失败')
}
}
async function selectFolder() {
const api = getPywebviewApi()
if (!api?.select_brand_folder) {
ElMessage.warning('当前环境不支持文件夹选择,请在本地客户端中打开')
return
}
try {
const folder = await api.select_brand_folder()
if (!folder) return
const result = await expandBrandFolderRecursive(folder)
if (!result.success || !result.items?.length) {
ElMessage.warning(result.error || '该文件夹下没有可用的 xlsx 文件')
return
}
if (!(await passGuard(checkSelectedFiles(result.items, { allowedExtensions: EXCEL_EXTENSIONS })))) return
const files = await uploadPathsToJava(getPywebviewApi(), result.items)
uploadedFiles.value = files
selectedFileNames.value = result.items.map((item) => item.relativePath || item.absolutePath)
lastTaskId.value = null
lastParseVo.value = null
ElMessage.success(`已选择文件夹内 ${result.items.length} 个 Excel 文件`)
} catch (error) {
uploadedFiles.value = []
selectedFileNames.value = []
lastTaskId.value = null
lastParseVo.value = null
ElMessage.error(error instanceof Error ? error.message : '选择失败')
}
}
function buildFiltersPayload() {
const minAmount = filters.minAmount === null || filters.minAmount === undefined || Number.isNaN(filters.minAmount)
? null
@@ -540,19 +489,17 @@ function normalizeTaskStatus(item: CollectDataHistoryItem) {
function statusText(item: CollectDataHistoryItem) {
const status = normalizeTaskStatus(item)
if (status === 'RUNNING') return '执行中'
if (status === 'PENDING') return '等待中'
if (status === 'SUCCESS' || item.success) return '已完成'
if (status === 'FAILED') return '失败'
return '等待中'
if (status === 'RUNNING' || status === 'PENDING') return taskStatusText(status)
if (status === 'SUCCESS' || item.success) return taskStatusText('SUCCESS')
return status === 'FAILED' ? taskStatusText('FAILED') : '等待中'
}
function statusClass(item: CollectDataHistoryItem) {
const status = normalizeTaskStatus(item)
if (status === 'RUNNING') return 'running'
if (status === 'FAILED') return 'failed'
if (status === 'SUCCESS' || item.success) return 'success'
return 'pending'
if (status === 'RUNNING' || status === 'FAILED') return taskStatusClass(status)
if (status === 'SUCCESS' || item.success) return taskStatusClass('SUCCESS')
// 其余(含 PENDING/CANCELLED)保持 'pending'
return taskStatusClass(status, { classMap: { CANCELLED: 'pending' } })
}
function taskFilterSummary(item: CollectDataHistoryItem) {
@@ -792,7 +739,6 @@ async function batchDeleteHistory(views: TaskItemView[]) {
.left-panel { width: 400px; background: #242424; padding: 20px; overflow-y: auto; border-right: 1px solid #2e3a52; }
.right-panel { flex: 1; min-width: 0; background: #242424; display: flex; flex-direction: column; }
.section-title { font-size: 13px; color: #a0acbe; margin: 12px 0 10px; }
.upload-zone { border: 1px dashed #3e4a62; border-radius: 10px; padding: 18px; background: #242424; margin-bottom: 18px; }
.hint, .loading-msg, .files, .muted { color: #5e6878; font-size: 12px; line-height: 1.5; }
.btns, .run-row { display: flex; gap: 10px; flex-wrap: wrap; }
.opt-btn, .btn-run, .btn-delete, .download { border: none; cursor: pointer; border-radius: 7px; }
@@ -800,9 +746,6 @@ async function batchDeleteHistory(views: TaskItemView[]) {
.btn-run { padding: 10px 18px; color: #f5f8fc; background: #3498db; font-weight: 600; }
.btn-run.btn-queue { background: #27ae60; }
.btn-run:disabled { opacity: .55; cursor: not-allowed; }
.selected-files { margin-top: 14px; color: #a0acbe; font-size: 12px; word-break: break-all; }
.selected-files span { display: block; margin: 4px 0; }
.selected-files .more-line { color: #5e6878; }
.filter-zone {
border: 1px solid #2e3a52;
@@ -5,23 +5,16 @@
<div class="main-content">
<aside class="left-panel">
<div class="section-title">选择文件</div>
<div class="upload-zone">
<div class="hint">选择需要转换的 Excel 文件或文件夹,将按所选模板生成 txt 文件。</div>
<div class="btns">
<button type="button" class="opt-btn" @click="selectConvertFiles">选择 Excel 文件</button>
<button type="button" class="opt-btn" @click="selectConvertFolder">选择文件夹</button>
</div>
<div class="selected-files clean-placeholder">
<template v-if="convertSelectedPaths.length">
<span v-for="path in convertDisplayPaths" :key="path">{{ path }}</span>
<span v-if="convertSelectedPaths.length > convertDisplayPaths.length" class="more-line">
还有 {{ convertSelectedPaths.length - convertDisplayPaths.length }} 个文件未展开显示
</span>
</template>
<span v-else>暂未选择待转换文件</span>
</div>
</div>
<FileUploadZone
hint="选择需要转换的 Excel 文件或文件夹,将按所选模板生成 txt 文件。"
:names="convertSelectedPaths"
:max-display="8"
files-label="选择 Excel 文件"
empty-text="暂未选择待转换文件"
files-class="clean-placeholder"
@select-files="selectConvertFiles"
@select-folder="selectConvertFolder"
/>
<div class="section-title">模板选择</div>
<div class="option-group">
@@ -152,9 +145,9 @@
import { computed, onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
import FileUploadZone from '@/shared/components/FileUploadZone.vue'
import TaskCenterPanel from '@/shared/components/tasks/TaskCenterPanel.vue'
import type { TaskItemView, TaskStatCard } from '@/shared/components/tasks/types'
import { expandBrandFolderRecursive } from '@/shared/api/brand'
import {
deleteConvertHistory,
getConvertHistory,
@@ -164,23 +157,38 @@ import {
type ConvertResultItem,
type ConvertTemplateVo,
} from '@/shared/api/java-modules'
import { getPywebviewApi, type UploadedJavaFile } from '@/shared/bridges/pywebview'
import { saveUrlWithProgress } from '@/shared/utils/download-progress'
import { EXCEL_EXTENSIONS, checkSelectedFiles, collectDistinctErrors, guardBlocked } from '@/shared/dispatch-guard'
import { collectDistinctErrors, guardBlocked } from '@/shared/dispatch-guard'
import { passGuard } from '@/shared/dispatch-guard-ui'
import { useExcelFileUpload } from '@/shared/composables/useExcelFileUpload'
import { formatDateTime } from '@/shared/utils/datetime'
import { uploadPathsToJava } from '@/shared/utils/upload-to-java'
import { runBatchDelete } from '@/shared/utils/batch-delete'
const convertSelectedPaths = ref<string[]>([])
const {
files: convertUploadedFiles,
selectedPaths: convertSelectedPaths,
selectFiles: selectConvertFiles,
selectFolder: selectConvertFolder,
} = useExcelFileUpload({
// 展示原始本机路径;文件夹展开后只展示相对路径(与原实现一致)
filePathsMode: 'raw',
folderPathsMode: 'relative',
filesSuccessMessage: (_files, paths) => `已选择 ${paths.length} 个待转换文件`,
folderSuccessMessage: (_files, items) => `已选择文件夹内 ${items.length} 个 xlsx 文件`,
folderEmptyWarning: (error) => error || '该文件夹下没有 xlsx 文件',
onFolderPicked: (folder) => {
convertArchiveName.value = folder.split(/[/\\]/).filter(Boolean).pop() || ''
},
onUploaded: (info) => {
if (info.action === 'files') convertArchiveName.value = ''
},
})
const convertArchiveName = ref('')
const convertUploadedFiles = ref<UploadedJavaFile[]>([])
const convertRunning = ref(false)
const convertResultItems = ref<ConvertResultItem[]>([])
const convertTemplates = ref<ConvertTemplateVo[]>([])
const convertTemplateId = ref('')
const convertDisplayPaths = computed(() => convertSelectedPaths.value.slice(0, 8))
const currentConvertTemplate = computed(
() => convertTemplates.value.find((item) => item.id === convertTemplateId.value) || null,
)
@@ -267,61 +275,6 @@ async function loadConvertTemplates(preferredTemplateId?: string) {
convertTemplateId.value = convertTemplates.value[0]?.id || ''
}
async function handleSelectedPaths(paths: string[], successMessage: string) {
convertSelectedPaths.value = paths
convertArchiveName.value = ''
convertUploadedFiles.value = await uploadPathsToJava(getPywebviewApi(), paths)
ElMessage.success(successMessage)
}
async function selectConvertFiles() {
const api = getPywebviewApi()
if (!api?.select_brand_xlsx_files) {
ElMessage.warning('当前环境不支持文件选择,请在本机客户端中打开')
return
}
try {
const paths = await api.select_brand_xlsx_files()
if (!paths?.length) return
if (!(await passGuard(checkSelectedFiles(paths, { allowedExtensions: EXCEL_EXTENSIONS })))) return
await handleSelectedPaths(paths, `已选择 ${paths.length} 个待转换文件`)
} catch (error) {
convertSelectedPaths.value = []
convertUploadedFiles.value = []
ElMessage.error(error instanceof Error ? error.message : '选择失败')
}
}
async function selectConvertFolder() {
const api = getPywebviewApi()
if (!api?.select_brand_folder) {
ElMessage.warning('当前环境不支持文件夹选择,请在本机客户端中打开')
return
}
try {
const folder = await api.select_brand_folder()
if (!folder) return
convertArchiveName.value = folder.split(/[/\\]/).filter(Boolean).pop() || ''
const result = await expandBrandFolderRecursive(folder)
if (result.success && result.items?.length) {
if (!(await passGuard(checkSelectedFiles(result.items, { allowedExtensions: EXCEL_EXTENSIONS })))) return
convertSelectedPaths.value = result.items.map((item) => item.relativePath)
convertUploadedFiles.value = await uploadPathsToJava(getPywebviewApi(), result.items)
ElMessage.success(`已选择文件夹内 ${result.items.length} 个 xlsx 文件`)
return
}
ElMessage.warning(result.error || '该文件夹下没有 xlsx 文件')
} catch (error) {
convertSelectedPaths.value = []
convertUploadedFiles.value = []
ElMessage.error(error instanceof Error ? error.message : '选择失败')
}
}
async function submitConvertRun() {
if (!convertUploadedFiles.value.length) {
ElMessage.warning('请先选择待转换 Excel 文件或文件夹')
@@ -460,17 +413,15 @@ async function batchDeleteHistory(views: TaskItemView[]) {
margin-bottom: 10px;
}
.upload-zone {
border: 1px dashed #3e4a62;
border-radius: 10px;
/* upload-zone 已抽到 FileUploadZone 组件;这里保留本 Tab 的差异样式 */
:deep(.upload-zone) {
padding: 24px;
text-align: center;
background: #242424;
margin-bottom: 20px;
transition: all 0.2s ease;
}
.upload-zone:hover {
:deep(.upload-zone:hover) {
border-color: #3498db;
background: #242424;
}
@@ -482,11 +433,42 @@ async function batchDeleteHistory(views: TaskItemView[]) {
line-height: 1.5;
}
.btns {
display: flex;
gap: 10px;
:deep(.upload-zone .hint) {
font-size: 13px;
margin-bottom: 12px;
}
:deep(.upload-zone .btns) {
justify-content: center;
flex-wrap: wrap;
}
:deep(.upload-zone .opt-btn) {
padding: 8px 16px;
font-size: 13px;
border-radius: 6px;
}
:deep(.upload-zone .opt-btn:hover) {
color: #3498db;
background: #333;
border-color: #3498db;
}
:deep(.upload-zone .opt-btn:disabled) {
cursor: not-allowed;
opacity: 0.55;
}
:deep(.selected-files) {
font-size: 12px;
color: #5e6878;
max-height: 112px;
overflow-y: auto;
text-align: left;
}
:deep(.more-line) {
color: #a0acbe;
}
.opt-btn,
@@ -529,25 +511,6 @@ async function batchDeleteHistory(views: TaskItemView[]) {
opacity: 0.55;
}
.selected-files {
margin-top: 14px;
font-size: 12px;
color: #5e6878;
max-height: 112px;
overflow-y: auto;
text-align: left;
}
.selected-files span {
display: block;
margin: 4px 0;
word-break: break-all;
}
.more-line {
color: #a0acbe;
}
.option-group {
margin-bottom: 20px;
}
@@ -5,23 +5,16 @@
<div class="main-content">
<aside class="left-panel">
<div class="section-title">选择文件</div>
<div class="upload-zone">
<div class="hint">选择需要清洗的 Excel 文件或文件夹,后续将按所选规则输出处理结果。</div>
<div class="btns">
<button type="button" class="opt-btn" @click="selectCleanFiles">选择 Excel 文件</button>
<button type="button" class="opt-btn" @click="selectCleanFolder">选择文件夹</button>
</div>
<div class="selected-files clean-placeholder">
<template v-if="cleanSelectedPaths.length">
<span v-for="path in cleanDisplayPaths" :key="path">{{ path }}</span>
<span v-if="cleanSelectedPaths.length > cleanDisplayPaths.length" class="more-line">
还有 {{ cleanSelectedPaths.length - cleanDisplayPaths.length }} 个文件未展开显示
</span>
</template>
<span v-else>暂未选择待清洗文件</span>
</div>
</div>
<FileUploadZone
hint="选择需要清洗的 Excel 文件或文件夹,后续将按所选规则输出处理结果。"
:names="cleanSelectedPaths"
:max-display="8"
files-label="选择 Excel 文件"
empty-text="暂未选择待清洗文件"
files-class="clean-placeholder"
@select-files="selectCleanFiles"
@select-folder="selectCleanFolder"
/>
<div class="section-title">保留列设置</div>
<div class="option-group column-option-group">
@@ -131,23 +124,42 @@
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
import FileUploadZone from '@/shared/components/FileUploadZone.vue'
import TaskCenterPanel from '@/shared/components/tasks/TaskCenterPanel.vue'
import type { TaskItemView, TaskStatCard } from '@/shared/components/tasks/types'
import { expandBrandFolderRecursive } from '@/shared/api/brand'
import { deleteDedupeHistory, getDedupeHistory, getDedupeResultDownloadUrl, getDedupeRunProgress, getExcelInfo, runDedupe, type DedupeResultItem, type DedupeRunProgressVo, type DedupeRunVo } from '@/shared/api/java-modules'
import { getPywebviewApi, type UploadedJavaFile } from '@/shared/bridges/pywebview'
import { saveUrlWithProgress } from '@/shared/utils/download-progress'
import { EXCEL_EXTENSIONS, checkSelectedFiles, collectDistinctErrors, guardBlocked } from '@/shared/dispatch-guard'
import { collectDistinctErrors, guardBlocked } from '@/shared/dispatch-guard'
import { passGuard } from '@/shared/dispatch-guard-ui'
import { useExcelFileUpload } from '@/shared/composables/useExcelFileUpload'
import { formatDateTime } from '@/shared/utils/datetime'
import { uploadPathsToJava } from '@/shared/utils/upload-to-java'
import { runBatchDelete } from '@/shared/utils/batch-delete'
const cleanAvailableColumns = ref<string[]>([])
const cleanSelectedColumns = ref<string[]>([])
const cleanSelectedPaths = ref<string[]>([])
const {
files: cleanUploadedFiles,
selectedPaths: cleanSelectedPaths,
selectFiles: selectCleanFiles,
selectFolder: selectCleanFolder,
} = useExcelFileUpload({
// 展示原始本机路径;文件夹展开后只展示相对路径(与原实现一致)
filePathsMode: 'raw',
folderPathsMode: 'relative',
filesSuccessMessage: (_files, paths) => `已选择 ${paths.length} 个待清洗文件`,
folderSuccessMessage: (_files, items) => `已选择文件夹内 ${items.length} 个 xlsx 文件`,
folderEmptyWarning: (error) => error || '该文件夹下没有 xlsx 文件',
onFolderPicked: (folder) => {
cleanArchiveName.value = folder.split(/[/\\]/).filter(Boolean).pop() || ''
},
onUploaded: async (info) => {
if (info.action === 'files') cleanArchiveName.value = ''
if (info.files.length > 0) {
await loadCleanHeaders(info.files[0].fileKey)
}
},
})
const cleanArchiveName = ref('')
const cleanUploadedFiles = ref<UploadedJavaFile[]>([])
const cleanKeepIntegerIds = ref(false)
const cleanKeepUnderscoreIds = ref(true)
const cleanKeepIntegerMainIdsWhenNoSubIds = ref(true)
@@ -155,7 +167,6 @@ const cleanRunning = ref(false)
const cleanProgressProcessed = ref(0)
const cleanResultItems = ref<DedupeResultItem[]>([])
const cleanSummary = ref<DedupeRunVo>({ total: 0, successCount: 0, failedCount: 0, items: [] })
const cleanDisplayPaths = computed(() => cleanSelectedPaths.value.slice(0, 8))
// 最近一次去重运行信息:用于右侧"当前任务"卡的占位展示(开始时间/运行ID/进度)
const latestRunId = ref('')
const cleanRunStartedAt = ref('')
@@ -255,67 +266,6 @@ async function loadCleanHeaders(fileKey: string) {
cleanSelectedColumns.value = defaultSelectedHeaders.filter((header) => orderedHeaders.includes(header))
}
async function handleSelectedPaths(paths: string[], successMessage: string) {
cleanSelectedPaths.value = paths
cleanArchiveName.value = ''
cleanUploadedFiles.value = await uploadPathsToJava(getPywebviewApi(), paths)
if (cleanUploadedFiles.value.length > 0) {
await loadCleanHeaders(cleanUploadedFiles.value[0].fileKey)
}
ElMessage.success(successMessage)
}
async function selectCleanFiles() {
const api = getPywebviewApi()
if (!api?.select_brand_xlsx_files) {
ElMessage.warning('当前环境不支持文件选择,请在本机客户端中打开')
return
}
try {
const paths = await api.select_brand_xlsx_files()
if (!paths?.length) return
if (!(await passGuard(checkSelectedFiles(paths, { allowedExtensions: EXCEL_EXTENSIONS })))) return
await handleSelectedPaths(paths, `已选择 ${paths.length} 个待清洗文件`)
} catch (error) {
cleanSelectedPaths.value = []
cleanUploadedFiles.value = []
ElMessage.error(error instanceof Error ? error.message : '选择失败')
}
}
async function selectCleanFolder() {
const api = getPywebviewApi()
if (!api?.select_brand_folder) {
ElMessage.warning('当前环境不支持文件夹选择,请在本机客户端中打开')
return
}
try {
const folder = await api.select_brand_folder()
if (!folder) return
cleanArchiveName.value = folder.split(/[/\\]/).filter(Boolean).pop() || ''
const result = await expandBrandFolderRecursive(folder)
if (result.success && result.items?.length) {
if (!(await passGuard(checkSelectedFiles(result.items, { allowedExtensions: EXCEL_EXTENSIONS })))) return
cleanSelectedPaths.value = result.items.map((item) => item.relativePath)
cleanUploadedFiles.value = await uploadPathsToJava(getPywebviewApi(), result.items)
if (cleanUploadedFiles.value.length > 0) {
await loadCleanHeaders(cleanUploadedFiles.value[0].fileKey)
}
ElMessage.success(`已选择文件夹内 ${result.items.length} 个 xlsx 文件`)
return
}
ElMessage.warning(result.error || '该文件夹下没有 xlsx 文件')
} catch (error) {
cleanSelectedPaths.value = []
cleanUploadedFiles.value = []
ElMessage.error(error instanceof Error ? error.message : '选择失败')
}
}
async function submitCleanRun() {
if (!cleanUploadedFiles.value.length) {
ElMessage.warning('请先选择待清洗 Excel 文件或文件夹')
@@ -519,33 +469,55 @@ async function batchDeleteHistory(views: TaskItemView[]) {
margin-bottom: 10px;
}
.upload-zone {
border: 1px dashed #3e4a62;
border-radius: 10px;
/* upload-zone 已抽到 FileUploadZone 组件;这里保留本 Tab 的差异样式 */
:deep(.upload-zone) {
padding: 24px;
text-align: center;
background: #242424;
margin-bottom: 20px;
transition: all 0.2s ease;
}
.upload-zone:hover {
:deep(.upload-zone:hover) {
border-color: #3498db;
background: #242424;
}
.hint {
color: #5e6878;
:deep(.upload-zone .hint) {
font-size: 13px;
margin-bottom: 12px;
line-height: 1.5;
}
.btns {
display: flex;
gap: 10px;
:deep(.upload-zone .btns) {
justify-content: center;
flex-wrap: wrap;
}
:deep(.upload-zone .opt-btn) {
padding: 8px 16px;
font-size: 13px;
border-radius: 6px;
}
:deep(.upload-zone .opt-btn:hover) {
color: #3498db;
background: #333;
border-color: #3498db;
}
:deep(.upload-zone .opt-btn:disabled) {
cursor: not-allowed;
opacity: 0.55;
}
:deep(.selected-files) {
font-size: 12px;
color: #5e6878;
max-height: 112px;
overflow-y: auto;
text-align: left;
}
:deep(.more-line) {
color: #a0acbe;
}
.opt-btn,
@@ -577,25 +549,6 @@ async function batchDeleteHistory(views: TaskItemView[]) {
border-color: #3498db;
}
.selected-files {
margin-top: 14px;
font-size: 12px;
color: #5e6878;
max-height: 112px;
overflow-y: auto;
text-align: left;
}
.selected-files span {
display: block;
margin: 4px 0;
word-break: break-all;
}
.more-line {
color: #a0acbe;
}
.option-group {
margin-bottom: 20px;
}
@@ -5,23 +5,16 @@
<div class="main-content">
<aside class="left-panel left-panel--with-template">
<div class="section-title">选择文件</div>
<div class="upload-zone">
<div class="hint">上传删除品牌 Excel;直接上传文件或上传文件夹批量导入都可以,每个 Excel 文件名会作为店铺名。</div>
<div class="btns">
<button type="button" class="opt-btn" @click="selectFiles">选择 Excel 文件</button>
<button type="button" class="opt-btn" @click="selectFolder">选择文件夹</button>
</div>
<div class="selected-files clean-placeholder split-selected-files">
<template v-if="selectedPaths.length">
<span v-for="path in displayPaths" :key="path">{{ path }}</span>
<span v-if="selectedPaths.length > displayPaths.length" class="more-line">
还有 {{ selectedPaths.length - displayPaths.length }} 个文件未展开显示
</span>
</template>
<span v-else>暂未选择删除品牌文件</span>
</div>
</div>
<FileUploadZone
hint="上传删除品牌 Excel;直接上传文件或上传文件夹批量导入都可以,每个 Excel 文件名会作为店铺名。"
:names="selectedPaths"
:max-display="10"
files-label="选择 Excel 文件"
empty-text="暂未选择删除品牌文件"
files-class="clean-placeholder split-selected-files"
@select-files="selectFiles"
@select-folder="selectFolder"
/>
<div class="section-title">执行说明</div>
<div class="option-group">
@@ -110,11 +103,11 @@
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
import FileUploadZone from '@/shared/components/FileUploadZone.vue'
import ModuleTemplateDownload from '@/shared/components/ModuleTemplateDownload.vue'
import TaskCenterPanel from '@/shared/components/tasks/TaskCenterPanel.vue'
import type { TaskItemView, TaskStatCard } from '@/shared/components/tasks/types'
import ZiniaoVersionSetting from '@/shared/components/ZiniaoVersionSetting.vue'
import { expandBrandFolderRecursive } from '@/shared/api/brand'
import {
deleteDeleteBrandHistory,
getDeleteBrandHistory,
@@ -127,20 +120,18 @@ import {
type DeleteBrandRunVo,
type DeleteBrandTaskDetailVo,
} from '@/shared/api/java-modules'
import { getPywebviewApi, type UploadedJavaFile } from '@/shared/bridges/pywebview'
import { getPywebviewApi } from '@/shared/bridges/pywebview'
import { getTaskPollIntervalMs } from '@/shared/task-progress-config'
import { createCategorizedTimers } from '@/shared/utils/categorized-timers'
import { saveUrlWithProgress } from '@/shared/utils/download-progress'
import {
EXCEL_EXTENSIONS,
checkQueuePayload,
checkSelectedFiles,
guardBlocked,
} from '@/shared/dispatch-guard'
import { passGuard } from '@/shared/dispatch-guard-ui'
import { useExcelFileUpload } from '@/shared/composables/useExcelFileUpload'
import { useZiniaoVersion } from '@/shared/utils/ziniao-version'
import { formatDateTime } from '@/shared/utils/datetime'
import { uploadPathsToJava } from '@/shared/utils/upload-to-java'
import { runBatchDelete } from '@/shared/utils/batch-delete'
interface SessionDeleteBrandItem extends DeleteBrandResultItem {
@@ -163,8 +154,20 @@ function getStorageKey() {
return `delete-brand:current-tasks:${uid}`
}
const selectedPaths = ref<string[]>([])
const uploadedFiles = ref<UploadedJavaFile[]>([])
const {
files: uploadedFiles,
selectedPaths,
selectFiles,
selectFolder,
} = useExcelFileUpload({
pickFilesUnavailableWarning: '当前环境不支持文件选择,请在本机客户端中打开',
folderUnavailableWarning: '当前环境不支持文件夹选择,请在本机客户端中打开',
folderEmptyWarning: (error) => error || '该文件夹下没有 xlsx 文件',
// 展示原始本机路径;文件夹展开后展示 relativePath || absolutePath(与原实现一致)
filePathsMode: 'raw',
filesSuccessMessage: (_files, paths) => `已选择 ${paths.length} 个删除品牌文件`,
folderSuccessMessage: (_files, items) => `已选择文件夹内 ${items.length} 个 xlsx 文件`,
})
const running = ref(false)
const resultItems = ref<DeleteBrandResultItem[]>([])
const sessionTasks = ref<StoredCurrentTask[]>([])
@@ -183,7 +186,6 @@ const autoRetryTimer = ref<number | null>(null)
const waitingForBackendRecovery = ref(false)
let disposed = false
const timers = createCategorizedTimers('delete-brand')
const displayPaths = computed(() => selectedPaths.value.slice(0, 10))
const currentSectionItems = computed(() => {
const sortedTasks = [...sessionTasks.value].sort((left, right) => (right.createdAt || 0) - (left.createdAt || 0))
@@ -1013,53 +1015,6 @@ function stopPolling() {
clearAutoRetryTimer()
}
async function selectFiles() {
const api = getPywebviewApi()
if (!api?.select_brand_xlsx_files) {
ElMessage.warning('当前环境不支持文件选择,请在本机客户端中打开')
return
}
try {
const paths = await api.select_brand_xlsx_files()
if (!paths?.length) return
if (!(await passGuard(checkSelectedFiles(paths, { allowedExtensions: EXCEL_EXTENSIONS })))) return
selectedPaths.value = paths
uploadedFiles.value = await uploadPathsToJava(getPywebviewApi(), paths)
ElMessage.success(`已选择 ${paths.length} 个删除品牌文件`)
} catch (error) {
// 上传失败时清空选择,避免残留上一批文件让用户误以为新文件已就绪
selectedPaths.value = []
uploadedFiles.value = []
ElMessage.error(error instanceof Error ? error.message : '选择失败')
}
}
async function selectFolder() {
const api = getPywebviewApi()
if (!api?.select_brand_folder) {
ElMessage.warning('当前环境不支持文件夹选择,请在本机客户端中打开')
return
}
try {
const folder = await api.select_brand_folder()
if (!folder) return
const result = await expandBrandFolderRecursive(folder)
if (!result.success || !result.items?.length) {
ElMessage.warning(result.error || '该文件夹下没有 xlsx 文件')
return
}
if (!(await passGuard(checkSelectedFiles(result.items, { allowedExtensions: EXCEL_EXTENSIONS })))) return
selectedPaths.value = result.items.map((item) => item.relativePath || item.absolutePath)
uploadedFiles.value = await uploadPathsToJava(getPywebviewApi(), result.items)
ElMessage.success(`已选择文件夹内 ${result.items.length} 个 xlsx 文件`)
} catch (error) {
selectedPaths.value = []
uploadedFiles.value = []
ElMessage.error(error instanceof Error ? error.message : '选择失败')
}
}
async function submitRun() {
if (!uploadedFiles.value.length) {
ElMessage.warning('请先选择待处理文件')
@@ -1583,26 +1538,56 @@ async function batchDeleteHistory(views: TaskItemView[]) {
margin-bottom: 10px;
}
.upload-zone {
border: 1px dashed #3e4a62;
border-radius: 10px;
/* upload-zone 已抽到 FileUploadZone 组件;这里保留本 Tab 的差异样式 */
:deep(.upload-zone) {
padding: 24px;
text-align: center;
background: #242424;
margin-bottom: 20px;
transition: all 0.2s ease;
}
.upload-zone:hover {
:deep(.upload-zone:hover) {
border-color: #3498db;
background: #242424;
}
.hint {
color: #5e6878;
:deep(.upload-zone .hint) {
font-size: 13px;
margin-bottom: 12px;
line-height: 1.5;
}
:deep(.upload-zone .btns) {
justify-content: center;
}
:deep(.upload-zone .opt-btn) {
padding: 8px 16px;
font-size: 13px;
border-radius: 6px;
}
:deep(.upload-zone .opt-btn:hover) {
color: #3498db;
background: #333;
border-color: #3498db;
}
:deep(.selected-files) {
font-size: 12px;
color: #5e6878;
max-height: 112px;
overflow-y: auto;
text-align: left;
}
:deep(.more-line) {
color: #a0acbe;
}
:deep(.split-selected-files) {
max-height: 120px;
min-height: 72px;
padding-right: 4px;
}
.btns {
@@ -1636,31 +1621,6 @@ async function batchDeleteHistory(views: TaskItemView[]) {
border-color: #3498db;
}
.selected-files {
margin-top: 14px;
font-size: 12px;
color: #5e6878;
max-height: 112px;
overflow-y: auto;
text-align: left;
}
.selected-files span {
display: block;
margin: 4px 0;
word-break: break-all;
}
.more-line {
color: #a0acbe;
}
.split-selected-files {
max-height: 120px;
min-height: 72px;
padding-right: 4px;
}
.option-group {
margin-bottom: 20px;
}
@@ -289,6 +289,7 @@ import {
sanitizeCountryCodes,
} from "@/shared/country-options";
import { formatDateTime } from '@/shared/utils/datetime'
import { RUNNING_UNTIL_DONE_STATUS_OPTIONS, taskStatusClass, taskStatusText } from '@/shared/utils/task-status-text'
import { useHistoryPolling } from '@/shared/composables/useHistoryPolling'
import { runBatchDelete } from '@/shared/utils/batch-delete'
import { isRecordMissingError } from '@/shared/utils/task-queue-state.ts'
@@ -645,17 +646,11 @@ function isTaskTerminal(status?: string) {
}
function statusText(status?: string) {
if (status === "SUCCESS" || status === "COMPLETED") return "已完成";
if (status === "FAILED") return "失败";
return "执行中";
return taskStatusText(status, RUNNING_UNTIL_DONE_STATUS_OPTIONS);
}
function statusClass(status?: string) {
return status === "SUCCESS" || status === "COMPLETED"
? "success"
: status === "FAILED"
? "failed"
: "running";
return taskStatusClass(status, RUNNING_UNTIL_DONE_STATUS_OPTIONS);
}
function canDownload(item: PatrolDeleteHistoryItem) {
@@ -40,19 +40,16 @@
<template v-if="asinModeEnabled">
<div class="section-title">ASIN文档 <span class="tag-badge">自定义模式</span></div>
<div class="upload-zone">
<div class="hint">上传包含ASIN的表格文件,按文档内的ASIN进行跟价。</div>
<div class="btns">
<button type="button" class="opt-btn" @click="selectAsinFile">选择ASIN文件</button>
<button type="button" class="opt-btn" @click="selectAsinFolder">选择文件夹</button>
</div>
<div class="selected-files clean-placeholder">
<template v-if="asinFiles.length">
<span v-for="(f, i) in asinFiles" :key="i">{{ f }}</span>
</template>
<span v-else class="text-muted">暂未选择</span>
</div>
</div>
<FileUploadZone
hint="上传包含ASIN的表格文件,按文档内的ASIN进行跟价。"
:names="asinFiles"
files-label="选择ASIN文件"
empty-text="暂未选择"
muted-empty
files-class="clean-placeholder"
@select-files="selectAsinFile"
@select-folder="selectAsinFolder"
/>
</template>
<div class="price-track-shop-candidates">
@@ -219,17 +216,17 @@ import { ElMessage } from 'element-plus'
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
import ModuleTemplateDownload from '@/shared/components/ModuleTemplateDownload.vue'
import ZiniaoVersionSetting from '@/shared/components/ZiniaoVersionSetting.vue'
import FileUploadZone from '@/shared/components/FileUploadZone.vue'
import TaskCenterPanel from '@/shared/components/tasks/TaskCenterPanel.vue'
import type { TaskItemView, TaskStatCard } from '@/shared/components/tasks/types'
import { expandBrandFolderRecursive } from '@/shared/api/brand'
import { getPywebviewApi, type PywebviewApi, type UploadedJavaFile } from '@/shared/bridges/pywebview'
import { getPywebviewApi, type PywebviewApi } from '@/shared/bridges/pywebview'
import { useExcelFileUpload } from '@/shared/composables/useExcelFileUpload'
import { getTaskPollIntervalMs } from '@/shared/task-progress-config'
import { createCategorizedTimers } from '@/shared/utils/categorized-timers'
import { saveUrlWithProgress } from '@/shared/utils/download-progress'
import {
EXCEL_CSV_EXTENSIONS,
checkQueuePayload,
checkSelectedFiles,
} from '@/shared/dispatch-guard'
import { passGuard } from '@/shared/dispatch-guard-ui'
import { useZiniaoVersion } from '@/shared/utils/ziniao-version'
@@ -267,7 +264,7 @@ import {
} from '@/shared/api/java-modules'
import { getPollingProgressBatch } from '@/shared/api/task-progress-polling.ts'
import { formatDateTime } from '@/shared/utils/datetime'
import { uploadPathsToJava } from '@/shared/utils/upload-to-java'
import { taskStatusClass, taskStatusText } from '@/shared/utils/task-status-text'
import { runBatchDelete } from '@/shared/utils/batch-delete'
import { isRecordMissingError } from '@/shared/utils/task-queue-state.ts'
import { useTablePaging } from '@/shared/composables/useTablePaging.ts'
@@ -317,8 +314,35 @@ const statusModeEnabled = ref(true) // 按商品状态(全量)
const asinModeEnabled = ref(false) // 按指定ASIN文档(自定义)
// 上传文件
const asinFiles = ref<string[]>([]) // ASIN文档
const asinUploadedFiles = ref<UploadedJavaFile[]>([])
const {
files: asinUploadedFiles,
selectedPaths: asinFiles,
selectFiles: selectAsinFile,
selectFolder: selectAsinFolder,
} = useExcelFileUpload({
allowedExtensions: EXCEL_CSV_EXTENSIONS,
// 上传失败时清空选择,避免本地路径残留被当作服务器路径提交给 Java
uploadOptions: { returnEmptyWhenUnavailable: true },
filePathsMode: 'raw',
filesSuccessMessage: (_files, paths) => `已选择 ${paths.length} 个ASIN文件`,
folderSuccessMessage: (_files, items) => `已选择文件夹内 ${items.length} 个ASIN文件`,
folderUnavailableWarning: '当前环境不支持文件夹选择,请在本地客户端中打开',
pickFiles: async () => {
const api = getPywebviewApi()
if (api?.select_files) {
const result = await api.select_files({
filters: [{ name: 'Excel/CSV', extensions: 'xlsx,xls,csv' }],
multiple: true,
})
return result?.paths || null
}
if (api?.select_brand_xlsx_files) {
return await api.select_brand_xlsx_files()
}
ElMessage.warning('当前环境不支持文件选择,请在本地客户端中打开')
return null
},
})
// 是否有有效模式
const hasValidMode = computed(() => statusModeEnabled.value || asinModeEnabled.value)
@@ -532,67 +556,6 @@ function saveActiveLoopRunId() {
setStorageJson(activeLoopStorageKey(), activeLoopRunId.value, !activeLoopRunId.value)
}
// ========== 文件上传 ==========
async function selectAsinFile() {
const api = getPywebviewApi()
let paths: string[] = []
if (api?.select_files) {
const result = await api.select_files({
filters: [{ name: 'Excel/CSV', extensions: 'xlsx,xls,csv' }],
multiple: true,
})
if (!result?.paths?.length) return
if (!(await passGuard(checkSelectedFiles(result.paths, { allowedExtensions: EXCEL_CSV_EXTENSIONS })))) return
paths = result.paths
} else if (api?.select_brand_xlsx_files) {
const selected = await api.select_brand_xlsx_files()
if (!selected?.length) return
if (!(await passGuard(checkSelectedFiles(selected, { allowedExtensions: EXCEL_CSV_EXTENSIONS })))) return
paths = selected
} else {
ElMessage.warning('当前环境不支持文件选择,请在本地客户端中打开')
return
}
try {
asinFiles.value = paths
asinUploadedFiles.value = await uploadPathsToJava(getPywebviewApi(), paths, { returnEmptyWhenUnavailable: true })
ElMessage.success(`已选择 ${paths.length} 个ASIN文件`)
} catch (error) {
// 上传失败时清空选择,避免本地路径残留被当作服务器路径提交给 Java
asinFiles.value = []
asinUploadedFiles.value = []
ElMessage.error(error instanceof Error ? error.message : '选择失败')
}
}
async function selectAsinFolder() {
const api = getPywebviewApi()
if (!api?.select_brand_folder) {
ElMessage.warning('当前环境不支持文件夹选择,请在本地客户端中打开')
return
}
try {
const folder = await api.select_brand_folder()
if (!folder) return
const result = await expandBrandFolderRecursive(folder)
if (!result.success || !result.items?.length) {
ElMessage.warning(result.error || '该文件夹下没有可用的 xlsx 文件')
return
}
if (!(await passGuard(checkSelectedFiles(result.items, { allowedExtensions: EXCEL_CSV_EXTENSIONS })))) return
asinFiles.value = result.items.map((item) => item.relativePath || item.absolutePath)
asinUploadedFiles.value = await uploadPathsToJava(getPywebviewApi(), result.items, { returnEmptyWhenUnavailable: true })
ElMessage.success(`已选择文件夹内 ${result.items.length} 个ASIN文件`)
} catch (error) {
// 上传失败时清空选择,避免残留上一批文件让用户误以为新文件已就绪
asinFiles.value = []
asinUploadedFiles.value = []
ElMessage.error(error instanceof Error ? error.message : '选择失败')
}
}
// ========== 国家顺序相关 ==========
function resolveAsinRequestPaths() {
// 提交上传返回的 fileKey(与去重/转换/采集等模块一致):服务端按 key 反查上传临时目录,
@@ -1643,18 +1606,15 @@ function resolvedTaskStatus(item: PriceTrackHistoryItem) {
function statusText(item: PriceTrackHistoryItem) {
const st = resolvedTaskStatus(item)
if (st === 'SUCCESS') return '已完成'
if (st === 'FAILED') return '失败'
if (st === 'RUNNING') return '执行中'
if (item.success) return '已完成'
return '等待中'
if (st === 'SUCCESS' || st === 'FAILED' || st === 'RUNNING') return taskStatusText(st)
return item.success ? taskStatusText('SUCCESS') : '等待中'
}
function statusClass(item: PriceTrackHistoryItem) {
const st = resolvedTaskStatus(item)
if (st === 'SUCCESS' || item.success) return 'success'
if (st === 'FAILED') return 'failed'
return 'running'
if (st === 'SUCCESS' || item.success) return taskStatusClass('SUCCESS')
// 其余(FAILED/未知状态)保持原实现:failed / running
return taskStatusClass(st, { classMap: { CANCELLED: 'running' }, classFallback: 'running' })
}
function canDownload(item: PriceTrackHistoryItem) {
@@ -1800,29 +1760,23 @@ async function batchDeleteHistory(views: TaskItemView[]) {
margin-bottom: 10px;
}
.upload-zone {
border: 1px dashed #3e4a62;
border-radius: 10px;
/* upload-zone 已抽到 FileUploadZone 组件;这里保留本 Tab 的差异样式 */
:deep(.upload-zone) {
padding: 16px;
background: #242424;
margin-bottom: 20px;
}
.hint {
color: #5e6878;
:deep(.upload-zone .hint) {
font-size: 12px;
margin-bottom: 12px;
line-height: 1.5;
text-align: left;
}
.btns {
display: flex;
gap: 10px;
:deep(.upload-zone .btns) {
margin-bottom: 10px;
}
.selected-files {
:deep(.selected-files) {
margin-top: 8px;
font-size: 12px;
display: flex;
@@ -1838,11 +1792,11 @@ async function batchDeleteHistory(views: TaskItemView[]) {
gap: 4px;
}
.selected-files span:not(.more-line) {
:deep(.selected-files span) {
color: #a0acbe;
}
.more-line {
:deep(.more-line) {
color: #5e6878;
font-style: italic;
}
@@ -183,6 +183,7 @@ import { passGuard } from '@/shared/dispatch-guard-ui'
import ZiniaoVersionSetting from '@/shared/components/ZiniaoVersionSetting.vue'
import { useZiniaoVersion } from '@/shared/utils/ziniao-version'
import { formatDateTime } from '@/shared/utils/datetime'
import { taskStatusClass, taskStatusText } from '@/shared/utils/task-status-text'
import { runBatchDelete } from '@/shared/utils/batch-delete'
import { isRecordMissingError } from '@/shared/utils/task-queue-state.ts'
import { useTablePaging } from '@/shared/composables/useTablePaging.ts'
@@ -1024,18 +1025,15 @@ function resolvedTaskStatus(item: ProductRiskHistoryItem) {
function statusText(item: ProductRiskHistoryItem) {
const st = resolvedTaskStatus(item)
if (st === 'SUCCESS') return '已完成'
if (st === 'FAILED') return '失败'
if (st === 'RUNNING') return '执行中'
if (item.success) return '已完成'
return '等待中'
if (st === 'SUCCESS' || st === 'FAILED' || st === 'RUNNING') return taskStatusText(st)
return item.success ? taskStatusText('SUCCESS') : '等待中'
}
function statusClass(item: ProductRiskHistoryItem) {
const st = resolvedTaskStatus(item)
if (st === 'SUCCESS' || item.success) return 'success'
if (st === 'FAILED') return 'failed'
return 'running'
if (st === 'SUCCESS' || item.success) return taskStatusClass('SUCCESS')
// 其余(FAILED/未知状态)保持原实现:failed / running
return taskStatusClass(st, { classMap: { CANCELLED: 'running' }, classFallback: 'running' })
}
function canDownload(item: ProductRiskHistoryItem) {
@@ -5,29 +5,19 @@
<div class="main-content">
<aside class="left-panel left-panel--with-template">
<div class="section-title">上传模块</div>
<div class="upload-zone">
<div class="hint">
选择需要上架的 Excel 文件或文件夹;每个 Excel 文件名会作为店铺名进行匹配。
</div>
<div class="btns">
<button type="button" class="opt-btn" :disabled="selectionDisabled" @click="selectFiles">
{{ uploading ? '上传中...' : '选择 Excel 文件' }}
</button>
<button type="button" class="opt-btn" :disabled="selectionDisabled" @click="selectFolder">
选择文件夹
</button>
</div>
<div class="selected-files clean-placeholder publish-selected-files">
<template v-if="selectedPaths.length">
<span v-for="path in displayPaths" :key="path">{{ path }}</span>
<span v-if="selectedPaths.length > displayPaths.length" class="more-line">
还有 {{ selectedPaths.length - displayPaths.length }} 个文件未展开显示
</span>
</template>
<span v-else>暂未选择上架文件</span>
</div>
</div>
<FileUploadZone
hint="选择需要上架的 Excel 文件或文件夹;每个 Excel 文件名会作为店铺名进行匹配。"
:names="selectedPaths"
:max-display="8"
files-label="选择 Excel 文件"
uploading-label="上传中..."
:uploading="uploading"
:disabled="selectionDisabled"
empty-text="暂未选择上架文件"
files-class="clean-placeholder publish-selected-files"
@select-files="selectFiles"
@select-folder="selectFolder"
/>
<div class="section-title">国家选择</div>
<div class="country-group">
@@ -187,11 +177,11 @@ import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
import FileUploadZone from '@/shared/components/FileUploadZone.vue'
import ModuleTemplateDownload from '@/shared/components/ModuleTemplateDownload.vue'
import TaskCenterPanel from '@/shared/components/tasks/TaskCenterPanel.vue'
import type { TaskItemView, TaskStatCard } from '@/shared/components/tasks/types'
import ZiniaoVersionSetting from '@/shared/components/ZiniaoVersionSetting.vue'
import { expandBrandFolderRecursive } from '@/shared/api/brand'
import {
activatePublishFile,
activatePublishTask,
@@ -206,22 +196,21 @@ import {
type PublishFileItem,
type PublishTaskDetailVo,
} from '@/shared/api/java-modules'
import { getPywebviewApi, type UploadedJavaFile } from '@/shared/bridges/pywebview'
import { getPywebviewApi } from '@/shared/bridges/pywebview'
import { useExcelFileUpload } from '@/shared/composables/useExcelFileUpload'
import { useTaskProgressLoop } from '@/shared/composables/useTaskProgressLoop'
import { getTaskPollIntervalMs } from '@/shared/task-progress-config'
import { createCategorizedTimers } from '@/shared/utils/categorized-timers'
import { saveUrlWithProgress } from '@/shared/utils/download-progress'
import { taskStatusClass, taskStatusText } from '@/shared/utils/task-status-text'
import {
EXCEL_EXTENSIONS,
checkParseResult,
checkQueuePayload,
checkSelectedFiles,
collectDistinctErrors,
guardBlocked,
} from '@/shared/dispatch-guard'
import { passGuard } from '@/shared/dispatch-guard-ui'
import { useZiniaoVersion, type ZiniaoVersion } from '@/shared/utils/ziniao-version'
import { uploadPathsToJava } from '@/shared/utils/upload-to-java'
import { runBatchDelete } from '@/shared/utils/batch-delete'
const COUNTRY_OPTIONS = [
@@ -251,9 +240,23 @@ interface StoredPublishQueueState {
pending: PublishQueueBatch[]
}
const selectedPaths = ref<string[]>([])
const uploadedFiles = ref<UploadedJavaFile[]>([])
const uploading = ref(false)
const {
files: uploadedFiles,
selectedPaths,
uploading,
selectFiles,
selectFolder,
} = useExcelFileUpload({
requireUploadCapability: true,
folderRequireUploadCapability: true,
pickFilesUnavailableWarning: '当前环境不支持文件选择或上传,请在本机客户端中打开',
folderUnavailableWarning: '当前环境不支持文件夹选择或上传,请在本机客户端中打开',
folderEmptyWarning: (error) => error || '该文件夹下没有 xlsx 文件',
// 展示原始本机路径;文件夹展开后展示 relativePath || absolutePath(与原实现一致)
filePathsMode: 'raw',
filesSuccessMessage: (files) => `已上传 ${files.length} 个待上架文件`,
folderSuccessMessage: (files) => `已上传文件夹内 ${files.length} 个 xlsx 文件`,
})
const parsing = ref(false)
const queueWorkerRunning = ref(false)
const queueMessage = ref('')
@@ -369,7 +372,6 @@ const progressLoop = useTaskProgressLoop<PublishTaskDetailVo>({
},
})
const displayPaths = computed(() => selectedPaths.value.slice(0, 8))
const activeBatchHasWork = computed(() => pendingFileIds.value.length > 0 || activeFileId.value != null)
const hasQueueWork = computed(() => activeBatchHasWork.value || queuedBatches.value.length > 0)
const selectionDisabled = computed(() => uploading.value || parsing.value)
@@ -480,60 +482,6 @@ function onSyncCountryChange(code: string, event: Event) {
syncCountries.value = COUNTRY_OPTIONS.map((item) => item.code).filter((item) => selected.has(item))
}
async function selectFiles() {
const api = getPywebviewApi()
if (!api?.select_brand_xlsx_files || !api.upload_file_to_java) {
ElMessage.warning('当前环境不支持文件选择或上传,请在本机客户端中打开')
return
}
try {
const paths = await api.select_brand_xlsx_files()
if (!paths?.length) return
if (!(await passGuard(checkSelectedFiles(paths, { allowedExtensions: EXCEL_EXTENSIONS })))) return
uploading.value = true
const uploaded = await uploadPathsToJava(getPywebviewApi(), paths)
selectedPaths.value = paths
uploadedFiles.value = uploaded
ElMessage.success(`已上传 ${uploaded.length} 个待上架文件`)
} catch (error) {
// 上传失败时清空选择,避免残留上一批文件让用户误以为新文件已就绪
selectedPaths.value = []
uploadedFiles.value = []
ElMessage.error(error instanceof Error ? error.message : '选择失败')
} finally {
uploading.value = false
}
}
async function selectFolder() {
const api = getPywebviewApi()
if (!api?.select_brand_folder || !api.upload_file_to_java) {
ElMessage.warning('当前环境不支持文件夹选择或上传,请在本机客户端中打开')
return
}
try {
const folder = await api.select_brand_folder()
if (!folder) return
const result = await expandBrandFolderRecursive(folder)
if (!result.success || !result.items?.length) {
ElMessage.warning(result.error || '该文件夹下没有 xlsx 文件')
return
}
if (!(await passGuard(checkSelectedFiles(result.items, { allowedExtensions: EXCEL_EXTENSIONS })))) return
uploading.value = true
const uploaded = await uploadPathsToJava(getPywebviewApi(), result.items)
selectedPaths.value = result.items.map((item) => item.relativePath || item.absolutePath)
uploadedFiles.value = uploaded
ElMessage.success(`已上传文件夹内 ${uploaded.length} 个 xlsx 文件`)
} catch (error) {
selectedPaths.value = []
uploadedFiles.value = []
ElMessage.error(error instanceof Error ? error.message : '选择失败')
} finally {
uploading.value = false
}
}
function isMatchedFile(file: PublishFileItem) {
const matchStatus = normalizeStatus(file.matchStatus)
return Boolean(
@@ -1048,20 +996,11 @@ function reconcileStoredQueue() {
}
function statusText(status?: string | null) {
const value = normalizeStatus(status)
if (value === 'SUCCESS' || value === 'COMPLETED') return '已完成'
if (value === 'FAILED') return '失败'
if (value === 'CANCELLED') return '已取消'
if (value === 'RUNNING') return '执行中'
return '等待中'
return taskStatusText(normalizeStatus(status))
}
function statusClass(status?: string | null) {
const value = normalizeStatus(status)
if (value === 'SUCCESS' || value === 'COMPLETED') return 'success'
if (value === 'FAILED' || value === 'CANCELLED') return 'failed'
if (value === 'RUNNING') return 'running'
return 'pending'
return taskStatusClass(normalizeStatus(status))
}
function matchText(file: PublishFileItem) {
@@ -1217,7 +1156,12 @@ async function batchDeleteHistory(views: TaskItemView[]) {
.left-panel { width: 400px; background: #242424; padding: 20px; overflow-y: auto; border-right: 1px solid #2e3a52; }
.right-panel { flex: 1; display: flex; flex-direction: column; min-width: 0; background: #242424; }
.section-title { margin-bottom: 10px; color: #a0acbe; font-size: 13px; }
.upload-zone { margin-bottom: 20px; padding: 20px; border: 1px dashed #3e4a62; border-radius: 8px; background: #242424; text-align: center; }
/* upload-zone 已抽到 FileUploadZone 组件;这里保留本 Tab 的差异样式 */
:deep(.upload-zone) { margin-bottom: 20px; padding: 20px; border-radius: 8px; text-align: center; }
:deep(.upload-zone .btns) { justify-content: center; }
:deep(.upload-zone .opt-btn) { padding: 8px 16px; font-size: 13px; border-radius: 6px; }
:deep(.upload-zone .opt-btn:hover:not(:disabled)) { border-color: #3498db; color: #67b7ef; }
:deep(.upload-zone .opt-btn:disabled) { opacity: .55; cursor: not-allowed; }
.hint, .loading-msg { color: #5e6878; font-size: 12px; line-height: 1.5; }
.btns, .run-row { display: flex; align-items: center; flex-wrap: wrap; gap: 10px; }
.btns { justify-content: center; }
@@ -1225,9 +1169,8 @@ async function batchDeleteHistory(views: TaskItemView[]) {
.opt-btn { padding: 8px 16px; border: 1px solid #3e4a62; background: #242424; color: #c8d2e2; font-size: 13px; }
.opt-btn:hover:not(:disabled) { border-color: #3498db; color: #67b7ef; }
.opt-btn:disabled, .btn-run:disabled { opacity: .55; cursor: not-allowed; }
.selected-files { max-height: 120px; min-height: 72px; margin-top: 14px; overflow-y: auto; color: #5e6878; font-size: 12px; text-align: left; }
.selected-files span { display: block; margin: 4px 0; word-break: break-all; }
.more-line { color: #a0acbe; }
:deep(.publish-selected-files) { max-height: 120px; min-height: 72px; overflow-y: auto; color: #5e6878; }
:deep(.more-line) { color: #a0acbe; }
.country-group { margin-bottom: 12px; padding: 14px; border: 1px solid #323e58; border-radius: 8px; background: #242424; }
.country-group-title { margin-bottom: 10px; color: #a0acbe; font-size: 12px; }
.country-checks { display: flex; flex-wrap: wrap; gap: 10px 16px; }
@@ -231,6 +231,7 @@ import { passGuard } from "@/shared/dispatch-guard-ui";
import ZiniaoVersionSetting from "@/shared/components/ZiniaoVersionSetting.vue";
import { useZiniaoVersion } from "@/shared/utils/ziniao-version";
import { formatDateTime } from '@/shared/utils/datetime'
import { RUNNING_UNTIL_DONE_STATUS_OPTIONS, taskStatusClass, taskStatusText } from '@/shared/utils/task-status-text'
import { useHistoryPolling } from '@/shared/composables/useHistoryPolling'
import { runBatchDelete } from '@/shared/utils/batch-delete'
import { isRecordMissingError, parseTaskStartTimes, removeTaskStartTime, upsertTaskStartTime } from '@/shared/utils/task-queue-state.ts'
@@ -518,17 +519,11 @@ function isTaskTerminal(status?: string) {
}
function statusText(status?: string) {
if (status === "SUCCESS" || status === "COMPLETED") return "已完成";
if (status === "FAILED") return "失败";
return "执行中";
return taskStatusText(status, RUNNING_UNTIL_DONE_STATUS_OPTIONS);
}
function statusClass(status?: string) {
return status === "SUCCESS" || status === "COMPLETED"
? "success"
: status === "FAILED"
? "failed"
: "running";
return taskStatusClass(status, RUNNING_UNTIL_DONE_STATUS_OPTIONS);
}
function canDownload(item: QueryAsinHistoryItem) {
@@ -140,6 +140,7 @@ import { getPywebviewApi } from '@/shared/bridges/pywebview'
import { getTaskPollIntervalMs } from '@/shared/task-progress-config'
import { createCategorizedTimers } from '@/shared/utils/categorized-timers'
import { saveUrlWithProgress } from '@/shared/utils/download-progress'
import { taskStatusClass, taskStatusText } from '@/shared/utils/task-status-text'
import { checkQueuePayload } from '@/shared/dispatch-guard'
import { passGuard } from '@/shared/dispatch-guard-ui'
import { mergeHistoryItems } from '@/shared/merge-history-items'
@@ -275,12 +276,11 @@ function isCountrySelectionLocked(code: string) { return orderedCountryCodes.val
function isTerminal(status?: string) { return status === 'SUCCESS' || status === 'FAILED' || status === 'COMPLETED' }
function statusText(item: ShopDataCrawlHistoryItem) {
const status = item.taskStatus
if (status === 'SUCCESS' || status === 'COMPLETED') return '已完成'
if (status === 'FAILED') return '失败'
if (status === 'SUCCESS' || status === 'COMPLETED' || status === 'FAILED') return taskStatusText(status)
if (item.success === true) return '结果文件生成中'
return '处理中'
}
function statusClass(status?: string) { return status === 'SUCCESS' || status === 'COMPLETED' ? 'success' : status === 'FAILED' ? 'failed' : 'running' }
function statusClass(status?: string) { return taskStatusClass(status, { classMap: { CANCELLED: 'running' }, classFallback: 'running' }) }
function canDownload(item: ShopDataCrawlHistoryItem) { return Boolean(item.resultId && (item.fileReady || item.downloadUrl)) }
function formatDateTime(value?: string) { if (!value) return '-'; const date = new Date(value); return Number.isNaN(date.getTime()) ? value : date.toLocaleString('zh-CN', { hour12: false }) }
function formatMatchStatus(status?: string) { return ({ MATCHED: '已匹配', PENDING: '待匹配', CONFLICT: '需确认', INDEX_STALE: '匹配已过期' } as Record<string, string>)[status || ''] || status || '-' }
@@ -129,6 +129,7 @@ import { getPywebviewApi } from '@/shared/bridges/pywebview'
import { getTaskPollIntervalMs } from '@/shared/task-progress-config'
import { createCategorizedTimers } from '@/shared/utils/categorized-timers'
import { saveUrlWithProgress } from '@/shared/utils/download-progress'
import { taskStatusClass, taskStatusText } from '@/shared/utils/task-status-text'
import { useZiniaoVersion } from '@/shared/utils/ziniao-version'
import { runBatchDelete } from '@/shared/utils/batch-delete'
import { useTablePaging } from '@/shared/composables/useTablePaging.ts'
@@ -531,8 +532,8 @@ function resolvedTaskStatus(item: ShopMatchHistoryItem) {
function taskSnapshotOf(item: ShopMatchHistoryItem) { const taskId = normalizeTaskId(item.taskId); return taskId ? taskSnapshots.value[taskId] : undefined }
function currentTaskStageText(item: ShopMatchHistoryItem) { const snapshot = taskSnapshotOf(item); const task = snapshot?.task; const stages = task?.scheduleStages || []; if (!stages.length) return ''; const total = stages.length; const activeIndex = typeof task?.activeStageIndex === 'number' ? task.activeStageIndex : undefined; const currentIndex = typeof task?.currentStageIndex === 'number' ? task.currentStageIndex : undefined; if (typeof activeIndex === 'number') return `执行进度: 第 ${activeIndex + 1}/${total} 次执行中`; if (typeof currentIndex === 'number') return `执行进度: 等待第 ${currentIndex + 1}/${total} 次`; return `执行进度: 共 ${total} 次`}
function nextScheduledDisplay(item: ShopMatchHistoryItem) { const snapshot = taskSnapshotOf(item); const task = snapshot?.task; const stages = task?.scheduleStages || []; if (typeof task?.currentStageIndex === 'number') { const stage = stages.find((entry) => entry.stageIndex === task.currentStageIndex); if (stage?.scheduledAt) return formatMonthDayTime(stage.scheduledAt) } if (item.scheduledAt) return formatMonthDayTime(item.scheduledAt); return '' }
function statusText(item: ShopMatchHistoryItem) { const status = resolvedTaskStatus(item); if (status === 'SCHEDULED') return '待执行'; if (status === 'RUNNING') return '执行中'; if (status === 'SUCCESS' || status === 'COMPLETED') return '已完成'; if (status === 'FAILED') return '失败'; return item.success ? '已完成' : '未知' }
function statusClass(item: ShopMatchHistoryItem) { const status = resolvedTaskStatus(item); return status === 'SUCCESS' || status === 'COMPLETED' ? 'success' : status === 'FAILED' ? 'failed' : 'running' }
function statusText(item: ShopMatchHistoryItem) { const status = resolvedTaskStatus(item); if (['SCHEDULED', 'RUNNING', 'SUCCESS', 'COMPLETED', 'FAILED'].includes(status)) return taskStatusText(status); return item.success ? taskStatusText('SUCCESS') : '未知' }
function statusClass(item: ShopMatchHistoryItem) { const status = resolvedTaskStatus(item); return taskStatusClass(status, { classMap: { SCHEDULED: 'running', CANCELLED: 'running' }, classFallback: 'running' }) }
// 失败任务也可能有已跑出来的部分结果文件(后端按已收分片组装),有文件就允许下载
function canDownload(item: ShopMatchHistoryItem) { const status = resolvedTaskStatus(item); return !!item.resultId && (!!item.fileReady || !!item.downloadUrl) && (status === 'SUCCESS' || status === 'COMPLETED' || status === 'FAILED') }
async function downloadResult(item: ShopMatchHistoryItem) { if (!item.resultId) return; const url = getShopMatchResultDownloadUrl(item.resultId); const filename = item.outputFilename || `${item.shopName || 'result'}.xlsx`; const result = await saveUrlWithProgress(url, filename, `shop-match:${item.resultId}`); if (result.success) ElMessage.success(`已保存: ${result.path || filename}`); else if (result.error && result.error !== '用户取消') ElMessage.error(result.error) }
File diff suppressed because it is too large Load Diff
@@ -5,23 +5,16 @@
<div class="main-content">
<aside class="left-panel">
<div class="section-title">选择文件</div>
<div class="upload-zone">
<div class="hint">选择需要拆分的 Excel 文件或文件夹,按规则拆成多个 Excel 文件。</div>
<div class="btns">
<button type="button" class="opt-btn" @click="selectSplitFiles">选择 Excel 文件</button>
<button type="button" class="opt-btn" @click="selectSplitFolder">选择文件夹</button>
</div>
<div class="selected-files clean-placeholder split-selected-files">
<template v-if="splitSelectedPaths.length">
<span v-for="path in splitDisplayPaths" :key="path">{{ path }}</span>
<span v-if="splitSelectedPaths.length > splitDisplayPaths.length" class="more-line">
还有 {{ splitSelectedPaths.length - splitDisplayPaths.length }} 个文件未展开显示
</span>
</template>
<span v-else>暂未选择待拆分文件</span>
</div>
</div>
<FileUploadZone
hint="选择需要拆分的 Excel 文件或文件夹,按规则拆成多个 Excel 文件。"
:names="splitSelectedPaths"
:max-display="8"
files-label="选择 Excel 文件"
empty-text="暂未选择待拆分文件"
files-class="clean-placeholder split-selected-files"
@select-files="selectSplitFiles"
@select-folder="selectSplitFolder"
/>
<div class="section-title">保留列设置</div>
<div class="option-group column-option-group">
@@ -139,21 +132,40 @@
import { computed, onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
import FileUploadZone from '@/shared/components/FileUploadZone.vue'
import TaskCenterPanel from '@/shared/components/tasks/TaskCenterPanel.vue'
import type { TaskItemView, TaskStatCard } from '@/shared/components/tasks/types'
import { expandBrandFolderRecursive } from '@/shared/api/brand'
import { deleteSplitHistory, getExcelInfo, getSplitHistory, getSplitResultDownloadUrl, runSplit, type SplitResultItem } from '@/shared/api/java-modules'
import { getPywebviewApi, type UploadedJavaFile } from '@/shared/bridges/pywebview'
import { saveUrlWithProgress } from '@/shared/utils/download-progress'
import { EXCEL_EXTENSIONS, checkSelectedFiles, collectDistinctErrors, guardBlocked } from '@/shared/dispatch-guard'
import { collectDistinctErrors, guardBlocked } from '@/shared/dispatch-guard'
import { passGuard } from '@/shared/dispatch-guard-ui'
import { useExcelFileUpload } from '@/shared/composables/useExcelFileUpload'
import { formatDateTime } from '@/shared/utils/datetime'
import { uploadPathsToJava } from '@/shared/utils/upload-to-java'
import { runBatchDelete } from '@/shared/utils/batch-delete'
const splitSelectedPaths = ref<string[]>([])
const {
files: splitUploadedFiles,
selectedPaths: splitSelectedPaths,
selectFiles: selectSplitFiles,
selectFolder: selectSplitFolder,
} = useExcelFileUpload({
// 展示原始本机路径;文件夹展开后只展示相对路径(与原实现一致)
filePathsMode: 'raw',
folderPathsMode: 'relative',
filesSuccessMessage: (_files, paths) => `已选择 ${paths.length} 个待拆分文件`,
folderSuccessMessage: (_files, items) => `已选择文件夹内 ${items.length} 个 xlsx 文件`,
folderEmptyWarning: (error) => error || '该文件夹下没有 xlsx 文件',
onFolderPicked: (folder) => {
splitArchiveName.value = folder.split(/[/\\]/).filter(Boolean).pop() || ''
},
onUploaded: async (info) => {
if (info.action === 'files') splitArchiveName.value = ''
if (info.files.length > 0) {
await loadSplitInfo(info.files[0].fileKey)
}
},
})
const splitArchiveName = ref('')
const splitUploadedFiles = ref<UploadedJavaFile[]>([])
const splitAvailableColumns = ref<string[]>([])
const splitSelectedColumns = ref<string[]>([])
const splitTotalRows = ref(0)
@@ -162,7 +174,6 @@ const splitRowsPerFile = ref<number | null>(2000)
const splitParts = ref<number | null>(5)
const splitRunning = ref(false)
const splitResultItems = ref<SplitResultItem[]>([])
const splitDisplayPaths = computed(() => splitSelectedPaths.value.slice(0, 8))
// ---- 右侧任务面板统一视图(TaskCenterPanel)----
const splitCards = computed<TaskStatCard[]>(() => [
@@ -232,67 +243,6 @@ async function loadSplitInfo(fileKey: string) {
splitTotalRows.value = result.totalRows || 0
}
async function handleSelectedPaths(paths: string[], successMessage: string) {
splitSelectedPaths.value = paths
splitArchiveName.value = ''
splitUploadedFiles.value = await uploadPathsToJava(getPywebviewApi(), paths)
if (splitUploadedFiles.value.length > 0) {
await loadSplitInfo(splitUploadedFiles.value[0].fileKey)
}
ElMessage.success(successMessage)
}
async function selectSplitFiles() {
const api = getPywebviewApi()
if (!api?.select_brand_xlsx_files) {
ElMessage.warning('当前环境不支持文件选择,请在本机客户端中打开')
return
}
try {
const paths = await api.select_brand_xlsx_files()
if (!paths?.length) return
if (!(await passGuard(checkSelectedFiles(paths, { allowedExtensions: EXCEL_EXTENSIONS })))) return
await handleSelectedPaths(paths, `已选择 ${paths.length} 个待拆分文件`)
} catch (error) {
splitSelectedPaths.value = []
splitUploadedFiles.value = []
ElMessage.error(error instanceof Error ? error.message : '选择失败')
}
}
async function selectSplitFolder() {
const api = getPywebviewApi()
if (!api?.select_brand_folder) {
ElMessage.warning('当前环境不支持文件夹选择,请在本机客户端中打开')
return
}
try {
const folder = await api.select_brand_folder()
if (!folder) return
splitArchiveName.value = folder.split(/[/\\]/).filter(Boolean).pop() || ''
const result = await expandBrandFolderRecursive(folder)
if (result.success && result.items?.length) {
if (!(await passGuard(checkSelectedFiles(result.items, { allowedExtensions: EXCEL_EXTENSIONS })))) return
splitSelectedPaths.value = result.items.map((item) => item.relativePath)
splitUploadedFiles.value = await uploadPathsToJava(getPywebviewApi(), result.items)
if (splitUploadedFiles.value.length > 0) {
await loadSplitInfo(splitUploadedFiles.value[0].fileKey)
}
ElMessage.success(`已选择文件夹内 ${result.items.length} 个 xlsx 文件`)
return
}
ElMessage.warning(result.error || '该文件夹下没有 xlsx 文件')
} catch (error) {
splitSelectedPaths.value = []
splitUploadedFiles.value = []
ElMessage.error(error instanceof Error ? error.message : '选择失败')
}
}
async function submitSplitRun() {
if (!splitUploadedFiles.value.length) {
ElMessage.warning('请先选择待拆分 Excel 文件或文件夹')
@@ -448,33 +398,61 @@ async function batchDeleteHistory(views: TaskItemView[]) {
margin-bottom: 10px;
}
.upload-zone {
border: 1px dashed #3e4a62;
border-radius: 10px;
/* upload-zone 已抽到 FileUploadZone 组件;这里保留本 Tab 的差异样式 */
:deep(.upload-zone) {
padding: 24px;
text-align: center;
background: #242424;
margin-bottom: 20px;
transition: all 0.2s ease;
}
.upload-zone:hover {
:deep(.upload-zone:hover) {
border-color: #3498db;
background: #242424;
}
.hint {
color: #5e6878;
:deep(.upload-zone .hint) {
font-size: 13px;
margin-bottom: 12px;
line-height: 1.5;
}
.btns {
display: flex;
gap: 10px;
:deep(.upload-zone .btns) {
justify-content: center;
flex-wrap: wrap;
}
:deep(.upload-zone .opt-btn) {
padding: 8px 16px;
font-size: 13px;
border-radius: 6px;
}
:deep(.upload-zone .opt-btn:hover) {
color: #3498db;
background: #333;
border-color: #3498db;
}
:deep(.upload-zone .opt-btn:disabled) {
cursor: not-allowed;
opacity: 0.55;
}
:deep(.selected-files) {
font-size: 12px;
color: #5e6878;
max-height: 112px;
overflow-y: auto;
text-align: left;
}
:deep(.more-line) {
color: #a0acbe;
}
:deep(.split-selected-files) {
max-height: 120px;
min-height: 72px;
padding-right: 4px;
}
.opt-btn,
@@ -506,31 +484,6 @@ async function batchDeleteHistory(views: TaskItemView[]) {
border-color: #3498db;
}
.selected-files {
margin-top: 14px;
font-size: 12px;
color: #5e6878;
max-height: 112px;
overflow-y: auto;
text-align: left;
}
.selected-files span {
display: block;
margin: 4px 0;
word-break: break-all;
}
.more-line {
color: #a0acbe;
}
.split-selected-files {
max-height: 120px;
min-height: 72px;
padding-right: 4px;
}
.option-group {
margin-bottom: 20px;
}
@@ -167,6 +167,7 @@ import {
type VariantTaskListItem,
} from '@/shared/bridges/pywebview'
import { saveUrlWithProgress } from '@/shared/utils/download-progress'
import { taskStatusClass, taskStatusText, type TaskStatusOptions } from '@/shared/utils/task-status-text'
/** 本地任务记录:桥接返回的列表项 + 前端维护字段 */
type VariantEntry = VariantTaskListItem & {
@@ -222,12 +223,32 @@ function taskMeta(item: VariantEntry) {
return item.meta || {}
}
// 数字状态(0-3) + 字符串状态的混合映射,与统一默认表不一致,整体走 overrides
const VARIANT_STATUS_OVERRIDES: TaskStatusOptions = {
text: {
'': '排队中',
'0': '排队中',
'1': '执行中',
'2': '已完成',
'3': '失败',
PENDING: '排队中',
PROCESSING: '执行中',
DONE: '已完成',
ERROR: '失败',
STOPPED: '已取消',
},
classMap: {
'1': 'running',
'2': 'success',
'3': 'failed',
DONE: 'success',
ERROR: 'failed',
CANCELLED: 'pending',
},
}
function statusClass(status?: number | string) {
const numeric = Number(status)
if (numeric === 1 || /running|processing/i.test(String(status))) return 'running'
if (numeric === 2 || /success|completed|done/i.test(String(status))) return 'success'
if (numeric === 3 || /failed|error/i.test(String(status))) return 'failed'
return 'pending'
return taskStatusClass(String(status ?? ''), VARIANT_STATUS_OVERRIDES)
}
let autoTimer: number | null = null
@@ -247,14 +268,11 @@ function baseName(path: string) {
}
function statusText(status?: number | string) {
const numeric = Number(status)
if (numeric === 0 || String(status).toLowerCase() === 'pending' || String(status).toLowerCase() === 'queued') return '排队中'
if (numeric === 1 || String(status).toLowerCase() === 'running' || String(status).toLowerCase() === 'processing') return '执行中'
if (numeric === 2 || ['success', 'completed', 'done'].includes(String(status).toLowerCase())) return '已完成'
if (numeric === 3 || ['failed', 'error'].includes(String(status).toLowerCase())) return '失败'
if (['cancelled', 'stopped'].includes(String(status).toLowerCase())) return '已取消'
if (status === 0 || status === 1 || status === 2 || status === 3) return statusText(String(status))
return String(status ?? '未知')
if (status === undefined || status === null) return '未知'
return taskStatusText(String(status), {
...VARIANT_STATUS_OVERRIDES,
textFallback: String(status),
})
}
function isBusy(status?: number | string) {
@@ -271,6 +271,7 @@ import { passGuard } from "@/shared/dispatch-guard-ui";
import ZiniaoVersionSetting from "@/shared/components/ZiniaoVersionSetting.vue";
import { useZiniaoVersion } from "@/shared/utils/ziniao-version";
import { formatDateTime } from '@/shared/utils/datetime'
import { RUNNING_UNTIL_DONE_STATUS_OPTIONS, taskStatusClass, taskStatusText } from '@/shared/utils/task-status-text'
import { useHistoryPolling } from '@/shared/composables/useHistoryPolling'
import { runBatchDelete } from '@/shared/utils/batch-delete'
import { isRecordMissingError, parseTaskStartTimes, removeTaskStartTime, upsertTaskStartTime } from '@/shared/utils/task-queue-state.ts'
@@ -658,17 +659,11 @@ function isTaskTerminal(status?: string) {
}
function statusText(status?: string) {
if (status === "SUCCESS" || status === "COMPLETED") return "已完成";
if (status === "FAILED") return "失败";
return "执行中";
return taskStatusText(status, RUNNING_UNTIL_DONE_STATUS_OPTIONS);
}
function statusClass(status?: string) {
return status === "SUCCESS" || status === "COMPLETED"
? "success"
: status === "FAILED"
? "failed"
: "running";
return taskStatusClass(status, RUNNING_UNTIL_DONE_STATUS_OPTIONS);
}
function canDownload(item: WithdrawTaskGroupItem) {
@@ -1,70 +0,0 @@
/**
* API 高频响应 schema 注册表(Task 27)。
*
* 为 task/result 核心响应与各业务模块注册字段 schema,供
* createApiFieldCompatChecker 在契约测试与联调前做字段漂移检查。
* 模块级 schema 目前复用 task+result 组合,后续某模块有独特字段时
* 在其定义内覆盖/追加即可,无需改动检查器。
*/
import { createApiFieldCompatChecker, type ApiFieldSpec } from './api-field-compat.ts'
export interface ApiFieldSchemaDef {
/** schema 版本号,变更时递增 */
version: number
/** 字段名 → 规格 */
schema: Record<string, ApiFieldSpec>
}
/** task 核心响应字段 */
export const taskCoreSchema: Record<string, ApiFieldSpec> = {
taskId: { type: 'number', required: true },
status: { type: 'string', required: true },
progress: { type: 'number' },
message: { type: 'string' },
resultId: { type: 'number' },
}
/** 结果文件阶段字段(与 ResultFilePhase 对应,全部可选) */
export const resultFileSchema: Record<string, ApiFieldSpec> = {
fileStatus: { type: 'string' },
fileReady: { type: 'boolean' },
fileProgress: { type: 'number' },
fileProgressLabel: { type: 'string' },
fileProgressStage: { type: 'string' },
downloadUrl: { type: 'string' },
freshDownloadUrl: { type: 'string' },
}
/** task + result 组合 schema */
export const taskWithResultSchema: Record<string, ApiFieldSpec> = {
...taskCoreSchema,
...resultFileSchema,
}
const BUSINESS_MODULES = [
'dedupe', 'split', 'convert', 'publish', 'similar-asin', 'appearance-patent',
'delete-brand', 'price-track', 'shop-match', 'query-asin', 'withdraw',
'collect-data', 'image-video',
] as const
export const apiFieldSchemas: Record<string, ApiFieldSchemaDef> = {
task: { version: 1, schema: taskCoreSchema },
result: { version: 1, schema: resultFileSchema },
'task-result': { version: 1, schema: taskWithResultSchema },
}
for (const module of BUSINESS_MODULES) {
apiFieldSchemas[module] = { version: 1, schema: taskWithResultSchema }
}
export function getApiFieldSchema(name: string): ApiFieldSchemaDef | null {
return apiFieldSchemas[name] ?? null
}
export function createModuleFieldChecker(module: string) {
const def = getApiFieldSchema(module)
if (!def) {
throw new Error(`未注册的模块: ${module}`)
}
return createApiFieldCompatChecker({ schema: def.schema })
}
@@ -7,6 +7,8 @@ export interface UploadedJavaFile {
localPath: string;
size: number;
relativePath?: string;
/** OSS 上传模式下返回的跨节点访问地址(uploadOss=true 时桌面桥可能附带) */
url?: string;
}
export type ProxyMode = 1 | 2;
@@ -1,196 +0,0 @@
/**
* 构建拆包规划器(Task 91)。
*
* 为多页应用(MPA)生成 manualChunks 配置,按页面拆分公共业务 chunk:
* - vendorRules:全局 vendor 规则(Element Plus、Vue 运行时等),所有入口共享;
* - perEntryRules:按入口隔离的页面私有 chunk(匹配需同时给出 entryName,
* 未匹配入口的模块不会被误拆到其他页面 chunk);
* - 同名 chunk 的规则自动合并去重;未匹配模块返回 undefined,交由 Vite
* 默认拆包逻辑处理,不强制拆包。
*
* 有界配置:maxRules 限制 vendor 规则数量(超限拒绝计数,规则不生效);
* maxEntries 限制登记的入口数量(超出部分连同其 per-entry 规则一并跳过)。
* 校验失败(空 chunk 名、空 patterns、非法上限)fail-fast 抛错且零状态变更;
* 规则读取抛错(依赖故障)时调用失败,规划状态不被污染,恢复后可继续使用。
*/
export interface ChunkRule {
/** chunk 名,不能为空 */
chunk: string
/** 匹配模块 id 的字符串 pattern 列表,不能为空 */
patterns: string[]
}
export interface EntryChunkRule extends ChunkRule {
/** 关联的入口名,不能为空 */
entry: string
}
export interface ChunkPlannerOptions {
/** 页面入口列表;超过 maxEntries 的部分被跳过 */
entries: string[]
/** 全局 vendor 拆包规则;数量超过 maxRules 的部分被拒绝 */
vendorRules?: ChunkRule[]
/** 按入口隔离的页面 chunk 规则 */
perEntryRules?: EntryChunkRule[]
/** vendor 规则数量上限,必须为正数,默认 100 */
maxRules?: number
/** 登记的入口数量上限,必须为正数,默认 100 */
maxEntries?: number
}
export interface ChunkPlan {
entry: string
chunks: string[]
}
export interface ChunkPlannerStats {
entryCount: number
chunkCount: number
sharedChunkCount: number
unmatchedCount: number
rejectedCount: number
}
export interface ChunkPlanner {
/** 分配模块到 chunk;未匹配返回 undefined(交给 Vite 默认拆包) */
assign: (moduleId: string, entryName?: string) => string | undefined
/** 生成 manualChunks 配置对象(chunk 名 → patterns) */
manualChunksConfig: () => Record<string, string[]>
/** 每个入口实际包含的 chunk 清单(公共 vendor + 页面私有) */
planByEntry: () => ChunkPlan[]
stats: () => ChunkPlannerStats
}
export function createChunkPlanner(options: ChunkPlannerOptions): ChunkPlanner {
if (!Array.isArray(options.entries)) {
throw new Error('entries 必须是数组')
}
const maxRules = options.maxRules ?? 100
const maxEntries = options.maxEntries ?? 100
if (!(maxRules > 0)) {
throw new Error('maxRules 必须为正数: ' + maxRules)
}
if (!(maxEntries > 0)) {
throw new Error('maxEntries 必须为正数: ' + maxEntries)
}
const entries = options.entries.slice(0, maxEntries)
const entrySet = new Set(entries)
const vendorRules: Array<{ chunk: string; patterns: string[] }> = []
const perEntryRulesByEntry = new Map<string, Array<{ chunk: string; patterns: string[] }>>()
const chunkNames: string[] = []
let rejectedCount = 0
let unmatchedCount = 0
function validateRule(rule: ChunkRule) {
if (typeof rule.chunk !== 'string' || rule.chunk.length === 0) {
throw new Error('chunk 名不能为空')
}
if (!Array.isArray(rule.patterns) || rule.patterns.length === 0) {
throw new Error('patterns 必须是非空数组')
}
}
function mergePatterns(target: string[] | undefined, patterns: string[]): string[] {
const result = target ? [...target] : []
for (const pattern of patterns) {
if (!result.includes(pattern)) result.push(pattern)
}
return result
}
function addVendorRule(rule: ChunkRule) {
validateRule(rule)
if (vendorRules.length >= maxRules) {
rejectedCount += 1
return
}
const existing = vendorRules.find((item) => item.chunk === rule.chunk)
if (existing) {
existing.patterns = mergePatterns(existing.patterns, rule.patterns)
} else {
vendorRules.push({ chunk: rule.chunk, patterns: [...rule.patterns] })
chunkNames.push(rule.chunk)
}
}
function addPerEntryRule(rule: EntryChunkRule) {
if (typeof rule.entry !== 'string' || rule.entry.length === 0) {
throw new Error('entry 名不能为空')
}
validateRule(rule)
if (!entrySet.has(rule.entry)) return
const rules = perEntryRulesByEntry.get(rule.entry) ?? []
const existing = rules.find((item) => item.chunk === rule.chunk)
if (existing) {
existing.patterns = mergePatterns(existing.patterns, rule.patterns)
} else {
rules.push({ chunk: rule.chunk, patterns: [...rule.patterns] })
perEntryRulesByEntry.set(rule.entry, rules)
chunkNames.push(rule.chunk)
}
}
for (const rule of options.vendorRules ?? []) {
addVendorRule(rule)
}
for (const rule of options.perEntryRules ?? []) {
addPerEntryRule(rule)
}
function matches(patterns: string[], moduleId: string): boolean {
for (const pattern of patterns) {
if (moduleId.includes(pattern)) return true
}
return false
}
function assign(moduleId: string, entryName?: string): string | undefined {
for (const rule of vendorRules) {
if (matches(rule.patterns, moduleId)) return rule.chunk
}
if (entryName !== undefined) {
const rules = perEntryRulesByEntry.get(entryName)
if (rules) {
for (const rule of rules) {
if (matches(rule.patterns, moduleId)) return rule.chunk
}
}
}
unmatchedCount += 1
return undefined
}
function manualChunksConfig(): Record<string, string[]> {
const config: Record<string, string[]> = {}
for (const rule of vendorRules) {
config[rule.chunk] = mergePatterns(config[rule.chunk], rule.patterns).sort()
}
for (const rules of perEntryRulesByEntry.values()) {
for (const rule of rules) {
config[rule.chunk] = mergePatterns(config[rule.chunk], rule.patterns).sort()
}
}
return config
}
function planByEntry(): ChunkPlan[] {
const vendorNames = vendorRules.map((rule) => rule.chunk)
return entries.map((entry) => ({
entry,
chunks: [...vendorNames, ...(perEntryRulesByEntry.get(entry)?.map((rule) => rule.chunk) ?? [])],
}))
}
function stats(): ChunkPlannerStats {
return {
entryCount: entries.length,
chunkCount: chunkNames.length,
sharedChunkCount: vendorRules.length,
unmatchedCount,
rejectedCount,
}
}
return { assign, manualChunksConfig, planByEntry, stats }
}
@@ -1,189 +0,0 @@
/**
* 首屏传输大小报告(Task 92)。
*
* 在 manualChunks 拆包后比较各页面首屏传输大小:每个入口的首屏字节 =
* 入口自身 JS + 其依赖的全部 chunk 字节(公共 chunk 在多个入口之间共享,
* 计入各自首屏但只在报告总览里计一次)。
*
* 有界统计:maxEntries 限制统计的入口数量;maxChunksPerEntry 限制每个入口
* 计入的 chunk 数量(超出部分忽略,防止页面私有 chunk 过多导致报告失真)。
* 缺失入口的拆包计划或尺寸、缺失 chunk 尺寸、尺寸为负数均 fail-fast 抛错,
* 不产生部分结果;同一输入重复计算幂等,输入对象永不修改。
*/
export interface ChunkPlanEntry {
entry: string
chunks: string[]
}
export interface ChunkTransferReportOptions {
/** 页面入口列表(顺序即报告顺序);超过 maxEntries 的部分被跳过 */
entries: string[]
/** 每个入口的 chunk 清单(来自拆包规划) */
plans: ChunkPlanEntry[]
/** chunk 名 → 字节数(构建产物尺寸) */
chunkSizes: Record<string, number>
/** 入口 → 入口自身 JS 字节数 */
entrySizes: Record<string, number>
/** 统计的入口数量上限,必须为正数,默认 100 */
maxEntries?: number
/** 每个入口计入的 chunk 数量上限,必须为正数,默认 100 */
maxChunksPerEntry?: number
}
export interface ChunkTransferLine {
entry: string
entryBytes: number
chunkBytes: number
transferBytes: number
chunkCount: number
}
export interface ChunkTransferReport {
/** 按入口顺序排列的首屏传输明细 */
entries: ChunkTransferLine[]
/** 被多个入口共享的 chunk 总字节(每个共享 chunk 只计一次) */
sharedBytes: number
/** 全部入口 transferBytes 之和 */
totalBytes: number
/** 首屏最大的入口(空输入为 undefined) */
largest: ChunkTransferLine | undefined
/** 首屏最小的入口(空输入为 undefined) */
smallest: ChunkTransferLine | undefined
/** 单个入口的 chunk 字节明细(chunk 名 → 字节数,不含被截断的 chunk) */
chunkBytesOf: (line: ChunkTransferLine) => Record<string, number>
}
function isRecord(value: unknown): value is Record<string, unknown> {
return (
typeof value === 'object' &&
value != null &&
!Array.isArray(value) &&
Object.getPrototypeOf(value) === Object.prototype
)
}
export function createChunkTransferReport(options: ChunkTransferReportOptions): ChunkTransferReport {
if (!Array.isArray(options.entries)) {
throw new Error('entries 必须是数组')
}
if (!Array.isArray(options.plans)) {
throw new Error('plans 必须是数组')
}
if (!isRecord(options.chunkSizes)) {
throw new Error('chunkSizes 必须是对象')
}
if (!isRecord(options.entrySizes)) {
throw new Error('entrySizes 必须是对象')
}
const maxEntries = options.maxEntries ?? 100
const maxChunksPerEntry = options.maxChunksPerEntry ?? 100
if (!(maxEntries > 0)) {
throw new Error('maxEntries 必须为正数: ' + maxEntries)
}
if (!(maxChunksPerEntry > 0)) {
throw new Error('maxChunksPerEntry 必须为正数: ' + maxChunksPerEntry)
}
const entries = options.entries.slice(0, maxEntries)
const planByEntry = new Map<string, string[]>()
for (const plan of options.plans) {
planByEntry.set(plan.entry, plan.chunks)
}
for (const entry of entries) {
if (!planByEntry.has(entry)) {
throw new Error('缺少 entry 的拆包计划: ' + entry)
}
if (!(entry in options.entrySizes)) {
throw new Error('缺少 entry 尺寸: ' + entry)
}
}
const chunkSizes: Record<string, number> = {}
for (const key of Object.keys(options.chunkSizes)) {
const size = options.chunkSizes[key]
if (!(size >= 0)) {
throw new Error('尺寸不能为负数: ' + key + '=' + size)
}
chunkSizes[key] = size
}
const entrySizes: Record<string, number> = {}
for (const key of Object.keys(options.entrySizes)) {
const size = options.entrySizes[key]
if (!(size >= 0)) {
throw new Error('尺寸不能为负数: ' + key + '=' + size)
}
entrySizes[key] = size
}
const chunkPerEntry = new Map<string, number[]>()
for (const entry of entries) {
const chunks = planByEntry.get(entry) ?? []
const sizes: number[] = []
for (const chunk of chunks.slice(0, maxChunksPerEntry)) {
if (!(chunk in chunkSizes)) {
throw new Error('缺少 chunk 尺寸: ' + chunk)
}
sizes.push(chunkSizes[chunk])
}
chunkPerEntry.set(entry, sizes)
}
// 被多个入口共享的 chunk 总字节(每个共享 chunk 只计一次)
const chunkCountByEntry = new Map<string, Set<string>>()
let sharedBytes = 0
{
const counts = new Map<string, number>()
for (const entry of entries) {
for (const chunk of planByEntry.get(entry) ?? []) {
counts.set(chunk, (counts.get(chunk) ?? 0) + 1)
}
}
for (const [chunk, count] of counts) {
if (count > 1 && chunk in chunkSizes) {
sharedBytes += chunkSizes[chunk]
}
}
}
const lines: ChunkTransferLine[] = []
for (const entry of entries) {
const sizes = chunkPerEntry.get(entry) ?? []
const entryBytes = entrySizes[entry]
const chunkBytes = sizes.reduce((sum, size) => sum + size, 0)
lines.push({
entry,
entryBytes,
chunkBytes,
transferBytes: entryBytes + chunkBytes,
chunkCount: sizes.length,
})
chunkCountByEntry.set(entry, new Set(planByEntry.get(entry) ?? []))
}
let totalBytes = 0
for (const line of lines) totalBytes += line.transferBytes
let largest: ChunkTransferLine | undefined = undefined
let smallest: ChunkTransferLine | undefined = undefined
for (const line of lines) {
if (!largest || line.transferBytes > largest.transferBytes) largest = line
if (!smallest || line.transferBytes < smallest.transferBytes) smallest = line
}
function chunkBytesOf(line: ChunkTransferLine): Record<string, number> {
const chunks = planByEntry.get(line.entry) ?? []
const detail: Record<string, number> = {}
for (const chunk of chunks.slice(0, maxChunksPerEntry)) {
detail[chunk] = chunkSizes[chunk]
}
return detail
}
return {
entries: lines,
sharedBytes,
totalBytes,
largest,
smallest,
chunkBytesOf,
}
}
@@ -1,18 +0,0 @@
/**
* collectdata 下载判定(Task 146)。
*
* collectdata 后端 history VO 不返回 file 阶段字段;前端下载判定自洽:
* success=true 且 downloadUrl 非空才可下载(任务成功且有结果文件)。
*/
export interface CollectDataItem {
success?: boolean | null
downloadUrl?: string | null
taskStatus?: string | null
}
/** collectdata 可下载判定:success + downloadUrl(任务成功且有结果文件,空白 URL 无效)。 */
export function canDownloadCollectDataItem(item: CollectDataItem | null | undefined): boolean {
if (!item) return false
const url = typeof item.downloadUrl === 'string' ? item.downloadUrl.trim() : ''
return Boolean(item.success && url)
}
@@ -0,0 +1,142 @@
<template>
<div class="upload-zone">
<div class="hint">{{ hint }}</div>
<div class="btns">
<button type="button" class="opt-btn" :disabled="disabled" @click="emit('select-files')">
{{ uploading && uploadingLabel ? uploadingLabel : filesLabel }}
</button>
<button v-if="showFolderButton" type="button" class="opt-btn" :disabled="disabled" @click="emit('select-folder')">
{{ folderLabel }}
</button>
</div>
<div class="selected-files" :class="filesClass">
<template v-if="names.length">
<span v-for="name in visibleNames" :key="name" :title="nameTitle ? name : undefined">{{ name }}</span>
<span v-if="names.length > visibleNames.length" class="more-line">
还有 {{ names.length - visibleNames.length }} 个文件未展开显示
</span>
</template>
<span v-else :class="{ 'text-muted': mutedEmpty }">{{ emptyText }}</span>
</div>
<div v-if="footerTip" class="bridge-tip">{{ footerTip }}</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
/**
* 「上传文件」区块:选择 Excel / 文件夹按钮 + 已选文件列表。
*
* 抽自各品牌 Tab 逐字重复的 upload-zone 模板与样式;差异点全部 props 化。
* Tab 保留自己的业务状态与 selectFiles / selectFolder 实现(通常来自
* useExcelFileUpload),组件只负责展示与点击事件。
*/
const props = withDefaults(
defineProps<{
/** 区块顶部提示文案 */
hint: string
/** 已选文件展示列表(完整列表,超出 maxDisplay 时折叠) */
names: string[]
/** 未选择时的占位文案 */
emptyText?: string
/** 「选择 Excel」按钮文案 */
filesLabel?: string
/** 上传中时「选择 Excel」按钮的文案(配合 uploading) */
uploadingLabel?: string
/** 「选择文件夹」按钮文案 */
folderLabel?: string
/** 是否显示「选择文件夹」按钮 */
showFolderButton?: boolean
/** 两个按钮是否禁用 */
disabled?: boolean
/** 上传中状态(配合 uploadingLabel) */
uploading?: boolean
/** 超过该数量折叠展示;不传则全量展示 */
maxDisplay?: number
/** selected-files 容器的附加 class(如 clean-placeholder) */
filesClass?: string
/** 空态文案是否加 text-muted */
mutedEmpty?: boolean
/** 文件名 span 是否带 title 提示完整路径 */
nameTitle?: boolean
/** 区块底部的附加提示(如浏览器环境的桥接提示),空串不显示 */
footerTip?: string
}>(),
{
emptyText: '暂未选择文件',
filesLabel: '选择 Excel',
folderLabel: '选择文件夹',
showFolderButton: true,
disabled: false,
uploading: false,
mutedEmpty: false,
nameTitle: false,
footerTip: '',
},
)
const emit = defineEmits<{
(event: 'select-files'): void
(event: 'select-folder'): void
}>()
const visibleNames = computed(() =>
props.maxDisplay && props.maxDisplay > 0 ? props.names.slice(0, props.maxDisplay) : props.names,
)
</script>
<style scoped>
/* 与多数品牌 Tab 原有的 upload-zone 写法保持一致;个别 Tab 的差异样式由
Tab 自身用 :deep(.upload-zone) 等覆写 */
.upload-zone {
border: 1px dashed #3e4a62;
border-radius: 10px;
padding: 18px;
background: #242424;
margin-bottom: 18px;
}
.hint {
color: #5e6878;
font-size: 12px;
line-height: 1.5;
}
.btns {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
.opt-btn {
border: none;
cursor: pointer;
border-radius: 7px;
padding: 8px 14px;
color: #c8d2e2;
background: #242424;
border: 1px solid #3e4a62;
}
.selected-files {
margin-top: 14px;
color: #a0acbe;
font-size: 12px;
word-break: break-all;
}
.selected-files span {
display: block;
margin: 4px 0;
}
.selected-files .more-line {
color: #5e6878;
}
.selected-files .text-muted {
color: #5e6878;
font-style: italic;
}
</style>
@@ -0,0 +1,210 @@
import { ref, type Ref } from 'vue'
import { ElMessage } from 'element-plus'
import { getPywebviewApi, type UploadedJavaFile } from '../bridges/pywebview.ts'
import { expandBrandFolderRecursive, type BrandExpandFolderItem } from '../api/types/modules/brand.ts'
import { EXCEL_EXTENSIONS, checkSelectedFiles } from '../dispatch-guard.ts'
import { passGuard } from '../dispatch-guard-ui.ts'
import { uploadPathsToJava, type UploadPathsToJavaOptions } from '../utils/upload-to-java.ts'
/**
* 「选文件 / 选文件夹 → 校验 → 上传 → 重置状态」组合式函数。
*
* 抽自各品牌 Tab 逐字重复的 selectFiles / selectFolder:能力检查 → 桥选路径 →
* passGuard(checkSelectedFiles(...)) → uploadPathsToJava(...) → 回填展示列表 →
* 成功 / 失败提示。各 Tab 的差异点(提示文案、展示路径来源、上传参数、成功后
* 的本地状态重置)全部参数化,保持每个 Tab 的既有行为与文案不变。
*
* 使用方式:
* const upload = useExcelFileUpload({
* onUploaded: () => { parseResult.value = null },
* })
* upload.selectFiles() / upload.selectFolder()
* upload.files / upload.selectedPaths / upload.uploading
*/
/** 选文件动作:成功回填的展示路径来源 */
export type ExcelFilePathsMode = 'uploaded' | 'raw'
/** 选文件夹动作:成功回填的展示路径来源 */
export type ExcelFolderPathsMode = 'items' | 'relative' | 'uploaded'
export interface ExcelFileUploadSuccessInfo {
action: 'files' | 'folder'
/** 上传结果列表 */
files: UploadedJavaFile[]
/** 展示用路径列表(与 selectedPaths ref 一致) */
displayPaths: string[]
/** 选文件动作的原始本机路径 */
paths?: string[]
/** 选文件夹动作的文件夹路径 */
folder?: string
/** 选文件夹动作展开出的条目 */
items?: BrandExpandFolderItem[]
}
export interface UseExcelFileUploadOptions {
/** 允许的扩展名;默认 EXCEL_EXTENSIONS */
allowedExtensions?: readonly string[]
/** 透传给 uploadPathsToJava 的参数(uploadOss / returnEmptyWhenUnavailable) */
uploadOptions?: UploadPathsToJavaOptions
/**
* 自定义「选择文件」实现(默认走桥的 select_brand_xlsx_files)。
* 返回 null / undefined / 空数组一律视为取消。
*/
pickFiles?: () => Promise<string[] | null | undefined>
/** 自定义「展开文件夹」实现(默认 expandBrandFolderRecursive) */
expandFolder?: (folder: string) => Promise<{ success: boolean; items?: BrandExpandFolderItem[]; error?: string }>
/** 选文件能力检查是否同时要求 upload_file_to_java;默认 false */
requireUploadCapability?: boolean
/** 选文件夹能力检查是否同时要求 upload_file_to_java;默认 false */
folderRequireUploadCapability?: boolean
/** 选文件能力缺失时的 warning 文案 */
pickFilesUnavailableWarning?: string
/** 选文件夹能力缺失时的 warning 文案 */
folderUnavailableWarning?: string
/** 文件夹下没有可用文件时的 warning 文案;默认 (error) => error || '该文件夹下没有可用的 xlsx 文件' */
folderEmptyWarning?: (error?: string) => string
/** 选文件成功提示;返回空串则不提示(默认不提示) */
filesSuccessMessage?: (files: UploadedJavaFile[], paths: string[]) => string
/** 选文件夹成功提示;返回空串则不提示 */
folderSuccessMessage?: (files: UploadedJavaFile[], items: BrandExpandFolderItem[]) => string
/** 失败时 ElMessage.error 的兜底文案;默认 '选择失败' */
errorFallbackMessage?: string | ((action: 'files' | 'folder') => string)
/** 选文件成功后回填展示列表的方式;默认 'uploaded'(取上传结果相对路径/文件名) */
filePathsMode?: ExcelFilePathsMode
/** 选文件夹成功后回填展示列表的方式;默认 'items'(relativePath || absolutePath) */
folderPathsMode?: ExcelFolderPathsMode
/** 上传成功回调(重置 Tab 本地解析状态等);可为 async,成功提示会等它完成 */
onUploaded?: (info: ExcelFileUploadSuccessInfo) => void | Promise<void>
/** 上传失败回调(清理 Tab 本地状态);失败时组件自身已清空 files/selectedPaths(除非 clearOnError=false) */
onFailed?: (action: 'files' | 'folder') => void
/** 选到文件夹后(展开前)回调;用于记录文件夹名等 Tab 本地状态 */
onFolderPicked?: (folder: string) => void
/** 上传失败时是否清空 files/selectedPaths;默认 true(品牌检测 Tab 上传失败保留旧文件) */
clearOnError?: boolean
}
export interface UseExcelFileUploadReturn {
/** 上传成功的结果列表 */
files: Ref<UploadedJavaFile[]>
/** 展示用路径列表(文件动作为原始路径或上传名,文件夹动作为展开条目路径) */
selectedPaths: Ref<string[]>
/** 上传进行中(仅覆盖 uploadPathsToJava 调用窗口) */
uploading: Ref<boolean>
selectFiles: () => Promise<void>
selectFolder: () => Promise<void>
/** 清空已选 / 已上传(不触发 onFailed) */
clear: () => void
}
function defaultErrorMessage(error: unknown, action: 'files' | 'folder', fallback: string | ((a: 'files' | 'folder') => string)) {
if (error instanceof Error && error.message) return error.message
return typeof fallback === 'function' ? fallback(action) : fallback
}
export function useExcelFileUpload(options: UseExcelFileUploadOptions = {}): UseExcelFileUploadReturn {
const allowedExtensions = options.allowedExtensions ?? EXCEL_EXTENSIONS
const requireUploadCapability = options.requireUploadCapability ?? false
const folderRequireUploadCapability = options.folderRequireUploadCapability ?? false
const pickWarning = options.pickFilesUnavailableWarning ?? '当前环境不支持文件选择,请在本机客户端中打开'
const folderWarning = options.folderUnavailableWarning ?? '当前环境不支持文件夹选择,请在本机客户端中打开'
const emptyWarning = options.folderEmptyWarning ?? ((error?: string) => error || '该文件夹下没有可用的 xlsx 文件')
const fallbackMessage = options.errorFallbackMessage ?? '选择失败'
const filePathsMode = options.filePathsMode ?? 'uploaded'
const folderPathsMode = options.folderPathsMode ?? 'items'
const clearOnError = options.clearOnError ?? true
const files = ref<UploadedJavaFile[]>([])
const selectedPaths = ref<string[]>([])
const uploading = ref(false)
function resetLocal() {
files.value = []
selectedPaths.value = []
}
function fail(action: 'files' | 'folder', error: unknown) {
if (clearOnError) resetLocal()
options.onFailed?.(action)
ElMessage.error(defaultErrorMessage(error, action, fallbackMessage))
}
async function selectFiles() {
try {
let paths: string[] | null | undefined
if (options.pickFiles) {
paths = await options.pickFiles()
} else {
const api = getPywebviewApi()
if (!api?.select_brand_xlsx_files || (requireUploadCapability && !api.upload_file_to_java)) {
ElMessage.warning(pickWarning)
return
}
paths = await api.select_brand_xlsx_files()
}
if (!paths?.length) return
if (!(await passGuard(checkSelectedFiles(paths, { allowedExtensions })))) return
uploading.value = true
const uploaded = await uploadPathsToJava(getPywebviewApi(), paths, options.uploadOptions)
files.value = uploaded
selectedPaths.value = filePathsMode === 'raw'
? [...paths]
: uploaded.map((f) => f.relativePath || f.originalFilename || f.fileKey)
await options.onUploaded?.({ action: 'files', files: uploaded, displayPaths: selectedPaths.value, paths: [...paths] })
const message = options.filesSuccessMessage?.(uploaded, paths)
if (message) ElMessage.success(message)
} catch (error) {
fail('files', error)
} finally {
uploading.value = false
}
}
async function selectFolder() {
try {
const api = getPywebviewApi()
if (!api?.select_brand_folder || (folderRequireUploadCapability && !api.upload_file_to_java)) {
ElMessage.warning(folderWarning)
return
}
const folder = await api.select_brand_folder()
if (!folder) return
options.onFolderPicked?.(folder)
const result = options.expandFolder
? await options.expandFolder(folder)
: await expandBrandFolderRecursive(folder)
if (!result.success || !result.items?.length) {
ElMessage.warning(emptyWarning(result.error))
return
}
if (!(await passGuard(checkSelectedFiles(result.items, { allowedExtensions })))) return
uploading.value = true
const uploaded = await uploadPathsToJava(getPywebviewApi(), result.items, options.uploadOptions)
files.value = uploaded
selectedPaths.value = resolveFolderPaths(folderPathsMode, uploaded, result.items)
await options.onUploaded?.({ action: 'folder', files: uploaded, displayPaths: selectedPaths.value, folder, items: result.items })
const message = options.folderSuccessMessage?.(uploaded, result.items)
if (message) ElMessage.success(message)
} catch (error) {
fail('folder', error)
} finally {
uploading.value = false
}
}
function clear() {
resetLocal()
}
return { files, selectedPaths, uploading, selectFiles, selectFolder, clear }
}
function resolveFolderPaths(
mode: ExcelFolderPathsMode,
uploaded: UploadedJavaFile[],
items: BrandExpandFolderItem[],
): string[] {
if (mode === 'relative') return items.map((item) => item.relativePath)
if (mode === 'uploaded') return uploaded.map((f) => f.relativePath || f.originalFilename || f.fileKey)
return items.map((item) => item.relativePath || item.absolutePath)
}
@@ -0,0 +1,713 @@
import { computed, ref, type ComputedRef, type Ref } from 'vue'
import { ElMessage } from 'element-plus'
import { getTaskPollIntervalMs } from '../task-progress-config.ts'
import { createCategorizedTimers } from '../utils/categorized-timers.ts'
import { saveUrlWithProgress } from '../utils/download-progress.ts'
import { runBatchDelete } from '../utils/batch-delete.ts'
import { confirmTaskDeletion } from '../task-delete-confirm.ts'
import type { TaskItemView } from '../components/tasks/types'
/**
* 「实时任务面板」组合式函数(BrandSimilarAsinTab / BrandAppearancePatentTab 的公共骨架)。
*
* 封装两个 Tab 逐字克隆的那部分:轮询 ID 持久化(localStorage,含 uid 后缀)、
* 双队列轮询(任务队列 + 结果文件生成队列)、live 进度合并兜底、history 去重合并、
* pending 文件任务结算、seed(从历史恢复)、下载 / 删除 / 批量删除胶水。
*
* 两 Tab 的真实差异全部参数化(见 UseLiveTaskBoardOptions):
* - 状态归一化 normalizeTaskStatus / isResultPreparing(两 Tab 语义不同)
* - 终态后是否登记 pending 文件任务、哪些任务状态参与文件结算
* - 进度批量请求的预/后处理(SimilarAsin 的 force 节流、Patent 的 light 行版本检查)
* - 轮询回调抛错时是否打断轮询(SimilarAsin 吞掉、Patent 上抛——保持原行为)
* - 下载 URL / 文件名兜底 / 进度 key 前缀、删除判定与本地清理
*
* 其余手写轮询的 Tab(DeleteBrand/PatrolDelete/QueryAsin/Withdraw 等)后续可渐进接入。
*/
/** 两个模块 history/progress item 的公共字段(SimilarAsinHistoryItem / AppearancePatentHistoryItem 结构一致) */
export interface LiveTaskHistoryItem {
resultId?: number
taskId?: number
sourceFilename?: string
resultFilename?: string
downloadUrl?: string
fileJobId?: number
fileStatus?: string
fileError?: string
fileReady?: boolean
fileProgressPercent?: number
fileProgressCurrent?: number
fileProgressTotal?: number
fileProgressMessage?: string
taskStatus?: string
success?: boolean
error?: string
rowCount?: number
createdAt?: string
startedAt?: string
finishedAt?: string
}
/** 批量进度响应的公共形状 */
export interface LiveTaskProgressDetail<TItem extends LiveTaskHistoryItem> {
task?: { id?: number; status?: string }
items?: TItem[]
}
export interface LiveTaskProgressBatch<TItem extends LiveTaskHistoryItem> {
items?: LiveTaskProgressDetail<TItem>[]
missingTaskIds?: number[]
}
export interface TaskBoardDashboardCounts {
pendingTaskCount: number
processedTaskCount: number
successTaskCount: number
failedTaskCount: number
}
export interface UseLiveTaskBoardOptions<T extends LiveTaskHistoryItem> {
/** categorized-timers 命名空间,例如 'similar-asin' */
scope: string
/** 轮询 ID 的 localStorage key(含 uid 后缀),如 () => `similar-asin:tasks:${uid}` */
pollingStorageKey: () => string
/** 历史记录接口 */
fetchHistory: () => Promise<{ items?: T[] }>
/** 批量进度接口 */
fetchProgressBatch: (taskIds: number[], options: { force: boolean }) => Promise<LiveTaskProgressBatch<T>>
/** 统计卡片接口 */
fetchDashboard: () => Promise<TaskBoardDashboardCounts>
/** 状态归一化(两 Tab 实现不同,必传) */
normalizeTaskStatus: (item: T) => string
/** 结果文件是否在生成中(两 Tab 实现不同,必传) */
isResultPreparing: (item: T) => boolean
/**
* 任务到达终态(SUCCESS/FAILED)后是否登记为「结果生成中」待跟踪任务。
* SimilarAsin: status === 'SUCCESS';Patent: item 存在且 isResultPreparing(item)。
*/
addPendingAfterFinalStatus: (task: { id?: number; status?: string }, item: T | undefined) => boolean
/**
* settlePendingFileTasks:对已找到 history 条目、文件未完成的任务,是否继续保留跟踪。
* SimilarAsin: taskStatus === 'SUCCESS';Patent: SUCCESS || FAILED。
*/
keepPendingFileTask: (item: T, taskStatus: string) => boolean
/** 终态后进行文件状态结算检查的任务状态集合。SimilarAsin: ['SUCCESS'];Patent: ['SUCCESS','FAILED'] */
settleOnTaskStatuses: string[]
/**
* 批量进度请求预处理:可裁剪 taskIds / 决定 force;返回 null 表示本轮直接跳过
* (Patent 的 light 行版本检查)。缺省为全量拉取、force=false。
*/
beforeBatch?: (
taskIds: number[],
pendingFileTaskIds: number[],
) => Promise<{ taskIds: number[]; force: boolean } | null> | { taskIds: number[]; force: boolean } | null
/** 批量进度请求后处理(SimilarAsin 的 force 节流登记)。 */
afterBatch?: (taskIds: number[], pendingFileTaskIds: number[], forced: boolean) => void
/**
* 轮询回调抛错时的处理:
* - 'swallow'(SimilarAsin):瞬时失败不打断轮询;
* - 'propagate'(Patent):异常上抛,轮询停止(与原实现一致)。
*/
pollErrorMode?: 'swallow' | 'propagate'
/** pending 文件任务被移除时的回调(SimilarAsin 的 forceThrottle.clear) */
onPendingFileTaskRemoved?: (taskId: number) => void
/** 当前任务区顶部的「解析待启动」占位条目;返回 null 表示没有 */
getPendingParseItem?: () => T | null
/** 下载胶水的模块差异 */
download?: {
/** resultId -> 下载地址(item.downloadUrl 优先) */
buildUrl: (resultId: number, item: T) => string
/** 文件名兜底前缀(item.sourceFilename 缺失时) */
fallbackFilename: string
/** 下载进度 key 前缀,如 'similar-asin' */
progressKeyPrefix: string
}
/** 删除胶水的模块差异 */
deleteTask?: {
/** 是否按「删除整个任务」处理(两 Tab 判定不同) */
shouldDeleteTask: (item: T, normalizedStatus: string) => boolean
deleteTask: (taskId: number) => Promise<unknown>
deleteHistory: (resultId: number) => Promise<unknown>
/** 任务删除成功后的本地清理 */
onTaskDeleted?: (item: T) => void
/** 结果记录删除成功后的本地清理 */
onHistoryDeleted?: (item: T) => void
}
}
export interface UseLiveTaskBoardReturn<T extends LiveTaskHistoryItem> {
/** 轮询中的任务队列(任务执行中) */
pollingTaskIds: Ref<number[]>
/** 结果文件生成中待跟踪队列(任务终态后文件仍未就绪) */
pendingFileTaskIds: Ref<number[]>
/** 最近一次 progress/batch 的实时进度缓存(history 兜底) */
liveProgressItems: Ref<Record<number, T>>
/** 历史记录(含进行中的;展示时经 historyOnlyItems 过滤) */
historyItems: Ref<T[]>
/** 统计卡片数据 */
dashboard: Ref<TaskBoardDashboardCounts>
/** 当前任务区条目(轮询/进行中 + live 兜底 + 解析占位) */
currentItems: ComputedRef<T[]>
/** 纯历史条目(排除 RUNNING/PENDING) */
historyOnlyItems: ComputedRef<T[]>
/** 从 localStorage 恢复轮询 ID */
loadPollingIds: () => void
/** 挂载后恢复种子:从历史回填 pending 文件任务与进行中任务 */
seedPendingFileTasksFromHistory: () => void
seedRunningTasksFromHistory: () => void
/** 有任何待轮询任务时启动轮询(与原 Tab 的 onMounted 守卫一致) */
ensurePollingIfAny: () => void
ensurePolling: () => void
stopPolling: () => void
/** 卸载清理(停止轮询 + 清空 timers) */
dispose: () => void
addPollingTask: (taskId: number) => void
removePollingTask: (taskId: number) => void
addPendingFileTask: (taskId: number) => void
removePendingFileTask: (taskId: number) => void
loadDashboard: () => Promise<void>
loadHistory: (options?: { force?: boolean }) => Promise<void>
refreshTaskProgress: () => Promise<void>
/** 状态判定(透出传入的实现与公共实现,供 Tab 的视图层函数复用) */
normalizeTaskStatus: (item: T) => string
isResultPreparing: (item: T) => boolean
canDownload: (item: T) => boolean
showFileProgress: (item: T) => boolean
downloadResult: (item: T) => Promise<void>
deleteTaskRecord: (item: T) => Promise<void>
/** 历史记录批量删除(复用单条删除逻辑) */
batchDeleteHistory: (views: TaskItemView[]) => Promise<void>
}
/** 模块无关的文件进度字段判定(两 Tab 逐字相同,抽为纯函数) */
export function hasMeaningfulProgressValue(value: unknown) {
const num = Number(value)
return Number.isFinite(num) && num > 0
}
export function activeFileJobStatus(item: LiveTaskHistoryItem) {
return (item.fileStatus || '').toUpperCase()
}
export function hasActiveFileJob(item: LiveTaskHistoryItem) {
const fileStatus = activeFileJobStatus(item)
return item.fileJobId != null || fileStatus === 'PENDING' || fileStatus === 'RUNNING'
}
export function hasFileProgressCount(item: LiveTaskHistoryItem) {
return (item.fileProgressTotal || 0) > 0
}
export function hasExplicitFileProgress(item: LiveTaskHistoryItem) {
return hasFileProgressCount(item)
|| Number(item.fileProgressPercent || 0) > 0
|| Boolean((item.fileProgressMessage || '').trim())
}
export function shouldShowFallbackJobProgress(item: LiveTaskHistoryItem) {
return hasActiveFileJob(item) && !hasExplicitFileProgress(item)
}
/** 两个 Tab 的 canDownload 实现逐字相同 */
export function defaultCanDownload(item: LiveTaskHistoryItem) {
return Boolean(item.resultId && (item.fileReady || item.downloadUrl))
}
const HISTORY_CACHE_TTL_MS = 3000
export function useLiveTaskBoard<T extends LiveTaskHistoryItem>(
options: UseLiveTaskBoardOptions<T>,
): UseLiveTaskBoardReturn<T> {
const timers = createCategorizedTimers(options.scope)
const pollErrorMode = options.pollErrorMode ?? 'swallow'
const pollingTaskIds = ref<number[]>([])
const pendingFileTaskIds = ref<number[]>([])
const liveProgressItems = ref({}) as Ref<Record<number, T>>
const historyItems = ref([]) as Ref<T[]>
const dashboard = ref<TaskBoardDashboardCounts>({
pendingTaskCount: 0,
processedTaskCount: 0,
successTaskCount: 0,
failedTaskCount: 0,
})
const pollTimer = ref<number | null>(null)
const pollingInFlight = ref(false)
let historyInFlight: Promise<void> | null = null
let lastHistoryLoadedAt = 0
let disposed = false
const { normalizeTaskStatus, isResultPreparing } = options
const canDownload = defaultCanDownload
function showFileProgress(item: T) {
const status = normalizeTaskStatus(item)
return (status === 'RUNNING' || isResultPreparing(item)) && (hasExplicitFileProgress(item) || shouldShowFallbackJobProgress(item))
}
// ---- 当前任务 / 纯历史(两 Tab 逐字相同)----
const currentItems = computed<T[]>(() => {
const activeIds = new Set([...pollingTaskIds.value, ...pendingFileTaskIds.value])
const activeItems = historyItems.value
.filter((item) => {
const status = normalizeTaskStatus(item)
return item.taskId != null && (activeIds.has(item.taskId) || status === 'RUNNING' || status === 'PENDING')
})
.map((item) => mergeCurrentTaskItem(item))
// 兜底:history 暂未返回该任务,但实时缓存里仍在跑,保留它在当前任务区
for (const [taskIdText, liveItem] of Object.entries(liveProgressItems.value)) {
const taskId = Number(taskIdText)
if (!Number.isFinite(taskId) || taskId <= 0) continue
if (!activeIds.has(taskId) && normalizeTaskStatus(liveItem) !== 'RUNNING' && normalizeTaskStatus(liveItem) !== 'PENDING') {
continue
}
if (activeItems.some((item) => item.taskId === taskId)) continue
activeItems.push(mergeCurrentTaskItem(liveItem))
}
const pendingParseItem = options.getPendingParseItem?.() ?? null
if (!pendingParseItem) return activeItems
const exists = activeItems.some((item) => item.taskId === pendingParseItem.taskId)
return exists ? activeItems : [pendingParseItem, ...activeItems]
})
const historyOnlyItems = computed<T[]>(() =>
historyItems.value.filter((i) => {
const status = normalizeTaskStatus(i)
return status !== 'RUNNING' && status !== 'PENDING'
}),
)
// ---- 轮询 ID 持久化(两 Tab 逐字相同,仅 key 不同)----
function pollingKey() {
return options.pollingStorageKey()
}
function savePollingIds() {
if (typeof window === 'undefined') return
const ids = Array.from(new Set([...pollingTaskIds.value, ...pendingFileTaskIds.value]))
if (!ids.length) window.localStorage.removeItem(pollingKey())
else window.localStorage.setItem(pollingKey(), JSON.stringify(ids))
}
function loadPollingIds() {
if (typeof window === 'undefined') return
try {
const raw = window.localStorage.getItem(pollingKey())
const ids = raw ? JSON.parse(raw) : []
pollingTaskIds.value = Array.isArray(ids)
? ids.filter((id): id is number => typeof id === 'number' && id > 0)
: []
} catch {
pollingTaskIds.value = []
}
}
// ---- 双队列维护(两 Tab 逐字相同;removePendingFileTask 多一个回调钩子)----
function addPollingTask(taskId: number) {
if (!pollingTaskIds.value.includes(taskId)) {
pollingTaskIds.value = [...pollingTaskIds.value, taskId]
savePollingIds()
}
ensurePolling()
}
function removePollingTask(taskId: number) {
pollingTaskIds.value = pollingTaskIds.value.filter((id) => id !== taskId)
if (!pendingFileTaskIds.value.includes(taskId)) {
const next = { ...liveProgressItems.value }
delete next[taskId]
liveProgressItems.value = next
}
savePollingIds()
}
function addPendingFileTask(taskId: number) {
if (!pendingFileTaskIds.value.includes(taskId)) {
pendingFileTaskIds.value = [...pendingFileTaskIds.value, taskId]
savePollingIds()
}
ensurePolling()
}
function removePendingFileTask(taskId: number) {
pendingFileTaskIds.value = pendingFileTaskIds.value.filter((id) => id !== taskId)
options.onPendingFileTaskRemoved?.(taskId)
if (!pollingTaskIds.value.includes(taskId)) {
const next = { ...liveProgressItems.value }
delete next[taskId]
liveProgressItems.value = next
}
savePollingIds()
}
// ---- 轮询循环(两 Tab 逐字相同;抛错处理按 pollErrorMode 参数化)----
function ensurePolling() {
if (disposed) return
if (pollTimer.value != null) return
scheduleNextPoll(true)
}
function ensurePollingIfAny() {
if (pollingTaskIds.value.length || pendingFileTaskIds.value.length) ensurePolling()
}
function stopPolling() {
if (pollTimer.value != null) {
timers.clearTimer('task-poll', pollTimer.value)
pollTimer.value = null
}
}
function scheduleNextPoll(immediate = false) {
if (disposed) return
if (pollTimer.value != null) {
if (!immediate) return
timers.clearTimer('task-poll', pollTimer.value)
pollTimer.value = null
}
if (immediate) void runPollCycle()
else pollTimer.value = timers.setTimeout('task-poll', runPollCycle, getTaskPollIntervalMs())
}
async function runPollCycle() {
pollTimer.value = null
if (disposed) return
if (!pollingTaskIds.value.length && !pendingFileTaskIds.value.length) return
if (pollErrorMode === 'propagate') {
await refreshTaskProgress()
scheduleFollowUp()
} else {
try {
await refreshTaskProgress()
} catch {
// A transient request failure must not stop progress polling permanently.
} finally {
scheduleFollowUp()
}
}
}
function scheduleFollowUp() {
if (!disposed && pollTimer.value == null && (pollingTaskIds.value.length || pendingFileTaskIds.value.length)) {
pollTimer.value = timers.setTimeout('task-poll', runPollCycle, getTaskPollIntervalMs())
}
}
// ---- 进度批量刷新(差异点经 beforeBatch / afterBatch / 钩子参数化)----
async function refreshTaskProgress() {
if (pollingInFlight.value || (!pollingTaskIds.value.length && !pendingFileTaskIds.value.length)) {
if (!pollingTaskIds.value.length && !pendingFileTaskIds.value.length) stopPolling()
return
}
pollingInFlight.value = true
try {
let shouldRefreshDashboard = false
let shouldRefreshHistory = false
const taskIds = Array.from(new Set([...pollingTaskIds.value, ...pendingFileTaskIds.value]))
if (taskIds.length) {
let batchIds = taskIds
let force = false
const prepared = options.beforeBatch
? await options.beforeBatch(taskIds, pendingFileTaskIds.value)
: { taskIds, force: false }
if (!prepared) {
// 预处理判断本轮无需拉取(Patent 的行版本未变路径):直接结束,不做结算
return
}
batchIds = prepared.taskIds
force = prepared.force
const batch = await options.fetchProgressBatch(batchIds, { force })
if (options.afterBatch) options.afterBatch(taskIds, pendingFileTaskIds.value, force)
for (const detail of batch.items || []) {
const task = detail.task
if (!task?.id) continue
const item = detail.items?.[0]
if (item) {
// 实时缓存:以最新一次 progress 为准,避免 history 接口字段缺失/延迟时丢失进度
liveProgressItems.value = {
...liveProgressItems.value,
[task.id]: item,
}
mergeHistoryItem(item)
}
if (task.status === 'SUCCESS' || task.status === 'FAILED') {
removePollingTask(task.id)
shouldRefreshDashboard = true
if (options.addPendingAfterFinalStatus(task, item)) addPendingFileTask(task.id)
else removePendingFileTask(task.id)
}
if (item && options.settleOnTaskStatuses.includes(task.status || '') && pendingFileTaskIds.value.includes(task.id)) {
const fileStatus = (item.fileStatus || '').toUpperCase()
if (item.fileReady || fileStatus === 'SUCCESS' || fileStatus === 'FAILED') {
removePendingFileTask(task.id)
shouldRefreshDashboard = true
shouldRefreshHistory = true
}
}
}
if (batch.missingTaskIds?.length) {
batch.missingTaskIds.forEach((taskId) => {
removePollingTask(taskId)
removePendingFileTask(taskId)
})
shouldRefreshHistory = true
shouldRefreshDashboard = true
}
}
if (shouldRefreshDashboard) {
await loadDashboard()
}
if (shouldRefreshHistory) {
await loadHistory()
}
settlePendingFileTasks()
} finally {
pollingInFlight.value = false
}
}
// ---- history 合并(两 Tab 逐字相同)----
function mergeHistoryItem(item: T) {
if (!item.taskId && !item.resultId) return
const index = historyItems.value.findIndex((row) =>
(item.resultId != null && row.resultId === item.resultId)
|| (item.taskId != null && row.taskId === item.taskId),
)
if (index >= 0) {
historyItems.value[index] = { ...historyItems.value[index], ...item }
} else {
historyItems.value = [item, ...historyItems.value]
}
}
function mergeCurrentTaskItem(item: T) {
if (item.taskId == null) return item
const liveItem = liveProgressItems.value[item.taskId]
if (!liveItem) return item
return {
...item,
...liveItem,
sourceFilename: liveItem.sourceFilename || item.sourceFilename,
resultFilename: liveItem.resultFilename || item.resultFilename,
rowCount: liveItem.rowCount ?? item.rowCount,
createdAt: liveItem.createdAt || item.createdAt,
}
}
function mergeHistoryItemsPreservingLiveProgress(
previousItems: T[],
incomingItems: T[],
) {
const previousByTaskId = new Map<number, T>()
const previousByResultId = new Map<number, T>()
for (const item of previousItems || []) {
if (item.taskId != null) previousByTaskId.set(item.taskId, item)
if (item.resultId != null) previousByResultId.set(item.resultId, item)
}
return (incomingItems || []).map((incoming) => {
const previous = incoming.resultId != null
? previousByResultId.get(incoming.resultId)
: incoming.taskId != null
? previousByTaskId.get(incoming.taskId)
: undefined
return mergeHistoryItemPreservingLiveProgress(previous, incoming)
})
}
function mergeHistoryItemPreservingLiveProgress(
previous: T | undefined,
incoming: T,
) {
if (!previous) return incoming
const shouldPreserveLiveProgress =
(normalizeTaskStatus(previous) === 'RUNNING' || isResultPreparing(previous) || showFileProgress(previous))
&& !showFileProgress(incoming)
&& !canDownload(incoming)
if (!shouldPreserveLiveProgress) {
return incoming
}
return {
...incoming,
fileJobId: incoming.fileJobId ?? previous.fileJobId,
fileStatus: incoming.fileStatus || previous.fileStatus,
fileError: incoming.fileError || previous.fileError,
fileReady: incoming.fileReady || previous.fileReady,
fileProgressPercent: hasMeaningfulProgressValue(incoming.fileProgressPercent)
? incoming.fileProgressPercent
: previous.fileProgressPercent,
fileProgressCurrent: hasMeaningfulProgressValue(incoming.fileProgressCurrent)
? incoming.fileProgressCurrent
: previous.fileProgressCurrent,
fileProgressTotal: hasMeaningfulProgressValue(incoming.fileProgressTotal)
? incoming.fileProgressTotal
: previous.fileProgressTotal,
fileProgressMessage: (incoming.fileProgressMessage || '').trim()
? incoming.fileProgressMessage
: previous.fileProgressMessage,
}
}
// ---- pending 文件任务结算与种子恢复(差异点经 keepPendingFileTask 参数化)----
function settlePendingFileTasks() {
if (!pendingFileTaskIds.value.length) return
const remaining: number[] = []
for (const taskId of pendingFileTaskIds.value) {
const item = historyItems.value.find((row) => row.taskId === taskId)
if (!item) {
remaining.push(taskId)
continue
}
const taskStatus = (item.taskStatus || '').toUpperCase()
const fileStatus = (item.fileStatus || '').toUpperCase()
if (item.fileReady || fileStatus === 'SUCCESS' || fileStatus === 'FAILED') {
continue
}
if (options.keepPendingFileTask(item, taskStatus)) {
remaining.push(taskId)
}
}
pendingFileTaskIds.value = remaining
savePollingIds()
if (pendingFileTaskIds.value.length) ensurePolling()
}
function seedPendingFileTasksFromHistory() {
const ids = historyItems.value
.filter((item) => item.taskId != null && isResultPreparing(item))
.map((item) => item.taskId as number)
pendingFileTaskIds.value = Array.from(new Set(ids))
savePollingIds()
if (pendingFileTaskIds.value.length) ensurePolling()
}
function seedRunningTasksFromHistory() {
const ids = historyItems.value
.filter((item) => item.taskId != null && normalizeTaskStatus(item) === 'RUNNING')
.map((item) => item.taskId as number)
if (!ids.length) return
pollingTaskIds.value = Array.from(new Set([...pollingTaskIds.value, ...ids]))
savePollingIds()
ensurePolling()
}
// ---- 数据加载(两 Tab 逐字相同,仅接口不同)----
async function loadDashboard() {
dashboard.value = await options.fetchDashboard()
}
async function loadHistory(opts: { force?: boolean } = {}) {
const now = Date.now()
if (!opts.force && historyItems.value.length && now - lastHistoryLoadedAt < HISTORY_CACHE_TTL_MS) return
if (historyInFlight) return historyInFlight
historyInFlight = options
.fetchHistory()
.then((res) => {
historyItems.value = mergeHistoryItemsPreservingLiveProgress(historyItems.value, res.items || [])
lastHistoryLoadedAt = Date.now()
})
.finally(() => {
historyInFlight = null
})
return historyInFlight
}
// ---- 下载 / 删除 / 批量删除胶水(差异点经 options 参数化)----
async function downloadResult(item: T) {
if (!item.resultId || !options.download) return
const url = item.downloadUrl || options.download.buildUrl(item.resultId, item)
const filename = item.resultFilename || `${item.sourceFilename || options.download.fallbackFilename}.xlsx`
const result = await saveUrlWithProgress(url, filename, `${options.download.progressKeyPrefix}:${item.resultId}`)
if (result.success) {
ElMessage.success(`已保存: ${result.path || filename}`)
} else if (result.error && result.error !== '用户取消') {
ElMessage.error(result.error)
}
}
async function deleteTaskRecord(item: T) {
if (!(await confirmTaskDeletion(item))) return
try {
const status = normalizeTaskStatus(item)
const deleteOptions = options.deleteTask
if (deleteOptions && deleteOptions.shouldDeleteTask(item, status)) {
await deleteOptions.deleteTask(item.taskId as number)
deleteOptions.onTaskDeleted?.(item)
} else if (item.resultId && deleteOptions) {
await deleteOptions.deleteHistory(item.resultId)
deleteOptions.onHistoryDeleted?.(item)
}
await loadDashboard()
await loadHistory({ force: true })
ElMessage.success('已删除')
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '删除失败')
}
}
/**
* 历史记录批量删除:复用单条删除逻辑(删除后原函数各自刷新列表)
*/
async function batchDeleteHistory(views: TaskItemView[]) {
const { total, failed } = await runBatchDelete(views, (view) => deleteTaskRecord(view.source as T))
if (!total) return
if (failed > 0) {
ElMessage.warning(`删除完成,${failed} 条失败`)
} else {
ElMessage.success(`已删除 ${total} 条历史记录`)
}
}
function dispose() {
disposed = true
stopPolling()
timers.clearScope()
}
return {
pollingTaskIds,
pendingFileTaskIds,
liveProgressItems,
historyItems,
dashboard,
currentItems,
historyOnlyItems,
loadPollingIds,
seedPendingFileTasksFromHistory,
seedRunningTasksFromHistory,
ensurePollingIfAny,
ensurePolling,
stopPolling,
dispose,
addPollingTask,
removePollingTask,
addPendingFileTask,
removePendingFileTask,
loadDashboard,
loadHistory,
refreshTaskProgress,
normalizeTaskStatus,
isResultPreparing,
canDownload,
showFileProgress,
downloadResult,
deleteTaskRecord,
batchDeleteHistory,
}
}
@@ -1,121 +0,0 @@
/**
* 健康检查执行器(Task 98)。
*
* 把真实启动、健康检查、核心请求、外部依赖调用四个验收探针收敛为
* 可注入探针的确定性流程:探针按序执行,全部产出结果与耗时。
*
* 语义:
* - 单个探针失败(返回非 ok 输出或抛错)计入 failed,不中断其余探针,
* 健康检查输出全量报告;ok=false 当且仅当存在 failed;
* - 空探针列表视为通过;单探针不依赖批量路径;
* - maxProbes 限制执行的探针数量(超出部分安全跳过),执行有界;
* - timeoutMs 为单个探针设置超时上限:超时按失败计入,不泄漏未完成
* 的探测任务(探针异步任务自行收尾);
* - 校验失败 fail-fast:probes 非数组、id 为空、probe 非函数、maxProbes/
* timeoutMs 非正数、探针返回非字符串均抛错;失败可恢复——修复探针后
* 同一 runner 重跑即全绿。
*/
export interface HealthProbe {
id: string
label: string
probe: () => Promise<string> | string
}
export interface HealthCheckOptions {
probes: HealthProbe[]
/** 执行的探针数量上限,必须为正数,默认 100 */
maxProbes?: number
/** 单个探针超时(毫秒),必须为正数,默认 30_000 */
timeoutMs?: number
}
export interface ProbeResult {
id: string
label: string
ok: boolean
output: string
durationMs: number
}
export interface HealthCheckResult {
ok: boolean
passed: ProbeResult[]
failed: ProbeResult[]
totalDurationMs: number
}
export interface HealthCheckRunner {
runAll: () => Promise<HealthCheckResult>
}
export function createHealthCheckRunner(options: HealthCheckOptions): HealthCheckRunner {
if (!Array.isArray(options.probes)) {
throw new Error('probes 必须是数组')
}
for (const probe of options.probes) {
if (typeof probe.id !== 'string' || probe.id.length === 0) {
throw new Error('probe id 不能为空')
}
if (typeof probe.probe !== 'function') {
throw new Error('probe 必须是函数')
}
}
const maxProbes = options.maxProbes ?? 100
const timeoutMs = options.timeoutMs ?? 30_000
if (!(maxProbes > 0)) {
throw new Error('maxProbes 必须为正数: ' + maxProbes)
}
if (!(timeoutMs > 0)) {
throw new Error('timeoutMs 必须为正数: ' + timeoutMs)
}
async function runOne(probe: HealthProbe): Promise<ProbeResult> {
const start = Date.now()
let output = ''
let failed = false
let timer: ReturnType<typeof setTimeout> | null = null
try {
const raw = await Promise.race([
Promise.resolve(probe.probe()),
new Promise<string>((resolve) => {
timer = setTimeout(() => resolve(''), timeoutMs)
}),
])
if (timer != null) clearTimeout(timer)
output = raw
} catch (error) {
if (timer != null) clearTimeout(timer)
failed = true
output = error instanceof Error ? error.message : String(error)
}
const durationMs = Date.now() - start
if (typeof output !== 'string') {
throw new Error('output 必须是字符串')
}
const ok = !failed && output !== ''
return { id: probe.id, label: probe.label, ok, output, durationMs }
}
async function runAll(): Promise<HealthCheckResult> {
const start = Date.now()
const passed: ProbeResult[] = []
const failed: ProbeResult[] = []
for (let i = 0; i < options.probes.length; i++) {
if (i >= maxProbes) break
const result = await runOne(options.probes[i])
if (result.ok) {
passed.push(result)
} else {
failed.push(result)
}
}
return {
ok: failed.length === 0,
passed,
failed,
totalDurationMs: Date.now() - start,
}
}
return { runAll }
}

Some files were not shown because too many files have changed in this diff Show More