refactor: 第二批收敛——公共 Excel 写出器 + 任务收尾零件下沉 + 前端上传区/任务面板抽取

This commit is contained in:
2026-10-01 15:00:52 +08:00
parent 4b29a150f3
commit fa4bd57016
32 changed files with 2467 additions and 2826 deletions
@@ -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);
}
}
}
@@ -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) {