mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 17:09:19 +08:00
refactor: 下线废弃的 EC 手动文件导入(ImportTask)能力
This commit is contained in:
@@ -1,88 +0,0 @@
|
||||
-- ========================================
|
||||
-- 电商-导入相关表设计
|
||||
-- ec_import_field_defs / ec_import_mappings / ec_import_tasks
|
||||
-- ========================================
|
||||
|
||||
-- ----------------------------
|
||||
-- 导入字段定义表
|
||||
-- ----------------------------
|
||||
DROP TABLE IF EXISTS `ec_import_field_defs`;
|
||||
CREATE TABLE `ec_import_field_defs` (
|
||||
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '字段定义ID',
|
||||
`type` enum('product','order') CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '导入类型(product-商品 order-订单)',
|
||||
`field_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '数据库字段名,如 name',
|
||||
`field_label` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '中文字段名,如 商品名称',
|
||||
`file_field_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '文件字段名,如 商品名称',
|
||||
`required` tinyint(1) NULL DEFAULT 0 COMMENT '是否必填',
|
||||
`sort` int UNSIGNED NULL DEFAULT 0 COMMENT '排序',
|
||||
`data_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT 'string' COMMENT 'string, number, date等',
|
||||
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
UNIQUE INDEX `uniq_type_field`(`type` ASC, `field_name` ASC) USING BTREE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '电商-导入字段定义表' ;
|
||||
|
||||
-- ----------------------------
|
||||
-- 导入映射表
|
||||
-- ----------------------------
|
||||
DROP TABLE IF EXISTS `ec_import_mappings`;
|
||||
CREATE TABLE `ec_import_mappings` (
|
||||
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '映射ID',
|
||||
`company_id` bigint UNSIGNED NOT NULL COMMENT '所属公司ID',
|
||||
`type` enum('PRODUCT','ORDER','ORDER_STATUS', 'PROMOTION_FEE') CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '导入类型(PRODUCT-商品 ORDER-订单 ORDER_STATUS-订单状态 PROMOTION_FEE-推广费)',
|
||||
`name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '映射名称',
|
||||
`mapping` json NOT NULL COMMENT '映射JSON',
|
||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人ID',
|
||||
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人ID',
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
UNIQUE INDEX `uniq_company_type_name`(`company_id` ASC, `type` ASC, `name` ASC) USING BTREE,
|
||||
INDEX `fk_import_mapping_creator`(`create_by` ASC) USING BTREE,
|
||||
INDEX `fk_import_mapping_updater`(`update_by` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_import_mapping_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_import_mapping_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_import_mapping_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '电商-导入映射表' ;
|
||||
|
||||
-- ----------------------------
|
||||
-- 导入任务表
|
||||
-- ----------------------------
|
||||
DROP TABLE IF EXISTS `ec_import_tasks`;
|
||||
CREATE TABLE `ec_import_tasks` (
|
||||
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
`company_id` bigint UNSIGNED NOT NULL COMMENT '所属公司ID',
|
||||
`shop_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '所属店铺ID',
|
||||
`type` enum('product','order', 'promotion_record') CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '导入类型(product-商品 order-订单 promotion_record-推广记录)',
|
||||
`task_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '任务名称',
|
||||
`file_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '原始文件名',
|
||||
`file_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '关联文件ID',
|
||||
`status` enum('pending','processing','success','failed') CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'pending' COMMENT '任务状态(pending-待处理 processing-处理中 success-成功 failed-失败)',
|
||||
`total_count` int UNSIGNED NULL DEFAULT 0 COMMENT '总行数',
|
||||
`success_count` int UNSIGNED NULL DEFAULT 0 COMMENT '成功行数',
|
||||
`fail_count` int UNSIGNED NULL DEFAULT 0 COMMENT '失败行数',
|
||||
`mapping` json NULL COMMENT '字段映射记录',
|
||||
`message` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL COMMENT '错误信息或备注',
|
||||
`started_at` datetime NULL DEFAULT NULL COMMENT '开始处理时间',
|
||||
`last_heartbeat_at` datetime NULL DEFAULT NULL COMMENT '最后心跳时间',
|
||||
`worker_id` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '处理实例标识',
|
||||
`redis_stream_key` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '入队 Stream Key',
|
||||
`redis_message_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT 'Redis Stream 消息ID',
|
||||
`enqueue_status` enum('pending_enqueue','enqueued','enqueue_failed') CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'pending_enqueue' COMMENT '入队状态',
|
||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人ID',
|
||||
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人ID',
|
||||
PRIMARY KEY (`id`) USING BTREE,
|
||||
INDEX `idx_company_id`(`company_id` ASC) USING BTREE,
|
||||
INDEX `idx_create_by`(`create_by` ASC) USING BTREE,
|
||||
INDEX `idx_update_by`(`update_by` ASC) USING BTREE,
|
||||
INDEX `idx_file_id`(`file_id` ASC) USING BTREE,
|
||||
INDEX `idx_import_task_dispatch`(`status` ASC, `type` ASC, `id` ASC) USING BTREE,
|
||||
INDEX `idx_import_task_recover`(`status` ASC, `last_heartbeat_at` ASC) USING BTREE,
|
||||
INDEX `idx_import_task_enqueue`(`enqueue_status` ASC, `status` ASC) USING BTREE,
|
||||
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_file` FOREIGN KEY (`file_id`) REFERENCES `sys_file` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '电商-导入任务表' ;
|
||||
@@ -0,0 +1,77 @@
|
||||
-- 下线 EC 手动文件导入(Redis Stream ImportTask):菜单隐藏 + 清权限绑定 + 删表
|
||||
-- 不影响 channel_pdd_* 广告费 OpenAPI 导入任务表
|
||||
|
||||
-- 解除岗位-菜单绑定(手动导入菜单)
|
||||
DELETE pm FROM `org_position_menu` pm
|
||||
INNER JOIN `sys_menu` m ON m.id = pm.menu_id
|
||||
WHERE m.route_name IN (
|
||||
'DataImportCatalog',
|
||||
'DataImport',
|
||||
'AdFeeImport',
|
||||
'FieldMappingConfig',
|
||||
'OrderStatusMappingConfig'
|
||||
)
|
||||
OR m.id IN (35, 36, 37, 48, 14003);
|
||||
|
||||
-- 解除菜单-权限绑定
|
||||
DELETE mp FROM `sys_menu_permission` mp
|
||||
INNER JOIN `sys_menu` m ON m.id = mp.menu_id
|
||||
WHERE m.route_name IN (
|
||||
'DataImportCatalog',
|
||||
'DataImport',
|
||||
'AdFeeImport',
|
||||
'FieldMappingConfig',
|
||||
'OrderStatusMappingConfig'
|
||||
)
|
||||
OR m.id IN (35, 36, 37, 48, 14003);
|
||||
|
||||
-- 禁用并隐藏菜单
|
||||
UPDATE `sys_menu`
|
||||
SET `status` = 0, `visible` = 0
|
||||
WHERE `route_name` IN (
|
||||
'DataImportCatalog',
|
||||
'DataImport',
|
||||
'AdFeeImport',
|
||||
'FieldMappingConfig',
|
||||
'OrderStatusMappingConfig'
|
||||
)
|
||||
OR `id` IN (35, 36, 37, 48, 14003);
|
||||
|
||||
-- 岗位权限解绑(手动导入相关)
|
||||
DELETE pp FROM `org_position_permission` pp
|
||||
INNER JOIN `sys_permission` p ON p.id = pp.permission_id
|
||||
WHERE p.code IN (
|
||||
'data:import',
|
||||
'data:import:create',
|
||||
'data:import:read',
|
||||
'data:import-mapping',
|
||||
'data:import-mapping:read',
|
||||
'data:import-mapping:create',
|
||||
'data:import-mapping:update',
|
||||
'data:import-mapping:delete',
|
||||
'ec:order:import'
|
||||
)
|
||||
OR p.code LIKE 'data:import-mapping:%'
|
||||
OR p.code LIKE 'data:import:%';
|
||||
|
||||
-- 权限点标记停用
|
||||
UPDATE `sys_permission`
|
||||
SET `status` = 0
|
||||
WHERE `code` IN (
|
||||
'data:import',
|
||||
'data:import:create',
|
||||
'data:import:read',
|
||||
'data:import-mapping',
|
||||
'data:import-mapping:read',
|
||||
'data:import-mapping:create',
|
||||
'data:import-mapping:update',
|
||||
'data:import-mapping:delete',
|
||||
'ec:order:import'
|
||||
)
|
||||
OR `code` LIKE 'data:import-mapping:%'
|
||||
OR `code` LIKE 'data:import:%';
|
||||
|
||||
-- 业务表(无其它模块依赖)
|
||||
DROP TABLE IF EXISTS `ec_import_tasks`;
|
||||
DROP TABLE IF EXISTS `ec_import_mappings`;
|
||||
DROP TABLE IF EXISTS `ec_import_field_defs`;
|
||||
-59
@@ -1,59 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.mapping.controller;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.mapping.model.dto.CreateImportMappingDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.mapping.model.dto.ImportMappingFilterDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.mapping.model.dto.UpdateImportMappingDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.mapping.model.vo.ImportMappingVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.mapping.service.ImportMappingService;
|
||||
|
||||
/**
|
||||
* 导入映射模板管理控制器
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/ec/import/mapping")
|
||||
public class ImportMappingController {
|
||||
|
||||
private final ImportMappingService importMappingService;
|
||||
|
||||
public ImportMappingController(ImportMappingService importMappingService) {
|
||||
this.importMappingService = importMappingService;
|
||||
}
|
||||
|
||||
@PostMapping("/create")
|
||||
@RequirePermission(value = "data:import-mapping:create", description = "创建导入映射模板", allowSuper = true)
|
||||
public ApiResponse<ImportMappingVO> createImportMapping(@Valid @RequestBody CreateImportMappingDTO createImportMappingDTO) {
|
||||
ImportMappingVO importMappingVO = importMappingService.createImportMapping(createImportMappingDTO);
|
||||
return ApiResponse.success("导入映射模板创建成功", importMappingVO);
|
||||
}
|
||||
|
||||
@PutMapping("/update/{id}")
|
||||
@RequirePermission(value = "data:import-mapping:update", description = "更新导入映射模板", allowSuper = true)
|
||||
public ApiResponse<ImportMappingVO> updateImportMapping(
|
||||
@Valid @RequestBody UpdateImportMappingDTO updateImportMappingDTO,
|
||||
@PathVariable Long id) {
|
||||
ImportMappingVO importMappingVO = importMappingService.updateImportMapping(updateImportMappingDTO, id);
|
||||
return ApiResponse.success("导入映射模板更新成功", importMappingVO);
|
||||
}
|
||||
|
||||
@DeleteMapping("/delete/{id}")
|
||||
@RequirePermission(value = "data:import-mapping:delete", description = "删除导入映射模板", allowSuper = true)
|
||||
public ApiResponse<Void> deleteImportMapping(
|
||||
@PathVariable Long id) {
|
||||
importMappingService.deleteImportMapping(id);
|
||||
return ApiResponse.success("导入映射模板删除成功");
|
||||
}
|
||||
|
||||
@PostMapping("/list")
|
||||
@RequirePermission(value = "data:import-mapping:read", description = "查询导入映射模板列表", allowSuper = true)
|
||||
public ApiResponse<PageResultVO<ImportMappingVO>> getImportMappingPage(
|
||||
@Valid @RequestBody PageQueryDTO<ImportMappingFilterDTO> pageQueryDTO) {
|
||||
PageResultVO<ImportMappingVO> result = importMappingService.getImportMappingPage(pageQueryDTO);
|
||||
return ApiResponse.success("获取导入映射模板列表成功", result);
|
||||
}
|
||||
}
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.mapping.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.mapping.model.po.ImportMappingPO;
|
||||
|
||||
/**
|
||||
* 导入映射Mapper接口
|
||||
*/
|
||||
@Mapper
|
||||
public interface ImportMappingMapper extends BaseMapper<ImportMappingPO> {
|
||||
}
|
||||
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.mapping.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 创建导入映射模板DTO
|
||||
*/
|
||||
@Data
|
||||
public class CreateImportMappingDTO {
|
||||
|
||||
/**
|
||||
* 导入类型(PRODUCT-商品 ORDER-订单 ORDER_STATUS-订单状态 PROMOTION_FEE-推广费)
|
||||
*/
|
||||
@NotBlank(message = "导入类型不能为空")
|
||||
@Pattern(regexp = "^(PRODUCT|ORDER|ORDER_STATUS|PROMOTION_FEE)$", message = "导入类型只能是PRODUCT、ORDER、ORDER_STATUS或PROMOTION_FEE")
|
||||
private String type;
|
||||
|
||||
/**
|
||||
* 模板名称
|
||||
*/
|
||||
@NotBlank(message = "模板名称不能为空")
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* 模板JSON
|
||||
*/
|
||||
@NotBlank(message = "模板JSON不能为空")
|
||||
private String mapping;
|
||||
}
|
||||
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.mapping.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 导入映射模板过滤DTO
|
||||
*/
|
||||
@Data
|
||||
public class ImportMappingFilterDTO {
|
||||
|
||||
/**
|
||||
* 导入类型(PRODUCT-商品 ORDER-订单 ORDER_STATUS-订单状态 PROMOTION_FEE-推广费)
|
||||
*/
|
||||
private String type;
|
||||
|
||||
/**
|
||||
* 模板名称(模糊查询)
|
||||
*/
|
||||
private String name;
|
||||
}
|
||||
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.mapping.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 更新导入映射模板DTO
|
||||
*/
|
||||
@Data
|
||||
public class UpdateImportMappingDTO {
|
||||
|
||||
/**
|
||||
* 模板名称
|
||||
*/
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* 模板JSON
|
||||
*/
|
||||
@NotBlank(message = "模板JSON不能为空")
|
||||
private String mapping;
|
||||
}
|
||||
|
||||
-71
@@ -1,71 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.mapping.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 导入映射实体
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@TableName("ec_import_mappings")
|
||||
public class ImportMappingPO {
|
||||
|
||||
/**
|
||||
* 映射ID
|
||||
*/
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
* 所属公司ID
|
||||
*/
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
/**
|
||||
* 导入类型(PRODUCT-商品 ORDER-订单 ORDER_STATUS-订单状态)
|
||||
*/
|
||||
@TableField("type")
|
||||
private String type;
|
||||
|
||||
/**
|
||||
* 映射名称
|
||||
*/
|
||||
@TableField("name")
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* 映射JSON
|
||||
*/
|
||||
@TableField("mapping")
|
||||
private String mapping;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
/**
|
||||
* 更新时间
|
||||
*/
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
|
||||
/**
|
||||
* 创建人ID
|
||||
*/
|
||||
@TableField("create_by")
|
||||
private Long createBy;
|
||||
|
||||
/**
|
||||
* 更新人ID
|
||||
*/
|
||||
@TableField("update_by")
|
||||
private Long updateBy;
|
||||
}
|
||||
|
||||
-58
@@ -1,58 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.mapping.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 导入映射模板VO
|
||||
*/
|
||||
@Data
|
||||
public class ImportMappingVO {
|
||||
|
||||
/**
|
||||
* 模板ID
|
||||
*/
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
* 所属公司ID
|
||||
*/
|
||||
private Long companyId;
|
||||
|
||||
/**
|
||||
* 导入类型(PRODUCT-商品 ORDER-订单 ORDER_STATUS-订单状态)
|
||||
*/
|
||||
private String type;
|
||||
|
||||
/**
|
||||
* 模板名称
|
||||
*/
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* 模板JSON
|
||||
*/
|
||||
private String mapping;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
private LocalDateTime createTime;
|
||||
|
||||
/**
|
||||
* 更新时间
|
||||
*/
|
||||
private LocalDateTime updateTime;
|
||||
|
||||
/**
|
||||
* 创建人ID
|
||||
*/
|
||||
private Long createBy;
|
||||
|
||||
/**
|
||||
* 更新人ID
|
||||
*/
|
||||
private Long updateBy;
|
||||
}
|
||||
|
||||
-49
@@ -1,49 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.mapping.service;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.mapping.model.dto.CreateImportMappingDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.mapping.model.dto.ImportMappingFilterDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.mapping.model.dto.UpdateImportMappingDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.mapping.model.po.ImportMappingPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.mapping.model.vo.ImportMappingVO;
|
||||
|
||||
/**
|
||||
* 导入映射模板服务接口
|
||||
*/
|
||||
public interface ImportMappingService extends IService<ImportMappingPO> {
|
||||
|
||||
/**
|
||||
* 创建导入映射模板
|
||||
*
|
||||
* @param createImportMappingDTO 创建导入映射模板DTO
|
||||
* @return 导入映射模板VO
|
||||
*/
|
||||
ImportMappingVO createImportMapping(CreateImportMappingDTO createImportMappingDTO);
|
||||
|
||||
/**
|
||||
* 更新导入映射模板
|
||||
*
|
||||
* @param updateImportMappingDTO 更新导入映射模板DTO
|
||||
* @param id 模板ID
|
||||
* @return 导入映射模板VO
|
||||
*/
|
||||
ImportMappingVO updateImportMapping(UpdateImportMappingDTO updateImportMappingDTO, Long id);
|
||||
|
||||
/**
|
||||
* 删除导入映射模板
|
||||
*
|
||||
* @param id 模板ID
|
||||
*/
|
||||
void deleteImportMapping(Long id);
|
||||
|
||||
/**
|
||||
* 分页获取导入映射模板列表
|
||||
*
|
||||
* @param pageQueryDTO 分页查询DTO
|
||||
* @return 分页结果
|
||||
*/
|
||||
PageResultVO<ImportMappingVO> getImportMappingPage(PageQueryDTO<ImportMappingFilterDTO> pageQueryDTO);
|
||||
}
|
||||
|
||||
-190
@@ -1,190 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.mapping.service.impl;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.common.utils.BeanCopyUtils;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.mapping.mapper.ImportMappingMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.mapping.model.dto.CreateImportMappingDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.mapping.model.dto.ImportMappingFilterDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.mapping.model.dto.UpdateImportMappingDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.mapping.model.po.ImportMappingPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.mapping.model.vo.ImportMappingVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.mapping.service.ImportMappingService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 导入映射模板服务实现类
|
||||
*/
|
||||
@Service
|
||||
public class ImportMappingServiceImpl extends ServiceImpl<ImportMappingMapper, ImportMappingPO> implements ImportMappingService {
|
||||
|
||||
private final CurrentUserContext currentUserContext;
|
||||
|
||||
public ImportMappingServiceImpl(CurrentUserContext currentUserContext) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建导入映射模板
|
||||
*
|
||||
* @param createImportMappingDTO 创建导入映射DTO
|
||||
* @return 导入映射VO
|
||||
*/
|
||||
@Override
|
||||
@Transactional
|
||||
public ImportMappingVO createImportMapping(CreateImportMappingDTO createImportMappingDTO) {
|
||||
// 从token中获取公司ID
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
|
||||
// 验证同一公司、同一类型、同一名称是否已存在模板(根据唯一索引)
|
||||
LambdaQueryWrapper<ImportMappingPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ImportMappingPO::getCompanyId, companyId)
|
||||
.eq(ImportMappingPO::getType, createImportMappingDTO.getType())
|
||||
.eq(ImportMappingPO::getName, createImportMappingDTO.getName());
|
||||
if (this.count(wrapper) > 0) {
|
||||
throw new BusinessException("该类型的导入映射模板名称已存在,请使用其他名称或更新接口");
|
||||
}
|
||||
|
||||
// 创建导入映射模板
|
||||
ImportMappingPO importMappingPO = new ImportMappingPO();
|
||||
BeanCopyUtils.copyProperties(createImportMappingDTO, importMappingPO);
|
||||
importMappingPO.setCompanyId(companyId);
|
||||
importMappingPO.setCreateBy(currentUserContext.getCurrentUserId());
|
||||
|
||||
this.save(importMappingPO);
|
||||
|
||||
// 转换为VO返回
|
||||
return convertToVO(importMappingPO);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新导入映射模板
|
||||
*
|
||||
* @param updateImportMappingDTO 更新导入映射DTO
|
||||
* @param id 映射ID
|
||||
* @return 导入映射VO
|
||||
*/
|
||||
@Override
|
||||
@Transactional
|
||||
public ImportMappingVO updateImportMapping(UpdateImportMappingDTO updateImportMappingDTO, Long id) {
|
||||
// 验证模板是否存在
|
||||
ImportMappingPO existingMapping = this.getById(id);
|
||||
if (existingMapping == null) {
|
||||
throw new BusinessException("导入映射模板不存在");
|
||||
}
|
||||
|
||||
// 验证公司权限
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
if (!existingMapping.getCompanyId().equals(companyId)) {
|
||||
throw new BusinessException("无权限操作此模板");
|
||||
}
|
||||
|
||||
// 如果更新了名称,验证新名称是否与同一公司、同一类型的其他模板冲突
|
||||
if (updateImportMappingDTO.getName() != null &&
|
||||
!updateImportMappingDTO.getName().equals(existingMapping.getName())) {
|
||||
LambdaQueryWrapper<ImportMappingPO> nameCheckWrapper = new LambdaQueryWrapper<>();
|
||||
nameCheckWrapper.eq(ImportMappingPO::getCompanyId, companyId)
|
||||
.eq(ImportMappingPO::getType, existingMapping.getType())
|
||||
.eq(ImportMappingPO::getName, updateImportMappingDTO.getName())
|
||||
.ne(ImportMappingPO::getId, id);
|
||||
if (this.count(nameCheckWrapper) > 0) {
|
||||
throw new BusinessException("该类型的导入映射模板名称已存在,请使用其他名称");
|
||||
}
|
||||
}
|
||||
|
||||
// 更新模板
|
||||
ImportMappingPO importMappingPO = new ImportMappingPO();
|
||||
BeanCopyUtils.copyProperties(updateImportMappingDTO, importMappingPO);
|
||||
importMappingPO.setId(id);
|
||||
importMappingPO.setUpdateBy(currentUserContext.getCurrentUserId());
|
||||
|
||||
this.updateById(importMappingPO);
|
||||
|
||||
// 转换为VO返回
|
||||
return convertToVO(this.getById(id));
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除导入映射
|
||||
*
|
||||
* @param id 映射ID
|
||||
*/
|
||||
@Override
|
||||
@Transactional
|
||||
public void deleteImportMapping(Long id) {
|
||||
// 验证模板是否存在
|
||||
ImportMappingPO existingMapping = this.getById(id);
|
||||
if (existingMapping == null) {
|
||||
throw new BusinessException("导入映射模板不存在");
|
||||
}
|
||||
|
||||
// 验证公司权限
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
if (!existingMapping.getCompanyId().equals(companyId)) {
|
||||
throw new BusinessException("无权限操作此模板");
|
||||
}
|
||||
|
||||
// 删除模板
|
||||
this.removeById(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页获取导入映射模板列表
|
||||
*
|
||||
* @param pageQueryDTO 分页查询DTO
|
||||
* @return 分页结果VO
|
||||
*/
|
||||
@Override
|
||||
public PageResultVO<ImportMappingVO> getImportMappingPage(PageQueryDTO<ImportMappingFilterDTO> pageQueryDTO) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
ImportMappingFilterDTO filter = pageQueryDTO.getFilters();
|
||||
|
||||
// 构建查询条件
|
||||
LambdaQueryWrapper<ImportMappingPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ImportMappingPO::getCompanyId, companyId);
|
||||
|
||||
if (filter != null) {
|
||||
if (StringUtils.hasText(filter.getType())) {
|
||||
wrapper.eq(ImportMappingPO::getType, filter.getType());
|
||||
}
|
||||
if (StringUtils.hasText(filter.getName())) {
|
||||
wrapper.like(ImportMappingPO::getName, filter.getName());
|
||||
}
|
||||
}
|
||||
|
||||
// 按创建时间倒序
|
||||
wrapper.orderByDesc(ImportMappingPO::getCreateTime);
|
||||
|
||||
// 分页查询
|
||||
Page<ImportMappingPO> page = new Page<>(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
|
||||
IPage<ImportMappingPO> pageResult = this.page(page, wrapper);
|
||||
|
||||
// 转换为VO
|
||||
List<ImportMappingVO> voList = pageResult.getRecords().stream()
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return PageResultVO.create(voList, pageResult.getTotal(), pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换为VO
|
||||
*/
|
||||
private ImportMappingVO convertToVO(ImportMappingPO importMappingPO) {
|
||||
ImportMappingVO importMappingVO = new ImportMappingVO();
|
||||
BeanCopyUtils.copyProperties(importMappingPO, importMappingVO);
|
||||
return importMappingVO;
|
||||
}
|
||||
}
|
||||
|
||||
-58
@@ -1,58 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 导入任务 Redis Stream 队列配置。
|
||||
*/
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "import-task")
|
||||
public class ImportTaskProperties {
|
||||
|
||||
private Queue queue = new Queue();
|
||||
private Worker worker = new Worker();
|
||||
|
||||
@Data
|
||||
public static class Queue {
|
||||
/** 是否启用 Redis Stream 调度 */
|
||||
private boolean enabled = true;
|
||||
private String streamPrefix = "import:task:stream";
|
||||
private String consumerGroup = "import-task-group";
|
||||
/** XREADGROUP 阻塞毫秒 */
|
||||
private long blockTimeoutMs = 5000;
|
||||
/** XAUTOCLAIM 最小空闲毫秒(PEL 回收) */
|
||||
private long claimIdleMs = 300_000;
|
||||
/** DB 对账周期毫秒 */
|
||||
private long reconcileIntervalMs = 60_000;
|
||||
/** processing 超时毫秒(心跳未更新则恢复) */
|
||||
private long stuckProcessingMs = 300_000;
|
||||
/** 对账分布式锁 TTL 秒 */
|
||||
private long reconcileLockSeconds = 55;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Worker {
|
||||
/** 各类型 worker 是否启用 */
|
||||
private Map<String, Boolean> typeEnabled = defaultTypeEnabled();
|
||||
/** 每类型并发线程数 */
|
||||
private int poolSizePerType = 1;
|
||||
|
||||
private static Map<String, Boolean> defaultTypeEnabled() {
|
||||
Map<String, Boolean> map = new LinkedHashMap<>();
|
||||
map.put("order", true);
|
||||
map.put("product", false);
|
||||
map.put("promotion_record", true);
|
||||
return map;
|
||||
}
|
||||
|
||||
public boolean isTypeEnabled(String type) {
|
||||
return typeEnabled.getOrDefault(type, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.config;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 导入任务 Redis Stream 命名。
|
||||
*/
|
||||
@Component
|
||||
public class ImportTaskStreamNames {
|
||||
|
||||
public static final List<String> ALL_TYPES = List.of("order", "product", "promotion_record");
|
||||
|
||||
private final ImportTaskProperties properties;
|
||||
|
||||
public ImportTaskStreamNames(ImportTaskProperties properties) {
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
public String streamKey(String type) {
|
||||
return properties.getQueue().getStreamPrefix() + ":" + type;
|
||||
}
|
||||
|
||||
public String consumerGroup() {
|
||||
return properties.getQueue().getConsumerGroup();
|
||||
}
|
||||
|
||||
public String reconcileLockKey() {
|
||||
return "import:task:reconcile:lock";
|
||||
}
|
||||
}
|
||||
-41
@@ -1,41 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.controller;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.model.dto.CreateImportTaskDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.model.dto.ImportTaskFilterDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.model.vo.ImportTaskVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.service.ImportTaskService;
|
||||
|
||||
/**
|
||||
* 导入任务管理控制器
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/ec/import/task")
|
||||
public class ImportTaskController {
|
||||
|
||||
private final ImportTaskService importTaskService;
|
||||
|
||||
public ImportTaskController(ImportTaskService importTaskService) {
|
||||
this.importTaskService = importTaskService;
|
||||
}
|
||||
|
||||
@PostMapping("/create")
|
||||
@RequirePermission(value = "data:import:create", description = "创建导入任务", allowSuper = true)
|
||||
public ApiResponse<ImportTaskVO> createImportTask(@Valid @RequestBody CreateImportTaskDTO createImportTaskDTO) {
|
||||
ImportTaskVO importTaskVO = importTaskService.createImportTask(createImportTaskDTO);
|
||||
return ApiResponse.success("导入任务创建成功", importTaskVO);
|
||||
}
|
||||
|
||||
@PostMapping("/list")
|
||||
@RequirePermission(value = "data:import:read", description = "查询导入任务列表", allowSuper = true)
|
||||
public ApiResponse<PageResultVO<ImportTaskVO>> getImportTaskPage(
|
||||
@Valid @RequestBody PageQueryDTO<ImportTaskFilterDTO> pageQueryDTO) {
|
||||
PageResultVO<ImportTaskVO> result = importTaskService.getImportTaskPage(pageQueryDTO);
|
||||
return ApiResponse.success("获取导入任务列表成功", result);
|
||||
}
|
||||
}
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.model.po.ImportTaskPO;
|
||||
|
||||
/**
|
||||
* 导入任务Mapper接口
|
||||
*/
|
||||
@Mapper
|
||||
public interface ImportTaskMapper extends BaseMapper<ImportTaskPO> {
|
||||
}
|
||||
|
||||
-44
@@ -1,44 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 创建导入任务DTO
|
||||
*/
|
||||
@Data
|
||||
public class CreateImportTaskDTO {
|
||||
|
||||
/**
|
||||
* 所属店铺ID
|
||||
*/
|
||||
@NotNull(message = "店铺ID不能为空")
|
||||
private Long shopId;
|
||||
|
||||
/**
|
||||
* 导入类型(product-商品 order-订单 promotion_record-推广记录)
|
||||
*/
|
||||
@NotBlank(message = "导入类型不能为空")
|
||||
@Pattern(regexp = "^(product|order|promotion_record)$", message = "导入类型只能是product、order或promotion_record")
|
||||
private String type;
|
||||
|
||||
/**
|
||||
* 原始文件名
|
||||
*/
|
||||
@NotBlank(message = "文件名不能为空")
|
||||
private String fileName;
|
||||
|
||||
/**
|
||||
* 关联文件ID(外键到sys_file)
|
||||
*/
|
||||
@NotNull(message = "文件ID不能为空")
|
||||
private Long fileId;
|
||||
|
||||
/**
|
||||
* 字段映射记录(JSON字符串)
|
||||
*/
|
||||
private String mapping;
|
||||
}
|
||||
|
||||
-31
@@ -1,31 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 导入任务过滤DTO
|
||||
*/
|
||||
@Data
|
||||
public class ImportTaskFilterDTO {
|
||||
|
||||
/**
|
||||
* 所属店铺ID
|
||||
*/
|
||||
private Long shopId;
|
||||
|
||||
/**
|
||||
* 导入类型(product-商品 order-订单)
|
||||
*/
|
||||
private String type;
|
||||
|
||||
/**
|
||||
* 任务状态
|
||||
*/
|
||||
private String status;
|
||||
|
||||
/**
|
||||
* 文件名(模糊查询)
|
||||
*/
|
||||
private String fileName;
|
||||
}
|
||||
|
||||
-43
@@ -1,43 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.model.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 订单导入映射配置(CSV 表头与订单字段、状态与状态ID 的映射)
|
||||
*/
|
||||
@Data
|
||||
public class OrderImportMappingConfig {
|
||||
|
||||
/**
|
||||
* 字段映射:CSV 表头 -> 订单字段
|
||||
*/
|
||||
@JsonProperty("fieldMapping")
|
||||
private List<FieldMappingItem> fieldMapping;
|
||||
|
||||
/**
|
||||
* 状态映射:CSV 状态文案 -> 订单状态码
|
||||
*/
|
||||
@JsonProperty("statusMapping")
|
||||
private List<StatusMappingItem> statusMapping;
|
||||
|
||||
@Data
|
||||
public static class FieldMappingItem {
|
||||
private Boolean required;
|
||||
/** 订单/实体字段名,如 sku_code, link_product_name */
|
||||
private String fieldName;
|
||||
private String fieldLabel;
|
||||
/** CSV 表头名称,如 商品、订单号 */
|
||||
private String fileFieldName;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class StatusMappingItem {
|
||||
/** CSV 中的状态文案,如 已发货,待收货 */
|
||||
private String csvStatus;
|
||||
/** 系统订单状态码 */
|
||||
private String mappedStatusCode;
|
||||
}
|
||||
}
|
||||
-117
@@ -1,117 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 订单导入单行数据(由 CSV 解析后按 fieldMapping 得到)
|
||||
*/
|
||||
@Data
|
||||
public class OrderImportRow {
|
||||
|
||||
/** 行号(从 1 开始,含表头则为数据行号) */
|
||||
private int rowIndex;
|
||||
|
||||
/** 字段名 -> 原始字符串值 */
|
||||
private Map<String, String> values;
|
||||
|
||||
public OrderImportRow(int rowIndex, Map<String, String> values) {
|
||||
this.rowIndex = rowIndex;
|
||||
this.values = values;
|
||||
}
|
||||
|
||||
public String get(String fieldName) {
|
||||
return values == null ? null : values.get(fieldName);
|
||||
}
|
||||
|
||||
public String getSkuCode() {
|
||||
String v = get("sku_code");
|
||||
return v != null ? v : get("spec_code");
|
||||
}
|
||||
|
||||
public String getLinkProductName() {
|
||||
return get("link_product_name");
|
||||
}
|
||||
|
||||
public String getProductCode() {
|
||||
return get("product_code");
|
||||
}
|
||||
|
||||
public String getPlatformOrderNo() {
|
||||
return get("platform_order_no");
|
||||
}
|
||||
|
||||
public String getLinkSkuName() {
|
||||
return get("link_spec_name");
|
||||
}
|
||||
|
||||
public String getStatusText() {
|
||||
return get("status");
|
||||
}
|
||||
|
||||
/** 根据 statusMapping 将 CSV 状态文案解析为订单状态码 */
|
||||
public String getMappedStatusCode(List<OrderImportMappingConfig.StatusMappingItem> statusMapping) {
|
||||
String text = getStatusText();
|
||||
if (text == null || text.isBlank() || statusMapping == null) {
|
||||
return null;
|
||||
}
|
||||
String trimmed = text.trim();
|
||||
for (OrderImportMappingConfig.StatusMappingItem item : statusMapping) {
|
||||
if (trimmed.equals(item.getCsvStatus() != null ? item.getCsvStatus().trim() : null)) {
|
||||
return item.getMappedStatusCode();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public Integer getProductQuantity() {
|
||||
String v = get("product_quantity");
|
||||
if (v == null || v.isBlank()) return null;
|
||||
try {
|
||||
return Integer.parseInt(v.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public BigDecimal getReceivedAmount() {
|
||||
String v = get("received_amount");
|
||||
if (v == null || v.isBlank()) return null;
|
||||
try {
|
||||
return new BigDecimal(v.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 下单时间,支持常见格式 */
|
||||
public LocalDateTime getOrderTime() {
|
||||
String v = get("order_time");
|
||||
if (v == null || v.isBlank()) return null;
|
||||
v = v.trim();
|
||||
DateTimeFormatter[] formatters = new DateTimeFormatter[]{
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"),
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"),
|
||||
DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"),
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"),
|
||||
DateTimeFormatter.ISO_LOCAL_DATE_TIME
|
||||
};
|
||||
for (DateTimeFormatter f : formatters) {
|
||||
try {
|
||||
return LocalDateTime.parse(v, f);
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
try {
|
||||
return LocalDate.parse(v, DateTimeFormatter.ISO_LOCAL_DATE).atStartOfDay();
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
-155
@@ -1,155 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 导入任务实体
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@TableName("ec_import_tasks")
|
||||
public class ImportTaskPO {
|
||||
|
||||
/**
|
||||
* 主键ID
|
||||
*/
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
* 所属公司ID
|
||||
*/
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
/**
|
||||
* 所属店铺ID
|
||||
*/
|
||||
@TableField("shop_id")
|
||||
private Long shopId;
|
||||
|
||||
/**
|
||||
* 导入类型(product-商品 order-订单)
|
||||
*/
|
||||
@TableField("type")
|
||||
private String type;
|
||||
|
||||
/**
|
||||
* 任务名称
|
||||
*/
|
||||
@TableField("task_name")
|
||||
private String taskName;
|
||||
|
||||
/**
|
||||
* 原始文件名
|
||||
*/
|
||||
@TableField("file_name")
|
||||
private String fileName;
|
||||
|
||||
/**
|
||||
* 关联文件ID(外键到sys_file)
|
||||
*/
|
||||
@TableField("file_id")
|
||||
private Long fileId;
|
||||
|
||||
/**
|
||||
* 任务状态(pending-待处理 processing-处理中 success-成功 failed-失败)
|
||||
*/
|
||||
@TableField("status")
|
||||
private String status;
|
||||
|
||||
/**
|
||||
* 总行数
|
||||
*/
|
||||
@TableField("total_count")
|
||||
private Integer totalCount;
|
||||
|
||||
/**
|
||||
* 成功行数
|
||||
*/
|
||||
@TableField("success_count")
|
||||
private Integer successCount;
|
||||
|
||||
/**
|
||||
* 失败行数
|
||||
*/
|
||||
@TableField("fail_count")
|
||||
private Integer failCount;
|
||||
|
||||
/**
|
||||
* 字段映射记录(JSON)
|
||||
*/
|
||||
@TableField("mapping")
|
||||
private String mapping;
|
||||
|
||||
/**
|
||||
* 错误信息或备注
|
||||
*/
|
||||
@TableField("message")
|
||||
private String message;
|
||||
|
||||
/**
|
||||
* 开始处理时间
|
||||
*/
|
||||
@TableField("started_at")
|
||||
private LocalDateTime startedAt;
|
||||
|
||||
/**
|
||||
* 最后心跳时间
|
||||
*/
|
||||
@TableField("last_heartbeat_at")
|
||||
private LocalDateTime lastHeartbeatAt;
|
||||
|
||||
/**
|
||||
* 处理实例标识
|
||||
*/
|
||||
@TableField("worker_id")
|
||||
private String workerId;
|
||||
|
||||
/**
|
||||
* 入队 Stream Key
|
||||
*/
|
||||
@TableField("redis_stream_key")
|
||||
private String redisStreamKey;
|
||||
|
||||
/**
|
||||
* Redis Stream 消息 ID
|
||||
*/
|
||||
@TableField("redis_message_id")
|
||||
private String redisMessageId;
|
||||
|
||||
/**
|
||||
* 入队状态:pending_enqueue / enqueued / enqueue_failed
|
||||
*/
|
||||
@TableField("enqueue_status")
|
||||
private String enqueueStatus;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
/**
|
||||
* 更新时间
|
||||
*/
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
|
||||
/**
|
||||
* 创建人ID
|
||||
*/
|
||||
@TableField("create_by")
|
||||
private Long createBy;
|
||||
|
||||
/**
|
||||
* 更新人ID
|
||||
*/
|
||||
@TableField("update_by")
|
||||
private Long updateBy;
|
||||
}
|
||||
|
||||
-103
@@ -1,103 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 导入任务VO
|
||||
*/
|
||||
@Data
|
||||
public class ImportTaskVO {
|
||||
|
||||
/**
|
||||
* 主键ID
|
||||
*/
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
* 所属公司ID
|
||||
*/
|
||||
private Long companyId;
|
||||
|
||||
/**
|
||||
* 所属店铺ID
|
||||
*/
|
||||
private Long shopId;
|
||||
|
||||
/**
|
||||
* 所属店铺名称
|
||||
*/
|
||||
private String shopName;
|
||||
|
||||
/**
|
||||
* 导入类型(product-商品 order-订单)
|
||||
*/
|
||||
private String type;
|
||||
|
||||
/**
|
||||
* 任务名称
|
||||
*/
|
||||
private String taskName;
|
||||
|
||||
/**
|
||||
* 原始文件名
|
||||
*/
|
||||
private String fileName;
|
||||
|
||||
/**
|
||||
* 关联文件ID
|
||||
*/
|
||||
private Long fileId;
|
||||
|
||||
/**
|
||||
* 任务状态
|
||||
*/
|
||||
private String status;
|
||||
|
||||
/**
|
||||
* 总行数
|
||||
*/
|
||||
private Integer totalCount;
|
||||
|
||||
/**
|
||||
* 成功行数
|
||||
*/
|
||||
private Integer successCount;
|
||||
|
||||
/**
|
||||
* 失败行数
|
||||
*/
|
||||
private Integer failCount;
|
||||
|
||||
/**
|
||||
* 字段映射记录(JSON字符串)
|
||||
*/
|
||||
private String mapping;
|
||||
|
||||
/**
|
||||
* 错误信息或备注
|
||||
*/
|
||||
private String message;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
private LocalDateTime createTime;
|
||||
|
||||
/**
|
||||
* 更新时间
|
||||
*/
|
||||
private LocalDateTime updateTime;
|
||||
|
||||
/**
|
||||
* 创建人ID
|
||||
*/
|
||||
private Long createBy;
|
||||
|
||||
/**
|
||||
* 更新人ID
|
||||
*/
|
||||
private Long updateBy;
|
||||
}
|
||||
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.queue;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.net.InetAddress;
|
||||
|
||||
/**
|
||||
* 生成当前 JVM 唯一的 Stream 消费者名。
|
||||
*/
|
||||
@Component
|
||||
public class ImportTaskConsumerNameFactory {
|
||||
|
||||
private final String consumerName;
|
||||
|
||||
public ImportTaskConsumerNameFactory() {
|
||||
String host = "unknown";
|
||||
try {
|
||||
host = InetAddress.getLocalHost().getHostName();
|
||||
} catch (Exception ignored) {
|
||||
// 使用默认 host
|
||||
}
|
||||
long pid = ProcessHandle.current().pid();
|
||||
this.consumerName = "import-task-" + host + "-" + pid;
|
||||
}
|
||||
|
||||
public String current() {
|
||||
return consumerName;
|
||||
}
|
||||
}
|
||||
-48
@@ -1,48 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.queue;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Redis Stream 消息体(仅 taskId + type)。
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ImportTaskQueueMessage {
|
||||
|
||||
private Long taskId;
|
||||
private String type;
|
||||
|
||||
public Map<String, String> toStreamBody() {
|
||||
Map<String, String> body = new HashMap<>();
|
||||
body.put("taskId", String.valueOf(taskId));
|
||||
body.put("type", type);
|
||||
body.put("enqueueAt", String.valueOf(System.currentTimeMillis()));
|
||||
return body;
|
||||
}
|
||||
|
||||
public static ImportTaskQueueMessage fromStreamBody(Map<Object, Object> body) {
|
||||
if (body == null || body.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
String taskIdStr = stringValue(body.get("taskId"));
|
||||
String type = stringValue(body.get("type"));
|
||||
if (taskIdStr == null || type == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return new ImportTaskQueueMessage(Long.parseLong(taskIdStr), type);
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static String stringValue(Object value) {
|
||||
return value == null ? null : String.valueOf(value);
|
||||
}
|
||||
}
|
||||
-144
@@ -1,144 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.queue;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.data.domain.Range;
|
||||
import org.springframework.data.redis.connection.RedisStreamCommands;
|
||||
import org.springframework.data.redis.connection.stream.*;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Redis Stream 薄封装:入队、消费、ACK、PEL 回收。
|
||||
*/
|
||||
@Component
|
||||
public class ImportTaskRedisQueue {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ImportTaskRedisQueue.class);
|
||||
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
|
||||
public ImportTaskRedisQueue(StringRedisTemplate stringRedisTemplate) {
|
||||
this.stringRedisTemplate = stringRedisTemplate;
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保消费组存在(MKSTREAM)。组已存在时静默忽略(BUSYGROUP)。
|
||||
*/
|
||||
public void ensureConsumerGroup(String streamKey, String groupName) {
|
||||
try {
|
||||
stringRedisTemplate.opsForStream().createGroup(streamKey, groupName);
|
||||
log.info("创建导入任务 Stream 消费组: stream={}, group={}", streamKey, groupName);
|
||||
} catch (DataAccessException e) {
|
||||
if (isBusyGroupException(e)) {
|
||||
return;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** Spring/Lettuce 常把 BUSYGROUP 包在 cause 链里,顶层 message 未必包含关键字。 */
|
||||
private boolean isBusyGroupException(Throwable throwable) {
|
||||
Throwable current = throwable;
|
||||
while (current != null) {
|
||||
String msg = current.getMessage();
|
||||
if (msg != null && (msg.contains("BUSYGROUP") || msg.contains("already exists"))) {
|
||||
return true;
|
||||
}
|
||||
current = current.getCause();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 入队并返回 messageId。
|
||||
*/
|
||||
public String enqueue(String streamKey, ImportTaskQueueMessage message) {
|
||||
MapRecord<String, String, String> record = StreamRecords.string(message.toStreamBody())
|
||||
.withStreamKey(streamKey);
|
||||
RecordId recordId = stringRedisTemplate.opsForStream().add(record);
|
||||
return recordId.getValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* 阻塞读取新消息(>)。
|
||||
*/
|
||||
public List<ImportTaskStreamRecord> readNew(String streamKey, String groupName, String consumerName, long blockMs) {
|
||||
StreamOffset<String> offset = StreamOffset.create(streamKey, ReadOffset.lastConsumed());
|
||||
List<MapRecord<String, Object, Object>> records = readGroup(
|
||||
Consumer.from(groupName, consumerName),
|
||||
StreamReadOptions.empty().count(10).block(Duration.ofMillis(Math.max(1, blockMs))),
|
||||
offset);
|
||||
return toRecords(streamKey, records);
|
||||
}
|
||||
|
||||
/** 封装 varargs 调用,避免泛型数组类型安全警告。 */
|
||||
@SafeVarargs
|
||||
private final List<MapRecord<String, Object, Object>> readGroup(
|
||||
Consumer consumer,
|
||||
StreamReadOptions options,
|
||||
StreamOffset<String>... offsets) {
|
||||
return stringRedisTemplate.opsForStream().read(consumer, options, offsets);
|
||||
}
|
||||
|
||||
/**
|
||||
* 回收超时 PEL 消息:先 XPENDING 再 XCLAIM(当前 Spring Data Redis 无 XAUTOCLAIM 封装)。
|
||||
*/
|
||||
public List<ImportTaskStreamRecord> autoClaim(String streamKey, String groupName, String consumerName, long minIdleMs) {
|
||||
try {
|
||||
Duration minIdle = Duration.ofMillis(Math.max(1, minIdleMs));
|
||||
PendingMessages pending = stringRedisTemplate.opsForStream()
|
||||
.pending(streamKey, groupName, Range.unbounded(), 10);
|
||||
if (pending == null || pending.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
String[] staleIds = pending.stream()
|
||||
.filter(pm -> !pm.getElapsedTimeSinceLastDelivery().minus(minIdle).isNegative())
|
||||
.map(PendingMessage::getIdAsString)
|
||||
.toArray(String[]::new);
|
||||
if (staleIds.length == 0) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
List<MapRecord<String, Object, Object>> claimed = stringRedisTemplate.opsForStream().claim(
|
||||
streamKey,
|
||||
groupName,
|
||||
consumerName,
|
||||
RedisStreamCommands.XClaimOptions.minIdle(minIdle).ids(staleIds));
|
||||
return toRecords(streamKey, claimed);
|
||||
} catch (Exception e) {
|
||||
log.warn("XCLAIM 回收 PEL 失败 stream={}: {}", streamKey, e.getMessage());
|
||||
return Collections.emptyList();
|
||||
}
|
||||
}
|
||||
|
||||
public void ack(String streamKey, String groupName, String messageId) {
|
||||
stringRedisTemplate.opsForStream().acknowledge(streamKey, groupName, messageId);
|
||||
}
|
||||
|
||||
public long streamLength(String streamKey) {
|
||||
Long len = stringRedisTemplate.opsForStream().size(streamKey);
|
||||
return len == null ? 0 : len;
|
||||
}
|
||||
|
||||
private List<ImportTaskStreamRecord> toRecords(String streamKey, List<MapRecord<String, Object, Object>> records) {
|
||||
if (records == null || records.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
List<ImportTaskStreamRecord> result = new ArrayList<>();
|
||||
for (MapRecord<String, Object, Object> record : records) {
|
||||
ImportTaskQueueMessage message = ImportTaskQueueMessage.fromStreamBody(record.getValue());
|
||||
if (message == null) {
|
||||
log.warn("忽略无效 Stream 消息: stream={}, id={}", streamKey, record.getId());
|
||||
continue;
|
||||
}
|
||||
result.add(new ImportTaskStreamRecord(streamKey, record.getId().getValue(), message));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.queue;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 从 Redis Stream 读取到的一条记录。
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class ImportTaskStreamRecord {
|
||||
|
||||
private String streamKey;
|
||||
private String messageId;
|
||||
private ImportTaskQueueMessage message;
|
||||
}
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.service;
|
||||
|
||||
/**
|
||||
* 导入任务消费者服务接口
|
||||
*/
|
||||
public interface ImportTaskConsumerService {
|
||||
|
||||
/**
|
||||
* 启动消费者
|
||||
*/
|
||||
void startConsumers();
|
||||
|
||||
/**
|
||||
* 停止消费者
|
||||
*/
|
||||
void stopConsumers();
|
||||
}
|
||||
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.service;
|
||||
|
||||
/**
|
||||
* 导入任务处理器服务接口
|
||||
*/
|
||||
public interface ImportTaskProcessorService {
|
||||
|
||||
/**
|
||||
* 处理导入任务
|
||||
*
|
||||
* @param taskId 任务ID
|
||||
*/
|
||||
void processImportTask(Long taskId);
|
||||
}
|
||||
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.service;
|
||||
|
||||
/**
|
||||
* 导入任务队列服务接口
|
||||
*/
|
||||
public interface ImportTaskQueueService {
|
||||
|
||||
/**
|
||||
* 发布导入任务到队列
|
||||
*
|
||||
* @param taskId 任务ID
|
||||
*/
|
||||
void publishImportTask(Long taskId);
|
||||
}
|
||||
|
||||
-51
@@ -1,51 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.service;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.model.dto.CreateImportTaskDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.model.dto.ImportTaskFilterDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.model.po.ImportTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.model.vo.ImportTaskVO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 导入任务服务接口
|
||||
*/
|
||||
public interface ImportTaskService extends IService<ImportTaskPO> {
|
||||
|
||||
ImportTaskVO createImportTask(CreateImportTaskDTO createImportTaskDTO);
|
||||
|
||||
PageResultVO<ImportTaskVO> getImportTaskPage(PageQueryDTO<ImportTaskFilterDTO> pageQueryDTO);
|
||||
|
||||
/**
|
||||
* 消费端抢锁:仅 pending 可转为 processing(幂等)。
|
||||
*/
|
||||
ImportTaskPO tryClaimForProcessing(Long taskId, String workerId);
|
||||
|
||||
/**
|
||||
* 标记任务失败
|
||||
*/
|
||||
void markFailed(Long taskId, String message);
|
||||
|
||||
/**
|
||||
* 刷新长任务心跳
|
||||
*/
|
||||
void touchHeartbeat(Long taskId);
|
||||
|
||||
/**
|
||||
* 查询需要补入队的 pending 任务
|
||||
*/
|
||||
List<ImportTaskPO> listPendingEnqueueTasks();
|
||||
|
||||
/**
|
||||
* 查询 processing 超时任务
|
||||
*/
|
||||
List<ImportTaskPO> listStuckProcessingTasks(long stuckThresholdMs);
|
||||
|
||||
/**
|
||||
* 重置为 pending 并等待对账入队
|
||||
*/
|
||||
void resetToPendingForRecovery(Long taskId, String message);
|
||||
}
|
||||
-280
@@ -1,280 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.service.impl;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderItemPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.model.po.ProductSkuPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopProductRelationPO;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
/**
|
||||
* 导入运行时上下文(贯穿整个导入过程)
|
||||
* <p>
|
||||
* 所有共享类型(内部类/枚举)也定义在此文件,避免循环依赖。
|
||||
* <p>
|
||||
* 线程安全:并行导入时,多个 Worker 线程并发读写集合,
|
||||
* 故缓存Map/Set使用 ConcurrentHashMap / ConcurrentHashMap.newKeySet(),
|
||||
* pendingOrders 使用 CopyOnWriteArrayList(写时复制,并行添加,flush时整体替换)。
|
||||
*/
|
||||
public class ImportRuntimeContext {
|
||||
|
||||
// ==================== 共享类型 ====================
|
||||
|
||||
/**
|
||||
* 字段映射定义
|
||||
*/
|
||||
public static class MappingField {
|
||||
private Boolean required;
|
||||
private String fieldName;
|
||||
private String fieldLabel;
|
||||
private String fileFieldName;
|
||||
|
||||
public MappingField() {}
|
||||
|
||||
public Boolean getRequired() { return required; }
|
||||
public void setRequired(Boolean required) { this.required = required; }
|
||||
public String getFieldName() { return fieldName; }
|
||||
public void setFieldName(String fieldName) { this.fieldName = fieldName; }
|
||||
public String getFieldLabel() { return fieldLabel; }
|
||||
public void setFieldLabel(String fieldLabel) { this.fieldLabel = fieldLabel; }
|
||||
public String getFileFieldName() { return fileFieldName; }
|
||||
public void setFileFieldName(String fileFieldName) { this.fileFieldName = fileFieldName; }
|
||||
}
|
||||
|
||||
/**
|
||||
* 状态映射定义
|
||||
*/
|
||||
public static class StatusMapping {
|
||||
private String csvStatus;
|
||||
private String mappedStatusCode;
|
||||
|
||||
public StatusMapping() {}
|
||||
|
||||
public String getCsvStatus() { return csvStatus; }
|
||||
public void setCsvStatus(String csvStatus) { this.csvStatus = csvStatus; }
|
||||
public String getMappedStatusCode() { return mappedStatusCode; }
|
||||
public void setMappedStatusCode(String mappedStatusCode) { this.mappedStatusCode = mappedStatusCode; }
|
||||
}
|
||||
|
||||
/**
|
||||
* 映射配置
|
||||
*/
|
||||
public static class MappingConfig {
|
||||
private List<MappingField> fieldMapping;
|
||||
private List<StatusMapping> statusMapping;
|
||||
|
||||
public MappingConfig() {}
|
||||
|
||||
public List<MappingField> getFieldMapping() { return fieldMapping; }
|
||||
public void setFieldMapping(List<MappingField> fieldMapping) { this.fieldMapping = fieldMapping; }
|
||||
public List<StatusMapping> getStatusMapping() { return statusMapping; }
|
||||
public void setStatusMapping(List<StatusMapping> statusMapping) { this.statusMapping = statusMapping; }
|
||||
}
|
||||
|
||||
/**
|
||||
* 待插入订单包装器
|
||||
*/
|
||||
public static class PendingOrderInsert {
|
||||
public int rowNumber;
|
||||
public String platformOrderNo;
|
||||
public OrderPO order;
|
||||
public OrderItemPO item;
|
||||
/**
|
||||
* 该导入行输入的 order_time 是否为空(仅用于更新跳过策略)。
|
||||
* <p>
|
||||
* 创建阶段不受此字段影响:创建时仍会用邻近行或本行解析出的下单时间写入。
|
||||
*/
|
||||
public boolean orderTimeEmptyInInput;
|
||||
public Long existingOrderId; // 不为空表示是更新操作
|
||||
public StringBuilder updateMessages;
|
||||
|
||||
public PendingOrderInsert(int rowNumber, String platformOrderNo, OrderPO order, OrderItemPO item,
|
||||
Long existingOrderId, StringBuilder updateMessages,
|
||||
boolean orderTimeEmptyInInput) {
|
||||
this.rowNumber = rowNumber;
|
||||
this.platformOrderNo = platformOrderNo;
|
||||
this.order = order;
|
||||
this.item = item;
|
||||
this.orderTimeEmptyInInput = orderTimeEmptyInInput;
|
||||
this.existingOrderId = existingOrderId;
|
||||
this.updateMessages = updateMessages;
|
||||
}
|
||||
|
||||
public void updateData(OrderPO newOrder, OrderItemPO newItem, Long newExistingOrderId,
|
||||
StringBuilder newUpdateMsg, int newRowNumber,
|
||||
boolean newOrderTimeEmptyInInput) {
|
||||
this.order = newOrder;
|
||||
this.item = newItem;
|
||||
this.rowNumber = newRowNumber;
|
||||
if (newExistingOrderId != null) this.existingOrderId = newExistingOrderId;
|
||||
if (newUpdateMsg != null && newUpdateMsg.length() > 0) this.updateMessages = newUpdateMsg;
|
||||
this.orderTimeEmptyInInput = newOrderTimeEmptyInInput;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 日期时间格式定义
|
||||
*/
|
||||
public static class DateTimeFormatPattern {
|
||||
public final String pattern;
|
||||
public final java.time.format.DateTimeFormatter formatter;
|
||||
public final boolean hasTime;
|
||||
|
||||
public DateTimeFormatPattern(String pattern, boolean hasTime) {
|
||||
this.pattern = pattern;
|
||||
this.formatter = java.time.format.DateTimeFormatter.ofPattern(pattern);
|
||||
this.hasTime = hasTime;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 导入结果
|
||||
*/
|
||||
public static class ImportResult {
|
||||
public int totalCount;
|
||||
public int successCount;
|
||||
public int failCount;
|
||||
public int insertCount;
|
||||
/** 实际执行了 UPDATE 的条数(与库中快照比较有变更) */
|
||||
public int updateCount;
|
||||
/** 已存在订单且内容一致,跳过 UPDATE 的条数 */
|
||||
public int existingUnchangedCount;
|
||||
/** 同一导入文件内按平台订单号合并(后者覆盖前者)的条数 */
|
||||
public int mergedDuplicatePlatformNoCount;
|
||||
/** 已存在订单但 UPDATE 失败的条数 */
|
||||
public int updateDbFailCount;
|
||||
public StringBuilder errorMessages = new StringBuilder();
|
||||
}
|
||||
|
||||
// ==================== 上下文字段(线程安全) ====================
|
||||
|
||||
private final Long companyId;
|
||||
private final Long shopId;
|
||||
private final Long createBy;
|
||||
private final Long taskId;
|
||||
|
||||
private DateTimeFormatPattern detectedDatePattern;
|
||||
|
||||
// 缓存:只读(预加载后不再写入),使用 ConcurrentHashMap 确保 workers 并行读取安全
|
||||
final ConcurrentHashMap<String, ProductSkuPO> skuByCodeCache = new ConcurrentHashMap<>();
|
||||
final ConcurrentHashMap<String, ProductPO> productByCodeCache = new ConcurrentHashMap<>();
|
||||
final ConcurrentHashMap<String, ProductPO> productByNameCache = new ConcurrentHashMap<>();
|
||||
final ConcurrentHashMap<Long, ProductPO> productByIdCache = new ConcurrentHashMap<>();
|
||||
final ConcurrentHashMap<String, String> statusCodeByNameCache = new ConcurrentHashMap<>();
|
||||
|
||||
// 已存在于 DB 的数据:预加载时填充(只写一次),后续只读
|
||||
final Set<String> existingPlatformOrderNos = ConcurrentHashMap.newKeySet();
|
||||
final Map<String, Long> existingOrderIdByPlatformNo = new ConcurrentHashMap<>();
|
||||
/** 平台订单号(规范化) → 库中订单业务字段快照;成功 UPDATE 后由主线程替换为新快照 */
|
||||
final ConcurrentHashMap<String, OrderImportSnapshot> existingOrderSnapshotByPlatformNo = new ConcurrentHashMap<>();
|
||||
final Set<String> existingRelationKeys = ConcurrentHashMap.newKeySet();
|
||||
|
||||
// pendingOrders:由 workers 并发添加(CopyOnWriteArrayList 读多写少场景高效)
|
||||
final CopyOnWriteArrayList<PendingOrderInsert> pendingOrders = new CopyOnWriteArrayList<>();
|
||||
// pendingOrderByPlatformNo:workers 并发 put,flush 时读取并清空
|
||||
final Map<String, PendingOrderInsert> pendingOrderByPlatformNo = Collections.synchronizedMap(new HashMap<>());
|
||||
// pendingPlatformOrderNos:workers 并发 add,flush 时读取并清空
|
||||
final Set<String> pendingPlatformOrderNos = Collections.synchronizedSet(new HashSet<>());
|
||||
|
||||
// pendingRelations:workers 并发添加,flush 时整体替换
|
||||
final CopyOnWriteArrayList<ShopProductRelationPO> pendingRelations = new CopyOnWriteArrayList<>();
|
||||
final Set<String> pendingRelationKeys = Collections.synchronizedSet(new HashSet<>());
|
||||
// 已处理的行数(workers 并发 +1,主线程读取用于推送进度)
|
||||
final AtomicInteger processedCount = new AtomicInteger(0);
|
||||
// 同一导入文件内重复平台订单号被合并的条数
|
||||
final AtomicInteger mergedDuplicatePlatformNoCount = new AtomicInteger(0);
|
||||
// 总行数(主线程设置,workers 读取用于回调)
|
||||
volatile int totalCount = 0;
|
||||
// 进度回调(主线程设置,workers 调用,线程安全包装)
|
||||
transient volatile BiConsumer<Integer, Integer> progressCallback;
|
||||
|
||||
/** 本任务涉及的自然日(订单统计已移除,保留空实现供导入流程调用) */
|
||||
public void markOrderStatDirty(LocalDateTime orderTime) {
|
||||
// no-op
|
||||
}
|
||||
|
||||
public void markOrderStatDirty(Long targetShopId, LocalDateTime orderTime) {
|
||||
// no-op
|
||||
}
|
||||
|
||||
/** 更新订单时标记旧快照日期(订单统计已移除,空实现) */
|
||||
public void markOrderStatDirtyFromSnapshot(OrderPO before) {
|
||||
// no-op
|
||||
}
|
||||
|
||||
/** 本次订单导入的字段映射(仅主线程在 process 入口设置,用于「有变更才更新」时按映射比较) */
|
||||
private transient Map<String, MappingField> orderImportFieldMapping;
|
||||
|
||||
/** 线程安全的进度回调(防止多 worker 并发调用) */
|
||||
public void reportProgress(int total, int done) {
|
||||
BiConsumer<Integer, Integer> cb = this.progressCallback;
|
||||
if (cb != null) {
|
||||
synchronized (this) {
|
||||
cb.accept(total, done);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public ImportRuntimeContext(Long companyId, Long shopId, Long createBy, Long taskId) {
|
||||
this.companyId = companyId;
|
||||
this.shopId = shopId;
|
||||
this.createBy = createBy;
|
||||
this.taskId = taskId;
|
||||
}
|
||||
|
||||
public Long getCompanyId() { return companyId; }
|
||||
public Long getShopId() { return shopId; }
|
||||
public Long getCreateBy() { return createBy; }
|
||||
public Long getTaskId() { return taskId; }
|
||||
public DateTimeFormatPattern getDetectedDatePattern() { return detectedDatePattern; }
|
||||
public void setDetectedDatePattern(DateTimeFormatPattern detectedDatePattern) { this.detectedDatePattern = detectedDatePattern; }
|
||||
|
||||
public void setOrderImportFieldMapping(Map<String, MappingField> orderImportFieldMapping) {
|
||||
this.orderImportFieldMapping = orderImportFieldMapping;
|
||||
}
|
||||
|
||||
/** 无变更比较用;未设置时视为空映射(仅比较公司/店铺/状态) */
|
||||
public Map<String, MappingField> getOrderImportFieldMapping() {
|
||||
return orderImportFieldMapping != null ? orderImportFieldMapping : Collections.emptyMap();
|
||||
}
|
||||
public Map<String, ProductSkuPO> getSpecByCodeCache() { return skuByCodeCache; }
|
||||
public Map<String, ProductPO> getProductByCodeCache() { return productByCodeCache; }
|
||||
public Map<String, ProductPO> getProductByNameCache() { return productByNameCache; }
|
||||
public Map<Long, ProductPO> getProductByIdCache() { return productByIdCache; }
|
||||
public Map<String, String> getStatusCodeByNameCache() { return statusCodeByNameCache; }
|
||||
public Set<String> getExistingPlatformOrderNos() { return existingPlatformOrderNos; }
|
||||
public Map<String, Long> getExistingOrderIdByPlatformNo() { return existingOrderIdByPlatformNo; }
|
||||
public Map<String, OrderImportSnapshot> getExistingOrderSnapshotByPlatformNo() { return existingOrderSnapshotByPlatformNo; }
|
||||
public Set<String> getExistingRelationKeys() { return existingRelationKeys; }
|
||||
public List<PendingOrderInsert> getPendingOrders() { return pendingOrders; }
|
||||
public Map<String, PendingOrderInsert> getPendingOrderByPlatformNo() { return pendingOrderByPlatformNo; }
|
||||
public List<ShopProductRelationPO> getPendingRelations() { return pendingRelations; }
|
||||
public Set<String> getPendingRelationKeys() { return pendingRelationKeys; }
|
||||
public Set<String> getPendingPlatformOrderNos() { return pendingPlatformOrderNos; }
|
||||
|
||||
public void addNormalizedValue(Set<String> target, String rawValue) {
|
||||
if (rawValue == null) return;
|
||||
String value = rawValue.trim();
|
||||
if (!value.isEmpty()) target.add(value);
|
||||
}
|
||||
|
||||
public String buildRelationKey(Long shopId, Long productId) {
|
||||
return shopId + "#" + productId;
|
||||
}
|
||||
|
||||
public static <T> List<List<T>> splitToChunks(Set<T> values, int chunkSize) {
|
||||
if (values == null || values.isEmpty()) return Collections.emptyList();
|
||||
List<T> all = new ArrayList<>(values);
|
||||
List<List<T>> chunks = new ArrayList<>();
|
||||
for (int i = 0; i < all.size(); i += chunkSize) {
|
||||
chunks.add(all.subList(i, Math.min(i + chunkSize, all.size())));
|
||||
}
|
||||
return chunks;
|
||||
}
|
||||
}
|
||||
-219
@@ -1,219 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.service.impl;
|
||||
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.config.ImportTaskProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.config.ImportTaskStreamNames;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.model.po.ImportTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.queue.ImportTaskConsumerNameFactory;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.queue.ImportTaskRedisQueue;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.queue.ImportTaskStreamRecord;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.service.ImportTaskConsumerService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.service.ImportTaskProcessorService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.service.ImportTaskService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.worker.ImportTaskRecoveryService;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/**
|
||||
* 导入任务消费者:Redis Stream + DB 状态机。
|
||||
*/
|
||||
@Service
|
||||
public class ImportTaskConsumerServiceImpl implements ImportTaskConsumerService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ImportTaskConsumerServiceImpl.class);
|
||||
|
||||
private final ImportTaskService importTaskService;
|
||||
private final ImportTaskProcessorService importTaskProcessorService;
|
||||
private final ImportTaskRedisQueue redisQueue;
|
||||
private final ImportTaskStreamNames streamNames;
|
||||
private final ImportTaskProperties properties;
|
||||
private final ImportTaskRecoveryService recoveryService;
|
||||
|
||||
private ExecutorService executorService;
|
||||
private final AtomicBoolean running = new AtomicBoolean(false);
|
||||
private final String consumerName;
|
||||
|
||||
public ImportTaskConsumerServiceImpl(ImportTaskService importTaskService,
|
||||
ImportTaskProcessorService importTaskProcessorService,
|
||||
ImportTaskRedisQueue redisQueue,
|
||||
ImportTaskStreamNames streamNames,
|
||||
ImportTaskProperties properties,
|
||||
ImportTaskConsumerNameFactory consumerNameFactory,
|
||||
ImportTaskRecoveryService recoveryService) {
|
||||
this.importTaskService = importTaskService;
|
||||
this.importTaskProcessorService = importTaskProcessorService;
|
||||
this.redisQueue = redisQueue;
|
||||
this.streamNames = streamNames;
|
||||
this.properties = properties;
|
||||
this.recoveryService = recoveryService;
|
||||
this.consumerName = consumerNameFactory.current();
|
||||
}
|
||||
|
||||
/**
|
||||
* 等 Web 容器就绪后再启动消费者,避免端口占用等启动失败时 Redis 长阻塞连接被强制断开。
|
||||
*/
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void onApplicationReady() {
|
||||
if (!properties.getQueue().isEnabled()) {
|
||||
log.warn("导入任务 Redis 队列未启用,消费者不启动");
|
||||
return;
|
||||
}
|
||||
log.info("初始化导入任务 Redis Stream 消费者,consumer={}", consumerName);
|
||||
recoveryService.recoverOnStartup();
|
||||
startConsumers();
|
||||
log.info("导入任务消费者初始化完成");
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void destroy() {
|
||||
stopConsumers();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startConsumers() {
|
||||
if (!properties.getQueue().isEnabled()) {
|
||||
return;
|
||||
}
|
||||
if (running.compareAndSet(false, true)) {
|
||||
int totalThreads = 0;
|
||||
List<Runnable> tasks = new ArrayList<>();
|
||||
for (String type : ImportTaskStreamNames.ALL_TYPES) {
|
||||
if (!properties.getWorker().isTypeEnabled(type)) {
|
||||
log.info("导入任务类型 {} 的 worker 已禁用", type);
|
||||
continue;
|
||||
}
|
||||
String streamKey = streamNames.streamKey(type);
|
||||
redisQueue.ensureConsumerGroup(streamKey, streamNames.consumerGroup());
|
||||
int pool = Math.max(1, properties.getWorker().getPoolSizePerType());
|
||||
for (int i = 0; i < pool; i++) {
|
||||
String threadConsumer = consumerName + "-" + type + "-" + i;
|
||||
tasks.add(() -> consumeLoop(streamKey, type, threadConsumer));
|
||||
totalThreads++;
|
||||
}
|
||||
}
|
||||
executorService = Executors.newFixedThreadPool(Math.max(1, totalThreads));
|
||||
for (Runnable task : tasks) {
|
||||
executorService.submit(task);
|
||||
}
|
||||
log.info("导入任务 Redis Stream 消费者已启动,threads={}", totalThreads);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stopConsumers() {
|
||||
if (running.compareAndSet(true, false)) {
|
||||
log.info("停止导入任务消费者...");
|
||||
if (executorService != null) {
|
||||
executorService.shutdown();
|
||||
try {
|
||||
if (!executorService.awaitTermination(30, TimeUnit.SECONDS)) {
|
||||
executorService.shutdownNow();
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
executorService.shutdownNow();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
log.info("导入任务消费者已停止");
|
||||
}
|
||||
}
|
||||
|
||||
private void consumeLoop(String streamKey, String type, String threadConsumer) {
|
||||
log.info("开始消费 {} 导入任务,stream={}, consumer={}", type, streamKey, threadConsumer);
|
||||
long blockMs = properties.getQueue().getBlockTimeoutMs();
|
||||
long claimIdleMs = properties.getQueue().getClaimIdleMs();
|
||||
String group = streamNames.consumerGroup();
|
||||
|
||||
while (running.get()) {
|
||||
try {
|
||||
List<ImportTaskStreamRecord> records = redisQueue.autoClaim(streamKey, group, threadConsumer, claimIdleMs);
|
||||
if (records.isEmpty()) {
|
||||
records = redisQueue.readNew(streamKey, group, threadConsumer, blockMs);
|
||||
}
|
||||
if (records.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
for (ImportTaskStreamRecord record : records) {
|
||||
handleRecord(streamKey, group, record);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
if (!running.get()) {
|
||||
break;
|
||||
}
|
||||
// 应用关闭或连接池回收时常见,降级日志避免误报
|
||||
if (isRedisConnectionIssue(e)) {
|
||||
log.warn("消费 {} Redis 连接中断,3s 后重试: {}", type, rootCauseMessage(e));
|
||||
} else {
|
||||
log.error("消费 {} 任务异常: {}", type, e.getMessage(), e);
|
||||
}
|
||||
sleepQuietly(3000);
|
||||
}
|
||||
}
|
||||
log.info("{} 导入任务消费者已停止,consumer={}", type, threadConsumer);
|
||||
}
|
||||
|
||||
private void handleRecord(String streamKey, String group, ImportTaskStreamRecord record) {
|
||||
Long taskId = record.getMessage().getTaskId();
|
||||
try {
|
||||
ImportTaskPO claimed = importTaskService.tryClaimForProcessing(taskId, consumerName);
|
||||
if (claimed == null) {
|
||||
log.info("任务 {} 已被其他实例处理或状态非 pending,直接 ACK", taskId);
|
||||
redisQueue.ack(streamKey, group, record.getMessageId());
|
||||
return;
|
||||
}
|
||||
|
||||
log.info("开始处理导入任务 taskId={}, type={}", taskId, claimed.getType());
|
||||
importTaskProcessorService.processImportTask(taskId);
|
||||
log.info("导入任务处理完成 taskId={}", taskId);
|
||||
} catch (Exception e) {
|
||||
log.error("导入任务 {} 处理失败: {}", taskId, e.getMessage(), e);
|
||||
importTaskService.markFailed(taskId, "处理失败: " + e.getMessage());
|
||||
} finally {
|
||||
try {
|
||||
redisQueue.ack(streamKey, group, record.getMessageId());
|
||||
} catch (Exception ackEx) {
|
||||
log.warn("ACK 任务 {} 失败: {}", taskId, ackEx.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isRedisConnectionIssue(Throwable throwable) {
|
||||
Throwable current = throwable;
|
||||
while (current != null) {
|
||||
String msg = current.getMessage();
|
||||
if (msg != null && (msg.contains("Connection closed")
|
||||
|| msg.contains("Connection reset")
|
||||
|| msg.contains("Redis exception"))) {
|
||||
return true;
|
||||
}
|
||||
current = current.getCause();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private String rootCauseMessage(Throwable throwable) {
|
||||
Throwable root = throwable;
|
||||
while (root.getCause() != null) {
|
||||
root = root.getCause();
|
||||
}
|
||||
return root.getMessage() == null ? throwable.getMessage() : root.getMessage();
|
||||
}
|
||||
|
||||
private void sleepQuietly(long ms) {
|
||||
try {
|
||||
Thread.sleep(ms);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
-460
@@ -1,460 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.service.impl;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.common.utils.BeanCopyUtils;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.apache.ibatis.session.SqlSessionFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.model.po.ImportTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.model.vo.ImportTaskVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.service.ImportTaskProcessorService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.service.ImportTaskService;
|
||||
import top.xyquan.ecomdmbbackend.modules.notify.sse.RealtimeSseEvents;
|
||||
import top.xyquan.ecomdmbbackend.modules.notify.sse.RealtimeSseService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderItemMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.cost.service.ProductSkuCostService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.service.ProductSkuService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.adfee.service.impl.AdFeeImportProcessor;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.mapper.ShopProductRelationMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.file.service.OssService;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.file.service.SysFileService;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.license.LicenseFeature;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.license.LicenseFeatureGuard;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.file.model.vo.SysFileVO;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.CharacterCodingException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.CharsetDecoder;
|
||||
import java.nio.charset.CodingErrorAction;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 导入任务处理器服务实现类
|
||||
*/
|
||||
@Service
|
||||
public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorService {
|
||||
|
||||
private final ImportTaskService importTaskService;
|
||||
private final RealtimeSseService realtimeSseService;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final OssService ossService;
|
||||
private final SysFileService sysFileService;
|
||||
|
||||
// 提取出的处理器(构造时组装,不单独持有 helper 的中间依赖)
|
||||
private final OrderImportProcessor orderImportProcessor;
|
||||
private final AdFeeImportProcessor adFeeImportProcessor;
|
||||
private final LicenseFeatureGuard licenseFeatureGuard;
|
||||
|
||||
public ImportTaskProcessorServiceImpl(ImportTaskService importTaskService,
|
||||
ProductSkuService productSkuService,
|
||||
ProductSkuCostService productSkuCostService,
|
||||
OrderMapper orderMapper,
|
||||
OrderItemMapper orderItemMapper,
|
||||
ProductMapper productMapper,
|
||||
ShopProductRelationMapper shopProductRelationMapper,
|
||||
RealtimeSseService realtimeSseService,
|
||||
ObjectMapper objectMapper,
|
||||
SqlSessionFactory sqlSessionFactory,
|
||||
OssService ossService,
|
||||
SysFileService sysFileService,
|
||||
AdFeeImportProcessor adFeeImportProcessor,
|
||||
LicenseFeatureGuard licenseFeatureGuard) {
|
||||
this.importTaskService = importTaskService;
|
||||
this.licenseFeatureGuard = licenseFeatureGuard;
|
||||
this.realtimeSseService = realtimeSseService;
|
||||
this.objectMapper = objectMapper;
|
||||
this.ossService = ossService;
|
||||
this.sysFileService = sysFileService;
|
||||
this.adFeeImportProcessor = adFeeImportProcessor;
|
||||
|
||||
ProductSkuImportHelper productSkuImportHelper = new ProductSkuImportHelper(
|
||||
productMapper, productSkuService, productSkuCostService, shopProductRelationMapper);
|
||||
this.orderImportProcessor = new OrderImportProcessor(
|
||||
productSkuImportHelper, orderMapper, orderItemMapper, shopProductRelationMapper, sqlSessionFactory);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processImportTask(Long taskId) {
|
||||
ImportTaskPO task = importTaskService.getById(taskId);
|
||||
if (task == null) return;
|
||||
|
||||
updateTaskStatus(taskId, "processing", null, 0, 0, 0);
|
||||
|
||||
try {
|
||||
ImportTaskPO updatedTask = importTaskService.getById(taskId);
|
||||
notifyTaskProgress(task.getCreateBy(), convertToVO(updatedTask));
|
||||
|
||||
if ("order".equals(task.getType())) {
|
||||
licenseFeatureGuard.require(LicenseFeature.ORDER_IMPORT);
|
||||
processOrderImport(task);
|
||||
} else if ("product".equals(task.getType())) {
|
||||
updateTaskStatus(taskId, "failed", "商品导入功能暂未实现", 0, 0, 0);
|
||||
} else if ("promotion_record".equals(task.getType())) {
|
||||
processAdFeeImport(task);
|
||||
} else {
|
||||
throw new BusinessException("不支持的导入类型: " + task.getType());
|
||||
}
|
||||
|
||||
ImportTaskPO completedTask = importTaskService.getById(taskId);
|
||||
notifyTaskProgress(task.getCreateBy(), convertToVO(completedTask));
|
||||
|
||||
} catch (Exception e) {
|
||||
String errMsg = e.getMessage();
|
||||
if (errMsg != null) {
|
||||
byte[] errBytes = errMsg.getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
if (errBytes.length > 59500) {
|
||||
errMsg = new String(errBytes, 0, 59500, java.nio.charset.StandardCharsets.UTF_8) + "...[已截断]";
|
||||
}
|
||||
}
|
||||
updateTaskStatus(taskId, "failed", "处理失败: " + errMsg, 0, 0, 0);
|
||||
ImportTaskPO failedTask = importTaskService.getById(taskId);
|
||||
notifyTaskProgress(task.getCreateBy(), convertToVO(failedTask));
|
||||
}
|
||||
}
|
||||
|
||||
private void processOrderImport(ImportTaskPO task) throws Exception {
|
||||
ImportRuntimeContext.MappingConfig mappingConfig = parseMappingConfig(task.getMapping());
|
||||
Map<String, ImportRuntimeContext.MappingField> fieldMapping = mappingConfig.getFieldMapping().stream()
|
||||
.collect(Collectors.toMap(
|
||||
ImportRuntimeContext.MappingField::getFieldName,
|
||||
field -> field, (v1, v2) -> v1));
|
||||
Map<String, String> statusMapping = mappingConfig.getStatusMapping() != null
|
||||
? mappingConfig.getStatusMapping().stream()
|
||||
.filter(sm -> sm.getCsvStatus() != null && sm.getMappedStatusCode() != null)
|
||||
.collect(Collectors.toMap(
|
||||
sm -> sm.getCsvStatus().trim(),
|
||||
ImportRuntimeContext.StatusMapping::getMappedStatusCode,
|
||||
(v1, v2) -> v1))
|
||||
: java.util.Collections.emptyMap();
|
||||
|
||||
File csvFile = null;
|
||||
File tempOssFile = null;
|
||||
|
||||
try {
|
||||
SysFileVO fileInfo = sysFileService.getFileById(task.getFileId());
|
||||
if (fileInfo == null) throw new BusinessException("文件不存在,fileId: " + task.getFileId());
|
||||
|
||||
String storagePath = fileInfo.getStoragePath();
|
||||
String storageType = fileInfo.getStorageType();
|
||||
String filename = fileInfo.getFilename() != null ? fileInfo.getFilename() : "";
|
||||
boolean isExcel = filename.toLowerCase().endsWith(".xlsx") || filename.toLowerCase().endsWith(".xls");
|
||||
String fileExt = isExcel ? (filename.toLowerCase().endsWith(".xlsx") ? ".xlsx" : ".xls") : ".csv";
|
||||
InputStream fileInputStream;
|
||||
|
||||
if ("local".equals(storageType)) {
|
||||
File localFile = new File(storagePath);
|
||||
if (!localFile.exists() || !localFile.isFile()) {
|
||||
throw new BusinessException("本地文件不存在: " + storagePath);
|
||||
}
|
||||
fileInputStream = new java.io.BufferedInputStream(new java.io.FileInputStream(localFile));
|
||||
csvFile = localFile;
|
||||
} else {
|
||||
tempOssFile = java.io.File.createTempFile("import-file-", fileExt);
|
||||
if (!ossService.downloadFile(storagePath, tempOssFile)) {
|
||||
throw new BusinessException("从对象存储下载文件失败,storagePath: " + storagePath);
|
||||
}
|
||||
csvFile = tempOssFile;
|
||||
fileInputStream = new java.io.BufferedInputStream(new java.io.FileInputStream(tempOssFile));
|
||||
}
|
||||
|
||||
Charset charset = isExcel ? java.nio.charset.StandardCharsets.UTF_8 : detectFileEncoding(fileInputStream);
|
||||
ImportRuntimeContext context = new ImportRuntimeContext(task.getCompanyId(), task.getShopId(), task.getCreateBy(), task.getId());
|
||||
|
||||
java.util.function.BiConsumer<Integer, Integer> progressCallback = (total, done) -> {
|
||||
updateTaskStatus(task.getId(), "processing", null, total, done, 0);
|
||||
ImportTaskPO updatedTask = importTaskService.getById(task.getId());
|
||||
notifyTaskProgress(task.getCreateBy(), convertToVO(updatedTask));
|
||||
};
|
||||
|
||||
// 根据文件类型路由到对应解析器
|
||||
final File finalImportFile = csvFile;
|
||||
ImportRuntimeContext.ImportResult result;
|
||||
if (isExcel) {
|
||||
result = orderImportProcessor.processExcel(
|
||||
task, finalImportFile, fieldMapping, statusMapping, context, progressCallback);
|
||||
} else {
|
||||
result = orderImportProcessor.process(
|
||||
task, finalImportFile, charset, fieldMapping, statusMapping, context, progressCallback);
|
||||
}
|
||||
|
||||
String finalStatus = result.failCount == 0 ? "success" : (result.insertCount > 0 ? "success" : "failed");
|
||||
String summary = String.format(
|
||||
"导入完成,处理 %d 条,新增 %d 条,更新 %d 条",
|
||||
result.totalCount, result.insertCount, result.updateCount);
|
||||
if (result.existingUnchangedCount > 0) {
|
||||
summary += String.format(",无变更跳过 %d 条", result.existingUnchangedCount);
|
||||
}
|
||||
if (result.mergedDuplicatePlatformNoCount > 0) {
|
||||
summary += String.format(",同文件重复订单号合并 %d 条", result.mergedDuplicatePlatformNoCount);
|
||||
}
|
||||
if (result.updateDbFailCount > 0) {
|
||||
summary += String.format(",更新失败 %d 条", result.updateDbFailCount);
|
||||
}
|
||||
String message = result.failCount > 0 ? summary + "\n" + result.errorMessages.toString() : summary;
|
||||
updateTaskStatus(task.getId(), finalStatus, message, result.totalCount, result.successCount, result.failCount);
|
||||
|
||||
} finally {
|
||||
if (tempOssFile != null && tempOssFile.exists()) tempOssFile.delete();
|
||||
}
|
||||
}
|
||||
|
||||
private void processAdFeeImport(ImportTaskPO task) throws Exception {
|
||||
com.fasterxml.jackson.databind.JsonNode rootNode;
|
||||
try {
|
||||
rootNode = objectMapper.readTree(task.getMapping());
|
||||
} catch (Exception e) {
|
||||
throw new BusinessException("解析映射配置失败: " + e.getMessage());
|
||||
}
|
||||
|
||||
Map<String, String> fieldMapping = new java.util.HashMap<>();
|
||||
com.fasterxml.jackson.databind.JsonNode fieldMappingNode = rootNode.get("fieldMapping");
|
||||
if (fieldMappingNode != null && fieldMappingNode.isArray()) {
|
||||
for (com.fasterxml.jackson.databind.JsonNode fieldNode : fieldMappingNode) {
|
||||
String fieldName = fieldNode.has("fieldName") ? fieldNode.get("fieldName").asText() : null;
|
||||
String fileFieldName = fieldNode.has("fileFieldName") ? fieldNode.get("fileFieldName").asText() : null;
|
||||
if (fieldName != null && fileFieldName != null) {
|
||||
fieldMapping.put(fieldName, fileFieldName);
|
||||
}
|
||||
}
|
||||
}
|
||||
String feeDateStr = rootNode.has("feeDate") ? rootNode.get("feeDate").asText() : null;
|
||||
|
||||
File csvFile = null;
|
||||
File tempOssFile = null;
|
||||
|
||||
try {
|
||||
SysFileVO fileInfo = sysFileService.getFileById(task.getFileId());
|
||||
if (fileInfo == null) throw new BusinessException("文件不存在,fileId: " + task.getFileId());
|
||||
|
||||
String storagePath = fileInfo.getStoragePath();
|
||||
String storageType = fileInfo.getStorageType();
|
||||
String filename = fileInfo.getFilename() != null ? fileInfo.getFilename() : "";
|
||||
boolean isExcel = filename.toLowerCase().endsWith(".xlsx") || filename.toLowerCase().endsWith(".xls");
|
||||
|
||||
if ("local".equals(storageType)) {
|
||||
File localFile = new File(storagePath);
|
||||
if (!localFile.exists() || !localFile.isFile()) {
|
||||
throw new BusinessException("本地文件不存在: " + storagePath);
|
||||
}
|
||||
csvFile = localFile;
|
||||
} else {
|
||||
String fileExt = isExcel ? (filename.toLowerCase().endsWith(".xlsx") ? ".xlsx" : ".xls") : ".csv";
|
||||
tempOssFile = java.io.File.createTempFile("import-ad-fee-", fileExt);
|
||||
if (!ossService.downloadFile(storagePath, tempOssFile)) {
|
||||
throw new BusinessException("从对象存储下载文件失败");
|
||||
}
|
||||
csvFile = tempOssFile;
|
||||
}
|
||||
|
||||
// 前端 wizard 生成的 patched CSV 固定为 UTF-8,避免被误判为 GBK 导致表头乱码
|
||||
boolean isPatchedPromotionCsv = filename != null
|
||||
&& filename.toLowerCase().contains("ad_fee_import_patched");
|
||||
Charset charset = isExcel || isPatchedPromotionCsv ? StandardCharsets.UTF_8
|
||||
: detectFileEncoding(new java.io.BufferedInputStream(new java.io.FileInputStream(csvFile)));
|
||||
AdFeeImportProcessor.ImportResult result = adFeeImportProcessor.processImport(
|
||||
task, csvFile, charset, fieldMapping, feeDateStr);
|
||||
|
||||
String finalStatus = result.failCount == 0 ? "success" : (result.successCount > 0 ? "success" : "failed");
|
||||
String summary = String.format("导入完成,处理 %d 条,成功 %d 条,失败 %d 条",
|
||||
result.totalCount, result.successCount, result.failCount);
|
||||
String message = summary;
|
||||
if (result.detailMessage != null && !result.detailMessage.isBlank()) {
|
||||
message += "\n" + result.detailMessage;
|
||||
}
|
||||
updateTaskStatus(task.getId(), finalStatus, message, result.totalCount, result.successCount, result.failCount);
|
||||
|
||||
} finally {
|
||||
if (tempOssFile != null && tempOssFile.exists()) tempOssFile.delete();
|
||||
}
|
||||
}
|
||||
|
||||
private ImportRuntimeContext.MappingConfig parseMappingConfig(String mappingJson) {
|
||||
try {
|
||||
if (mappingJson == null || mappingJson.trim().isEmpty()) {
|
||||
throw new BusinessException("映射配置不能为空");
|
||||
}
|
||||
com.fasterxml.jackson.databind.JsonNode rootNode;
|
||||
try {
|
||||
rootNode = objectMapper.readTree(mappingJson);
|
||||
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
|
||||
throw new BusinessException("解析字段映射失败: JSON格式错误 - " + e.getMessage());
|
||||
}
|
||||
if (!rootNode.isObject()) {
|
||||
throw new BusinessException("解析字段映射失败: 映射配置必须是JSON对象");
|
||||
}
|
||||
|
||||
ImportRuntimeContext.MappingConfig config = new ImportRuntimeContext.MappingConfig();
|
||||
|
||||
com.fasterxml.jackson.databind.JsonNode fieldMappingNode = rootNode.get("fieldMapping");
|
||||
if (fieldMappingNode == null || !fieldMappingNode.isArray()) {
|
||||
throw new BusinessException("解析字段映射失败: 缺少fieldMapping字段");
|
||||
}
|
||||
|
||||
java.util.List<ImportRuntimeContext.MappingField> mappingFields = new java.util.ArrayList<>();
|
||||
for (com.fasterxml.jackson.databind.JsonNode fieldNode : fieldMappingNode) {
|
||||
if (!fieldNode.isObject()) continue;
|
||||
ImportRuntimeContext.MappingField field = new ImportRuntimeContext.MappingField();
|
||||
if (fieldNode.has("required")) field.setRequired(fieldNode.get("required").asBoolean());
|
||||
if (fieldNode.has("fieldName")) field.setFieldName(fieldNode.get("fieldName").asText());
|
||||
if (fieldNode.has("fieldLabel")) field.setFieldLabel(fieldNode.get("fieldLabel").asText());
|
||||
if (fieldNode.has("fileFieldName")) field.setFileFieldName(fieldNode.get("fileFieldName").asText());
|
||||
mappingFields.add(field);
|
||||
}
|
||||
config.setFieldMapping(mappingFields);
|
||||
|
||||
com.fasterxml.jackson.databind.JsonNode statusMappingNode = rootNode.get("statusMapping");
|
||||
if (statusMappingNode != null && statusMappingNode.isArray()) {
|
||||
java.util.List<ImportRuntimeContext.StatusMapping> statusMappings = new java.util.ArrayList<>();
|
||||
for (com.fasterxml.jackson.databind.JsonNode statusNode : statusMappingNode) {
|
||||
if (!statusNode.isObject()) continue;
|
||||
ImportRuntimeContext.StatusMapping sm = new ImportRuntimeContext.StatusMapping();
|
||||
if (statusNode.has("csvStatus")) sm.setCsvStatus(statusNode.get("csvStatus").asText());
|
||||
if (statusNode.has("mappedStatusCode")) {
|
||||
sm.setMappedStatusCode(statusNode.get("mappedStatusCode").asText());
|
||||
} else if (statusNode.has("mappedStatusId")) {
|
||||
sm.setMappedStatusCode(statusNode.get("mappedStatusId").asText());
|
||||
}
|
||||
statusMappings.add(sm);
|
||||
}
|
||||
config.setStatusMapping(statusMappings);
|
||||
}
|
||||
|
||||
if (config.getFieldMapping() == null || config.getFieldMapping().isEmpty()) {
|
||||
throw new BusinessException("解析字段映射失败: 字段映射不能为空");
|
||||
}
|
||||
return config;
|
||||
} catch (BusinessException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new BusinessException("解析映射配置失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void updateTaskStatus(Long taskId, String status, String message,
|
||||
Integer totalCount, Integer successCount, Integer failCount) {
|
||||
LambdaUpdateWrapper<ImportTaskPO> updateWrapper = new LambdaUpdateWrapper<>();
|
||||
updateWrapper.eq(ImportTaskPO::getId, taskId);
|
||||
updateWrapper.set(ImportTaskPO::getStatus, status);
|
||||
if (message != null) {
|
||||
byte[] msgBytes = message.getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
String safeMsg = msgBytes.length > 60000
|
||||
? new String(msgBytes, 0, 60000, java.nio.charset.StandardCharsets.UTF_8)
|
||||
: message;
|
||||
updateWrapper.set(ImportTaskPO::getMessage, safeMsg);
|
||||
}
|
||||
if (totalCount != null) updateWrapper.set(ImportTaskPO::getTotalCount, totalCount);
|
||||
if (successCount != null) updateWrapper.set(ImportTaskPO::getSuccessCount, successCount);
|
||||
if (failCount != null) updateWrapper.set(ImportTaskPO::getFailCount, failCount);
|
||||
if ("processing".equals(status)) {
|
||||
updateWrapper.set(ImportTaskPO::getLastHeartbeatAt, java.time.LocalDateTime.now());
|
||||
}
|
||||
importTaskService.update(updateWrapper);
|
||||
}
|
||||
|
||||
private void notifyTaskProgress(Long userId, ImportTaskVO taskVO) {
|
||||
if (userId == null || taskVO == null) return;
|
||||
try {
|
||||
Map<String, Object> payload = Map.of(
|
||||
"type", RealtimeSseEvents.IMPORT_TASK_PROGRESS,
|
||||
"task", taskVO
|
||||
);
|
||||
realtimeSseService.sendToUser(userId, RealtimeSseEvents.IMPORT_TASK_PROGRESS, payload);
|
||||
if ("success".equals(taskVO.getStatus()) || "failed".equals(taskVO.getStatus())) {
|
||||
notifyImportAllCompletedIfIdle(userId);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// SSE 发送失败不影响主流程
|
||||
}
|
||||
}
|
||||
|
||||
private void notifyImportAllCompletedIfIdle(Long userId) {
|
||||
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ImportTaskPO> wrapper =
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
|
||||
wrapper.eq(ImportTaskPO::getCreateBy, userId)
|
||||
.in(ImportTaskPO::getStatus, "pending", "processing");
|
||||
if (importTaskService.count(wrapper) > 0) {
|
||||
return;
|
||||
}
|
||||
Map<String, Object> payload = Map.of(
|
||||
"type", RealtimeSseEvents.IMPORT_ALL_TASKS_COMPLETED,
|
||||
"message", "所有任务已完成"
|
||||
);
|
||||
realtimeSseService.sendToUser(userId, RealtimeSseEvents.IMPORT_ALL_TASKS_COMPLETED, payload);
|
||||
}
|
||||
|
||||
private ImportTaskVO convertToVO(ImportTaskPO importTaskPO) {
|
||||
if (importTaskPO == null) return null;
|
||||
ImportTaskVO vo = new ImportTaskVO();
|
||||
BeanCopyUtils.copyProperties(importTaskPO, vo);
|
||||
return vo;
|
||||
}
|
||||
|
||||
private Charset detectFileEncoding(InputStream inputStream) throws IOException {
|
||||
inputStream.mark(8196);
|
||||
byte[] bom = new byte[3];
|
||||
int bomRead = inputStream.read(bom);
|
||||
boolean hasUtf8Bom = bomRead >= 3 && bom[0] == (byte) 0xEF && bom[1] == (byte) 0xBB && bom[2] == (byte) 0xBF;
|
||||
inputStream.reset();
|
||||
if (hasUtf8Bom) {
|
||||
return StandardCharsets.UTF_8;
|
||||
}
|
||||
|
||||
byte[] sample = inputStream.readNBytes(8192);
|
||||
inputStream.reset();
|
||||
if (sample.length > 0 && isStrictValidUtf8(sample)) {
|
||||
return StandardCharsets.UTF_8;
|
||||
}
|
||||
|
||||
Charset[] charsets = {
|
||||
Charset.forName("GBK"),
|
||||
Charset.forName("GB2312"),
|
||||
Charset.forName("ISO-8859-1")
|
||||
};
|
||||
for (Charset charset : charsets) {
|
||||
String content = decodeSample(sample, charset);
|
||||
if (content != null && containsChineseImportKeywords(content)) {
|
||||
return charset;
|
||||
}
|
||||
}
|
||||
return Charset.forName("GBK");
|
||||
}
|
||||
|
||||
private static boolean isStrictValidUtf8(byte[] bytes) {
|
||||
CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder()
|
||||
.onMalformedInput(CodingErrorAction.REPORT)
|
||||
.onUnmappableCharacter(CodingErrorAction.REPORT);
|
||||
try {
|
||||
decoder.decode(ByteBuffer.wrap(bytes));
|
||||
return true;
|
||||
} catch (CharacterCodingException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static String decodeSample(byte[] sample, Charset charset) {
|
||||
if (sample.length == 0) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return charset.decode(ByteBuffer.wrap(sample)).toString();
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean containsChineseImportKeywords(String content) {
|
||||
return content.contains("商家") || content.contains("编码")
|
||||
|| content.contains("商品") || content.contains("订单")
|
||||
|| content.contains("规格") || content.contains("金额")
|
||||
|| content.contains("推广") || content.contains("花费");
|
||||
}
|
||||
}
|
||||
-79
@@ -1,79 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.service.impl;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.config.ImportTaskProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.config.ImportTaskStreamNames;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.model.po.ImportTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.queue.ImportTaskQueueMessage;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.queue.ImportTaskRedisQueue;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.service.ImportTaskQueueService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.service.ImportTaskService;
|
||||
|
||||
/**
|
||||
* 导入任务 Redis Stream 生产者。
|
||||
*/
|
||||
@Service
|
||||
public class ImportTaskQueueServiceImpl implements ImportTaskQueueService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ImportTaskQueueServiceImpl.class);
|
||||
|
||||
private final ImportTaskService importTaskService;
|
||||
private final ImportTaskRedisQueue redisQueue;
|
||||
private final ImportTaskStreamNames streamNames;
|
||||
private final ImportTaskProperties properties;
|
||||
|
||||
public ImportTaskQueueServiceImpl(@Lazy ImportTaskService importTaskService,
|
||||
ImportTaskRedisQueue redisQueue,
|
||||
ImportTaskStreamNames streamNames,
|
||||
ImportTaskProperties properties) {
|
||||
this.importTaskService = importTaskService;
|
||||
this.redisQueue = redisQueue;
|
||||
this.streamNames = streamNames;
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void publishImportTask(Long taskId) {
|
||||
if (!properties.getQueue().isEnabled()) {
|
||||
log.warn("导入任务 Redis 队列未启用,taskId={} 仅保留 DB pending 状态", taskId);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
ImportTaskPO task = importTaskService.getById(taskId);
|
||||
if (task == null) {
|
||||
log.error("导入任务不存在,taskId={}", taskId);
|
||||
return;
|
||||
}
|
||||
if (!"pending".equals(task.getStatus())) {
|
||||
log.info("任务 {} 非 pending,跳过入队,status={}", taskId, task.getStatus());
|
||||
return;
|
||||
}
|
||||
|
||||
String streamKey = streamNames.streamKey(task.getType());
|
||||
redisQueue.ensureConsumerGroup(streamKey, streamNames.consumerGroup());
|
||||
|
||||
String messageId = redisQueue.enqueue(streamKey, new ImportTaskQueueMessage(taskId, task.getType()));
|
||||
|
||||
ImportTaskPO update = new ImportTaskPO();
|
||||
update.setId(taskId);
|
||||
update.setEnqueueStatus("enqueued");
|
||||
update.setRedisStreamKey(streamKey);
|
||||
update.setRedisMessageId(messageId);
|
||||
importTaskService.updateById(update);
|
||||
|
||||
log.info("导入任务已入队 Redis Stream,taskId={}, type={}, stream={}, messageId={}",
|
||||
taskId, task.getType(), streamKey, messageId);
|
||||
} catch (Exception e) {
|
||||
log.error("导入任务入队失败,taskId={}", taskId, e);
|
||||
ImportTaskPO update = new ImportTaskPO();
|
||||
update.setId(taskId);
|
||||
update.setEnqueueStatus("enqueue_failed");
|
||||
update.setMessage("入队失败: " + e.getMessage());
|
||||
importTaskService.updateById(update);
|
||||
}
|
||||
}
|
||||
}
|
||||
-239
@@ -1,239 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
import org.springframework.util.StringUtils;
|
||||
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
|
||||
import top.xyquan.ecomdmbbackend.common.utils.BeanCopyUtils;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.mapper.ImportTaskMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.model.dto.CreateImportTaskDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.model.dto.ImportTaskFilterDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.model.po.ImportTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.model.vo.ImportTaskVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.service.ImportTaskQueueService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.service.ImportTaskService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.service.ShopService;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.license.LicenseFeature;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.license.LicenseFeatureGuard;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 导入任务服务实现类
|
||||
*/
|
||||
@Service
|
||||
public class ImportTaskServiceImpl extends ServiceImpl<ImportTaskMapper, ImportTaskPO> implements ImportTaskService {
|
||||
|
||||
private final ShopService shopService;
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final ImportTaskQueueService importTaskQueueService;
|
||||
private final LicenseFeatureGuard licenseFeatureGuard;
|
||||
|
||||
public ImportTaskServiceImpl(CurrentUserContext currentUserContext,
|
||||
ImportTaskQueueService importTaskQueueService,
|
||||
ShopService shopService,
|
||||
LicenseFeatureGuard licenseFeatureGuard) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.importTaskQueueService = importTaskQueueService;
|
||||
this.shopService = shopService;
|
||||
this.licenseFeatureGuard = licenseFeatureGuard;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public ImportTaskVO createImportTask(CreateImportTaskDTO createImportTaskDTO) {
|
||||
if ("order".equals(createImportTaskDTO.getType())) {
|
||||
licenseFeatureGuard.require(LicenseFeature.ORDER_IMPORT);
|
||||
}
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
Long currentUserId = currentUserContext.getCurrentUserId();
|
||||
|
||||
ImportTaskPO importTaskPO = new ImportTaskPO();
|
||||
BeanCopyUtils.copyProperties(createImportTaskDTO, importTaskPO);
|
||||
importTaskPO.setCompanyId(companyId);
|
||||
importTaskPO.setTaskName(generateTaskName(companyId, createImportTaskDTO.getType()));
|
||||
importTaskPO.setStatus("pending");
|
||||
importTaskPO.setEnqueueStatus("pending_enqueue");
|
||||
importTaskPO.setTotalCount(0);
|
||||
importTaskPO.setSuccessCount(0);
|
||||
importTaskPO.setFailCount(0);
|
||||
importTaskPO.setCreateBy(currentUserId);
|
||||
|
||||
this.save(importTaskPO);
|
||||
|
||||
Long taskId = importTaskPO.getId();
|
||||
TransactionSynchronizationManager.registerSynchronization(
|
||||
new org.springframework.transaction.support.TransactionSynchronization() {
|
||||
@Override
|
||||
public void afterCommit() {
|
||||
importTaskQueueService.publishImportTask(taskId);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return convertToVO(importTaskPO);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageResultVO<ImportTaskVO> getImportTaskPage(PageQueryDTO<ImportTaskFilterDTO> pageQueryDTO) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
ImportTaskFilterDTO filter = pageQueryDTO.getFilters();
|
||||
|
||||
LambdaQueryWrapper<ImportTaskPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ImportTaskPO::getCompanyId, companyId);
|
||||
|
||||
if (filter != null) {
|
||||
if (filter.getShopId() != null) {
|
||||
wrapper.eq(ImportTaskPO::getShopId, filter.getShopId());
|
||||
}
|
||||
if (StringUtils.hasText(filter.getType())) {
|
||||
wrapper.eq(ImportTaskPO::getType, filter.getType());
|
||||
}
|
||||
if (StringUtils.hasText(filter.getStatus())) {
|
||||
wrapper.eq(ImportTaskPO::getStatus, filter.getStatus());
|
||||
}
|
||||
if (StringUtils.hasText(filter.getFileName())) {
|
||||
wrapper.like(ImportTaskPO::getFileName, filter.getFileName());
|
||||
}
|
||||
}
|
||||
|
||||
wrapper.orderByDesc(ImportTaskPO::getCreateTime);
|
||||
|
||||
Page<ImportTaskPO> page = new Page<>(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
|
||||
IPage<ImportTaskPO> pageResult = this.page(page, wrapper);
|
||||
|
||||
List<ImportTaskVO> voList = pageResult.getRecords().stream()
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return PageResultVO.create(voList, pageResult.getTotal(), pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public ImportTaskPO tryClaimForProcessing(Long taskId, String workerId) {
|
||||
LambdaUpdateWrapper<ImportTaskPO> updateWrapper = new LambdaUpdateWrapper<>();
|
||||
updateWrapper.eq(ImportTaskPO::getId, taskId)
|
||||
.eq(ImportTaskPO::getStatus, "pending")
|
||||
.set(ImportTaskPO::getStatus, "processing")
|
||||
.set(ImportTaskPO::getWorkerId, workerId)
|
||||
.set(ImportTaskPO::getStartedAt, LocalDateTime.now())
|
||||
.set(ImportTaskPO::getLastHeartbeatAt, LocalDateTime.now());
|
||||
|
||||
if (!this.update(updateWrapper)) {
|
||||
return null;
|
||||
}
|
||||
return this.getById(taskId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void markFailed(Long taskId, String message) {
|
||||
LambdaUpdateWrapper<ImportTaskPO> updateWrapper = new LambdaUpdateWrapper<>();
|
||||
updateWrapper.eq(ImportTaskPO::getId, taskId)
|
||||
.set(ImportTaskPO::getStatus, "failed")
|
||||
.set(ImportTaskPO::getMessage, message)
|
||||
.set(ImportTaskPO::getLastHeartbeatAt, LocalDateTime.now());
|
||||
this.update(updateWrapper);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void touchHeartbeat(Long taskId) {
|
||||
LambdaUpdateWrapper<ImportTaskPO> updateWrapper = new LambdaUpdateWrapper<>();
|
||||
updateWrapper.eq(ImportTaskPO::getId, taskId)
|
||||
.eq(ImportTaskPO::getStatus, "processing")
|
||||
.set(ImportTaskPO::getLastHeartbeatAt, LocalDateTime.now());
|
||||
this.update(updateWrapper);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ImportTaskPO> listPendingEnqueueTasks() {
|
||||
LambdaQueryWrapper<ImportTaskPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ImportTaskPO::getStatus, "pending")
|
||||
.in(ImportTaskPO::getEnqueueStatus, "pending_enqueue", "enqueue_failed")
|
||||
.orderByAsc(ImportTaskPO::getId);
|
||||
return this.list(wrapper);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ImportTaskPO> listStuckProcessingTasks(long stuckThresholdMs) {
|
||||
LocalDateTime threshold = LocalDateTime.now().minus(Duration.ofMillis(stuckThresholdMs));
|
||||
LambdaQueryWrapper<ImportTaskPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ImportTaskPO::getStatus, "processing")
|
||||
.and(w -> w.isNull(ImportTaskPO::getLastHeartbeatAt)
|
||||
.or()
|
||||
.lt(ImportTaskPO::getLastHeartbeatAt, threshold))
|
||||
.orderByAsc(ImportTaskPO::getId);
|
||||
return this.list(wrapper);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resetToPendingForRecovery(Long taskId, String message) {
|
||||
LambdaUpdateWrapper<ImportTaskPO> updateWrapper = new LambdaUpdateWrapper<>();
|
||||
updateWrapper.eq(ImportTaskPO::getId, taskId)
|
||||
.eq(ImportTaskPO::getStatus, "processing")
|
||||
.set(ImportTaskPO::getStatus, "pending")
|
||||
.set(ImportTaskPO::getEnqueueStatus, "pending_enqueue")
|
||||
.set(ImportTaskPO::getWorkerId, null)
|
||||
.set(ImportTaskPO::getStartedAt, null)
|
||||
.set(ImportTaskPO::getMessage, message);
|
||||
this.update(updateWrapper);
|
||||
}
|
||||
|
||||
private ImportTaskVO convertToVO(ImportTaskPO importTaskPO) {
|
||||
ImportTaskVO importTaskVO = new ImportTaskVO();
|
||||
BeanCopyUtils.copyProperties(importTaskPO, importTaskVO);
|
||||
if (importTaskPO.getShopId() != null) {
|
||||
ShopPO shop = shopService.getById(importTaskPO.getShopId());
|
||||
if (shop != null) {
|
||||
importTaskVO.setShopName(shop.getName());
|
||||
}
|
||||
}
|
||||
return importTaskVO;
|
||||
}
|
||||
|
||||
private String generateTaskName(Long companyId, String type) {
|
||||
String dateStr = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
|
||||
String typePrefix = switch (type) {
|
||||
case "order" -> "ORD";
|
||||
case "promotion_record" -> "PRM";
|
||||
default -> "PROD";
|
||||
};
|
||||
|
||||
String prefixPattern = typePrefix + "-" + companyId + "-" + dateStr + "-%";
|
||||
LambdaQueryWrapper<ImportTaskPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.likeRight(ImportTaskPO::getTaskName, prefixPattern);
|
||||
wrapper.orderByDesc(ImportTaskPO::getTaskName);
|
||||
wrapper.last("LIMIT 1");
|
||||
ImportTaskPO lastTask = this.getOne(wrapper);
|
||||
|
||||
int seq = 1;
|
||||
if (lastTask != null && lastTask.getTaskName() != null) {
|
||||
String lastName = lastTask.getTaskName();
|
||||
int lastDashIndex = lastName.lastIndexOf("-");
|
||||
if (lastDashIndex > 0) {
|
||||
String lastSeqStr = lastName.substring(lastDashIndex + 1);
|
||||
try {
|
||||
seq = Integer.parseInt(lastSeqStr) + 1;
|
||||
} catch (NumberFormatException ignored) {
|
||||
seq = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return String.format("%s-%d-%s-%03d", typePrefix, companyId, dateStr, seq);
|
||||
}
|
||||
}
|
||||
-1785
File diff suppressed because it is too large
Load Diff
-37
@@ -1,37 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.service.impl;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderItemPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderPO;
|
||||
|
||||
/**
|
||||
* 导入场景订单快照(主表 + 首行明细,当前一行一单)
|
||||
*/
|
||||
public class OrderImportSnapshot {
|
||||
|
||||
private OrderPO order;
|
||||
private OrderItemPO item;
|
||||
|
||||
public OrderImportSnapshot() {
|
||||
}
|
||||
|
||||
public OrderImportSnapshot(OrderPO order, OrderItemPO item) {
|
||||
this.order = order;
|
||||
this.item = item;
|
||||
}
|
||||
|
||||
public OrderPO getOrder() {
|
||||
return order;
|
||||
}
|
||||
|
||||
public void setOrder(OrderPO order) {
|
||||
this.order = order;
|
||||
}
|
||||
|
||||
public OrderItemPO getItem() {
|
||||
return item;
|
||||
}
|
||||
|
||||
public void setItem(OrderItemPO item) {
|
||||
this.item = item;
|
||||
}
|
||||
}
|
||||
-591
@@ -1,591 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderItemMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderItemPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.status.model.enums.OrderStatus;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.model.dto.CreateProductSkuDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.model.po.ProductSkuPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.cost.service.ProductSkuCostService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.service.ProductSkuService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.mapper.ShopProductRelationMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopProductRelationPO;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 商品/SKU查找与创建辅助类
|
||||
* <p>
|
||||
* 职责:
|
||||
* - 商品/SKU/状态缓存查找
|
||||
* - 商品/SKU/状态创建
|
||||
* - 预加载(填充 ImportRuntimeContext)
|
||||
*/
|
||||
public class ProductSkuImportHelper {
|
||||
|
||||
private static final int IN_QUERY_BATCH_SIZE = 1000;
|
||||
|
||||
private final ProductMapper productMapper;
|
||||
private final ProductSkuService productSkuService;
|
||||
private final ProductSkuCostService productSkuCostService;
|
||||
private final ShopProductRelationMapper shopProductRelationMapper;
|
||||
|
||||
public ProductSkuImportHelper(ProductMapper productMapper,
|
||||
ProductSkuService productSkuService,
|
||||
ProductSkuCostService productSkuCostService,
|
||||
ShopProductRelationMapper shopProductRelationMapper) {
|
||||
this.productMapper = productMapper;
|
||||
this.productSkuService = productSkuService;
|
||||
this.productSkuCostService = productSkuCostService;
|
||||
this.shopProductRelationMapper = shopProductRelationMapper;
|
||||
}
|
||||
|
||||
/** 将 SKU 当前生效成本写入订单 DTO 快照字段 */
|
||||
public void fillSkuCostSnapshot(Long skuId, java.util.function.Consumer<java.math.BigDecimal> productCostSetter,
|
||||
java.util.function.Consumer<java.math.BigDecimal> shippingCostSetter,
|
||||
java.util.function.Consumer<java.math.BigDecimal> otherCostSetter) {
|
||||
var cost = productSkuCostService.getCurrentCost(skuId);
|
||||
productCostSetter.accept(cost != null && cost.getProductCost() != null ? cost.getProductCost() : BigDecimal.ZERO);
|
||||
shippingCostSetter.accept(cost != null && cost.getShippingCost() != null ? cost.getShippingCost() : BigDecimal.ZERO);
|
||||
otherCostSetter.accept(cost != null && cost.getOtherCost() != null ? cost.getOtherCost() : BigDecimal.ZERO);
|
||||
}
|
||||
|
||||
// ==================== 缓存查找 ====================
|
||||
|
||||
public ProductSkuPO findProductSkuBySkuCode(String skuCode, Long companyId,
|
||||
ImportRuntimeContext context) {
|
||||
if (skuCode == null || skuCode.trim().isEmpty()) return null;
|
||||
return context.skuByCodeCache.get(skuCode.trim());
|
||||
}
|
||||
|
||||
public ProductPO findProductByProductCode(String productCode, Long companyId,
|
||||
ImportRuntimeContext context) {
|
||||
return findProductForOrderImport(companyId, productCode, null, context);
|
||||
}
|
||||
|
||||
public ProductPO findProductByName(String productName, Long companyId,
|
||||
ImportRuntimeContext context) {
|
||||
return findProductForOrderImport(companyId, null, productName, context);
|
||||
}
|
||||
|
||||
/**
|
||||
* 有编码时按公司+编码匹配(公司内唯一);仅名称时要求同名唯一。
|
||||
*/
|
||||
public ProductPO findProductForOrderImport(Long companyId, String productCode, String linkProductName,
|
||||
ImportRuntimeContext context) {
|
||||
String code = normalizeProductCode(productCode);
|
||||
String name = linkProductName != null ? linkProductName.trim() : "";
|
||||
boolean hasCode = code != null;
|
||||
boolean hasName = !name.isEmpty();
|
||||
if (!hasCode && !hasName) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (hasCode) {
|
||||
ProductPO cached = context.productByCodeCache.get(code);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
ProductPO fromDb = selectProductByCompanyCodeFromDb(companyId, code);
|
||||
if (fromDb != null) {
|
||||
cacheProduct(context, fromDb);
|
||||
}
|
||||
return fromDb;
|
||||
}
|
||||
|
||||
LambdaQueryWrapper<ProductPO> w = new LambdaQueryWrapper<>();
|
||||
w.eq(ProductPO::getCompanyId, companyId).eq(ProductPO::getName, name);
|
||||
List<ProductPO> list = productMapper.selectList(w);
|
||||
if (list.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
if (list.size() == 1) {
|
||||
cacheProduct(context, list.get(0));
|
||||
return list.get(0);
|
||||
}
|
||||
throw new BusinessException(
|
||||
"该公司下存在多条同名商品(编码不同),请在本行填写商品编码以便唯一匹配");
|
||||
}
|
||||
|
||||
/** 空白编码规范为 null。 */
|
||||
private static String normalizeProductCode(String productCode) {
|
||||
if (productCode == null || productCode.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
return productCode.trim();
|
||||
}
|
||||
|
||||
private ProductPO selectProductByCompanyCodeFromDb(Long companyId, String normalizedCode) {
|
||||
LambdaQueryWrapper<ProductPO> w = new LambdaQueryWrapper<>();
|
||||
w.eq(ProductPO::getCompanyId, companyId).eq(ProductPO::getProductCode, normalizedCode);
|
||||
return productMapper.selectOne(w);
|
||||
}
|
||||
|
||||
/**
|
||||
* 插入商品;若触发 uk_ec_product_company_code 冲突,则按公司+编码从库中加载已存在行。
|
||||
*/
|
||||
private ProductPO insertProductOrFetchExisting(ProductPO draft, Long companyId,
|
||||
ImportRuntimeContext context) {
|
||||
if (draft.getName() == null || draft.getName().trim().isEmpty()) {
|
||||
throw new BusinessException("商品名称不能为空");
|
||||
}
|
||||
draft.setName(draft.getName().trim());
|
||||
draft.setProductCode(normalizeProductCode(draft.getProductCode()));
|
||||
try {
|
||||
productMapper.insert(draft);
|
||||
return draft;
|
||||
} catch (Exception ex) {
|
||||
if (!isDuplicateKeyException(ex)) {
|
||||
if (ex instanceof RuntimeException re) {
|
||||
throw re;
|
||||
}
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
if (draft.getProductCode() == null) {
|
||||
throw new BusinessException("商品因唯一约束已存在但编码为空,无法按编码回查");
|
||||
}
|
||||
ProductPO existing = selectProductByCompanyCodeFromDb(companyId, draft.getProductCode());
|
||||
if (existing != null) {
|
||||
return existing;
|
||||
}
|
||||
throw new BusinessException(
|
||||
"商品因唯一约束已存在但重新查询失败,请稍后重试导入或检查公司与商品编码是否与已存在记录一致");
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isDuplicateKeyException(Throwable ex) {
|
||||
Throwable t = ex;
|
||||
while (t != null) {
|
||||
if (t instanceof DuplicateKeyException) {
|
||||
return true;
|
||||
}
|
||||
if (t instanceof java.sql.SQLIntegrityConstraintViolationException) {
|
||||
String msg = t.getMessage();
|
||||
if (msg != null && (msg.contains("Duplicate") || msg.contains("duplicate"))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
t = t.getCause();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private ProductSkuPO selectSkuByCompanyAndSkuCodeFromDb(Long companyId, String skuCode) {
|
||||
if (skuCode == null || skuCode.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
LambdaQueryWrapper<ProductSkuPO> w = new LambdaQueryWrapper<>();
|
||||
w.eq(ProductSkuPO::getCompanyId, companyId).eq(ProductSkuPO::getSkuCode, skuCode);
|
||||
return productSkuService.getOne(w);
|
||||
}
|
||||
|
||||
/**
|
||||
* 订单导入插入SKU:同公司已存在该SKU编码时<strong>不更新</strong>已有行,直接复用;
|
||||
* 不存在则新建(走 {@link ProductSkuService#createProductSkuForImport},与其它入口一致)。
|
||||
* 并发下仍可能触发唯一约束,则回查已存在行。
|
||||
*/
|
||||
private ProductSkuPO insertSkuOrFetchExisting(ProductSkuPO draft, BigDecimal productCost,
|
||||
BigDecimal shippingCost, BigDecimal otherCost,
|
||||
Long companyId, ImportRuntimeContext context) {
|
||||
String rawCode = draft.getSkuCode();
|
||||
if (rawCode != null && !rawCode.trim().isEmpty()) {
|
||||
ProductSkuPO existing = selectSkuByCompanyAndSkuCodeFromDb(companyId, rawCode.trim());
|
||||
if (existing != null) {
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
|
||||
CreateProductSkuDTO dto = new CreateProductSkuDTO();
|
||||
dto.setProductId(draft.getProductId());
|
||||
dto.setName(draft.getName());
|
||||
dto.setSkuCode(draft.getSkuCode());
|
||||
dto.setProductCost(productCost != null ? productCost : BigDecimal.ZERO);
|
||||
dto.setShippingCost(shippingCost);
|
||||
dto.setOtherCost(otherCost);
|
||||
dto.setRemark(draft.getRemark());
|
||||
Long createBy = draft.getCreateBy();
|
||||
try {
|
||||
return productSkuService.getById(
|
||||
productSkuService.createProductSkuForImport(dto, companyId, createBy).getId());
|
||||
} catch (Exception ex) {
|
||||
if (!isDuplicateKeyException(ex)) {
|
||||
if (ex instanceof RuntimeException re) {
|
||||
throw re;
|
||||
}
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
String code = draft.getSkuCode();
|
||||
if (code == null || code.trim().isEmpty()) {
|
||||
throw new BusinessException(
|
||||
"SKU因唯一约束已存在但SKU编码为空,无法回查已存在记录");
|
||||
}
|
||||
ProductSkuPO existing = selectSkuByCompanyAndSkuCodeFromDb(companyId, code.trim());
|
||||
if (existing != null) {
|
||||
return existing;
|
||||
}
|
||||
throw new BusinessException(
|
||||
"SKU因唯一约束已存在但重新查询失败,请稍后重试导入");
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 商品/SKU创建 ====================
|
||||
|
||||
/**
|
||||
* 根据已知商品创建SKU(跳过 selectById)
|
||||
*/
|
||||
public ProductSkuPO createSkuForProduct(ProductPO product, String skuCode, String skuName,
|
||||
BigDecimal productCost, Long companyId,
|
||||
Long createBy, ImportRuntimeContext context) {
|
||||
if (product == null) {
|
||||
throw new BusinessException("商品不能为空");
|
||||
}
|
||||
|
||||
String trimmedCode = skuCode != null ? skuCode.trim() : null;
|
||||
String trimmedName = skuName != null ? skuName.trim() : null;
|
||||
|
||||
// 检查缓存(插入前再读一次,减少并行线程重复 insert)
|
||||
if (trimmedCode != null) {
|
||||
ProductSkuPO existing = context.skuByCodeCache.get(trimmedCode);
|
||||
if (existing != null) {
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
|
||||
ProductSkuPO sku = new ProductSkuPO();
|
||||
sku.setProductId(product.getId());
|
||||
sku.setCompanyId(companyId);
|
||||
sku.setSkuCode(trimmedCode);
|
||||
String finalSkuName = trimmedName != null ? trimmedName : (trimmedCode != null ? trimmedCode : "未知SKU");
|
||||
sku.setName(finalSkuName);
|
||||
sku.setCreateBy(createBy);
|
||||
sku = insertSkuOrFetchExisting(sku, productCost, null, null, companyId, context);
|
||||
|
||||
if (trimmedCode != null) {
|
||||
context.skuByCodeCache.put(trimmedCode, sku);
|
||||
}
|
||||
return sku;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找或创建商品,再查找或创建SKU
|
||||
*/
|
||||
public ProductSkuPO createProductAndSkuIfNotExists(String productCode, String productName,
|
||||
String skuCode, String skuName,
|
||||
BigDecimal productCost, Long companyId,
|
||||
Long createBy, ImportRuntimeContext context) {
|
||||
String trimmedCode = productCode != null ? productCode.trim() : null;
|
||||
String trimmedName = productName != null ? productName.trim() : null;
|
||||
if ((trimmedCode == null || trimmedCode.isEmpty())
|
||||
&& (trimmedName == null || trimmedName.isEmpty())) {
|
||||
throw new BusinessException("商品编码和商品名称不能同时为空");
|
||||
}
|
||||
|
||||
ProductPO product = findProductForOrderImport(companyId, productCode, productName, context);
|
||||
|
||||
if (product == null) {
|
||||
product = new ProductPO();
|
||||
product.setCompanyId(companyId);
|
||||
product.setProductCode(trimmedCode != null && !trimmedCode.isEmpty() ? trimmedCode : null);
|
||||
String resolvedName =
|
||||
trimmedName != null && !trimmedName.isEmpty() ? trimmedName
|
||||
: (trimmedCode != null && !trimmedCode.isEmpty() ? trimmedCode : "未知商品");
|
||||
product.setName(resolvedName);
|
||||
product.setCreateBy(createBy);
|
||||
product = insertProductOrFetchExisting(product, companyId, context);
|
||||
cacheProduct(context, product);
|
||||
}
|
||||
|
||||
return createSkuForProduct(product, skuCode, skuName, productCost, companyId, createBy, context);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据SKU编码查找SKU,找不到则按"编码创建SKU/无编码返回空"逻辑处理
|
||||
*/
|
||||
public ProductSkuPO createSkuForProduct(String productCode, String productName,
|
||||
String skuCode, String skuName,
|
||||
BigDecimal productCost, Long companyId,
|
||||
Long createBy, ImportRuntimeContext context) {
|
||||
String trimmedSkuCode = skuCode != null ? skuCode.trim() : null;
|
||||
if (trimmedSkuCode != null && !trimmedSkuCode.isEmpty()) {
|
||||
ProductSkuPO existing = findProductSkuBySkuCode(trimmedSkuCode, companyId, context);
|
||||
if (existing != null) return existing;
|
||||
return createProductAndSkuIfNotExists(productCode, productName, skuCode, skuName,
|
||||
productCost, companyId, createBy, context);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public ProductSkuPO createSkuForProductWithValidation(String productCode, String productName,
|
||||
String skuCode, String skuName,
|
||||
BigDecimal productCost, Long companyId,
|
||||
Long createBy, ImportRuntimeContext context) {
|
||||
String trimmedSkuCode = skuCode != null ? skuCode.trim() : null;
|
||||
String trimmedSkuName = skuName != null ? skuName.trim() : null;
|
||||
|
||||
if (trimmedSkuCode == null || trimmedSkuCode.isEmpty()) {
|
||||
throw new BusinessException("SKU编码不能为空");
|
||||
}
|
||||
if (trimmedSkuName == null || trimmedSkuName.isEmpty()) {
|
||||
throw new BusinessException("SKU名称不能为空");
|
||||
}
|
||||
|
||||
ProductSkuPO existing = findProductSkuBySkuCode(trimmedSkuCode, companyId, context);
|
||||
if (existing != null) return existing;
|
||||
|
||||
return createProductAndSkuIfNotExists(productCode, productName, skuCode, skuName,
|
||||
productCost, companyId, createBy, context);
|
||||
}
|
||||
|
||||
/** 旧签名(兼容旧版调用) */
|
||||
public ProductSkuPO createSkuForProduct(Long companyId, Long productId, String skuName,
|
||||
String skuCode, Long createBy,
|
||||
ImportRuntimeContext context) {
|
||||
ProductPO product = getProductById(productId, context);
|
||||
if (product == null || !product.getCompanyId().equals(companyId)) {
|
||||
throw new BusinessException("商品不存在");
|
||||
}
|
||||
// 已知 productId 时应直接基于该商品创建SKU,不能再走“按商品编码/名称查商品”的路径,
|
||||
// 否则会在 productCode/productName 为空时误报“商品编码和商品名称不能同时为空”。
|
||||
return createSkuForProduct(product, skuCode, skuName, null, companyId, createBy, context);
|
||||
}
|
||||
|
||||
/** 旧签名(兼容旧版调用):参数顺序 companyId, productName, productCode, skuName, skuCode */
|
||||
public ProductSkuPO createProductAndSkuIfNotExists(Long companyId, String productName,
|
||||
String productCode, String skuName,
|
||||
String skuCode, Long createBy,
|
||||
ImportRuntimeContext context) {
|
||||
if (productName == null || productName.trim().isEmpty()) {
|
||||
throw new BusinessException("商品名称不能为空");
|
||||
}
|
||||
String trimmedName = productName.trim();
|
||||
|
||||
ProductPO product = findProductForOrderImport(companyId, productCode, trimmedName, context);
|
||||
|
||||
if (product == null) {
|
||||
product = new ProductPO();
|
||||
product.setCompanyId(companyId);
|
||||
product.setName(trimmedName);
|
||||
String trimmedCode = productCode != null ? productCode.trim() : "";
|
||||
product.setProductCode(trimmedCode.isEmpty() ? null : trimmedCode);
|
||||
product.setCreateBy(createBy);
|
||||
product = insertProductOrFetchExisting(product, companyId, context);
|
||||
}
|
||||
|
||||
cacheProduct(context, product);
|
||||
return createSkuForProduct(product, skuCode, skuName, null, companyId, createBy, context);
|
||||
}
|
||||
|
||||
public ProductPO getProductById(Long productId, ImportRuntimeContext context) {
|
||||
ProductPO cached = context.productByIdCache.get(productId);
|
||||
if (cached != null) return cached;
|
||||
ProductPO product = productMapper.selectById(productId);
|
||||
if (product != null) cacheProduct(context, product);
|
||||
return product;
|
||||
}
|
||||
|
||||
public void cacheProduct(ImportRuntimeContext context, ProductPO product) {
|
||||
context.productByIdCache.put(product.getId(), product);
|
||||
String nm = product.getName() != null ? product.getName().trim() : "";
|
||||
String cd = normalizeProductCode(product.getProductCode());
|
||||
if (!nm.isEmpty()) {
|
||||
context.productByNameCache.put(nm, product);
|
||||
}
|
||||
if (cd != null) {
|
||||
context.productByCodeCache.put(cd, product);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 订单状态 ====================
|
||||
|
||||
/** 按名称或 code 解析状态码,结果写入缓存。 */
|
||||
public String resolveOrderStatusCode(String statusName, ImportRuntimeContext context) {
|
||||
if (statusName == null || statusName.trim().isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
String trimmed = statusName.trim();
|
||||
if (context.statusCodeByNameCache.containsKey(trimmed)) {
|
||||
return context.statusCodeByNameCache.get(trimmed);
|
||||
}
|
||||
String code = OrderStatus.fromName(trimmed).getCode();
|
||||
context.statusCodeByNameCache.put(trimmed, code);
|
||||
return code;
|
||||
}
|
||||
|
||||
public void preloadStatuses(ImportRuntimeContext context, Set<String> statusNames,
|
||||
Map<String, String> statusMapping) {
|
||||
if (statusMapping != null) {
|
||||
context.statusCodeByNameCache.putAll(statusMapping);
|
||||
}
|
||||
if (statusNames == null) {
|
||||
return;
|
||||
}
|
||||
for (String name : statusNames) {
|
||||
if (name != null && !name.isBlank()) {
|
||||
resolveOrderStatusCode(name, context);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 预加载 ====================
|
||||
|
||||
public void preloadProductSkus(ImportRuntimeContext context, Set<String> skuCodes) {
|
||||
for (List<String> chunk : ImportRuntimeContext.splitToChunks(skuCodes, IN_QUERY_BATCH_SIZE)) {
|
||||
LambdaQueryWrapper<ProductSkuPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ProductSkuPO::getCompanyId, context.getCompanyId())
|
||||
.in(ProductSkuPO::getSkuCode, chunk);
|
||||
for (ProductSkuPO sku : productSkuService.list(wrapper)) {
|
||||
context.skuByCodeCache.put(sku.getSkuCode(), sku);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void preloadProductsByCode(ImportRuntimeContext context, Set<String> productCodes) {
|
||||
for (List<String> chunk : ImportRuntimeContext.splitToChunks(productCodes, IN_QUERY_BATCH_SIZE)) {
|
||||
LambdaQueryWrapper<ProductPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ProductPO::getCompanyId, context.getCompanyId())
|
||||
.in(ProductPO::getProductCode, chunk);
|
||||
for (ProductPO product : productMapper.selectList(wrapper)) {
|
||||
cacheProduct(context, product);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void preloadProductsByName(ImportRuntimeContext context, Set<String> productNames) {
|
||||
for (List<String> chunk : ImportRuntimeContext.splitToChunks(productNames, IN_QUERY_BATCH_SIZE)) {
|
||||
LambdaQueryWrapper<ProductPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ProductPO::getCompanyId, context.getCompanyId())
|
||||
.in(ProductPO::getName, chunk);
|
||||
for (ProductPO product : productMapper.selectList(wrapper)) {
|
||||
cacheProduct(context, product);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按公司 + 平台订单号预加载已存在订单,不按店铺过滤,以便导入任务 {@code shop_id} 变更后仍能命中并更新 {@code shop_id}。
|
||||
* 库表唯一键为 {@code uk_company_platform(company_id, platform_order_no)} 时,同号非空至多一行;若仍出现多行(未迁完库等),
|
||||
* 见 {@link #pickExistingOrderForPlatformNo} 的兜底选择。
|
||||
*/
|
||||
public void preloadPlatformOrderNos(ImportRuntimeContext context, Set<String> platformOrderNos,
|
||||
OrderMapper orderMapper, OrderItemMapper orderItemMapper) {
|
||||
for (List<String> chunk : ImportRuntimeContext.splitToChunks(platformOrderNos, IN_QUERY_BATCH_SIZE)) {
|
||||
LambdaQueryWrapper<OrderPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(OrderPO::getCompanyId, context.getCompanyId())
|
||||
.in(OrderPO::getPlatformOrderNo, chunk);
|
||||
List<OrderPO> rows = orderMapper.selectList(wrapper);
|
||||
Map<String, List<OrderPO>> byNormalized = new HashMap<>();
|
||||
for (OrderPO order : rows) {
|
||||
if (order.getPlatformOrderNo() == null) {
|
||||
continue;
|
||||
}
|
||||
String normalized = order.getPlatformOrderNo().trim();
|
||||
byNormalized.computeIfAbsent(normalized, k -> new ArrayList<>()).add(order);
|
||||
}
|
||||
List<Long> chosenOrderIds = new ArrayList<>();
|
||||
Map<String, OrderPO> chosenByNormalized = new HashMap<>();
|
||||
for (Map.Entry<String, List<OrderPO>> e : byNormalized.entrySet()) {
|
||||
OrderPO chosen = pickExistingOrderForPlatformNo(context, e.getValue());
|
||||
if (chosen == null) {
|
||||
continue;
|
||||
}
|
||||
chosenByNormalized.put(e.getKey(), chosen);
|
||||
chosenOrderIds.add(chosen.getId());
|
||||
}
|
||||
Map<Long, OrderItemPO> firstItemByOrderId = loadFirstItemsByOrderIds(orderItemMapper, chosenOrderIds);
|
||||
for (Map.Entry<String, OrderPO> e : chosenByNormalized.entrySet()) {
|
||||
String normalized = e.getKey();
|
||||
OrderPO chosen = e.getValue();
|
||||
context.existingPlatformOrderNos.add(normalized);
|
||||
context.existingOrderIdByPlatformNo.put(normalized, chosen.getId());
|
||||
context.existingOrderSnapshotByPlatformNo.put(normalized,
|
||||
new OrderImportSnapshot(chosen, firstItemByOrderId.get(chosen.getId())));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<Long, OrderItemPO> loadFirstItemsByOrderIds(OrderItemMapper orderItemMapper,
|
||||
List<Long> orderIds) {
|
||||
if (orderIds == null || orderIds.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
LambdaQueryWrapper<OrderItemPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.in(OrderItemPO::getOrderId, orderIds).orderByAsc(OrderItemPO::getLineNo);
|
||||
Map<Long, OrderItemPO> map = new HashMap<>();
|
||||
for (OrderItemPO item : orderItemMapper.selectList(wrapper)) {
|
||||
map.putIfAbsent(item.getOrderId(), item);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* 正常库结构下同一 {@code (company_id, platform_order_no)}(非空)仅一行。
|
||||
* 若多行:优先与当前导入任务 {@code shop_id} 一致的一条;否则取 {@code id} 最大(兼容迁移前重复数据)。
|
||||
*/
|
||||
private static OrderPO pickExistingOrderForPlatformNo(ImportRuntimeContext context,
|
||||
List<OrderPO> samePlatform) {
|
||||
if (samePlatform == null || samePlatform.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
if (samePlatform.size() == 1) {
|
||||
return samePlatform.get(0);
|
||||
}
|
||||
Long taskShopId = context.getShopId();
|
||||
if (taskShopId != null) {
|
||||
List<OrderPO> matchTaskShop = new ArrayList<>();
|
||||
for (OrderPO o : samePlatform) {
|
||||
if (taskShopId.equals(o.getShopId())) {
|
||||
matchTaskShop.add(o);
|
||||
}
|
||||
}
|
||||
if (matchTaskShop.size() == 1) {
|
||||
return matchTaskShop.get(0);
|
||||
}
|
||||
if (matchTaskShop.size() > 1) {
|
||||
return matchTaskShop.stream().max(Comparator.comparing(OrderPO::getId)).orElseThrow();
|
||||
}
|
||||
}
|
||||
return samePlatform.stream().max(Comparator.comparing(OrderPO::getId)).orElse(null);
|
||||
}
|
||||
|
||||
public void preloadShopProductRelations(ImportRuntimeContext context,
|
||||
ShopProductRelationMapper shopProductRelationMapper) {
|
||||
LambdaQueryWrapper<ShopProductRelationPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ShopProductRelationPO::getCompanyId, context.getCompanyId())
|
||||
.eq(ShopProductRelationPO::getShopId, context.getShopId())
|
||||
.select(ShopProductRelationPO::getProductId);
|
||||
for (ShopProductRelationPO relation : shopProductRelationMapper.selectList(wrapper)) {
|
||||
context.existingRelationKeys.add(context.buildRelationKey(context.getShopId(), relation.getProductId()));
|
||||
}
|
||||
}
|
||||
|
||||
public void ensureShopProductRelation(Long shopId, Long productId, Long companyId, Long createBy) {
|
||||
LambdaQueryWrapper<ShopProductRelationPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ShopProductRelationPO::getShopId, shopId)
|
||||
.eq(ShopProductRelationPO::getProductId, productId)
|
||||
.eq(ShopProductRelationPO::getCompanyId, companyId);
|
||||
ShopProductRelationPO existing = shopProductRelationMapper.selectOne(wrapper);
|
||||
if (existing == null) {
|
||||
ShopProductRelationPO relation = new ShopProductRelationPO();
|
||||
relation.setCompanyId(companyId);
|
||||
relation.setShopId(shopId);
|
||||
relation.setProductId(productId);
|
||||
relation.setSortOrder(0);
|
||||
relation.setCreateBy(createBy);
|
||||
shopProductRelationMapper.insert(relation);
|
||||
}
|
||||
}
|
||||
}
|
||||
-62
@@ -1,62 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.util;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* 导入任务明细消息拼接器,限制明细条数与 UTF-8 字节长度,避免写入任务表时溢出。
|
||||
*/
|
||||
public class ImportTaskMessageAppender {
|
||||
|
||||
/** 预留摘要等文案空间,略小于 {@code ImportTaskProcessorServiceImpl} 的 60000 字节上限 */
|
||||
private static final int MAX_MESSAGE_BYTES = 55_000;
|
||||
private static final int MAX_DETAIL_LINES = 100;
|
||||
|
||||
private final StringBuilder buffer = new StringBuilder();
|
||||
private int detailLineCount;
|
||||
private int suppressedLineCount;
|
||||
|
||||
/**
|
||||
* 追加一行明细;超出条数或字节上限时仅累计抑制条数,不再写入。
|
||||
*
|
||||
* @return 是否已写入 buffer
|
||||
*/
|
||||
public boolean appendDetailLine(String line) {
|
||||
if (line == null || line.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
if (detailLineCount >= MAX_DETAIL_LINES) {
|
||||
suppressedLineCount++;
|
||||
return false;
|
||||
}
|
||||
String entry = line.strip() + System.lineSeparator();
|
||||
if (currentUtf8Length() + entry.getBytes(StandardCharsets.UTF_8).length > MAX_MESSAGE_BYTES) {
|
||||
suppressedLineCount++;
|
||||
return false;
|
||||
}
|
||||
buffer.append(entry);
|
||||
detailLineCount++;
|
||||
return true;
|
||||
}
|
||||
|
||||
public int getSuppressedLineCount() {
|
||||
return suppressedLineCount;
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return buffer.length() == 0 && suppressedLineCount == 0;
|
||||
}
|
||||
|
||||
public String build() {
|
||||
if (suppressedLineCount > 0) {
|
||||
String suffix = String.format("(另有 %d 条明细未展示)%n", suppressedLineCount);
|
||||
if (currentUtf8Length() + suffix.getBytes(StandardCharsets.UTF_8).length <= MAX_MESSAGE_BYTES) {
|
||||
buffer.append(suffix);
|
||||
}
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
private int currentUtf8Length() {
|
||||
return buffer.toString().getBytes(StandardCharsets.UTF_8).length;
|
||||
}
|
||||
}
|
||||
-102
@@ -1,102 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.util;
|
||||
|
||||
import org.apache.commons.csv.CSVFormat;
|
||||
import org.apache.commons.csv.CSVParser;
|
||||
import org.apache.commons.csv.CSVRecord;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.model.dto.OrderImportMappingConfig;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.model.dto.OrderImportRow;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 订单导入 CSV 解析工具:按字段映射与状态映射解析 CSV,得到订单行数据列表。
|
||||
*/
|
||||
public final class OrderImportCsvParser {
|
||||
|
||||
private static final String BOM = "\uFEFF";
|
||||
|
||||
private OrderImportCsvParser() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 从文件路径解析订单导入 CSV
|
||||
*
|
||||
* @param filePath 文件路径(可为相对 user.dir 或绝对路径)
|
||||
* @param config 字段映射与状态映射配置
|
||||
* @return 解析后的订单行列表(不含表头)
|
||||
* @throws IOException 读取或解析失败
|
||||
*/
|
||||
public static List<OrderImportRow> parse(Path filePath, OrderImportMappingConfig config) throws IOException {
|
||||
try (InputStream in = Files.newInputStream(filePath)) {
|
||||
return parse(in, config);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从输入流解析订单导入 CSV(UTF-8)
|
||||
*
|
||||
* @param inputStream 输入流
|
||||
* @param config 字段映射与状态映射配置
|
||||
* @return 解析后的订单行列表(不含表头)
|
||||
* @throws IOException 读取或解析失败
|
||||
*/
|
||||
public static List<OrderImportRow> parse(InputStream inputStream, OrderImportMappingConfig config) throws IOException {
|
||||
if (config == null || config.getFieldMapping() == null || config.getFieldMapping().isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
List<OrderImportMappingConfig.FieldMappingItem> fieldMapping = config.getFieldMapping();
|
||||
// CSV 表头名 -> 实体字段名
|
||||
Map<String, String> fileHeaderToField = new HashMap<>();
|
||||
for (OrderImportMappingConfig.FieldMappingItem item : fieldMapping) {
|
||||
if (item.getFileFieldName() != null && item.getFieldName() != null) {
|
||||
fileHeaderToField.put(item.getFileFieldName().trim(), item.getFieldName());
|
||||
}
|
||||
}
|
||||
|
||||
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
|
||||
CSVFormat format = CSVFormat.DEFAULT.builder()
|
||||
.setHeader()
|
||||
.setSkipHeaderRecord(true)
|
||||
.setTrim(true)
|
||||
.setIgnoreEmptyLines(true)
|
||||
.build();
|
||||
|
||||
List<OrderImportRow> rows = new ArrayList<>();
|
||||
try (CSVParser parser = CSVParser.parse(reader, format)) {
|
||||
List<String> headerNames = parser.getHeaderNames();
|
||||
if (headerNames == null) {
|
||||
return rows;
|
||||
}
|
||||
|
||||
int rowIndex = 1;
|
||||
for (CSVRecord record : parser) {
|
||||
rowIndex++;
|
||||
Map<String, String> values = new HashMap<>();
|
||||
for (String fileHeader : headerNames) {
|
||||
if (fileHeader == null) continue;
|
||||
String normalizedHeader = fileHeader.startsWith(BOM) ? fileHeader.substring(BOM.length()).trim() : fileHeader.trim();
|
||||
String fieldName = fileHeaderToField.get(normalizedHeader);
|
||||
if (fieldName != null) {
|
||||
String value = record.get(fileHeader);
|
||||
if (value != null) {
|
||||
value = value.trim();
|
||||
}
|
||||
values.put(fieldName, value);
|
||||
}
|
||||
}
|
||||
rows.add(new OrderImportRow(rowIndex, values));
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
}
|
||||
-119
@@ -1,119 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.imports.task.worker;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.config.ImportTaskProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.config.ImportTaskStreamNames;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.model.po.ImportTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.queue.ImportTaskRedisQueue;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.service.ImportTaskQueueService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.service.ImportTaskService;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 启动恢复 + 定时对账:DB 真相源补入 Redis Stream。
|
||||
*/
|
||||
@Service
|
||||
public class ImportTaskRecoveryService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ImportTaskRecoveryService.class);
|
||||
|
||||
private final ImportTaskService importTaskService;
|
||||
private final ImportTaskQueueService importTaskQueueService;
|
||||
private final ImportTaskRedisQueue redisQueue;
|
||||
private final ImportTaskStreamNames streamNames;
|
||||
private final ImportTaskProperties properties;
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
|
||||
public ImportTaskRecoveryService(ImportTaskService importTaskService,
|
||||
ImportTaskQueueService importTaskQueueService,
|
||||
ImportTaskRedisQueue redisQueue,
|
||||
ImportTaskStreamNames streamNames,
|
||||
ImportTaskProperties properties,
|
||||
StringRedisTemplate stringRedisTemplate) {
|
||||
this.importTaskService = importTaskService;
|
||||
this.importTaskQueueService = importTaskQueueService;
|
||||
this.redisQueue = redisQueue;
|
||||
this.streamNames = streamNames;
|
||||
this.properties = properties;
|
||||
this.stringRedisTemplate = stringRedisTemplate;
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动时执行一次全量对账。
|
||||
*/
|
||||
public void recoverOnStartup() {
|
||||
if (!properties.getQueue().isEnabled()) {
|
||||
log.info("导入任务 Redis 队列未启用,跳过启动对账");
|
||||
return;
|
||||
}
|
||||
log.info("导入任务启动对账开始...");
|
||||
for (String type : ImportTaskStreamNames.ALL_TYPES) {
|
||||
String streamKey = streamNames.streamKey(type);
|
||||
redisQueue.ensureConsumerGroup(streamKey, streamNames.consumerGroup());
|
||||
}
|
||||
reconcileInternal();
|
||||
log.info("导入任务启动对账完成");
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelayString = "${import-task.queue.reconcile-interval-ms:60000}")
|
||||
public void scheduledReconcile() {
|
||||
if (!properties.getQueue().isEnabled()) {
|
||||
return;
|
||||
}
|
||||
if (!tryAcquireReconcileLock()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
reconcileInternal();
|
||||
} finally {
|
||||
releaseReconcileLock();
|
||||
}
|
||||
}
|
||||
|
||||
private void reconcileInternal() {
|
||||
recoverStuckProcessingTasks();
|
||||
reenqueuePendingTasks();
|
||||
}
|
||||
|
||||
private void recoverStuckProcessingTasks() {
|
||||
long stuckMs = properties.getQueue().getStuckProcessingMs();
|
||||
List<ImportTaskPO> stuckTasks = importTaskService.listStuckProcessingTasks(stuckMs);
|
||||
if (stuckTasks.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
log.warn("发现 {} 个 processing 超时任务,重置为 pending", stuckTasks.size());
|
||||
for (ImportTaskPO task : stuckTasks) {
|
||||
importTaskService.resetToPendingForRecovery(task.getId(), "处理超时,自动恢复");
|
||||
importTaskQueueService.publishImportTask(task.getId());
|
||||
}
|
||||
}
|
||||
|
||||
private void reenqueuePendingTasks() {
|
||||
List<ImportTaskPO> pendingTasks = importTaskService.listPendingEnqueueTasks();
|
||||
if (pendingTasks.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
log.info("对账补入队 {} 个 pending 任务", pendingTasks.size());
|
||||
for (ImportTaskPO task : pendingTasks) {
|
||||
importTaskQueueService.publishImportTask(task.getId());
|
||||
}
|
||||
}
|
||||
|
||||
private boolean tryAcquireReconcileLock() {
|
||||
Boolean ok = stringRedisTemplate.opsForValue().setIfAbsent(
|
||||
streamNames.reconcileLockKey(),
|
||||
"1",
|
||||
Duration.ofSeconds(properties.getQueue().getReconcileLockSeconds()));
|
||||
return Boolean.TRUE.equals(ok);
|
||||
}
|
||||
|
||||
private void releaseReconcileLock() {
|
||||
stringRedisTemplate.delete(streamNames.reconcileLockKey());
|
||||
}
|
||||
}
|
||||
-11
@@ -7,16 +7,13 @@ import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.dto.BatchDeleteOrderDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.dto.BatchImportOrderDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.dto.CreateOrderDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.dto.OrderFilterDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.dto.UpdateOrderDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.vo.BatchImportResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.vo.OrderFieldConstants;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.vo.OrderFieldVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.vo.OrderVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.service.OrderService;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.license.LicenseRequired;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.license.RequiresOrderCreateLicense;
|
||||
|
||||
import java.util.List;
|
||||
@@ -81,14 +78,6 @@ public class OrderController {
|
||||
return ApiResponse.success("获取订单详情成功", orderVO);
|
||||
}
|
||||
|
||||
@PostMapping("/batch-import")
|
||||
@LicenseRequired
|
||||
@RequirePermission(value = "ec:order:import", description = "批量导入订单", allowSuper = true)
|
||||
public ApiResponse<BatchImportResultVO> batchImportOrders(@Valid @RequestBody BatchImportOrderDTO batchImportOrderDTO) {
|
||||
BatchImportResultVO result = orderService.batchImportOrders(batchImportOrderDTO);
|
||||
return ApiResponse.success("批量导入订单成功", result);
|
||||
}
|
||||
|
||||
@GetMapping("/fields")
|
||||
@RequirePermission(value = "ec:order:read", description = "获取订单字段信息列表", allowSuper = true)
|
||||
public ApiResponse<List<OrderFieldVO>> getOrderFieldDefs() {
|
||||
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.order.model.dto;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 批量导入订单DTO
|
||||
*/
|
||||
@Data
|
||||
public class BatchImportOrderDTO {
|
||||
|
||||
/**
|
||||
* 订单列表
|
||||
*/
|
||||
@NotEmpty(message = "订单列表不能为空")
|
||||
@Valid
|
||||
private List<CreateOrderDTO> orders;
|
||||
}
|
||||
-59
@@ -1,59 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.order.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 批量导入结果VO
|
||||
*/
|
||||
@Data
|
||||
public class BatchImportResultVO {
|
||||
|
||||
/**
|
||||
* 总数量
|
||||
*/
|
||||
private Integer totalCount;
|
||||
|
||||
/**
|
||||
* 成功数量
|
||||
*/
|
||||
private Integer successCount;
|
||||
|
||||
/**
|
||||
* 失败数量
|
||||
*/
|
||||
private Integer failureCount;
|
||||
|
||||
/**
|
||||
* 成功创建的订单列表
|
||||
*/
|
||||
private List<OrderVO> successOrders;
|
||||
|
||||
/**
|
||||
* 失败记录列表
|
||||
*/
|
||||
private List<ImportFailureRecord> failureRecords;
|
||||
|
||||
/**
|
||||
* 导入失败记录
|
||||
*/
|
||||
@Data
|
||||
public static class ImportFailureRecord {
|
||||
|
||||
/**
|
||||
* 失败行号(从1开始)
|
||||
*/
|
||||
private Integer rowNumber;
|
||||
|
||||
/**
|
||||
* 平台订单号
|
||||
*/
|
||||
private String platformOrderNo;
|
||||
|
||||
/**
|
||||
* 失败原因
|
||||
*/
|
||||
private String failureReason;
|
||||
}
|
||||
}
|
||||
-20
@@ -3,12 +3,10 @@ package top.xyquan.ecomdmbbackend.modules.ec.order.service;
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.dto.BatchImportOrderDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.dto.CreateOrderDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.dto.OrderFilterDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.dto.UpdateOrderDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.vo.BatchImportResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.vo.OrderVO;
|
||||
|
||||
import java.util.List;
|
||||
@@ -65,24 +63,6 @@ public interface OrderService extends IService<OrderPO> {
|
||||
*/
|
||||
OrderVO getOrderById(Long id);
|
||||
|
||||
/**
|
||||
* 批量导入订单
|
||||
*
|
||||
* @param batchImportOrderDTO 批量导入订单DTO
|
||||
* @return 批量导入结果VO
|
||||
*/
|
||||
BatchImportResultVO batchImportOrders(BatchImportOrderDTO batchImportOrderDTO);
|
||||
|
||||
/**
|
||||
* 导入场景下创建订单(不依赖当前请求用户上下文)
|
||||
*
|
||||
* @param createOrderDTO 创建订单DTO
|
||||
* @param companyId 公司ID
|
||||
* @param userId 操作人ID
|
||||
* @return 订单VO
|
||||
*/
|
||||
OrderVO createOrderForImport(CreateOrderDTO createOrderDTO, Long companyId, Long userId);
|
||||
|
||||
/**
|
||||
* 在指定公司下,返回传入规格 ID 中存在至少一条订单的子集(无顺序保证,调用方可再与期望顺序求交)
|
||||
*
|
||||
|
||||
-59
@@ -10,7 +10,6 @@ import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderItemMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.dto.BatchImportOrderDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.dto.CreateOrderDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.dto.CreateOrderItemDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.dto.OrderFilterDTO;
|
||||
@@ -23,7 +22,6 @@ import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.model.po.ProductSkuPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.vo.BatchImportResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.vo.OrderItemVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.vo.OrderVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.vo.ProductVO;
|
||||
@@ -97,25 +95,6 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
|
||||
return convertToVO(order);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public OrderVO createOrderForImport(CreateOrderDTO createOrderDTO, Long companyId, Long userId) {
|
||||
ShopPO shop = requireShop(createOrderDTO.getShopId(), companyId);
|
||||
List<CreateOrderItemDTO> itemDtos = OrderDtoSupport.resolveItems(createOrderDTO);
|
||||
validateItems(itemDtos, companyId);
|
||||
validateOrderStatus(createOrderDTO.getStatus());
|
||||
assertPlatformOrderNoUnique(createOrderDTO.getPlatformOrderNo(), companyId,
|
||||
createOrderDTO.getShopId(), null);
|
||||
|
||||
OrderPO order = new OrderPO();
|
||||
order.setCompanyId(companyId);
|
||||
OrderDtoSupport.applyHeaderFromCreate(createOrderDTO, order, shop.getPlatformCode());
|
||||
order.setCreateBy(userId);
|
||||
this.save(order);
|
||||
saveItems(order, itemDtos, companyId, userId);
|
||||
return convertToVO(order);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public OrderVO updateOrder(UpdateOrderDTO updateOrderDTO, Long id) {
|
||||
@@ -224,44 +203,6 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
|
||||
return convertToVO(order);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public BatchImportResultVO batchImportOrders(BatchImportOrderDTO batchImportOrderDTO) {
|
||||
licenseFeatureGuard.require(LicenseFeature.ORDER_IMPORT);
|
||||
List<CreateOrderDTO> orders = batchImportOrderDTO.getOrders();
|
||||
List<OrderVO> successOrders = new ArrayList<>();
|
||||
List<BatchImportResultVO.ImportFailureRecord> failureRecords = new ArrayList<>();
|
||||
int successCount = 0;
|
||||
int failureCount = 0;
|
||||
Long importCompanyId = currentUserContext.getCurrentCompanyId();
|
||||
Long importUserId = currentUserContext.getCurrentUserId();
|
||||
|
||||
for (int i = 0; i < orders.size(); i++) {
|
||||
CreateOrderDTO rowOrder = orders.get(i);
|
||||
int rowNumber = i + 1;
|
||||
try {
|
||||
OrderVO orderVO = this.createOrderForImport(rowOrder, importCompanyId, importUserId);
|
||||
successOrders.add(orderVO);
|
||||
successCount++;
|
||||
} catch (Exception e) {
|
||||
BatchImportResultVO.ImportFailureRecord failureRecord = new BatchImportResultVO.ImportFailureRecord();
|
||||
failureRecord.setRowNumber(rowNumber);
|
||||
failureRecord.setPlatformOrderNo(rowOrder.getPlatformOrderNo());
|
||||
failureRecord.setFailureReason(e.getMessage());
|
||||
failureRecords.add(failureRecord);
|
||||
failureCount++;
|
||||
}
|
||||
}
|
||||
|
||||
BatchImportResultVO result = new BatchImportResultVO();
|
||||
result.setTotalCount(orders.size());
|
||||
result.setSuccessCount(successCount);
|
||||
result.setFailureCount(failureCount);
|
||||
result.setSuccessOrders(successOrders);
|
||||
result.setFailureRecords(failureRecords);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Long> skuIdsHavingOrders(Long companyId, List<Long> skuIds) {
|
||||
if (skuIds == null || skuIds.isEmpty()) {
|
||||
|
||||
-436
@@ -1,436 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.shop.adfee.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import org.apache.commons.csv.CSVFormat;
|
||||
import org.apache.commons.csv.CSVParser;
|
||||
import org.apache.commons.csv.CSVRecord;
|
||||
import org.apache.poi.ss.usermodel.*;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.model.po.ImportTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.imports.task.util.ImportTaskMessageAppender;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.adfee.mapper.AdFeeMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.adfee.model.po.AdFeePO;
|
||||
|
||||
import java.io.*;
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.charset.Charset;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 广告费导入处理器
|
||||
* 负责解析 CSV/Excel 文件中的推广费数据,按字段映射提取 campaignName/feeAmount,
|
||||
* 从文件列中直接读取 productId,按 product_id + fee_date 联合唯一 upsert 写入 ec_product_ad_fee。
|
||||
*/
|
||||
@Service
|
||||
public class AdFeeImportProcessor extends ServiceImpl<AdFeeMapper, AdFeePO> {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(AdFeeImportProcessor.class);
|
||||
/** 每批处理条数 */
|
||||
private static final int BATCH_SIZE = 500;
|
||||
/** 推广费金额不合规时的统一失败原因 */
|
||||
private static final String INVALID_FEE_AMOUNT_REASON = "推广费金额为空或须大于0";
|
||||
|
||||
/**
|
||||
* 执行导入
|
||||
*/
|
||||
public ImportResult processImport(ImportTaskPO task, File file, Charset charset,
|
||||
Map<String, String> fieldMapping, String feeDateStr) throws Exception {
|
||||
boolean isExcel = file.getName().toLowerCase().endsWith(".xlsx")
|
||||
|| file.getName().toLowerCase().endsWith(".xls");
|
||||
ParseResult parseResult = isExcel
|
||||
? parseExcel(file, fieldMapping, feeDateStr, task)
|
||||
: parseCsv(file, charset, fieldMapping, feeDateStr, task);
|
||||
|
||||
if (parseResult.totalCount == 0) {
|
||||
return new ImportResult(0, 0, 0, "文件中没有有效数据");
|
||||
}
|
||||
|
||||
List<AdFeePO> records = collapseByProductDate(parseResult.records);
|
||||
int success = 0;
|
||||
int upsertFailCount = 0;
|
||||
ImportTaskMessageAppender detailMessages = parseResult.detailMessages;
|
||||
|
||||
for (int i = 0; i < records.size(); i += BATCH_SIZE) {
|
||||
int end = Math.min(i + BATCH_SIZE, records.size());
|
||||
List<AdFeePO> batch = records.subList(i, end);
|
||||
try {
|
||||
success += upsertBatch(batch);
|
||||
} catch (Exception e) {
|
||||
upsertFailCount += batch.size();
|
||||
detailMessages.appendDetailLine(String.format("第%d~%d条:批量写入失败,%s",
|
||||
i + 1, end, e.getMessage()));
|
||||
log.error("批量写入广告费记录失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
return new ImportResult(
|
||||
parseResult.totalCount,
|
||||
success,
|
||||
parseResult.failCount + upsertFailCount,
|
||||
detailMessages.build());
|
||||
}
|
||||
|
||||
/**
|
||||
* 同文件内相同 productId + feeDate 保留最后一行,避免撞唯一键。
|
||||
*/
|
||||
private List<AdFeePO> collapseByProductDate(List<AdFeePO> records) {
|
||||
LinkedHashMap<String, AdFeePO> byKey = new LinkedHashMap<>();
|
||||
for (AdFeePO po : records) {
|
||||
if (po.getProductId() == null || po.getFeeDate() == null) {
|
||||
continue;
|
||||
}
|
||||
byKey.put(po.getProductId() + "|" + po.getFeeDate(), po);
|
||||
}
|
||||
return new ArrayList<>(byKey.values());
|
||||
}
|
||||
|
||||
private int upsertBatch(List<AdFeePO> batch) {
|
||||
if (batch.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
LocalDate feeDate = batch.get(0).getFeeDate();
|
||||
List<Long> productIds = batch.stream()
|
||||
.map(AdFeePO::getProductId)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
if (productIds.isEmpty() || feeDate == null) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
Map<Long, AdFeePO> existingByProduct = new HashMap<>();
|
||||
List<AdFeePO> existing = list(new LambdaQueryWrapper<AdFeePO>()
|
||||
.eq(AdFeePO::getFeeDate, feeDate)
|
||||
.in(AdFeePO::getProductId, productIds));
|
||||
for (AdFeePO po : existing) {
|
||||
existingByProduct.put(po.getProductId(), po);
|
||||
}
|
||||
|
||||
List<AdFeePO> toInsert = new ArrayList<>();
|
||||
List<AdFeePO> toUpdate = new ArrayList<>();
|
||||
for (AdFeePO incoming : batch) {
|
||||
if (incoming.getProductId() == null) {
|
||||
continue;
|
||||
}
|
||||
AdFeePO found = existingByProduct.get(incoming.getProductId());
|
||||
if (found == null) {
|
||||
toInsert.add(incoming);
|
||||
continue;
|
||||
}
|
||||
found.setShopId(incoming.getShopId());
|
||||
found.setCampaignName(incoming.getCampaignName());
|
||||
found.setFeeAmount(incoming.getFeeAmount());
|
||||
found.setRemark(incoming.getRemark());
|
||||
found.setUpdateBy(incoming.getUpdateBy());
|
||||
toUpdate.add(found);
|
||||
}
|
||||
|
||||
if (!toInsert.isEmpty()) {
|
||||
saveBatch(toInsert);
|
||||
}
|
||||
if (!toUpdate.isEmpty()) {
|
||||
updateBatchById(toUpdate);
|
||||
}
|
||||
return toInsert.size() + toUpdate.size();
|
||||
}
|
||||
|
||||
private ParseResult parseCsv(File file, Charset charset,
|
||||
Map<String, String> fieldMapping, String feeDateStr,
|
||||
ImportTaskPO task) throws IOException {
|
||||
ParseResult result = new ParseResult();
|
||||
try (Reader reader = new InputStreamReader(new FileInputStream(file), charset);
|
||||
CSVParser parser = CSVFormat.DEFAULT.builder()
|
||||
.setHeader()
|
||||
.setSkipHeaderRecord(true)
|
||||
.setTrim(true)
|
||||
.build()
|
||||
.parse(reader)) {
|
||||
|
||||
LocalDate feeDate = parseFeeDate(feeDateStr);
|
||||
Map<String, Integer> headerMap = parser.getHeaderMap();
|
||||
for (CSVRecord record : parser) {
|
||||
int rowNumber = (int) record.getRecordNumber();
|
||||
Function<String, String> cellGetter = colName -> getCsvColumnValue(record, headerMap, colName);
|
||||
collectRow(result, rowNumber, cellGetter, fieldMapping, feeDate, task);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private ParseResult parseExcel(File file, Map<String, String> fieldMapping,
|
||||
String feeDateStr, ImportTaskPO task) throws IOException {
|
||||
ParseResult result = new ParseResult();
|
||||
Workbook workbook = null;
|
||||
try {
|
||||
workbook = file.getName().toLowerCase().endsWith(".xlsx")
|
||||
? createXssfWorkbook(file) : new HSSFWorkbook(new FileInputStream(file));
|
||||
Sheet sheet = workbook.getSheetAt(0);
|
||||
if (sheet == null) {
|
||||
return result;
|
||||
}
|
||||
|
||||
Row headerRow = sheet.getRow(0);
|
||||
if (headerRow == null) {
|
||||
return result;
|
||||
}
|
||||
|
||||
Map<String, Integer> headerIndex = new HashMap<>();
|
||||
for (int i = 0; i < headerRow.getLastCellNum(); i++) {
|
||||
Cell cell = headerRow.getCell(i);
|
||||
if (cell != null) {
|
||||
headerIndex.put(normalizeColumnName(getCellStringValue(cell)), i);
|
||||
}
|
||||
}
|
||||
|
||||
LocalDate feeDate = parseFeeDate(feeDateStr);
|
||||
for (int rowIdx = 1; rowIdx <= sheet.getLastRowNum(); rowIdx++) {
|
||||
Row row = sheet.getRow(rowIdx);
|
||||
if (row == null) {
|
||||
continue;
|
||||
}
|
||||
int rowNumber = rowIdx + 1;
|
||||
Function<String, String> cellGetter = colName -> {
|
||||
Integer idx = headerIndex.get(normalizeColumnName(colName));
|
||||
if (idx == null) {
|
||||
return null;
|
||||
}
|
||||
Cell cell = row.getCell(idx);
|
||||
return cell == null ? null : getCellStringValue(cell);
|
||||
};
|
||||
collectRow(result, rowNumber, cellGetter, fieldMapping, feeDate, task);
|
||||
}
|
||||
} finally {
|
||||
if (workbook != null) {
|
||||
try {
|
||||
workbook.close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private void collectRow(ParseResult result, int rowNumber, Function<String, String> cellGetter,
|
||||
Map<String, String> fieldMapping, LocalDate feeDate, ImportTaskPO task) {
|
||||
result.totalCount++;
|
||||
RowBuildResult buildResult = buildPo(cellGetter, fieldMapping, feeDate, task);
|
||||
if (buildResult.po != null) {
|
||||
result.records.add(buildResult.po);
|
||||
result.recordStartRows.add(rowNumber);
|
||||
return;
|
||||
}
|
||||
if (buildResult.failReason != null) {
|
||||
result.failCount++;
|
||||
result.detailMessages.appendDetailLine(formatFailLine(rowNumber, buildResult.failReason,
|
||||
buildResult.campaignName));
|
||||
}
|
||||
}
|
||||
|
||||
private static String formatFailLine(int rowNumber, String reason, String campaignName) {
|
||||
if (campaignName != null && !campaignName.isBlank()) {
|
||||
return String.format("第%d行:%s(%s)", rowNumber, reason, campaignName.trim());
|
||||
}
|
||||
return String.format("第%d行:%s", rowNumber, reason);
|
||||
}
|
||||
|
||||
private RowBuildResult buildPo(Function<String, String> cellGetter,
|
||||
Map<String, String> fieldMapping, LocalDate feeDate,
|
||||
ImportTaskPO task) {
|
||||
String campaignName = getMappedValue(cellGetter, fieldMapping, "campaignName");
|
||||
String feeAmountStr = getMappedValue(cellGetter, fieldMapping, "feeAmount");
|
||||
|
||||
if (!isValidFeeAmount(feeAmountStr)) {
|
||||
return RowBuildResult.invalid(INVALID_FEE_AMOUNT_REASON, campaignName);
|
||||
}
|
||||
|
||||
BigDecimal feeAmount = new BigDecimal(normalizeFeeAmount(feeAmountStr));
|
||||
Long productId = parseLong(cellGetter.apply("productId"));
|
||||
if (productId == null) {
|
||||
return RowBuildResult.invalid("商品ID不能为空", campaignName);
|
||||
}
|
||||
|
||||
AdFeePO po = new AdFeePO();
|
||||
po.setCompanyId(task.getCompanyId());
|
||||
po.setShopId(task.getShopId());
|
||||
po.setFeeDate(feeDate);
|
||||
po.setProductId(productId);
|
||||
po.setCampaignName(campaignName);
|
||||
po.setFeeAmount(feeAmount);
|
||||
po.setCreateBy(task.getCreateBy());
|
||||
po.setUpdateBy(task.getCreateBy());
|
||||
return RowBuildResult.ok(po);
|
||||
}
|
||||
|
||||
private String getCsvColumnValue(CSVRecord record, Map<String, Integer> headerMap, String colName) {
|
||||
String headerKey = resolveHeaderKey(headerMap, colName);
|
||||
if (headerKey == null) {
|
||||
return null;
|
||||
}
|
||||
return record.get(headerKey);
|
||||
}
|
||||
|
||||
private static String resolveHeaderKey(Map<String, Integer> headerMap, String colName) {
|
||||
if (colName == null || colName.isBlank() || headerMap == null) {
|
||||
return null;
|
||||
}
|
||||
String normalized = normalizeColumnName(colName);
|
||||
if (headerMap.containsKey(normalized)) {
|
||||
return normalized;
|
||||
}
|
||||
for (String header : headerMap.keySet()) {
|
||||
if (normalizeColumnName(header).equals(normalized)) {
|
||||
return header;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String normalizeColumnName(String name) {
|
||||
if (name == null) {
|
||||
return "";
|
||||
}
|
||||
return name.replace("\uFEFF", "").trim();
|
||||
}
|
||||
|
||||
private String getMappedValue(Function<String, String> cellGetter,
|
||||
Map<String, String> fieldMapping, String fieldName) {
|
||||
String fileColumn = fieldMapping.get(fieldName);
|
||||
if (fileColumn == null) {
|
||||
return null;
|
||||
}
|
||||
return cellGetter.apply(fileColumn);
|
||||
}
|
||||
|
||||
private static boolean isValidFeeAmount(String feeAmountStr) {
|
||||
if (feeAmountStr == null || feeAmountStr.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
String normalized = normalizeFeeAmount(feeAmountStr);
|
||||
if (normalized.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
return new BigDecimal(normalized).compareTo(BigDecimal.ZERO) > 0;
|
||||
} catch (NumberFormatException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static String normalizeFeeAmount(String feeAmountStr) {
|
||||
return feeAmountStr.trim().replace(",", "");
|
||||
}
|
||||
|
||||
private Long parseLong(String value) {
|
||||
if (value == null || value.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Long.parseLong(value.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private LocalDate parseFeeDate(String feeDateStr) {
|
||||
if (feeDateStr == null || feeDateStr.isBlank()) {
|
||||
return LocalDate.now();
|
||||
}
|
||||
try {
|
||||
return LocalDate.parse(feeDateStr.trim(), DateTimeFormatter.ISO_LOCAL_DATE);
|
||||
} catch (Exception e) {
|
||||
return LocalDate.now();
|
||||
}
|
||||
}
|
||||
|
||||
private String getCellStringValue(Cell cell) {
|
||||
if (cell == null) {
|
||||
return "";
|
||||
}
|
||||
return switch (cell.getCellType()) {
|
||||
case STRING -> cell.getStringCellValue();
|
||||
case NUMERIC -> {
|
||||
double val = cell.getNumericCellValue();
|
||||
if (val == Math.floor(val) && !Double.isInfinite(val)) {
|
||||
yield String.valueOf((long) val);
|
||||
}
|
||||
yield String.valueOf(val);
|
||||
}
|
||||
case BOOLEAN -> String.valueOf(cell.getBooleanCellValue());
|
||||
case FORMULA -> {
|
||||
try {
|
||||
yield String.valueOf(cell.getNumericCellValue());
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
yield cell.getStringCellValue();
|
||||
} catch (Exception e2) {
|
||||
yield "";
|
||||
}
|
||||
}
|
||||
}
|
||||
default -> "";
|
||||
};
|
||||
}
|
||||
|
||||
private static XSSFWorkbook createXssfWorkbook(File file) throws IOException {
|
||||
try {
|
||||
return new XSSFWorkbook(file);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new IOException("无法打开Excel文件: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private static class ParseResult {
|
||||
final List<AdFeePO> records = new ArrayList<>();
|
||||
/** 与 records 一一对应,用于插入失败时标注行号 */
|
||||
final List<Integer> recordStartRows = new ArrayList<>();
|
||||
final ImportTaskMessageAppender detailMessages = new ImportTaskMessageAppender();
|
||||
int totalCount;
|
||||
int failCount;
|
||||
}
|
||||
|
||||
private static class RowBuildResult {
|
||||
final AdFeePO po;
|
||||
final String failReason;
|
||||
final String campaignName;
|
||||
|
||||
private RowBuildResult(AdFeePO po, String failReason, String campaignName) {
|
||||
this.po = po;
|
||||
this.failReason = failReason;
|
||||
this.campaignName = campaignName;
|
||||
}
|
||||
|
||||
static RowBuildResult ok(AdFeePO po) {
|
||||
return new RowBuildResult(po, null, null);
|
||||
}
|
||||
|
||||
static RowBuildResult invalid(String reason, String campaignName) {
|
||||
return new RowBuildResult(null, reason, campaignName);
|
||||
}
|
||||
}
|
||||
|
||||
public static class ImportResult {
|
||||
public final int totalCount;
|
||||
public final int successCount;
|
||||
public final int failCount;
|
||||
/** 失败明细(已限制条数与长度) */
|
||||
public final String detailMessage;
|
||||
|
||||
public ImportResult(int totalCount, int successCount, int failCount, String detailMessage) {
|
||||
this.totalCount = totalCount;
|
||||
this.successCount = successCount;
|
||||
this.failCount = failCount;
|
||||
this.detailMessage = detailMessage == null ? "" : detailMessage;
|
||||
}
|
||||
}
|
||||
}
|
||||
-6
@@ -14,12 +14,6 @@ public final class RealtimeSseEvents {
|
||||
/** 心跳 */
|
||||
public static final String PING = "ping";
|
||||
|
||||
/** 导入任务进度 */
|
||||
public static final String IMPORT_TASK_PROGRESS = "import_task_progress";
|
||||
|
||||
/** 导入任务全部结束(可刷新列表) */
|
||||
public static final String IMPORT_ALL_TASKS_COMPLETED = "import_all_tasks_completed";
|
||||
|
||||
/** 拼多多订单全量同步任务进度 */
|
||||
public static final String PDD_ORDER_FULL_SYNC_PROGRESS = "pdd_order_full_sync_progress";
|
||||
}
|
||||
|
||||
+1
-1
@@ -33,7 +33,7 @@ public class LicenseAspect {
|
||||
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
|
||||
Method method = signature.getMethod();
|
||||
LicenseRequired annotation = AnnotatedElementUtils.findMergedAnnotation(method, LicenseRequired.class);
|
||||
LicenseFeature feature = annotation != null ? annotation.value() : LicenseFeature.ORDER_IMPORT;
|
||||
LicenseFeature feature = annotation != null ? annotation.value() : LicenseFeature.ORDER_CREATE;
|
||||
licenseValidator.check();
|
||||
licenseValidator.requireFeature(feature);
|
||||
return joinPoint.proceed();
|
||||
|
||||
+3
-1
@@ -8,7 +8,9 @@ import lombok.Getter;
|
||||
@Getter
|
||||
public enum LicenseFeature {
|
||||
|
||||
/** 订单批量/文件导入 */
|
||||
/**
|
||||
* 订单批量/文件导入(已下线,保留枚举以兼容旧 License JSON)。
|
||||
*/
|
||||
ORDER_IMPORT("order-import"),
|
||||
|
||||
/** 手动创建单条订单 */
|
||||
|
||||
+2
-2
@@ -12,6 +12,6 @@ import java.lang.annotation.Target;
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface LicenseRequired {
|
||||
|
||||
/** 需要的功能,默认订单导入 */
|
||||
LicenseFeature value() default LicenseFeature.ORDER_IMPORT;
|
||||
/** 需要的功能,默认手动建单 */
|
||||
LicenseFeature value() default LicenseFeature.ORDER_CREATE;
|
||||
}
|
||||
|
||||
@@ -100,24 +100,6 @@ ecom:
|
||||
# Agent 数据租户;BI tool 依赖此值
|
||||
company-id: ${AGENT_MCP_COMPANY_ID:}
|
||||
|
||||
# 导入任务 Redis Stream 队列(DB 为真相源,Redis 负责调度)
|
||||
import-task:
|
||||
queue:
|
||||
enabled: true
|
||||
stream-prefix: import:task:stream
|
||||
consumer-group: import-task-group
|
||||
block-timeout-ms: 5000
|
||||
claim-idle-ms: 300000
|
||||
reconcile-interval-ms: 60000
|
||||
stuck-processing-ms: 300000
|
||||
reconcile-lock-seconds: 55
|
||||
worker:
|
||||
pool-size-per-type: 1
|
||||
type-enabled:
|
||||
order: true
|
||||
product: false
|
||||
promotion_record: true
|
||||
|
||||
# JWT 令牌有效期(密钥见各环境配置)
|
||||
jwt:
|
||||
access-token-expiration: 900
|
||||
|
||||
@@ -383,9 +383,6 @@ INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status
|
||||
SELECT 3204, (SELECT id FROM `sys_permission` WHERE `code` = 'ec:order' LIMIT 1), 'ec:order:delete', '删除', 'api', 1, '', 4
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3204 OR `code` = 'ec:order:delete');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT 3205, (SELECT id FROM `sys_permission` WHERE `code` = 'ec:order' LIMIT 1), 'ec:order:import', '导入', 'api', 1, '', 5
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3205 OR `code` = 'ec:order:import');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT 3300, (SELECT id FROM `sys_permission` WHERE `code` = 'ec' LIMIT 1), 'ec:shop', '店铺', 'module', 1, '', 40
|
||||
@@ -603,41 +600,11 @@ INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status
|
||||
SELECT 3744, (SELECT id FROM `sys_permission` WHERE `code` = 'bi:order-stat:calc' LIMIT 1), 'bi:order-stat:calc:update', '恢复/更新', 'api', 1, '', 3
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3744 OR `code` = 'bi:order-stat:calc:update');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT 4100, (SELECT id FROM `sys_permission` WHERE `code` = 'data' LIMIT 1), 'data:import', '数据导入', 'module', 1, '', 10
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 4100 OR `code` = 'data:import');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT 4101, (SELECT id FROM `sys_permission` WHERE `code` = 'data:import' LIMIT 1), 'data:import:create', '创建任务', 'api', 1, '', 1
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 4101 OR `code` = 'data:import:create');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT 4102, (SELECT id FROM `sys_permission` WHERE `code` = 'data:import' LIMIT 1), 'data:import:read', '查看任务', 'api', 1, '', 2
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 4102 OR `code` = 'data:import:read');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT 4200, (SELECT id FROM `sys_permission` WHERE `code` = 'data' LIMIT 1), 'data:export', '数据导出', 'api', 1, '导出接口', 20
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 4200 OR `code` = 'data:export');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT 4300, (SELECT id FROM `sys_permission` WHERE `code` = 'data' LIMIT 1), 'data:import-mapping', '导入映射', 'module', 1, '', 30
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 4300 OR `code` = 'data:import-mapping');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT 4301, (SELECT id FROM `sys_permission` WHERE `code` = 'data:import-mapping' LIMIT 1), 'data:import-mapping:read', '查看', 'api', 1, '', 1
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 4301 OR `code` = 'data:import-mapping:read');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT 4302, (SELECT id FROM `sys_permission` WHERE `code` = 'data:import-mapping' LIMIT 1), 'data:import-mapping:create', '创建', 'api', 1, '', 2
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 4302 OR `code` = 'data:import-mapping:create');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT 4303, (SELECT id FROM `sys_permission` WHERE `code` = 'data:import-mapping' LIMIT 1), 'data:import-mapping:update', '更新', 'api', 1, '', 3
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 4303 OR `code` = 'data:import-mapping:update');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT 4304, (SELECT id FROM `sys_permission` WHERE `code` = 'data:import-mapping' LIMIT 1), 'data:import-mapping:delete', '删除', 'api', 1, '', 4
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 4304 OR `code` = 'data:import-mapping:delete');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT 5100, (SELECT id FROM `sys_permission` WHERE `code` = 'open' LIMIT 1), 'open:api-key', 'API Key', 'module', 1, '', 5
|
||||
@@ -731,9 +698,6 @@ INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path
|
||||
SELECT 12031, NULL, 0, 'TaobaoChannel', '淘宝', '', '', '', 'ri:taobao-fill', 'menu', 1, 1, 0, 1
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 12031 OR `route_name` = 'TaobaoChannel');
|
||||
|
||||
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
|
||||
SELECT 14003, NULL, 0, 'DataImportCatalog', '数据导入', '/upload', '', '', 'material-symbols:upload-rounded', 'catalog', 0, 1, 1, 13
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14003 OR `route_name` = 'DataImportCatalog');
|
||||
|
||||
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
|
||||
SELECT 14005, NULL, 0, 'CompanyConfig', '公司配置', '/company', '', '', 'mdi:company', 'catalog', 1, 1, 0, 10
|
||||
@@ -795,17 +759,8 @@ INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path
|
||||
SELECT 33, (SELECT id FROM `sys_menu` WHERE `id` = 6 OR `title` = '电商页面' LIMIT 1), 0, 'ShopOverview', '店铺概览', '/ec/shop/overview/:id', '/ec/shop/overview/index', '', 'gravity-ui:chart-line', 'embedded', 0, 1, 1, 1
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 33 OR `route_name` = 'ShopOverview');
|
||||
|
||||
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
|
||||
SELECT 35, (SELECT id FROM `sys_menu` WHERE `id` = 14003 OR `title` = '数据导入' LIMIT 1), 0, 'DataImport', '订单导入', '/upload/order', '/ec/import/order/index', '', 'lucide:upload', 'menu', 1, 1, 0, 1
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 35 OR `route_name` = 'DataImport');
|
||||
|
||||
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
|
||||
SELECT 36, (SELECT id FROM `sys_menu` WHERE `id` = 11 OR `title` = '配置管理' LIMIT 1), 0, 'FieldMappingConfig', '字段映射模板', '/config/field-mapping', '/config/field-mapping/index', '', 'lucide:key', 'menu', 1, 1, 1, 1
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 36 OR `route_name` = 'FieldMappingConfig');
|
||||
|
||||
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
|
||||
SELECT 37, (SELECT id FROM `sys_menu` WHERE `id` = 11 OR `title` = '配置管理' LIMIT 1), 0, 'OrderStatusMappingConfig', '订单状态映射模板', '/config/order-status-mapping', '/config/order-status-mapping/index', '', 'lucide:star', 'menu', 1, 1, 1, 2
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 37 OR `route_name` = 'OrderStatusMappingConfig');
|
||||
|
||||
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
|
||||
SELECT 38, (SELECT id FROM `sys_menu` WHERE `id` = 14 OR `title` = '组织管理' LIMIT 1), 0, 'PositionPermissionManagePage', '职位权限', '/org/position/permission', '/org/position/permission/index', '', 'lucide:shield-check', 'menu', 1, 1, 0, 5
|
||||
@@ -843,9 +798,6 @@ INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path
|
||||
SELECT 46, (SELECT id FROM `sys_menu` WHERE `id` = 6 OR `title` = '电商页面' LIMIT 1), 0, 'ShopDetails', '店铺详情', '/ec/shop/details/:id', '/ec/shop/details/index', '', 'material-symbols-light:shop-outline', 'embedded', 0, 1, 1, 3
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 46 OR `route_name` = 'ShopDetails');
|
||||
|
||||
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
|
||||
SELECT 48, (SELECT id FROM `sys_menu` WHERE `id` = 14003 OR `title` = '数据导入' LIMIT 1), 0, 'AdFeeImport', '广告费导入', '/import/ad-fee', '/ec/import/ad-fee/index', '', 'hugeicons:promotion', 'menu', 1, 1, 0, 2
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 48 OR `route_name` = 'AdFeeImport');
|
||||
|
||||
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
|
||||
SELECT 51, (SELECT id FROM `sys_menu` WHERE `id` = 1 OR `title` = '系统设置' LIMIT 1), 0, 'OrderStatManage', '聚合管理', '/sys/order-stat-manage', '/sys/order-stat-manage/index', '', 'oui:aggregate', 'menu', 1, 1, 0, 5
|
||||
@@ -968,11 +920,6 @@ SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'ec:s
|
||||
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'ec:product:category:%' WHERE m.name = '商品类目';
|
||||
|
||||
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code IN ('ec:order:import', 'data:import:create', 'data:import:read') WHERE m.name = '订单导入';
|
||||
|
||||
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code IN ('data:import:create', 'data:import:read', 'channel:pdd:ad-fee:import') WHERE m.name = '广告费导入';
|
||||
|
||||
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'open:api-key:%' WHERE m.name = 'OpenApiKeyManagement';
|
||||
@@ -986,8 +933,3 @@ SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON (p.code LIKE 'ec:
|
||||
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code = 'bi:workbench:read' WHERE m.name = '工作台';
|
||||
|
||||
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'data:import-mapping:%' WHERE m.name = '字段映射模板';
|
||||
|
||||
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'data:import-mapping:%' WHERE m.name = '订单状态映射模板';
|
||||
|
||||
Reference in New Issue
Block a user