refactor(order-import): 改用 sys_file 外键替代 file_path

数据库变更:
- ec_import_tasks 表:移除 file_path 字段,新增 file_id 外键关联 sys_file
- sql/temp.sql:包含 ALTER 语句用于线上数据库变更

代码变更:
- ImportTaskPO/VO/DTO:filePath → fileId
- SysFileService:新增 getFileById 方法
- ImportTaskProcessorServiceImpl:
  - 注入 SysFileService
  - 通过 fileId 获取文件信息
  - 根据 storageType(local/oss)读取文件:本地直读,OSS 下载到临时文件后处理
  - 临时文件不再依赖 deleteOnExit
This commit is contained in:
小蟑螂
2026-03-29 14:13:13 +08:00
parent b8b0a3d6d8
commit bee92ce7ce
8 changed files with 84 additions and 45 deletions
@@ -36,11 +36,11 @@ public class CreateImportTaskDTO {
private String fileName;
/**
* 存储路径
* 关联文件ID(外键到sys_file)
*/
@Schema(description = "存储路径", example = "/uploads/import/2025/01/xxx.xlsx", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "存储路径不能为空")
private String filePath;
@Schema(description = "关联文件ID", example = "1", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "文件ID不能为空")
private Long fileId;
/**
* 字段映射记录(JSON字符串)
@@ -51,10 +51,10 @@ public class ImportTaskPO {
private String fileName;
/**
* 存储路径
* 关联文件ID(外键到sys_file)
*/
@TableField("file_path")
private String filePath;
@TableField("file_id")
private Long fileId;
/**
* 任务状态(pending-待处理 processing-处理中 success-成功 failed-失败)
@@ -49,10 +49,10 @@ public class ImportTaskVO {
private String fileName;
/**
* 存储路径
* 关联文件ID
*/
@Schema(description = "存储路径", example = "/uploads/import/2025/01/xxx.xlsx")
private String filePath;
@Schema(description = "关联文件ID", example = "1")
private Long fileId;
/**
* 任务状态
@@ -34,6 +34,8 @@ import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService;
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSpecService;
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.SseNotificationService;
import top.xyquan.ecomdmbbackend.modules.sys.file.service.OssService;
import top.xyquan.ecomdmbbackend.modules.sys.file.service.SysFileService;
import top.xyquan.ecomdmbbackend.modules.sys.file.model.vo.SysFileVO;
import java.io.File;
import java.io.InputStream;
@@ -213,6 +215,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
private final OrderStatusService orderStatusService;
private final SqlSessionFactory sqlSessionFactory;
private final OssService ossService;
private final SysFileService sysFileService;
public ImportTaskProcessorServiceImpl(ImportTaskService importTaskService,
OrderService orderService,
@@ -226,7 +229,8 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
ObjectMapper objectMapper,
OrderStatusService orderStatusService,
SqlSessionFactory sqlSessionFactory,
OssService ossService) {
OssService ossService,
SysFileService sysFileService) {
this.importTaskService = importTaskService;
this.productSpecService = productSpecService;
this.orderMapper = orderMapper;
@@ -238,6 +242,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
this.orderStatusService = orderStatusService;
this.sqlSessionFactory = sqlSessionFactory;
this.ossService = ossService;
this.sysFileService = sysFileService;
}
/**
@@ -302,44 +307,38 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
Long companyId = task.getCompanyId();
// 读取CSV文件
// 处理文件路径:优先从本地文件系统读取,如果不存在则尝试从OSS下载
String filePath = task.getFilePath();
// 通过 fileId 从统一文件系统获取文件信息,根据存储类型读取文件
File csvFile = null;
InputStream fileInputStream = null;
if (filePath.contains(":")) {
// 包含:的路径,认为是绝对路径(Windows路径如 C:\...)
csvFile = new File(filePath);
} else if (filePath.startsWith("/")) {
// 以/开头的路径,去掉开头的/,转换为相对于当前工作目录的路径
// 例如:/uploads/files/xxx.csv -> uploads/files/xxx.csv
csvFile = new File(filePath.substring(1));
} else {
// 相对路径,直接使用
csvFile = new File(filePath);
// 获取文件信息
SysFileVO fileInfo = sysFileService.getFileById(task.getFileId());
if (fileInfo == null) {
throw new BusinessException("文件不存在,fileId: " + task.getFileId());
}
// 首先尝试从本地文件系统读取
if (csvFile.exists() && csvFile.isFile()) {
// 本地文件存在,直接使用
// 使用BufferedInputStream包装以支持mark/reset(用于编码检测)
fileInputStream = new java.io.BufferedInputStream(new java.io.FileInputStream(csvFile));
} else {
// 本地文件不存在,尝试从OSS下载
// 使用storagePath作为OSS的key(去掉开头的/)
String ossKey = filePath.startsWith("/") ? filePath.substring(1) : filePath;
// 创建临时文件
File tempFile = java.io.File.createTempFile("import-csv-", ".csv");
tempFile.deleteOnExit();
if (ossService.downloadFile(ossKey, tempFile)) {
csvFile = tempFile;
// 使用BufferedInputStream包装以支持mark/reset(用于编码检测)
fileInputStream = new java.io.BufferedInputStream(new java.io.FileInputStream(tempFile));
String storagePath = fileInfo.getStoragePath();
String storageType = fileInfo.getStorageType();
if ("local".equals(storageType)) {
// 本地存储:使用 storagePath 作为本地文件路径
File localFile = new File(storagePath);
if (localFile.exists() && localFile.isFile()) {
fileInputStream = new java.io.BufferedInputStream(new java.io.FileInputStream(localFile));
csvFile = localFile;
} else {
throw new BusinessException("CSV文件不存在: " + task.getFilePath() + " (本地路径: " + csvFile.getAbsolutePath() + ",OSS Key: " + ossKey + ")");
throw new BusinessException("本地文件不存在: " + storagePath);
}
} else {
// 对象存储(oss/s3/qiniu/cos等):从 OSS 下载到临时文件
File tempFile = java.io.File.createTempFile("import-csv-", ".csv");
if (!ossService.downloadFile(storagePath, tempFile)) {
throw new BusinessException("从对象存储下载文件失败,storagePath: " + storagePath);
}
csvFile = tempFile;
fileInputStream = new java.io.BufferedInputStream(new java.io.FileInputStream(tempFile));
}
// 获取默认订单状态ID(尝试查找"未知状态",如果不存在则使用第一个状态)
@@ -91,5 +91,13 @@ public interface SysFileService {
* @param dto 更新内容
*/
void updateFile(Long id, SysFileUpdateDTO dto);
/**
* 通过文件ID获取文件信息
*
* @param fileId 文件ID
* @return 文件信息VO
*/
SysFileVO getFileById(Long fileId);
}
@@ -617,5 +617,19 @@ public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFilePO> im
}
this.updateById(file);
}
@Override
public SysFileVO getFileById(Long fileId) {
if (fileId == null) {
return null;
}
SysFilePO file = this.getById(fileId);
if (file == null) {
return null;
}
SysFileVO vo = new SysFileVO();
BeanUtils.copyProperties(file, vo);
return vo;
}
}
+4 -2
View File
@@ -93,7 +93,7 @@ CREATE TABLE `ec_import_tasks` (
`type` enum('product','order') NOT NULL COMMENT '导入类型(product-商品 order-订单)',
`task_name` varchar(100) DEFAULT NULL COMMENT '任务名称',
`file_name` varchar(255) NOT NULL COMMENT '原始文件名',
`file_path` varchar(500) NOT NULL COMMENT '存储路径',
`file_id` bigint unsigned DEFAULT NULL COMMENT '关联文件ID(外键到sys_file)',
`status` enum('pending','processing','success','failed') NOT NULL DEFAULT 'pending' COMMENT '任务状态(pending-待处理 processing-处理中 success-成功 failed-失败)',
`total_count` int unsigned DEFAULT '0' COMMENT '总行数',
`success_count` int unsigned DEFAULT '0' COMMENT '成功行数',
@@ -108,9 +108,11 @@ CREATE TABLE `ec_import_tasks` (
KEY `idx_company_id` (`company_id`),
KEY `idx_create_by` (`create_by`),
KEY `idx_update_by` (`update_by`),
KEY `idx_file_id` (`file_id`),
CONSTRAINT `fk_import_task_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_import_task_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_import_task_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
CONSTRAINT `fk_import_task_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_import_task_file` FOREIGN KEY (`file_id`) REFERENCES `sys_file` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=174 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='电商-导入任务表'
-- ========================================
+17 -1
View File
@@ -1,2 +1,18 @@
-- ========================================
-- 修改 ec_import_tasks 表:移除 file_path,改用 file_id 外键关联 sys_file
-- ========================================
-- 1. 添加 file_id 列(允许为空,因为历史数据可能没有文件记录)
ALTER TABLE `ec_import_tasks`
ADD COLUMN `task_name` VARCHAR(100) DEFAULT NULL COMMENT '任务名称' AFTER `type`;
ADD COLUMN `file_id` bigint unsigned DEFAULT NULL COMMENT '关联文件ID' AFTER `file_name`;
-- 2. 添加外键约束
ALTER TABLE `ec_import_tasks`
ADD CONSTRAINT `fk_import_task_file` FOREIGN KEY (`file_id`) REFERENCES `sys_file` (`id`) ON DELETE SET NULL ON UPDATE CASCADE;
-- 3. 为 file_id 添加索引(导入任务查询时可能需要按文件筛选)
ALTER TABLE `ec_import_tasks`
ADD INDEX `idx_file_id` (`file_id`);
-- 4. 删除旧的 file_path 列(等数据迁移后再执行,或确认无需保留时执行)
-- ALTER TABLE `ec_import_tasks` DROP COLUMN `file_path`;