mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19: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 = '订单状态映射模板';
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
import type { ImportMappingDTO, ImportMappingVO } from './types';
|
||||
|
||||
import type { PageQueryDTO, PageResultVO } from '#/types/common';
|
||||
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
/**
|
||||
* 导入映射管理API
|
||||
*/
|
||||
|
||||
/**
|
||||
* 创建导入映射模板
|
||||
*/
|
||||
export async function createImportMappingApi(
|
||||
data: ImportMappingDTO.CreateImportMappingDTO,
|
||||
) {
|
||||
return requestClient.post<ImportMappingVO.ImportMappingInfoVO>(
|
||||
'/ec/import/mapping/create',
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新导入映射模板
|
||||
*/
|
||||
export async function updateImportMappingApi(
|
||||
id: number,
|
||||
data: ImportMappingDTO.UpdateImportMappingDTO,
|
||||
) {
|
||||
return requestClient.put<ImportMappingVO.ImportMappingInfoVO>(
|
||||
`/ec/import/mapping/update/${id}`,
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除导入映射
|
||||
*/
|
||||
export async function deleteImportMappingApi(id: number) {
|
||||
return requestClient.delete(`/ec/import/mapping/delete/${id}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页获取导入映射列表
|
||||
*/
|
||||
export async function getImportMappingPageApi(
|
||||
params: PageQueryDTO<ImportMappingDTO.ImportMappingFilterDTO>,
|
||||
) {
|
||||
return requestClient.post<PageResultVO<ImportMappingVO.ImportMappingInfoVO>>(
|
||||
'/ec/import/mapping/list',
|
||||
params,
|
||||
);
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
/**
|
||||
* 导入映射模块API导出
|
||||
*/
|
||||
|
||||
export * from './apis';
|
||||
export * from './types';
|
||||
@@ -1,7 +0,0 @@
|
||||
/**
|
||||
* 导入映射模块类型定义导出
|
||||
*/
|
||||
|
||||
export * from './types.dto';
|
||||
export * from './types.vo';
|
||||
export * from './types.enum';
|
||||
@@ -1,33 +0,0 @@
|
||||
import type { ImportMappingType } from './types.enum';
|
||||
|
||||
/**
|
||||
* 导入映射模块DTO类型定义
|
||||
*/
|
||||
|
||||
export namespace ImportMappingDTO {
|
||||
/** 创建导入映射参数 */
|
||||
export interface CreateImportMappingDTO {
|
||||
/** 导入类型(PRODUCT-商品 ORDER-订单 ORDER_STATUS-订单状态) */
|
||||
type: ImportMappingType;
|
||||
/** 映射名称 */
|
||||
name: string;
|
||||
/** 字段映射(JSON格式) */
|
||||
mapping: string;
|
||||
}
|
||||
|
||||
/** 更新导入映射参数 */
|
||||
export interface UpdateImportMappingDTO {
|
||||
/** 映射名称 */
|
||||
name?: string;
|
||||
/** 字段映射(JSON格式) */
|
||||
mapping: string;
|
||||
}
|
||||
|
||||
/** 导入映射过滤条件 */
|
||||
export interface ImportMappingFilterDTO {
|
||||
/** 导入类型(PRODUCT-商品 ORDER-订单 ORDER_STATUS-订单状态) */
|
||||
type?: ImportMappingType;
|
||||
/** 映射名称(模糊查询) */
|
||||
name?: string;
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
/**
|
||||
* 导入映射类型枚举
|
||||
*/
|
||||
export enum ImportMappingType {
|
||||
/** 商品 */
|
||||
PRODUCT = 'PRODUCT',
|
||||
/** 订单 */
|
||||
ORDER = 'ORDER',
|
||||
/** 订单状态 */
|
||||
ORDER_STATUS = 'ORDER_STATUS',
|
||||
/** 推广费 */
|
||||
PROMOTION_FEE = 'PROMOTION_FEE',
|
||||
}
|
||||
|
||||
/**
|
||||
* 导入映射类型选项配置
|
||||
*/
|
||||
export const IMPORT_MAPPING_TYPE_OPTIONS = [
|
||||
{ label: '商品', value: ImportMappingType.PRODUCT },
|
||||
{ label: '订单', value: ImportMappingType.ORDER },
|
||||
{ label: '订单状态', value: ImportMappingType.ORDER_STATUS },
|
||||
{ label: '推广费', value: ImportMappingType.PROMOTION_FEE },
|
||||
];
|
||||
|
||||
/**
|
||||
* 根据导入映射类型枚举值获取中文名称
|
||||
*/
|
||||
export function getImportMappingTypeName(type: ImportMappingType): string {
|
||||
const option = IMPORT_MAPPING_TYPE_OPTIONS.find((opt) => opt.value === type);
|
||||
return option?.label || '未知类型';
|
||||
}
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
import type { ImportMappingType } from './types.enum';
|
||||
|
||||
/**
|
||||
* 导入映射模块VO类型定义
|
||||
*/
|
||||
|
||||
export namespace ImportMappingVO {
|
||||
/** 导入映射信息 */
|
||||
export interface ImportMappingInfoVO {
|
||||
/** 映射ID */
|
||||
id: number;
|
||||
/** 所属公司ID */
|
||||
companyId?: number;
|
||||
/** 导入类型(PRODUCT-商品 ORDER-订单 ORDER_STATUS-订单状态) */
|
||||
type: ImportMappingType;
|
||||
/** 映射名称 */
|
||||
name: string;
|
||||
/** 字段映射(JSON格式) */
|
||||
mapping: string;
|
||||
/** 创建时间 */
|
||||
createTime: string;
|
||||
/** 更新时间 */
|
||||
updateTime: string;
|
||||
/** 创建人ID */
|
||||
createBy?: number;
|
||||
/** 更新人ID */
|
||||
updateBy?: number;
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
import type { ImportTaskDTO, ImportTaskVO } from './types';
|
||||
|
||||
import type { PageQueryDTO, PageResultVO } from '#/types/common';
|
||||
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
/**
|
||||
* 导入任务管理API
|
||||
*/
|
||||
|
||||
/**
|
||||
* 创建导入任务
|
||||
*/
|
||||
export async function createImportTaskApi(
|
||||
data: ImportTaskDTO.CreateImportTaskDTO,
|
||||
) {
|
||||
return requestClient.post<ImportTaskVO.ImportTaskInfoVO>(
|
||||
'/ec/import/task/create',
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页获取导入任务列表
|
||||
*/
|
||||
export async function getImportTaskPageApi(
|
||||
params: PageQueryDTO<ImportTaskDTO.ImportTaskFilterDTO>,
|
||||
) {
|
||||
return requestClient.post<PageResultVO<ImportTaskVO.ImportTaskInfoVO>>(
|
||||
'/ec/import/task/list',
|
||||
params,
|
||||
);
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
/**
|
||||
* 导入任务模块API导出
|
||||
*/
|
||||
|
||||
export * from './apis';
|
||||
export * from './types';
|
||||
@@ -1,6 +0,0 @@
|
||||
/**
|
||||
* 导入任务模块类型定义导出
|
||||
*/
|
||||
|
||||
export * from './types.dto';
|
||||
export * from './types.vo';
|
||||
@@ -1,31 +0,0 @@
|
||||
/**
|
||||
* 导入任务模块DTO类型定义
|
||||
*/
|
||||
|
||||
export namespace ImportTaskDTO {
|
||||
/** 创建导入任务参数 */
|
||||
export interface CreateImportTaskDTO {
|
||||
/** 所属店铺ID */
|
||||
shopId: number;
|
||||
/** 导入类型(product-商品 order-订单) */
|
||||
type: string;
|
||||
/** 原始文件名 */
|
||||
fileName: string;
|
||||
/** 关联文件ID */
|
||||
fileId: number;
|
||||
/** 字段映射记录(JSON字符串) */
|
||||
mapping?: string;
|
||||
}
|
||||
|
||||
/** 导入任务过滤条件 */
|
||||
export interface ImportTaskFilterDTO {
|
||||
/** 所属店铺ID */
|
||||
shopId?: number;
|
||||
/** 导入类型(product-商品 order-订单) */
|
||||
type?: string;
|
||||
/** 任务状态 */
|
||||
status?: string;
|
||||
/** 文件名(模糊查询) */
|
||||
fileName?: string;
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
/**
|
||||
* 导入任务模块VO类型定义
|
||||
*/
|
||||
|
||||
export namespace ImportTaskVO {
|
||||
/** 导入任务信息 */
|
||||
export interface ImportTaskInfoVO {
|
||||
/** 主键ID */
|
||||
id: number;
|
||||
/** 所属公司ID */
|
||||
companyId?: number;
|
||||
/** 所属店铺ID */
|
||||
shopId?: number;
|
||||
/** 所属店铺名称 */
|
||||
shopName?: string;
|
||||
/** 导入类型(product-商品 order-订单) */
|
||||
type: string;
|
||||
/** 原始文件名 */
|
||||
fileName: string;
|
||||
/** 关联文件ID */
|
||||
fileId?: number;
|
||||
/** 任务状态 */
|
||||
status: string;
|
||||
/** 总行数 */
|
||||
totalCount?: number;
|
||||
/** 成功行数 */
|
||||
successCount?: number;
|
||||
/** 失败行数 */
|
||||
failCount?: number;
|
||||
/** 字段映射记录(JSON字符串) */
|
||||
mapping?: string;
|
||||
/** 错误信息或备注 */
|
||||
message?: string;
|
||||
/** 创建时间 */
|
||||
createTime: string;
|
||||
/** 更新时间 */
|
||||
updateTime: string;
|
||||
/** 创建人ID */
|
||||
createBy?: number;
|
||||
/** 更新人ID */
|
||||
updateBy?: number;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { BatchImportResultVO, OrderDTO, OrderFieldVO, OrderVO } from './types';
|
||||
import type { OrderDTO, OrderFieldVO, OrderVO } from './types';
|
||||
|
||||
import type { PageQueryDTO, PageResultVO } from '#/types/common';
|
||||
|
||||
@@ -53,16 +53,6 @@ export async function getOrderByIdApi(id: number) {
|
||||
return requestClient.get<OrderVO.Info>(`/ec/order/detail/${id}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量导入订单
|
||||
*/
|
||||
export async function batchImportOrdersApi(data: OrderDTO.BatchImport) {
|
||||
return requestClient.post<BatchImportResultVO.Info>(
|
||||
'/ec/order/batch-import',
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取订单字段信息列表
|
||||
*/
|
||||
|
||||
@@ -121,12 +121,6 @@ export namespace OrderDTO {
|
||||
productId?: number;
|
||||
}
|
||||
|
||||
/** 批量导入订单参数 */
|
||||
export interface BatchImport {
|
||||
/** 订单列表 */
|
||||
orders: Create[];
|
||||
}
|
||||
|
||||
/** 批量删除订单参数 */
|
||||
export interface BatchDelete {
|
||||
/** 订单 ID 列表 */
|
||||
|
||||
@@ -164,21 +164,3 @@ export namespace OrderFieldVO {
|
||||
dataType?: string;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量导入结果相关 VO 类型定义
|
||||
*/
|
||||
|
||||
export namespace BatchImportResultVO {
|
||||
/** 批量导入结果 */
|
||||
export interface Info {
|
||||
/** 总数量 */
|
||||
totalCount: number;
|
||||
/** 成功数量 */
|
||||
successCount: number;
|
||||
/** 失败数量 */
|
||||
failureCount: number;
|
||||
/** 失败详情 */
|
||||
failureDetails: string[];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,8 +7,6 @@ const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
|
||||
export const RealtimeSseEvent = {
|
||||
CONNECTED: 'message',
|
||||
PING: 'ping',
|
||||
IMPORT_TASK_PROGRESS: 'import_task_progress',
|
||||
IMPORT_ALL_TASKS_COMPLETED: 'import_all_tasks_completed',
|
||||
PDD_ORDER_FULL_SYNC_PROGRESS: 'pdd_order_full_sync_progress',
|
||||
} as const;
|
||||
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
|
||||
import { createIconifyIcon } from '@vben/icons';
|
||||
|
||||
import { Button } from 'ant-design-vue';
|
||||
|
||||
import { useImportTaskStore } from '#/store';
|
||||
|
||||
import ImportTaskDropdown from './ImportTaskDropdown.vue';
|
||||
|
||||
defineOptions({ name: 'ImportTaskButton' });
|
||||
|
||||
// 创建下载图标组件
|
||||
const DownloadIcon = createIconifyIcon('lucide:download');
|
||||
|
||||
const importTaskStore = useImportTaskStore();
|
||||
|
||||
// 计算属性:是否有进行中的任务
|
||||
const hasActiveTasks = computed(() => importTaskStore.hasActiveTasks);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ImportTaskDropdown>
|
||||
<template #trigger>
|
||||
<div class="flex-center mr-2 h-full">
|
||||
<Button type="text" shape="circle" class="relative">
|
||||
<template #icon>
|
||||
<DownloadIcon class="size-4" />
|
||||
</template>
|
||||
<span
|
||||
v-if="hasActiveTasks"
|
||||
class="bg-primary absolute right-0.5 top-0.5 h-2 w-2 rounded"
|
||||
></span>
|
||||
</Button>
|
||||
</div>
|
||||
</template>
|
||||
</ImportTaskDropdown>
|
||||
</template>
|
||||
@@ -1,243 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { ImportTaskVO } from '#/api/ec/import/task';
|
||||
|
||||
import { computed, ref, watch } from 'vue';
|
||||
|
||||
import { useVbenModal } from '@vben/common-ui';
|
||||
|
||||
import { useToggle } from '@vueuse/core';
|
||||
import { Button, Empty, List, Popover, Progress, Tag } from 'ant-design-vue';
|
||||
|
||||
import { useImportTaskStore } from '#/store';
|
||||
|
||||
defineOptions({ name: 'ImportTaskDropdown' });
|
||||
|
||||
const importTaskStore = useImportTaskStore();
|
||||
|
||||
const [open] = useToggle();
|
||||
|
||||
// 监听 store 中的 shouldOpenDropdown 状态,自动打开下拉菜单
|
||||
watch(
|
||||
() => importTaskStore.shouldOpenDropdown,
|
||||
(shouldOpen) => {
|
||||
if (shouldOpen) {
|
||||
open.value = true;
|
||||
// 重置状态,避免重复触发
|
||||
importTaskStore.closeDropdown();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// 创建消息详情模态框
|
||||
const [MessageModal, messageModalApi] = useVbenModal({
|
||||
draggable: true,
|
||||
class: 'w-[700px]',
|
||||
title: '任务消息详情',
|
||||
showCancelButton: false,
|
||||
showConfirmButton: false,
|
||||
footer: false,
|
||||
});
|
||||
|
||||
// 当前要显示的消息
|
||||
const currentMessage = ref<string>('');
|
||||
|
||||
// 计算属性:任务列表(按创建时间倒序)
|
||||
const taskList = computed(() => {
|
||||
return [...importTaskStore.tasks].sort(
|
||||
(a, b) =>
|
||||
new Date(b.createTime).getTime() - new Date(a.createTime).getTime(),
|
||||
);
|
||||
});
|
||||
|
||||
// 获取任务状态标签
|
||||
function getStatusTag(status: string) {
|
||||
const statusMap: Record<string, { color: string; text: string }> = {
|
||||
pending: { color: 'default', text: '等待中' },
|
||||
processing: { color: 'processing', text: '处理中' },
|
||||
success: { color: 'success', text: '成功' },
|
||||
failed: { color: 'error', text: '失败' },
|
||||
};
|
||||
return statusMap[status] || { color: 'default', text: status };
|
||||
}
|
||||
|
||||
// 获取任务进度百分比
|
||||
function getProgress(task: ImportTaskVO.ImportTaskInfoVO): number {
|
||||
if (!task.totalCount || task.totalCount === 0) {
|
||||
return 0;
|
||||
}
|
||||
const processed = (task.successCount || 0) + (task.failCount || 0);
|
||||
return Math.round((processed / task.totalCount) * 100);
|
||||
}
|
||||
|
||||
// 获取任务进度文本
|
||||
function getProgressText(task: ImportTaskVO.ImportTaskInfoVO): string {
|
||||
if (!task.totalCount || task.totalCount === 0) {
|
||||
return '等待开始';
|
||||
}
|
||||
const processed = (task.successCount || 0) + (task.failCount || 0);
|
||||
return `${processed}/${task.totalCount}`;
|
||||
}
|
||||
|
||||
// 打开消息详情模态框
|
||||
function openMessageModal(message: string) {
|
||||
currentMessage.value = message;
|
||||
messageModalApi.open();
|
||||
}
|
||||
|
||||
// 格式化时间
|
||||
function formatTime(time: string): string {
|
||||
return new Date(time).toLocaleString();
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Popover
|
||||
v-model:open="open"
|
||||
trigger="click"
|
||||
:overlay-style="{ width: '400px', padding: 0 }"
|
||||
placement="bottomRight"
|
||||
>
|
||||
<template #content>
|
||||
<div class="relative">
|
||||
<div class="flex items-center justify-between border-b p-4 py-3">
|
||||
<div class="font-medium">导入任务管理</div>
|
||||
<Button
|
||||
v-if="taskList.length > 0"
|
||||
size="small"
|
||||
type="text"
|
||||
@click="importTaskStore.fetchTasks(true)"
|
||||
>
|
||||
刷新
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div v-if="taskList.length > 0" class="max-h-[400px] overflow-y-auto">
|
||||
<List :data-source="taskList" item-layout="vertical">
|
||||
<template #renderItem="{ item }">
|
||||
<List.Item class="border-b px-4 py-3">
|
||||
<div class="flex w-full flex-col gap-2">
|
||||
<!-- 任务标题和状态 -->
|
||||
<div class="flex items-center justify-between">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-sm font-medium">{{
|
||||
item.fileName
|
||||
}}</span>
|
||||
<Tag
|
||||
:color="getStatusTag(item.status).color"
|
||||
size="small"
|
||||
>
|
||||
{{ getStatusTag(item.status).text }}
|
||||
</Tag>
|
||||
</div>
|
||||
<span class="text-xs text-gray-500">
|
||||
{{ formatTime(item.createTime) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- 进度条 -->
|
||||
<div v-if="item.status === 'processing'" class="space-y-1">
|
||||
<Progress
|
||||
:percent="getProgress(item)"
|
||||
:show-info="true"
|
||||
size="small"
|
||||
:status="
|
||||
item.status === 'failed' ? 'exception' : 'active'
|
||||
"
|
||||
/>
|
||||
<div class="flex justify-between text-xs text-gray-500">
|
||||
<span>已处理: {{ getProgressText(item) }}</span>
|
||||
<span>
|
||||
成功: {{ item.successCount || 0 }} / 失败:
|
||||
{{ item.failCount || 0 }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 完成信息 -->
|
||||
<div
|
||||
v-if="item.status === 'success' || item.status === 'failed'"
|
||||
class="flex justify-between text-xs text-gray-500"
|
||||
>
|
||||
<span>总行数: {{ item.totalCount || 0 }}</span>
|
||||
<span>
|
||||
成功: {{ item.successCount || 0 }} / 失败:
|
||||
{{ item.failCount || 0 }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- 任务详情信息(失败任务) -->
|
||||
<div
|
||||
v-if="item.status === 'failed' && item.message"
|
||||
class="flex items-center gap-2 rounded bg-red-50 p-2 dark:bg-red-950"
|
||||
>
|
||||
<div
|
||||
class="flex-1 overflow-hidden text-ellipsis whitespace-nowrap text-xs text-red-600 dark:text-red-400"
|
||||
>
|
||||
{{ item.message }}
|
||||
</div>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
class="h-auto p-0 text-xs"
|
||||
@click="openMessageModal(item.message)"
|
||||
>
|
||||
查看
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<!-- 任务详情信息(成功任务) -->
|
||||
<div
|
||||
v-if="item.status === 'success' && item.message"
|
||||
class="flex items-center gap-2 rounded bg-green-50 p-2 dark:bg-green-950"
|
||||
>
|
||||
<div
|
||||
class="flex-1 overflow-hidden text-ellipsis whitespace-nowrap text-xs text-green-600 dark:text-green-400"
|
||||
>
|
||||
{{ item.message }}
|
||||
</div>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
class="h-auto p-0 text-xs"
|
||||
@click="openMessageModal(item.message)"
|
||||
>
|
||||
查看
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<!-- 任务类型和店铺 -->
|
||||
<div class="flex items-center gap-3 text-xs text-gray-400">
|
||||
<span>类型: {{ item.type === 'order' ? '订单导入' : '商品导入' }}</span>
|
||||
<span v-if="item.shopName">店铺: {{ item.shopName }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</List.Item>
|
||||
</template>
|
||||
</List>
|
||||
</div>
|
||||
|
||||
<Empty v-else description="暂无导入任务" class="min-h-[150px]" />
|
||||
</div>
|
||||
</template>
|
||||
<template #default>
|
||||
<slot name="trigger"></slot>
|
||||
</template>
|
||||
</Popover>
|
||||
|
||||
<!-- 消息详情模态框 -->
|
||||
<MessageModal>
|
||||
<div class="max-h-[500px] overflow-y-auto">
|
||||
<div
|
||||
class="whitespace-pre-wrap break-words rounded bg-gray-50 p-4 text-sm dark:bg-gray-800"
|
||||
>
|
||||
{{ currentMessage }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 底部操作栏 -->
|
||||
<div class="mt-4 flex justify-end border-t pt-4">
|
||||
<Button @click="messageModalApi.close()">关闭</Button>
|
||||
</div>
|
||||
</MessageModal>
|
||||
</template>
|
||||
@@ -16,10 +16,9 @@ import {
|
||||
import { preferences } from '@vben/preferences';
|
||||
import { useAccessStore, useUserStore } from '@vben/stores';
|
||||
|
||||
import ImportTaskButton from '#/components/ImportTaskButton.vue';
|
||||
import SwitchAccountModal from '#/components/SwitchAccountModal.vue';
|
||||
import SwitchCompanyModal from '#/components/SwitchCompanyModal.vue';
|
||||
import { useAuthStore, useImportTaskStore, useRealtimeStore } from '#/store';
|
||||
import { useAuthStore, useRealtimeStore } from '#/store';
|
||||
import LoginForm from '#/views/_core/authentication/login.vue';
|
||||
|
||||
const router = useRouter();
|
||||
@@ -58,20 +57,18 @@ const notifications = ref<NotificationItem[]>([
|
||||
const userStore = useUserStore();
|
||||
const authStore = useAuthStore();
|
||||
const accessStore = useAccessStore();
|
||||
const importTaskStore = useImportTaskStore();
|
||||
const realtimeStore = useRealtimeStore();
|
||||
const { destroyWatermark, updateWatermark } = useWatermark();
|
||||
const showDot = computed(() =>
|
||||
notifications.value.some((item) => !item.isRead),
|
||||
);
|
||||
|
||||
// 登录布局挂载:已登录才建 SSE 与导入任务
|
||||
// 登录布局挂载:已登录才建 SSE
|
||||
onMounted(() => {
|
||||
if (!accessStore.accessToken) {
|
||||
return;
|
||||
}
|
||||
realtimeStore.start();
|
||||
importTaskStore.init();
|
||||
});
|
||||
|
||||
// 切换账户模态框引用
|
||||
@@ -209,9 +206,6 @@ watch(
|
||||
@logout="handleLogout"
|
||||
/>
|
||||
</template>
|
||||
<template #header-right-90>
|
||||
<ImportTaskButton />
|
||||
</template>
|
||||
<template #notification>
|
||||
<Notification
|
||||
:dot="showDot"
|
||||
|
||||
@@ -1,160 +0,0 @@
|
||||
import type { ImportTaskVO } from '#/api/ec/import/task';
|
||||
import type { PageQueryDTO } from '#/types/common';
|
||||
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
import { useAccessStore } from '@vben/stores';
|
||||
import { defineStore } from 'pinia';
|
||||
|
||||
import { getImportTaskPageApi } from '#/api/ec/import/task';
|
||||
import { RealtimeSseEvent } from '#/api/notify/sse';
|
||||
import { useRealtimeStore } from '#/store/realtime';
|
||||
|
||||
/**
|
||||
* 导入任务管理 Store(进度通过全局 realtime SSE 订阅)
|
||||
*/
|
||||
export const useImportTaskStore = defineStore('import-task', () => {
|
||||
const tasks = ref<ImportTaskVO.ImportTaskInfoVO[]>([]);
|
||||
|
||||
const pagination = ref({
|
||||
current: 1,
|
||||
pageSize: 10,
|
||||
total: 0,
|
||||
});
|
||||
|
||||
const loading = ref(false);
|
||||
const shouldOpenDropdown = ref(false);
|
||||
|
||||
let unsubProgress: (() => void) | null = null;
|
||||
let unsubAllDone: (() => void) | null = null;
|
||||
|
||||
const hasActiveTasks = computed(() => {
|
||||
return tasks.value.some(
|
||||
(task) => task.status === 'pending' || task.status === 'processing',
|
||||
);
|
||||
});
|
||||
|
||||
const activeTaskCount = computed(() => {
|
||||
return tasks.value.filter(
|
||||
(task) => task.status === 'pending' || task.status === 'processing',
|
||||
).length;
|
||||
});
|
||||
|
||||
async function fetchTasks(reset = false) {
|
||||
if (loading.value) return;
|
||||
|
||||
try {
|
||||
loading.value = true;
|
||||
|
||||
if (reset) {
|
||||
pagination.value.current = 1;
|
||||
}
|
||||
|
||||
const params: PageQueryDTO = {
|
||||
page: pagination.value.current,
|
||||
pageSize: pagination.value.pageSize,
|
||||
filters: {},
|
||||
};
|
||||
|
||||
const result = await getImportTaskPageApi(params);
|
||||
|
||||
if (reset) {
|
||||
tasks.value = result.records || [];
|
||||
} else {
|
||||
tasks.value.push(...(result.records || []));
|
||||
}
|
||||
|
||||
pagination.value.total = result.total || 0;
|
||||
} catch (error) {
|
||||
console.error('获取导入任务列表失败:', error);
|
||||
throw error;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function updateTask(task: ImportTaskVO.ImportTaskInfoVO) {
|
||||
const index = tasks.value.findIndex((t) => t.id === task.id);
|
||||
if (index === -1) {
|
||||
tasks.value.unshift(task);
|
||||
} else {
|
||||
tasks.value[index] = task;
|
||||
}
|
||||
}
|
||||
|
||||
function subscribeRealtime() {
|
||||
if (unsubProgress) {
|
||||
return;
|
||||
}
|
||||
const realtime = useRealtimeStore();
|
||||
unsubProgress = realtime.on(
|
||||
RealtimeSseEvent.IMPORT_TASK_PROGRESS,
|
||||
(event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
if (data.task) {
|
||||
updateTask(data.task);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('解析导入任务进度失败:', error);
|
||||
}
|
||||
},
|
||||
);
|
||||
unsubAllDone = realtime.on(
|
||||
RealtimeSseEvent.IMPORT_ALL_TASKS_COMPLETED,
|
||||
() => {
|
||||
fetchTasks(true).catch(() => {});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function unsubscribeRealtime() {
|
||||
unsubProgress?.();
|
||||
unsubAllDone?.();
|
||||
unsubProgress = null;
|
||||
unsubAllDone = null;
|
||||
}
|
||||
|
||||
/** 登录后才拉任务列表并订阅 SSE */
|
||||
async function init() {
|
||||
if (!useAccessStore().accessToken) {
|
||||
return;
|
||||
}
|
||||
subscribeRealtime();
|
||||
await fetchTasks(true);
|
||||
}
|
||||
|
||||
function $reset() {
|
||||
unsubscribeRealtime();
|
||||
tasks.value = [];
|
||||
pagination.value = {
|
||||
current: 1,
|
||||
pageSize: 10,
|
||||
total: 0,
|
||||
};
|
||||
loading.value = false;
|
||||
}
|
||||
|
||||
function openDropdown() {
|
||||
shouldOpenDropdown.value = true;
|
||||
}
|
||||
|
||||
function closeDropdown() {
|
||||
shouldOpenDropdown.value = false;
|
||||
}
|
||||
|
||||
return {
|
||||
tasks,
|
||||
pagination,
|
||||
loading,
|
||||
shouldOpenDropdown,
|
||||
hasActiveTasks,
|
||||
activeTaskCount,
|
||||
fetchTasks,
|
||||
updateTask,
|
||||
init,
|
||||
openDropdown,
|
||||
closeDropdown,
|
||||
$reset,
|
||||
};
|
||||
});
|
||||
@@ -1,5 +1,4 @@
|
||||
export * from './auth';
|
||||
export * from './app-config';
|
||||
export * from './col-sidebar-layout';
|
||||
export * from './import-task';
|
||||
export * from './realtime';
|
||||
|
||||
@@ -1,206 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { VxeGridProps } from '#/adapter/vxe-table';
|
||||
import type { ImportMappingVO } from '#/api/ec/import/mapping';
|
||||
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
import { createIconifyIcon } from '@vben/icons';
|
||||
|
||||
import { Button, message, Popconfirm, Space, Tag } from 'ant-design-vue';
|
||||
|
||||
import { useVbenVxeGrid } from '#/adapter/vxe-table';
|
||||
import {
|
||||
deleteImportMappingApi,
|
||||
getImportMappingPageApi,
|
||||
} from '#/api/ec/import/mapping';
|
||||
import { PermissionGate } from '#/components/permission';
|
||||
import {
|
||||
syncVxeGridColumns,
|
||||
useActionColumnVisible,
|
||||
} from '#/composables/use-vxe-action-column';
|
||||
import { ImportMappingType } from '#/api/ec/import/mapping/types/types.enum';
|
||||
|
||||
import ImportMappingFormModal from '../import-mapping/components/ImportMappingFormModal.vue';
|
||||
|
||||
defineOptions({ name: 'FieldMappingConfig' });
|
||||
|
||||
const PlusIcon = createIconifyIcon('lucide:plus');
|
||||
|
||||
const loading = ref(false);
|
||||
const formModalRef = ref();
|
||||
|
||||
const mappingActionCodes = [
|
||||
'data:import-mapping:create',
|
||||
'data:import-mapping:update',
|
||||
'data:import-mapping:delete',
|
||||
];
|
||||
const showActionColumn = useActionColumnVisible(mappingActionCodes);
|
||||
|
||||
const mappingTableBaseColumns: VxeGridProps<any>['columns'] = [
|
||||
{ type: 'seq', width: 80, title: '序号' },
|
||||
{
|
||||
field: 'name',
|
||||
title: '模板名称',
|
||||
minWidth: 'auto',
|
||||
showOverflow: 'tooltip',
|
||||
},
|
||||
{ field: 'type', title: '类型', width: 120, slots: { default: 'type' } },
|
||||
{
|
||||
title: '映射字段数',
|
||||
width: 120,
|
||||
slots: { default: 'mappingCount' },
|
||||
},
|
||||
{ field: 'createTime', title: '创建时间', width: 180 },
|
||||
{ field: 'updateTime', title: '更新时间', width: 180 },
|
||||
];
|
||||
|
||||
const mappingActionColumn: NonNullable<VxeGridProps<any>['columns']>[number] = {
|
||||
title: '操作',
|
||||
width: 160,
|
||||
fixed: 'right',
|
||||
slots: { default: 'action' },
|
||||
};
|
||||
|
||||
const mappingTableColumns = computed(() =>
|
||||
showActionColumn.value
|
||||
? [...(mappingTableBaseColumns ?? []), mappingActionColumn]
|
||||
: (mappingTableBaseColumns ?? []),
|
||||
);
|
||||
|
||||
const gridOptions: VxeGridProps<any> = {
|
||||
columns: mappingTableColumns.value,
|
||||
height: 'auto',
|
||||
border: true,
|
||||
stripe: true,
|
||||
rowConfig: { isHover: true },
|
||||
showOverflow: true,
|
||||
size: 'small',
|
||||
toolbarConfig: {
|
||||
custom: true,
|
||||
refresh: true,
|
||||
zoom: true,
|
||||
},
|
||||
data: [],
|
||||
pagerConfig: { enabled: false },
|
||||
proxyConfig: {
|
||||
ajax: {
|
||||
query: async () => {
|
||||
try {
|
||||
loading.value = true;
|
||||
const result = await getImportMappingPageApi({
|
||||
page: 1,
|
||||
pageSize: 100,
|
||||
filters: { type: ImportMappingType.ORDER },
|
||||
});
|
||||
return { items: result.records || [], total: result.total || 0 };
|
||||
} catch {
|
||||
message.error('获取字段映射模板列表失败');
|
||||
return { items: [], total: 0 };
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const [Grid, gridApi] = useVbenVxeGrid({
|
||||
gridOptions,
|
||||
showSearchForm: false,
|
||||
tableTitle: '字段映射模板',
|
||||
});
|
||||
syncVxeGridColumns(gridApi, mappingTableColumns);
|
||||
|
||||
function refresh() {
|
||||
gridApi?.reload();
|
||||
}
|
||||
|
||||
function handleAdd() {
|
||||
formModalRef.value?.open(true);
|
||||
}
|
||||
|
||||
function handleEdit(row: ImportMappingVO.ImportMappingInfoVO) {
|
||||
formModalRef.value?.open(false, row);
|
||||
}
|
||||
|
||||
async function handleDelete(row: ImportMappingVO.ImportMappingInfoVO) {
|
||||
try {
|
||||
await deleteImportMappingApi(row.id);
|
||||
message.success('删除成功');
|
||||
refresh();
|
||||
} catch {
|
||||
message.error('删除失败');
|
||||
}
|
||||
}
|
||||
|
||||
function getMappingCount(mapping: string): number {
|
||||
try {
|
||||
const arr = JSON.parse(mapping);
|
||||
return Array.isArray(arr) ? arr.length : 0;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
function getTypeName(type: ImportMappingType): string {
|
||||
const map: Record<string, string> = {
|
||||
[ImportMappingType.ORDER]: '订单字段',
|
||||
[ImportMappingType.ORDER_STATUS]: '订单状态',
|
||||
[ImportMappingType.PRODUCT]: '商品字段',
|
||||
};
|
||||
return map[type] || type;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Page title="字段映射模板" auto-content-height>
|
||||
<template #description>
|
||||
<div class="text-foreground/80 mt-2">
|
||||
管理订单导入时的字段映射模板,支持创建、编辑和删除
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<Grid :loading="loading">
|
||||
<template #toolbar-tools>
|
||||
<Space>
|
||||
<PermissionGate code="data:import-mapping:create">
|
||||
<Button type="primary" @click="handleAdd">
|
||||
<PlusIcon />
|
||||
新建模板
|
||||
</Button>
|
||||
</PermissionGate>
|
||||
</Space>
|
||||
</template>
|
||||
|
||||
<template #type="{ row }: { row: ImportMappingVO.ImportMappingInfoVO }">
|
||||
<Tag color="blue">{{ getTypeName(row.type) }}</Tag>
|
||||
</template>
|
||||
|
||||
<template
|
||||
#mappingCount="{ row }: { row: ImportMappingVO.ImportMappingInfoVO }"
|
||||
>
|
||||
<Tag color="green">{{ getMappingCount(row.mapping) }} 个字段</Tag>
|
||||
</template>
|
||||
|
||||
<template v-if="showActionColumn" #action="{ row }: { row: ImportMappingVO.ImportMappingInfoVO }">
|
||||
<Space>
|
||||
<PermissionGate code="data:import-mapping:update">
|
||||
<Button size="small" @click="handleEdit(row)">编辑</Button>
|
||||
</PermissionGate>
|
||||
<PermissionGate code="data:import-mapping:delete">
|
||||
<Popconfirm title="确定删除该模板?" @confirm="handleDelete(row)">
|
||||
<Button size="small" danger>删除</Button>
|
||||
</Popconfirm>
|
||||
</PermissionGate>
|
||||
</Space>
|
||||
</template>
|
||||
</Grid>
|
||||
|
||||
<ImportMappingFormModal
|
||||
ref="formModalRef"
|
||||
:type="ImportMappingType.ORDER"
|
||||
@success="refresh"
|
||||
/>
|
||||
</Page>
|
||||
</template>
|
||||
-284
@@ -1,284 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { OrderFieldVO } from '#/api/ec/order/types';
|
||||
import type { ImportMappingVO } from '#/api/ec/import/mapping';
|
||||
import type { ImportMappingType } from '#/api/ec/import/mapping/types/types.enum';
|
||||
import type { OrderStatusVO } from '#/api/ec/order/status';
|
||||
|
||||
import { ref } from 'vue';
|
||||
|
||||
import { useVbenModal } from '@vben/common-ui';
|
||||
|
||||
import { Form, Input, message, Select } from 'ant-design-vue';
|
||||
|
||||
import { getOrderFieldsApi } from '#/api/ec/order';
|
||||
import {
|
||||
createImportMappingApi,
|
||||
updateImportMappingApi,
|
||||
} from '#/api/ec/import/mapping';
|
||||
import { ImportMappingType as MappingTypeEnum } from '#/api/ec/import/mapping/types/types.enum';
|
||||
import { getAllOrderStatusListApi } from '#/api/ec/order/status';
|
||||
|
||||
defineOptions({ name: 'ImportMappingFormModal' });
|
||||
|
||||
// Props: 传入模板类型
|
||||
const props = defineProps<{
|
||||
type: ImportMappingType;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
success: [];
|
||||
}>();
|
||||
|
||||
// 弹窗
|
||||
const [Modal, modalApi] = useVbenModal({
|
||||
draggable: true,
|
||||
class: 'w-[700px]',
|
||||
showCancelButton: true,
|
||||
showConfirmButton: true,
|
||||
onConfirm: handleConfirm,
|
||||
onCancel() {
|
||||
resetForm();
|
||||
modalApi.close();
|
||||
},
|
||||
});
|
||||
|
||||
// 状态
|
||||
const loading = ref(false);
|
||||
const isEdit = ref(false);
|
||||
const editId = ref<number | undefined>();
|
||||
const templateName = ref('');
|
||||
|
||||
// 字段映射相关(ORDER 类型)
|
||||
interface FieldMappingItem {
|
||||
fieldName: string;
|
||||
fieldLabel: string;
|
||||
fileFieldName?: string;
|
||||
required: boolean;
|
||||
}
|
||||
const fieldDefs = ref<OrderFieldVO.Info[]>([]);
|
||||
const fieldMappings = ref<Record<string, string>>({});
|
||||
|
||||
// 订单状态映射相关(ORDER_STATUS 类型)
|
||||
interface StatusMappingItem {
|
||||
csvStatus: string;
|
||||
mappedStatusCode: string;
|
||||
}
|
||||
const orderStatusList = ref<OrderStatusVO.Meta[]>([]);
|
||||
const statusMappings = ref<StatusMappingItem[]>([]);
|
||||
|
||||
// 获取字段定义
|
||||
async function fetchFieldDefs() {
|
||||
try {
|
||||
if (props.type === MappingTypeEnum.ORDER) {
|
||||
fieldDefs.value = (await getOrderFieldsApi()) || [];
|
||||
} else {
|
||||
fieldDefs.value = [];
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取字段定义失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// 获取订单状态列表(仅 ORDER_STATUS 类型)
|
||||
async function fetchOrderStatuses() {
|
||||
try {
|
||||
const result = await getAllOrderStatusListApi();
|
||||
orderStatusList.value = result || [];
|
||||
} catch (error) {
|
||||
console.error('获取订单状态列表失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// 打开弹窗
|
||||
async function open(
|
||||
isNew: boolean,
|
||||
record?: ImportMappingVO.ImportMappingInfoVO,
|
||||
) {
|
||||
isEdit.value = !isNew;
|
||||
editId.value = record?.id;
|
||||
modalApi.open();
|
||||
|
||||
await (props.type === MappingTypeEnum.ORDER_STATUS
|
||||
? fetchOrderStatuses()
|
||||
: fetchFieldDefs());
|
||||
|
||||
if (isNew) {
|
||||
// 新建:初始化空映射
|
||||
templateName.value = '';
|
||||
if (props.type === MappingTypeEnum.ORDER_STATUS) {
|
||||
statusMappings.value = [];
|
||||
} else {
|
||||
fieldMappings.value = {};
|
||||
}
|
||||
} else if (record) {
|
||||
// 编辑:解析现有映射
|
||||
templateName.value = record.name;
|
||||
try {
|
||||
const mappingArr = JSON.parse(record.mapping);
|
||||
if (props.type === MappingTypeEnum.ORDER_STATUS) {
|
||||
statusMappings.value = mappingArr || [];
|
||||
} else {
|
||||
const mapping: Record<string, string> = {};
|
||||
(mappingArr || []).forEach((item: FieldMappingItem) => {
|
||||
mapping[item.fieldName] = item.fileFieldName || '';
|
||||
});
|
||||
fieldMappings.value = mapping;
|
||||
}
|
||||
} catch {
|
||||
if (props.type === MappingTypeEnum.ORDER_STATUS) {
|
||||
statusMappings.value = [];
|
||||
} else {
|
||||
fieldMappings.value = {};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 重置表单
|
||||
function resetForm() {
|
||||
templateName.value = '';
|
||||
fieldMappings.value = {};
|
||||
statusMappings.value = [];
|
||||
fieldDefs.value = [];
|
||||
orderStatusList.value = [];
|
||||
}
|
||||
|
||||
// 确认保存
|
||||
async function handleConfirm() {
|
||||
if (!templateName.value.trim()) {
|
||||
message.warning('请输入模板名称');
|
||||
return;
|
||||
}
|
||||
|
||||
loading.value = true;
|
||||
try {
|
||||
let mappingJson = '[]';
|
||||
if (props.type === MappingTypeEnum.ORDER_STATUS) {
|
||||
// 过滤掉未映射的
|
||||
const validMappings = statusMappings.value.filter(
|
||||
(m) => m.mappedStatusCode,
|
||||
);
|
||||
mappingJson = JSON.stringify(validMappings);
|
||||
} else {
|
||||
const items: FieldMappingItem[] = fieldDefs.value
|
||||
.filter((f) => fieldMappings.value[f.fieldName])
|
||||
.map((f) => ({
|
||||
fieldName: f.fieldName,
|
||||
fieldLabel: f.fieldLabel,
|
||||
fileFieldName: fieldMappings.value[f.fieldName],
|
||||
required: f.required,
|
||||
}));
|
||||
mappingJson = JSON.stringify(items);
|
||||
}
|
||||
|
||||
if (isEdit.value && editId.value) {
|
||||
await updateImportMappingApi(editId.value, {
|
||||
name: templateName.value.trim(),
|
||||
mapping: mappingJson,
|
||||
});
|
||||
message.success('更新成功');
|
||||
} else {
|
||||
await createImportMappingApi({
|
||||
type: props.type,
|
||||
name: templateName.value.trim(),
|
||||
mapping: mappingJson,
|
||||
});
|
||||
message.success('创建成功');
|
||||
}
|
||||
|
||||
emit('success');
|
||||
resetForm();
|
||||
modalApi.close();
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '保存失败');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// 暴露方法
|
||||
defineExpose({ open });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Modal
|
||||
:loading="loading"
|
||||
:title="isEdit ? '编辑映射模板' : '新建映射模板'"
|
||||
:confirm-text="isEdit ? '保存' : '创建'"
|
||||
>
|
||||
<Form :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
|
||||
<Form.Item label="模板名称" required>
|
||||
<Input
|
||||
v-model:value="templateName"
|
||||
placeholder="请输入模板名称"
|
||||
:maxlength="50"
|
||||
show-count
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<!-- 订单状态映射编辑 -->
|
||||
<Form.Item
|
||||
v-if="type === MappingTypeEnum.ORDER_STATUS"
|
||||
label="状态映射"
|
||||
:wrapper-col="{ span: 20 }"
|
||||
>
|
||||
<div class="max-h-[400px] space-y-2 overflow-y-auto">
|
||||
<div
|
||||
v-for="(item, idx) in statusMappings"
|
||||
:key="idx"
|
||||
class="flex items-center space-x-2 rounded border p-2"
|
||||
>
|
||||
<span class="w-[200px] truncate text-gray-600">{{
|
||||
item.csvStatus
|
||||
}}</span>
|
||||
<span class="text-gray-400">→</span>
|
||||
<Select
|
||||
v-model:value="item.mappedStatusCode"
|
||||
placeholder="选择订单状态"
|
||||
class="flex-1"
|
||||
show-search
|
||||
allow-clear
|
||||
:options="
|
||||
orderStatusList.map((s) => ({
|
||||
label: s.label,
|
||||
value: s.code,
|
||||
}))
|
||||
"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
v-if="statusMappings.length === 0"
|
||||
class="py-4 text-center text-gray-400"
|
||||
>
|
||||
暂无映射数据
|
||||
</div>
|
||||
</div>
|
||||
</Form.Item>
|
||||
|
||||
<!-- 字段映射编辑(只读展示) -->
|
||||
<Form.Item v-else label="字段映射" :wrapper-col="{ span: 20 }">
|
||||
<div class="max-h-[400px] space-y-2 overflow-y-auto">
|
||||
<div
|
||||
v-for="field in fieldDefs"
|
||||
:key="field.fieldName"
|
||||
class="flex items-center space-x-2 rounded border p-2"
|
||||
:class="{
|
||||
'border-red-200 bg-red-50':
|
||||
field.required && !fieldMappings[field.fieldName],
|
||||
}"
|
||||
>
|
||||
<span class="w-[140px]">
|
||||
{{ field.fieldLabel }}
|
||||
<span v-if="field.required" class="text-red-500">*</span>
|
||||
</span>
|
||||
<Input
|
||||
v-model:value="fieldMappings[field.fieldName]"
|
||||
placeholder="CSV列名(如:商品名称)"
|
||||
class="flex-1"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</template>
|
||||
@@ -1,206 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { VxeGridProps } from '#/adapter/vxe-table';
|
||||
import type { ImportMappingVO } from '#/api/ec/import/mapping';
|
||||
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
import { createIconifyIcon } from '@vben/icons';
|
||||
|
||||
import { Button, message, Popconfirm, Space, Tag } from 'ant-design-vue';
|
||||
|
||||
import { useVbenVxeGrid } from '#/adapter/vxe-table';
|
||||
import {
|
||||
deleteImportMappingApi,
|
||||
getImportMappingPageApi,
|
||||
} from '#/api/ec/import/mapping';
|
||||
import { PermissionGate } from '#/components/permission';
|
||||
import {
|
||||
syncVxeGridColumns,
|
||||
useActionColumnVisible,
|
||||
} from '#/composables/use-vxe-action-column';
|
||||
import { ImportMappingType } from '#/api/ec/import/mapping/types/types.enum';
|
||||
|
||||
import ImportMappingFormModal from '../import-mapping/components/ImportMappingFormModal.vue';
|
||||
|
||||
defineOptions({ name: 'OrderStatusMappingConfig' });
|
||||
|
||||
const PlusIcon = createIconifyIcon('lucide:plus');
|
||||
|
||||
const loading = ref(false);
|
||||
const formModalRef = ref();
|
||||
|
||||
const mappingActionCodes = [
|
||||
'data:import-mapping:create',
|
||||
'data:import-mapping:update',
|
||||
'data:import-mapping:delete',
|
||||
];
|
||||
const showActionColumn = useActionColumnVisible(mappingActionCodes);
|
||||
|
||||
const mappingTableBaseColumns: VxeGridProps<any>['columns'] = [
|
||||
{ type: 'seq', width: 80, title: '序号' },
|
||||
{
|
||||
field: 'name',
|
||||
title: '模板名称',
|
||||
minWidth: 'auto',
|
||||
showOverflow: 'tooltip',
|
||||
},
|
||||
{ field: 'type', title: '类型', width: 120, slots: { default: 'type' } },
|
||||
{
|
||||
title: '映射状态数',
|
||||
width: 120,
|
||||
slots: { default: 'mappingCount' },
|
||||
},
|
||||
{ field: 'createTime', title: '创建时间', width: 180 },
|
||||
{ field: 'updateTime', title: '更新时间', width: 180 },
|
||||
];
|
||||
|
||||
const mappingActionColumn: NonNullable<VxeGridProps<any>['columns']>[number] = {
|
||||
title: '操作',
|
||||
width: 160,
|
||||
fixed: 'right',
|
||||
slots: { default: 'action' },
|
||||
};
|
||||
|
||||
const mappingTableColumns = computed(() =>
|
||||
showActionColumn.value
|
||||
? [...(mappingTableBaseColumns ?? []), mappingActionColumn]
|
||||
: (mappingTableBaseColumns ?? []),
|
||||
);
|
||||
|
||||
const gridOptions: VxeGridProps<any> = {
|
||||
columns: mappingTableColumns.value,
|
||||
height: 'auto',
|
||||
border: true,
|
||||
stripe: true,
|
||||
rowConfig: { isHover: true },
|
||||
showOverflow: true,
|
||||
size: 'small',
|
||||
toolbarConfig: {
|
||||
custom: true,
|
||||
refresh: true,
|
||||
zoom: true,
|
||||
},
|
||||
data: [],
|
||||
pagerConfig: { enabled: false },
|
||||
proxyConfig: {
|
||||
ajax: {
|
||||
query: async () => {
|
||||
try {
|
||||
loading.value = true;
|
||||
const result = await getImportMappingPageApi({
|
||||
page: 1,
|
||||
pageSize: 100,
|
||||
filters: { type: ImportMappingType.ORDER_STATUS },
|
||||
});
|
||||
return { items: result.records || [], total: result.total || 0 };
|
||||
} catch {
|
||||
message.error('获取订单状态映射模板列表失败');
|
||||
return { items: [], total: 0 };
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const [Grid, gridApi] = useVbenVxeGrid({
|
||||
gridOptions,
|
||||
showSearchForm: false,
|
||||
tableTitle: '订单状态映射模板',
|
||||
});
|
||||
syncVxeGridColumns(gridApi, mappingTableColumns);
|
||||
|
||||
function refresh() {
|
||||
gridApi?.reload();
|
||||
}
|
||||
|
||||
function handleAdd() {
|
||||
formModalRef.value?.open(true);
|
||||
}
|
||||
|
||||
function handleEdit(row: ImportMappingVO.ImportMappingInfoVO) {
|
||||
formModalRef.value?.open(false, row);
|
||||
}
|
||||
|
||||
async function handleDelete(row: ImportMappingVO.ImportMappingInfoVO) {
|
||||
try {
|
||||
await deleteImportMappingApi(row.id);
|
||||
message.success('删除成功');
|
||||
refresh();
|
||||
} catch {
|
||||
message.error('删除失败');
|
||||
}
|
||||
}
|
||||
|
||||
function getMappingCount(mapping: string): number {
|
||||
try {
|
||||
const arr = JSON.parse(mapping);
|
||||
return Array.isArray(arr) ? arr.length : 0;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
function getTypeName(type: ImportMappingType): string {
|
||||
const map: Record<string, string> = {
|
||||
[ImportMappingType.ORDER]: '订单字段',
|
||||
[ImportMappingType.ORDER_STATUS]: '订单状态',
|
||||
[ImportMappingType.PRODUCT]: '商品字段',
|
||||
};
|
||||
return map[type] || type;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Page title="订单状态映射模板" auto-content-height>
|
||||
<template #description>
|
||||
<div class="text-foreground/80 mt-2">
|
||||
管理订单导入时的订单状态映射模板,支持创建、编辑和删除
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<Grid :loading="loading">
|
||||
<template #toolbar-tools>
|
||||
<Space>
|
||||
<PermissionGate code="data:import-mapping:create">
|
||||
<Button type="primary" @click="handleAdd">
|
||||
<PlusIcon />
|
||||
新建模板
|
||||
</Button>
|
||||
</PermissionGate>
|
||||
</Space>
|
||||
</template>
|
||||
|
||||
<template #type="{ row }: { row: ImportMappingVO.ImportMappingInfoVO }">
|
||||
<Tag color="orange">{{ getTypeName(row.type) }}</Tag>
|
||||
</template>
|
||||
|
||||
<template
|
||||
#mappingCount="{ row }: { row: ImportMappingVO.ImportMappingInfoVO }"
|
||||
>
|
||||
<Tag color="green">{{ getMappingCount(row.mapping) }} 个状态</Tag>
|
||||
</template>
|
||||
|
||||
<template v-if="showActionColumn" #action="{ row }: { row: ImportMappingVO.ImportMappingInfoVO }">
|
||||
<Space>
|
||||
<PermissionGate code="data:import-mapping:update">
|
||||
<Button size="small" @click="handleEdit(row)">编辑</Button>
|
||||
</PermissionGate>
|
||||
<PermissionGate code="data:import-mapping:delete">
|
||||
<Popconfirm title="确定删除该模板?" @confirm="handleDelete(row)">
|
||||
<Button size="small" danger>删除</Button>
|
||||
</Popconfirm>
|
||||
</PermissionGate>
|
||||
</Space>
|
||||
</template>
|
||||
</Grid>
|
||||
|
||||
<ImportMappingFormModal
|
||||
ref="formModalRef"
|
||||
:type="ImportMappingType.ORDER_STATUS"
|
||||
@success="refresh"
|
||||
/>
|
||||
</Page>
|
||||
</template>
|
||||
@@ -1,163 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
|
||||
import { createIconifyIcon } from '@vben/icons';
|
||||
|
||||
import { message, Spin } from 'ant-design-vue';
|
||||
|
||||
defineOptions({ name: 'AdFeeFileUploadArea' });
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
loading?: boolean;
|
||||
}>(),
|
||||
{
|
||||
loading: false,
|
||||
},
|
||||
);
|
||||
|
||||
const emit = defineEmits<Emits>();
|
||||
|
||||
const UploadIcon = createIconifyIcon('lucide:upload');
|
||||
const LoaderIcon = createIconifyIcon('lucide:loader-2');
|
||||
|
||||
interface Emits {
|
||||
(e: 'fileSelected', file: File): void;
|
||||
}
|
||||
|
||||
const isDragOver = ref(false);
|
||||
const fileInputRef = ref<HTMLInputElement>();
|
||||
|
||||
const validateFile = (file: File): boolean => {
|
||||
const ext = file.name.toLowerCase().split('.').pop() || '';
|
||||
const allowedExts = ['csv', 'xlsx', 'xls'];
|
||||
if (!allowedExts.includes(ext)) {
|
||||
message.error('只能上传 CSV 或 Excel 格式的文件!');
|
||||
return false;
|
||||
}
|
||||
|
||||
const isLt10M = file.size / 1024 / 1024 < 10;
|
||||
if (!isLt10M) {
|
||||
message.error('文件大小不能超过10MB!');
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
const processFile = (file: File) => {
|
||||
if (props.loading) return;
|
||||
if (!validateFile(file)) return;
|
||||
emit('fileSelected', file);
|
||||
};
|
||||
|
||||
const handleDragOver = (e: DragEvent) => {
|
||||
e.preventDefault();
|
||||
isDragOver.value = true;
|
||||
};
|
||||
|
||||
const handleDragLeave = (e: DragEvent) => {
|
||||
e.preventDefault();
|
||||
isDragOver.value = false;
|
||||
};
|
||||
|
||||
const handleDrop = (e: DragEvent) => {
|
||||
e.preventDefault();
|
||||
isDragOver.value = false;
|
||||
|
||||
const files = e.dataTransfer?.files;
|
||||
if (files && files.length > 0) {
|
||||
const file = files[0];
|
||||
if (file) {
|
||||
processFile(file);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const triggerFileInput = () => {
|
||||
fileInputRef.value?.click();
|
||||
};
|
||||
|
||||
const handleFileSelect = (e: Event) => {
|
||||
const target = e.target as HTMLInputElement;
|
||||
const files = target.files;
|
||||
if (files && files.length > 0) {
|
||||
const file = files[0];
|
||||
if (file) {
|
||||
processFile(file);
|
||||
}
|
||||
}
|
||||
target.value = '';
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Spin :spinning="loading" tip="正在解析文件...">
|
||||
<div
|
||||
class="rounded-lg border-2 border-dashed border-gray-300 dark:border-[hsl(240deg_3.7%_22%)] p-8 text-center transition-colors cursor-pointer"
|
||||
:class="{
|
||||
'border-blue-500 bg-blue-50 dark:bg-[hsl(240deg_3.7%_15.9%/20%)]': isDragOver && !loading,
|
||||
'cursor-not-allowed opacity-60': loading,
|
||||
}"
|
||||
@dragover.prevent="!loading && handleDragOver($event)"
|
||||
@dragleave.prevent="!loading && handleDragLeave($event)"
|
||||
@drop.prevent="!loading && handleDrop($event)"
|
||||
@click="!loading && triggerFileInput()"
|
||||
>
|
||||
<div class="space-y-4">
|
||||
<div class="relative mx-auto h-12 w-12">
|
||||
<UploadIcon
|
||||
v-if="!loading"
|
||||
class="h-12 w-12 text-gray-400 dark:text-[hsl(240deg_5%_64.9%)]"
|
||||
:class="{ 'text-blue-500': isDragOver }"
|
||||
/>
|
||||
<LoaderIcon v-else class="h-12 w-12 animate-spin text-blue-500" />
|
||||
</div>
|
||||
<div>
|
||||
<p
|
||||
class="text-lg font-medium"
|
||||
:class="loading ? 'text-gray-500 dark:text-[hsl(240deg_5%_64.9%)]' : 'text-gray-700 dark:text-[hsl(0deg_0%_95%)]'"
|
||||
>
|
||||
{{
|
||||
loading
|
||||
? '正在解析文件,请稍候...'
|
||||
: '拖拽 CSV 或 Excel 文件到此处或点击上传'
|
||||
}}
|
||||
</p>
|
||||
<p v-if="!loading" class="text-sm text-gray-500 dark:text-[hsl(240deg_5%_64.9%)]">
|
||||
支持 .csv / .xlsx / .xls 格式,最大 10MB
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<input
|
||||
ref="fileInputRef"
|
||||
type="file"
|
||||
accept=".csv,.xlsx,.xls"
|
||||
style="display: none"
|
||||
:disabled="loading"
|
||||
@change="handleFileSelect"
|
||||
/>
|
||||
</div>
|
||||
</Spin>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.border-dashed {
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.border-dashed:hover {
|
||||
border-color: #1890ff !important;
|
||||
background-color: #f0f8ff !important;
|
||||
}
|
||||
|
||||
:deep(.border-dashed:hover) {
|
||||
border-color: #1890ff !important;
|
||||
background-color: #f0f8ff !important;
|
||||
}
|
||||
|
||||
html.dark .border-dashed:hover {
|
||||
border-color: hsl(240deg 3.7% 40%) !important;
|
||||
background-color: hsl(240deg 3.7% 15.9% / 15%) !important;
|
||||
}
|
||||
</style>
|
||||
@@ -1,850 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { AdFeeFieldVO } from '#/api/ec/shop/ad-fee/types';
|
||||
import type { ImportMappingVO } from '#/api/ec/import/mapping';
|
||||
import type { ImportTaskDTO } from '#/api/ec/import/task';
|
||||
import type { ShopVO } from '#/api/ec/shop/types';
|
||||
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
import { useVbenModal } from '@vben/common-ui';
|
||||
|
||||
import { Button, DatePicker, Form, Input, message, Select, Spin, Steps } from 'ant-design-vue';
|
||||
|
||||
import {
|
||||
createImportMappingApi,
|
||||
getImportMappingPageApi,
|
||||
ImportMappingType,
|
||||
updateImportMappingApi,
|
||||
} from '#/api/ec/import/mapping';
|
||||
import { getAdFeeFieldsApi } from '#/api/ec/shop/ad-fee/apis';
|
||||
import { getShopPageApi } from '#/api/ec/shop';
|
||||
import { createImportTaskApi } from '#/api/ec/import/task';
|
||||
import { useImportTaskStore } from '#/store';
|
||||
import { PermissionGate } from '#/components/permission';
|
||||
import { FileCategory } from '#/constants/file-category';
|
||||
import { uploadFile } from '#/utils/upload-file';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
interface FieldMappingItem {
|
||||
fieldName: string;
|
||||
fieldLabel: string;
|
||||
fileFieldName?: string;
|
||||
required: boolean;
|
||||
}
|
||||
|
||||
defineOptions({ name: 'AdFeeImportTaskWizard' });
|
||||
|
||||
const emit = defineEmits<{
|
||||
success: [];
|
||||
}>();
|
||||
|
||||
const currentStep = ref(0);
|
||||
const fieldDefsLoading = ref(false);
|
||||
const createTaskSubmitting = ref(false);
|
||||
const csvHeaders = ref<string[]>([]);
|
||||
const previewData = defineModel<any[]>('previewData', { default: () => [] });
|
||||
const originalImportFile = ref<File | null>(null);
|
||||
const selectedFile = ref<File | null>(null);
|
||||
|
||||
const shopList = ref<ShopVO.Info[]>([]);
|
||||
const selectedShopId = ref<number | undefined>();
|
||||
const shopLoading = ref(false);
|
||||
const shopPage = ref(1);
|
||||
const shopPageSize = ref(20);
|
||||
const shopHasMore = ref(true);
|
||||
const shopSearchValue = ref('');
|
||||
|
||||
const feeDate = ref<any>(undefined);
|
||||
|
||||
const fieldDefs = ref<AdFeeFieldVO.Info[]>([]);
|
||||
const fieldMappings = ref<
|
||||
Record<string, { fieldDef: AdFeeFieldVO.Info; mappedHeader?: string }>
|
||||
>({});
|
||||
|
||||
const mappingTemplates = ref<ImportMappingVO.ImportMappingInfoVO[]>([]);
|
||||
const selectedTemplateId = ref<number | undefined>();
|
||||
const selectedTemplateName = ref('');
|
||||
const templateLoading = ref(false);
|
||||
const savingTemplate = ref(false);
|
||||
const templateName = ref('');
|
||||
const savingFieldToTemplate = ref<null | string>(null);
|
||||
const currentTemplateMappings = ref<FieldMappingItem[]>([]);
|
||||
|
||||
const [SaveTemplateModal, saveTemplateModalApi] = useVbenModal({
|
||||
draggable: true,
|
||||
class: 'w-[500px]',
|
||||
title: '保存映射模板',
|
||||
showCancelButton: true,
|
||||
showConfirmButton: true,
|
||||
confirmText: '保存',
|
||||
cancelText: '取消',
|
||||
onConfirm: handleConfirmSaveTemplate,
|
||||
onCancel() {
|
||||
templateName.value = '';
|
||||
saveTemplateModalApi.close();
|
||||
},
|
||||
});
|
||||
|
||||
const importTaskStore = useImportTaskStore();
|
||||
|
||||
const canGoToNextStep = computed(() => {
|
||||
if (currentStep.value === 0) {
|
||||
const requiredFields = fieldDefs.value.filter((f) => f.required);
|
||||
return requiredFields.every((field) => {
|
||||
const mapping = fieldMappings.value[field.fieldName];
|
||||
return mapping && mapping.mappedHeader;
|
||||
});
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
const isMappingFromTemplate = (fieldDefId: string): boolean => {
|
||||
if (!selectedTemplateId.value || currentTemplateMappings.value.length === 0) return false;
|
||||
const fieldDef = fieldDefs.value.find((f) => f.fieldName === fieldDefId);
|
||||
if (!fieldDef) return false;
|
||||
const templateItem = currentTemplateMappings.value.find(
|
||||
(item) => item.fieldName === fieldDef.fieldName,
|
||||
);
|
||||
if (!templateItem) return false;
|
||||
const currentMapping = fieldMappings.value[fieldDef.fieldName];
|
||||
return currentMapping?.mappedHeader === templateItem.fileFieldName;
|
||||
};
|
||||
|
||||
const isMappingChangedFromTemplate = (fieldDefId: string): boolean => {
|
||||
if (!selectedTemplateId.value || currentTemplateMappings.value.length === 0) return false;
|
||||
const fieldDef = fieldDefs.value.find((f) => f.fieldName === fieldDefId);
|
||||
if (!fieldDef) return false;
|
||||
const templateItem = currentTemplateMappings.value.find(
|
||||
(item) => item.fieldName === fieldDef.fieldName,
|
||||
);
|
||||
if (!templateItem) return false;
|
||||
const currentMapping = fieldMappings.value[fieldDef.fieldName];
|
||||
if (templateItem.fileFieldName && currentMapping?.mappedHeader !== templateItem.fileFieldName) return true;
|
||||
return false;
|
||||
};
|
||||
|
||||
const initFieldMappings = () => {
|
||||
const mappings: typeof fieldMappings.value = {};
|
||||
fieldDefs.value.forEach((fieldDef) => {
|
||||
let mappedHeader: string | undefined;
|
||||
if (fieldDef.fileFieldName) {
|
||||
const matched = csvHeaders.value.find((h) => h === fieldDef.fileFieldName);
|
||||
if (matched) mappedHeader = matched;
|
||||
}
|
||||
mappings[fieldDef.fieldName] = { fieldDef, mappedHeader };
|
||||
});
|
||||
fieldMappings.value = mappings;
|
||||
};
|
||||
|
||||
const fetchShopList = async (reset = false) => {
|
||||
if (shopLoading.value) return;
|
||||
try {
|
||||
shopLoading.value = true;
|
||||
if (reset) {
|
||||
shopList.value = [];
|
||||
shopPage.value = 1;
|
||||
shopHasMore.value = true;
|
||||
}
|
||||
const result = await getShopPageApi({
|
||||
page: shopPage.value,
|
||||
pageSize: shopPageSize.value,
|
||||
filters: { name: shopSearchValue.value || undefined },
|
||||
});
|
||||
if (reset) {
|
||||
shopList.value = result.records || [];
|
||||
} else {
|
||||
shopList.value.push(...(result.records || []));
|
||||
}
|
||||
shopHasMore.value = (result.records?.length || 0) === shopPageSize.value;
|
||||
if (shopHasMore.value) shopPage.value++;
|
||||
} catch (error) {
|
||||
console.error('获取店铺列表失败:', error);
|
||||
message.error('获取店铺列表失败');
|
||||
} finally {
|
||||
shopLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const handleShopSearch = (value: string) => {
|
||||
shopSearchValue.value = value;
|
||||
fetchShopList(true);
|
||||
};
|
||||
|
||||
const handleShopScroll = (e: any) => {
|
||||
const { target } = e;
|
||||
if (target.scrollTop + target.offsetHeight === target.scrollHeight && shopHasMore.value && !shopLoading.value) {
|
||||
fetchShopList();
|
||||
}
|
||||
};
|
||||
|
||||
const fetchFieldDefs = async () => {
|
||||
try {
|
||||
fieldDefsLoading.value = true;
|
||||
const result = await getAdFeeFieldsApi();
|
||||
fieldDefs.value = (result || []) as unknown as AdFeeFieldVO.Info[];
|
||||
initFieldMappings();
|
||||
} catch (error) {
|
||||
console.error('获取字段定义失败:', error);
|
||||
message.error('获取字段定义失败');
|
||||
} finally {
|
||||
fieldDefsLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const fetchMappingTemplates = async () => {
|
||||
try {
|
||||
templateLoading.value = true;
|
||||
const result = await getImportMappingPageApi({
|
||||
page: 1,
|
||||
pageSize: 100,
|
||||
filters: { type: ImportMappingType.PROMOTION_FEE },
|
||||
});
|
||||
mappingTemplates.value = result.records || [];
|
||||
if (mappingTemplates.value.length > 0 && !selectedTemplateId.value) {
|
||||
const firstTemplate = mappingTemplates.value[0];
|
||||
if (firstTemplate?.id) {
|
||||
selectedTemplateId.value = firstTemplate.id;
|
||||
await handleSelectTemplate(firstTemplate.id);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取映射模板列表失败:', error);
|
||||
message.error('获取映射模板列表失败');
|
||||
} finally {
|
||||
templateLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const handleSelectTemplate = async (value: any) => {
|
||||
const templateId = typeof value === 'number' ? value : undefined;
|
||||
if (!templateId) {
|
||||
selectedTemplateName.value = '';
|
||||
currentTemplateMappings.value = [];
|
||||
if (fieldDefs.value.length > 0) initFieldMappings();
|
||||
return;
|
||||
}
|
||||
if (fieldDefs.value.length === 0) return;
|
||||
|
||||
const template = mappingTemplates.value.find((t) => t.id === templateId);
|
||||
if (!template) return;
|
||||
|
||||
try {
|
||||
const mappingItems: FieldMappingItem[] = JSON.parse(template.mapping);
|
||||
selectedTemplateName.value = template.name;
|
||||
currentTemplateMappings.value = mappingItems;
|
||||
|
||||
const mappings: typeof fieldMappings.value = {};
|
||||
fieldDefs.value.forEach((fieldDef) => {
|
||||
const templateItem = mappingItems.find((item) => item.fieldName === fieldDef.fieldName);
|
||||
let mappedHeader: string | undefined;
|
||||
if (templateItem?.fileFieldName) {
|
||||
const matched = csvHeaders.value.find((h) => h === templateItem.fileFieldName);
|
||||
if (matched) mappedHeader = matched;
|
||||
}
|
||||
mappings[fieldDef.fieldName] = { fieldDef, mappedHeader };
|
||||
});
|
||||
fieldMappings.value = mappings;
|
||||
message.success('已应用映射模板');
|
||||
} catch (error) {
|
||||
console.error('应用映射模板失败:', error);
|
||||
message.error('应用映射模板失败,模板格式可能不正确');
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddFieldToTemplate = async (fieldDefId: string) => {
|
||||
if (!selectedTemplateId.value) {
|
||||
message.warning('请先选择一个模板');
|
||||
return;
|
||||
}
|
||||
const mapping = fieldMappings.value[fieldDefId];
|
||||
if (!mapping || !mapping.mappedHeader) {
|
||||
message.warning('请先完成该字段的映射');
|
||||
return;
|
||||
}
|
||||
|
||||
const fieldDef = mapping.fieldDef;
|
||||
const fieldItem: FieldMappingItem = {
|
||||
fieldName: fieldDef.fieldName,
|
||||
fieldLabel: fieldDef.fieldLabel,
|
||||
fileFieldName: mapping.mappedHeader,
|
||||
required: fieldDef.required,
|
||||
};
|
||||
|
||||
try {
|
||||
savingFieldToTemplate.value = fieldDefId;
|
||||
const template = mappingTemplates.value.find((t) => t.id === selectedTemplateId.value);
|
||||
if (!template) {
|
||||
message.error('模板不存在');
|
||||
return;
|
||||
}
|
||||
let mappingItems: FieldMappingItem[] = [];
|
||||
try {
|
||||
mappingItems = JSON.parse(template.mapping);
|
||||
} catch {
|
||||
mappingItems = [];
|
||||
}
|
||||
const existingIdx = mappingItems.findIndex((item) => item.fieldName === fieldDef.fieldName);
|
||||
if (existingIdx === -1) {
|
||||
mappingItems.push(fieldItem);
|
||||
} else {
|
||||
mappingItems[existingIdx] = fieldItem;
|
||||
}
|
||||
const mappingJson = JSON.stringify(mappingItems);
|
||||
await updateImportMappingApi(selectedTemplateId.value, {
|
||||
name: template.name,
|
||||
mapping: mappingJson,
|
||||
});
|
||||
template.mapping = mappingJson;
|
||||
currentTemplateMappings.value = mappingItems;
|
||||
message.success(`已将「${fieldDef.fieldLabel}」映射添加到模板`);
|
||||
} catch (error: any) {
|
||||
console.error('添加到模板失败:', error);
|
||||
message.error(error?.message || '添加到模板失败');
|
||||
} finally {
|
||||
savingFieldToTemplate.value = null;
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveTemplate = () => {
|
||||
if (selectedTemplateId.value) {
|
||||
message.info('已有模板选中,请使用每行「添加到模板」按钮单独更新字段映射');
|
||||
return;
|
||||
}
|
||||
const mappingItems: FieldMappingItem[] = Object.values(fieldMappings.value)
|
||||
.filter((m) => m.mappedHeader)
|
||||
.map((m) => ({
|
||||
fieldName: m.fieldDef.fieldName,
|
||||
fieldLabel: m.fieldDef.fieldLabel,
|
||||
fileFieldName: m.mappedHeader,
|
||||
required: m.fieldDef.required,
|
||||
}));
|
||||
if (mappingItems.length === 0) {
|
||||
message.warning('请先完成字段映射');
|
||||
return;
|
||||
}
|
||||
templateName.value = '';
|
||||
saveTemplateModalApi.open();
|
||||
};
|
||||
|
||||
async function handleConfirmSaveTemplate() {
|
||||
if (!templateName.value.trim()) {
|
||||
message.warning('请输入模板名称');
|
||||
return;
|
||||
}
|
||||
const requiredFields = fieldDefs.value.filter((f) => f.required);
|
||||
const unMappedFields = requiredFields.filter((field) => {
|
||||
const mapping = fieldMappings.value[field.fieldName];
|
||||
return !mapping || !mapping.mappedHeader;
|
||||
});
|
||||
if (unMappedFields.length > 0) {
|
||||
message.warning(`请先绑定所有必填字段:${unMappedFields.map((f) => f.fieldLabel).join('、')}`);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
savingTemplate.value = true;
|
||||
saveTemplateModalApi.lock();
|
||||
const mappingItems: FieldMappingItem[] = Object.values(fieldMappings.value)
|
||||
.filter((m) => m.mappedHeader)
|
||||
.map((m) => ({
|
||||
fieldName: m.fieldDef.fieldName,
|
||||
fieldLabel: m.fieldDef.fieldLabel,
|
||||
fileFieldName: m.mappedHeader,
|
||||
required: m.fieldDef.required,
|
||||
}));
|
||||
await createImportMappingApi({
|
||||
type: ImportMappingType.PROMOTION_FEE,
|
||||
name: templateName.value.trim(),
|
||||
mapping: JSON.stringify(mappingItems),
|
||||
});
|
||||
message.success('保存映射模板成功');
|
||||
templateName.value = '';
|
||||
saveTemplateModalApi.close();
|
||||
await fetchMappingTemplates();
|
||||
} catch (error: any) {
|
||||
console.error('保存映射模板失败:', error);
|
||||
message.error(error?.message || '保存映射模板失败');
|
||||
} finally {
|
||||
savingTemplate.value = false;
|
||||
saveTemplateModalApi.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
const handleNext = async () => {
|
||||
if (currentStep.value !== 0) return;
|
||||
const requiredFields = fieldDefs.value.filter((f) => f.required);
|
||||
const unMappedFields = requiredFields.filter((field) => {
|
||||
const mapping = fieldMappings.value[field.fieldName];
|
||||
return !mapping || !mapping.mappedHeader;
|
||||
});
|
||||
if (unMappedFields.length > 0) {
|
||||
message.warning(`请先绑定必填字段:${unMappedFields.map((f) => f.fieldLabel).join('、')}`);
|
||||
return;
|
||||
}
|
||||
if (shopList.value.length === 0) {
|
||||
shopSearchValue.value = '';
|
||||
shopPage.value = 1;
|
||||
shopHasMore.value = true;
|
||||
await fetchShopList(true);
|
||||
}
|
||||
currentStep.value = 1;
|
||||
};
|
||||
|
||||
const handlePrev = () => {
|
||||
if (currentStep.value > 0) currentStep.value--;
|
||||
};
|
||||
|
||||
const buildPatchedCsv = (): File => {
|
||||
const headers = [...csvHeaders.value, 'productId'];
|
||||
const rows = previewData.value.map((row: any) =>
|
||||
headers.map((h: string) => {
|
||||
if (h === 'productId') return row._productId ?? '';
|
||||
return row[h] ?? '';
|
||||
}),
|
||||
);
|
||||
const csvContent = `\uFEFF${[
|
||||
headers.join(','),
|
||||
...rows.map((r: any[]) => r.map((v: any) => `"${String(v).replace(/"/g, '""')}"`).join(',')),
|
||||
].join('\n')}`;
|
||||
return new File([csvContent], buildPatchedFileName(originalImportFile.value?.name || 'data.csv'), {
|
||||
type: 'text/csv;charset=utf-8',
|
||||
});
|
||||
};
|
||||
|
||||
const buildPatchedFileName = (_original: string): string => {
|
||||
return 'ad_fee_import_patched.csv';
|
||||
};
|
||||
|
||||
const handleCreateTask = async () => {
|
||||
if (!selectedFile.value && !originalImportFile.value) {
|
||||
message.error('文件信息丢失,请重新上传');
|
||||
return;
|
||||
}
|
||||
if (selectedShopId.value === undefined) {
|
||||
message.warning('请选择店铺');
|
||||
return;
|
||||
}
|
||||
if (!feeDate.value) {
|
||||
message.warning('请选择广告费发生日期');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
createTaskSubmitting.value = true;
|
||||
message.loading('正在上传文件...', 0);
|
||||
const patchedFile = buildPatchedCsv();
|
||||
const fileInfo = await uploadFile(patchedFile, {
|
||||
category: FileCategory.FILE,
|
||||
errorMessage: '文件上传失败,请重试',
|
||||
});
|
||||
message.destroy();
|
||||
|
||||
const mappingItems: FieldMappingItem[] = Object.values(fieldMappings.value)
|
||||
.filter((m) => m.mappedHeader)
|
||||
.map((m) => ({
|
||||
fieldName: m.fieldDef.fieldName,
|
||||
fieldLabel: m.fieldDef.fieldLabel,
|
||||
fileFieldName: m.mappedHeader,
|
||||
required: m.fieldDef.required,
|
||||
}));
|
||||
|
||||
const fullMapping = {
|
||||
fieldMapping: mappingItems,
|
||||
feeDate: dayjs(feeDate.value).format('YYYY-MM-DD'),
|
||||
};
|
||||
|
||||
const createData: ImportTaskDTO.CreateImportTaskDTO = {
|
||||
shopId: selectedShopId.value!,
|
||||
type: 'promotion_record',
|
||||
fileName: patchedFile.name,
|
||||
fileId: fileInfo.id,
|
||||
mapping: JSON.stringify(fullMapping),
|
||||
};
|
||||
|
||||
const task = await createImportTaskApi(createData);
|
||||
message.success('创建导入任务成功');
|
||||
importTaskStore.updateTask(task);
|
||||
await importTaskStore.fetchTasks(true);
|
||||
importTaskStore.openDropdown();
|
||||
|
||||
currentStep.value = 0;
|
||||
selectedShopId.value = undefined;
|
||||
feeDate.value = undefined;
|
||||
fieldMappings.value = {};
|
||||
csvHeaders.value = [];
|
||||
previewData.value = [];
|
||||
selectedFile.value = null;
|
||||
originalImportFile.value = null;
|
||||
selectedTemplateId.value = undefined;
|
||||
emit('success');
|
||||
} catch (error: any) {
|
||||
message.destroy();
|
||||
console.error('创建导入任务失败:', error);
|
||||
message.error(error?.message || '创建导入任务失败');
|
||||
} finally {
|
||||
createTaskSubmitting.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
async function open(headers: string[], file?: File) {
|
||||
csvHeaders.value = headers;
|
||||
originalImportFile.value = file ?? null;
|
||||
selectedFile.value = file ?? null;
|
||||
currentStep.value = 0;
|
||||
fieldMappings.value = {};
|
||||
|
||||
if (shopList.value.length === 0) {
|
||||
shopSearchValue.value = '';
|
||||
shopPage.value = 1;
|
||||
shopHasMore.value = true;
|
||||
void fetchShopList(true);
|
||||
}
|
||||
|
||||
if (fieldDefs.value.length === 0) {
|
||||
await fetchFieldDefs();
|
||||
} else {
|
||||
initFieldMappings();
|
||||
}
|
||||
|
||||
if (mappingTemplates.value.length === 0) {
|
||||
await fetchMappingTemplates();
|
||||
} else if (selectedTemplateId.value) {
|
||||
await handleSelectTemplate(selectedTemplateId.value);
|
||||
} else {
|
||||
const firstTemplate = mappingTemplates.value[0];
|
||||
if (firstTemplate?.id) {
|
||||
selectedTemplateId.value = firstTemplate.id;
|
||||
await handleSelectTemplate(firstTemplate.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function reset() {
|
||||
currentStep.value = 0;
|
||||
selectedShopId.value = undefined;
|
||||
feeDate.value = undefined;
|
||||
fieldMappings.value = {};
|
||||
csvHeaders.value = [];
|
||||
previewData.value = [];
|
||||
selectedFile.value = null;
|
||||
originalImportFile.value = null;
|
||||
selectedTemplateId.value = undefined;
|
||||
}
|
||||
|
||||
defineExpose({ open, reset });
|
||||
|
||||
const shopOptions = computed(() => {
|
||||
return shopList.value.map((shop: ShopVO.Info) => ({
|
||||
label: shop.platformName ? `${shop.name} (${shop.platformName})` : shop.name,
|
||||
value: shop.id,
|
||||
}));
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="import-task-wizard flex h-full min-h-0 w-full flex-col overflow-hidden rounded-2xl border border-slate-200/80 bg-white shadow-sm dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
|
||||
>
|
||||
<div class="shrink-0 border-b border-slate-100 px-4 py-3 dark:border-[hsl(240deg_3.7%_22%)]">
|
||||
<div class="text-base font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
|
||||
创建导入任务
|
||||
</div>
|
||||
<p
|
||||
v-if="selectedFile"
|
||||
class="mb-0 mt-1 truncate text-xs text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]"
|
||||
>
|
||||
{{ selectedFile.name }} · {{ previewData.length }} 条
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||
<div
|
||||
class="import-task-wizard-main grid min-h-0 min-w-0 w-full flex-1 grid-rows-[auto_minmax(0,1fr)] gap-3 overflow-hidden px-3 py-3"
|
||||
>
|
||||
<div class="min-w-0 shrink-0">
|
||||
<Steps :current="currentStep">
|
||||
<Steps.Step title="字段映射" />
|
||||
<Steps.Step title="确认信息" />
|
||||
</Steps>
|
||||
</div>
|
||||
<div class="flex h-full min-h-0 min-w-0 flex-col overflow-hidden">
|
||||
<div
|
||||
v-if="currentStep === 0"
|
||||
class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden py-2"
|
||||
>
|
||||
<div class="mb-3 flex shrink-0 flex-wrap items-center justify-between gap-2 gap-y-3">
|
||||
<div class="text-sm text-gray-600 dark:text-gray-300">
|
||||
请为每个广告费字段选择对应的CSV列,必填字段必须绑定
|
||||
</div>
|
||||
<div class="flex items-center space-x-2">
|
||||
<Select
|
||||
v-model:value="selectedTemplateId"
|
||||
placeholder="选择已有模板"
|
||||
class="w-[200px]"
|
||||
:loading="templateLoading"
|
||||
allow-clear
|
||||
@change="handleSelectTemplate"
|
||||
>
|
||||
<template #notFoundContent>
|
||||
<div v-if="templateLoading" class="py-4 text-center">
|
||||
<Spin size="small" />
|
||||
<div class="mt-2">加载中...</div>
|
||||
</div>
|
||||
<div v-else class="py-4 text-center text-gray-400 dark:text-gray-500">
|
||||
暂无模板
|
||||
</div>
|
||||
</template>
|
||||
<Select.Option
|
||||
v-for="template in mappingTemplates"
|
||||
:key="template.id"
|
||||
:value="template.id"
|
||||
>
|
||||
{{ template.name }}
|
||||
<span class="ml-2 text-xs text-gray-400 dark:text-gray-500">
|
||||
({{ new Date(template.createTime).toLocaleDateString() }})
|
||||
</span>
|
||||
</Select.Option>
|
||||
</Select>
|
||||
<PermissionGate code="data:import-mapping:create">
|
||||
<Button
|
||||
:disabled="selectedTemplateId !== undefined"
|
||||
@click="handleSaveTemplate"
|
||||
>
|
||||
保存为模板
|
||||
</Button>
|
||||
</PermissionGate>
|
||||
</div>
|
||||
</div>
|
||||
<template v-if="fieldDefsLoading">
|
||||
<div class="flex min-h-[200px] flex-1 items-center justify-center text-gray-500 dark:text-gray-400">
|
||||
<Spin size="large" />
|
||||
<span class="ml-3 text-sm">加载字段定义中…</span>
|
||||
</div>
|
||||
</template>
|
||||
<div
|
||||
v-else
|
||||
class="min-h-0 flex-1 space-y-3 overflow-y-auto overscroll-y-contain pr-0.5"
|
||||
>
|
||||
<div
|
||||
v-for="fieldDef in fieldDefs"
|
||||
:key="fieldDef.fieldName"
|
||||
class="flex min-w-0 flex-col overflow-hidden rounded-lg border p-0"
|
||||
:class="
|
||||
fieldDef.required && !fieldMappings[fieldDef.fieldName]?.mappedHeader
|
||||
? 'border-red-300 dark:border-red-700'
|
||||
: isMappingChangedFromTemplate(fieldDef.fieldName)
|
||||
? 'border-yellow-200 dark:border-yellow-700'
|
||||
: isMappingFromTemplate(fieldDef.fieldName)
|
||||
? 'border-blue-200 dark:border-blue-700'
|
||||
: 'border-slate-200 dark:border-slate-600'
|
||||
"
|
||||
>
|
||||
<div
|
||||
class="border-b border-slate-200/90 bg-gradient-to-r to-transparent px-3 py-2.5 dark:border-slate-600"
|
||||
:class="
|
||||
fieldDef.required && !fieldMappings[fieldDef.fieldName]?.mappedHeader
|
||||
? 'from-red-50/90 dark:from-red-950/35'
|
||||
: isMappingChangedFromTemplate(fieldDef.fieldName)
|
||||
? 'from-amber-50/75 dark:from-amber-950/30'
|
||||
: isMappingFromTemplate(fieldDef.fieldName)
|
||||
? 'from-blue-50/90 dark:from-blue-950/40'
|
||||
: 'from-blue-50/95 dark:from-blue-950/35'
|
||||
"
|
||||
>
|
||||
<div class="mb-2 flex flex-wrap items-center gap-2">
|
||||
<span
|
||||
class="shrink-0 rounded bg-blue-600 px-2 py-0.5 text-[11px] font-semibold text-white shadow-sm dark:bg-blue-500"
|
||||
>
|
||||
系统
|
||||
</span>
|
||||
<span class="text-xs font-medium text-slate-600 dark:text-slate-300">
|
||||
广告费字段
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-x-2 gap-y-1">
|
||||
<span class="font-medium leading-snug text-slate-900 dark:text-slate-100">
|
||||
{{ fieldDef.fieldLabel }}
|
||||
</span>
|
||||
<span v-if="fieldDef.required" class="text-xs text-red-500 dark:text-red-400">
|
||||
必填
|
||||
</span>
|
||||
<span
|
||||
v-if="selectedTemplateId && isMappingFromTemplate(fieldDef.fieldName)"
|
||||
class="rounded bg-blue-100 px-1.5 py-0.5 text-xs text-blue-700 dark:bg-blue-900/50 dark:text-blue-300"
|
||||
>
|
||||
模板映射
|
||||
</span>
|
||||
<span
|
||||
v-if="selectedTemplateId && isMappingChangedFromTemplate(fieldDef.fieldName)"
|
||||
class="rounded bg-amber-100 px-1.5 py-0.5 text-xs text-amber-800 dark:bg-amber-900/40 dark:text-amber-200"
|
||||
>
|
||||
已变更
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="bg-gradient-to-r from-amber-50/90 to-transparent px-3 py-2.5 dark:from-amber-950/25"
|
||||
>
|
||||
<div class="mb-2 flex flex-wrap items-center gap-2">
|
||||
<span
|
||||
class="shrink-0 rounded bg-amber-600 px-2 py-0.5 text-[11px] font-semibold text-white shadow-sm dark:bg-amber-600"
|
||||
>
|
||||
文件
|
||||
</span>
|
||||
<span class="text-xs font-medium text-slate-600 dark:text-slate-300">
|
||||
CSV 列
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex min-w-0 flex-col gap-2 sm:flex-row sm:items-center sm:gap-2">
|
||||
<Select
|
||||
v-if="fieldMappings[fieldDef.fieldName]"
|
||||
v-model:value="fieldMappings[fieldDef.fieldName]!.mappedHeader"
|
||||
placeholder="选择该字段对应的 CSV 列"
|
||||
class="w-full min-w-0 sm:flex-1"
|
||||
show-search
|
||||
allow-clear
|
||||
:options="csvHeaders.map((h) => ({ label: h, value: h }))"
|
||||
/>
|
||||
<Button
|
||||
v-if="selectedTemplateId && fieldMappings[fieldDef.fieldName]?.mappedHeader"
|
||||
size="small"
|
||||
type="link"
|
||||
class="h-auto shrink-0 self-start px-0 py-0 sm:self-center"
|
||||
:disabled="isMappingFromTemplate(fieldDef.fieldName)"
|
||||
:loading="savingFieldToTemplate === fieldDef.fieldName"
|
||||
@click="handleAddFieldToTemplate(fieldDef.fieldName)"
|
||||
>
|
||||
添加到模板
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="currentStep === 1"
|
||||
class="flex min-h-0 min-w-0 flex-1 flex-col overflow-y-auto py-2"
|
||||
>
|
||||
<div class="space-y-4">
|
||||
<Form :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
|
||||
<Form.Item label="选择店铺" required>
|
||||
<Select
|
||||
v-model:value="selectedShopId"
|
||||
placeholder="请选择店铺"
|
||||
show-search
|
||||
:filter-option="false"
|
||||
:loading="shopLoading"
|
||||
@search="handleShopSearch"
|
||||
@popup-scroll="handleShopScroll"
|
||||
>
|
||||
<template #notFoundContent>
|
||||
<div v-if="shopLoading" class="py-4 text-center">
|
||||
<Spin size="small" />
|
||||
<div class="mt-2">加载中...</div>
|
||||
</div>
|
||||
<div v-else class="py-4 text-center text-gray-400 dark:text-gray-500">
|
||||
暂无数据
|
||||
</div>
|
||||
</template>
|
||||
<Select.Option
|
||||
v-for="option in shopOptions"
|
||||
:key="option.value"
|
||||
:value="option.value"
|
||||
:label="option.label"
|
||||
>
|
||||
{{ option.label }}
|
||||
</Select.Option>
|
||||
</Select>
|
||||
</Form.Item>
|
||||
<Form.Item label="发生日期" required>
|
||||
<DatePicker
|
||||
v-model:value="feeDate"
|
||||
placeholder="选择广告费发生日期"
|
||||
style="width: 100%"
|
||||
/>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
<div class="rounded bg-gray-50 p-4 dark:bg-gray-800">
|
||||
<div class="mb-2 font-medium">字段映射</div>
|
||||
<div class="space-y-2">
|
||||
<div
|
||||
v-for="mapping in Object.values(fieldMappings).filter((m) => m.mappedHeader)"
|
||||
:key="mapping.fieldDef.fieldName"
|
||||
class="flex justify-between text-sm"
|
||||
>
|
||||
<span class="text-gray-600 dark:text-gray-300">{{ mapping.fieldDef.fieldLabel }}:</span>
|
||||
<span class="font-medium">{{ mapping.mappedHeader }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded bg-gray-50 p-4 dark:bg-gray-800">
|
||||
<div class="mb-2 font-medium">导入配置摘要</div>
|
||||
<div class="space-y-2">
|
||||
<div class="flex justify-between text-sm">
|
||||
<span class="text-gray-600 dark:text-gray-300">数据行数</span>
|
||||
<span class="font-medium">{{ previewData.length }}</span>
|
||||
</div>
|
||||
<div class="flex justify-between text-sm">
|
||||
<span class="text-gray-600 dark:text-gray-300">已映射字段</span>
|
||||
<span class="font-medium">{{ Object.values(fieldMappings).filter((m) => m.mappedHeader).length }}/{{ fieldDefs.length }}</span>
|
||||
</div>
|
||||
<div class="flex justify-between text-sm">
|
||||
<span class="text-gray-600 dark:text-gray-300">商品</span>
|
||||
<span class="font-medium text-green-600">表格中逐行设置</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="flex shrink-0 flex-wrap justify-end gap-2 border-t border-slate-100 bg-slate-50/80 px-3 py-3 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/40%)]"
|
||||
>
|
||||
<Button v-if="currentStep > 0" @click="handlePrev">上一步</Button>
|
||||
<Button
|
||||
v-if="currentStep < 1"
|
||||
type="primary"
|
||||
:disabled="!canGoToNextStep"
|
||||
@click="handleNext"
|
||||
>
|
||||
下一步
|
||||
</Button>
|
||||
<PermissionGate code="data:import:create">
|
||||
<Button
|
||||
v-if="currentStep === 1"
|
||||
type="primary"
|
||||
:loading="createTaskSubmitting"
|
||||
@click="handleCreateTask"
|
||||
>
|
||||
创建导入任务
|
||||
</Button>
|
||||
</PermissionGate>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SaveTemplateModal :confirm-loading="savingTemplate">
|
||||
<Form :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
|
||||
<Form.Item label="模板名称" required>
|
||||
<Input
|
||||
v-model:value="templateName"
|
||||
placeholder="请输入模板名称"
|
||||
:maxlength="50"
|
||||
show-count
|
||||
@press-enter="handleConfirmSaveTemplate"
|
||||
/>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</SaveTemplateModal>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.import-task-wizard-main {
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.import-task-wizard-main > :last-child {
|
||||
min-height: 0;
|
||||
align-self: stretch;
|
||||
}
|
||||
</style>
|
||||
@@ -1,351 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { VxeGridProps } from '#/adapter/vxe-table';
|
||||
|
||||
import { computed, nextTick, onMounted, onUnmounted, ref } from 'vue';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
import { Button, message } from 'ant-design-vue';
|
||||
|
||||
import { useVbenVxeGrid } from '#/adapter/vxe-table';
|
||||
|
||||
import ImportTaskWizard from './components/ImportTaskWizard.vue';
|
||||
import FileUploadArea from './components/FileUploadArea.vue';
|
||||
import { parseFileToRawData } from '#/views/ec/import/order/utils/fileParser';
|
||||
import { getProductPageApi } from '#/api/ec/product/apis';
|
||||
import type { ProductVO } from '#/api/ec/product/types';
|
||||
|
||||
defineOptions({ name: 'AdFeeImport' });
|
||||
|
||||
const csvData = ref<any[]>([]);
|
||||
const csvHeaders = ref<string[]>([]);
|
||||
const importLoading = ref(false);
|
||||
const currentFile = ref<File | null>(null);
|
||||
const tableContainerRef = ref<HTMLElement>();
|
||||
const tableHeight = ref<number>(600);
|
||||
|
||||
const importTaskWizardRef = ref<InstanceType<typeof ImportTaskWizard>>();
|
||||
|
||||
const productList = ref<ProductVO.Info[]>([]);
|
||||
|
||||
const loadReferenceData = async () => {
|
||||
try {
|
||||
const productRes = await getProductPageApi({
|
||||
page: 1,
|
||||
pageSize: 9999,
|
||||
filters: {},
|
||||
});
|
||||
productList.value = ((productRes as any).records || []) as ProductVO.Info[];
|
||||
} catch (e) {
|
||||
console.error('加载参考数据失败', e);
|
||||
}
|
||||
};
|
||||
|
||||
const gridColumns = computed(() => {
|
||||
if (csvHeaders.value.length === 0) return [];
|
||||
|
||||
const columns: VxeGridProps<any>['columns'] = [
|
||||
{ type: 'seq' as const, title: '序号', width: 80, fixed: 'left' as const },
|
||||
];
|
||||
|
||||
csvHeaders.value.forEach((header) => {
|
||||
columns.push({
|
||||
field: header,
|
||||
title: header,
|
||||
minWidth: 150,
|
||||
showOverflow: 'tooltip' as const,
|
||||
});
|
||||
});
|
||||
|
||||
columns.push({
|
||||
field: '_productId',
|
||||
title: '商品',
|
||||
width: 180,
|
||||
fixed: 'right' as const,
|
||||
cellRender: {
|
||||
name: 'CellSelect',
|
||||
props: {
|
||||
options: productList.value.map((p) => ({
|
||||
label: `${p.name}${p.productCode ? ` (${p.productCode})` : ''}`,
|
||||
value: p.id,
|
||||
})),
|
||||
allowClear: true,
|
||||
placeholder: '请选择商品',
|
||||
showSearch: true,
|
||||
filterOption: (input: string, option: any) =>
|
||||
option.label.toLowerCase().includes(input.toLowerCase()),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return columns;
|
||||
});
|
||||
|
||||
const gridOptions: VxeGridProps<any> = {
|
||||
columns: [],
|
||||
height: tableHeight.value,
|
||||
border: true,
|
||||
stripe: true,
|
||||
rowConfig: { isHover: true, height: 44 },
|
||||
showOverflow: true,
|
||||
size: 'small',
|
||||
data: [],
|
||||
pagerConfig: {
|
||||
enabled: true,
|
||||
pageSize: 50,
|
||||
pageSizes: [10, 20, 50, 100],
|
||||
layouts: [
|
||||
'PrevJump',
|
||||
'PrevPage',
|
||||
'Number',
|
||||
'NextPage',
|
||||
'NextJump',
|
||||
'Sizes',
|
||||
'FullJump',
|
||||
'Total',
|
||||
] as (
|
||||
| 'FullJump'
|
||||
| 'NextJump'
|
||||
| 'NextPage'
|
||||
| 'Number'
|
||||
| 'PrevJump'
|
||||
| 'PrevPage'
|
||||
| 'Sizes'
|
||||
| 'Total'
|
||||
)[],
|
||||
},
|
||||
proxyConfig: {
|
||||
ajax: {
|
||||
query: async ({ page }) => {
|
||||
if (csvData.value.length === 0) {
|
||||
return { items: [], total: 0 };
|
||||
}
|
||||
|
||||
const currentPage = page.currentPage || 1;
|
||||
const pageSize = page.pageSize || 50;
|
||||
const startIndex = (currentPage - 1) * pageSize;
|
||||
const endIndex = startIndex + pageSize;
|
||||
|
||||
const pageData = csvData.value.slice(startIndex, endIndex);
|
||||
pageData.forEach((row, i) => {
|
||||
(row as Record<string, unknown>).__srcRowIndex = startIndex + i;
|
||||
});
|
||||
|
||||
return {
|
||||
items: pageData,
|
||||
total: csvData.value.length,
|
||||
};
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const gridEvents = {};
|
||||
|
||||
const [Grid, gridApi] = useVbenVxeGrid({
|
||||
gridOptions,
|
||||
gridEvents,
|
||||
});
|
||||
|
||||
const updateTable = () => {
|
||||
gridApi.setGridOptions({
|
||||
columns: gridColumns.value,
|
||||
height: tableHeight.value,
|
||||
});
|
||||
gridApi.reload();
|
||||
};
|
||||
|
||||
const syncWizardOpen = () => {
|
||||
if (csvData.value.length === 0 || csvHeaders.value.length === 0) return;
|
||||
nextTick(() => {
|
||||
importTaskWizardRef.value?.open(
|
||||
[...csvHeaders.value],
|
||||
currentFile.value ?? undefined,
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
const handleFileUpload = async (file: File) => {
|
||||
importLoading.value = true;
|
||||
try {
|
||||
const result = await parseFileToRawData(file, { preserveEmptyRows: true });
|
||||
|
||||
if (result.errors.length > 0) {
|
||||
message.warning(result.errors.join('; '));
|
||||
}
|
||||
|
||||
if (result.data.length === 0) {
|
||||
message.error('文件没有有效数据');
|
||||
return;
|
||||
}
|
||||
|
||||
csvData.value = result.data;
|
||||
csvHeaders.value = result.headers;
|
||||
currentFile.value = file;
|
||||
|
||||
updateTable();
|
||||
nextTick(() => {
|
||||
calculateTableHeight();
|
||||
});
|
||||
syncWizardOpen();
|
||||
|
||||
const fileExt = file.name.toLowerCase().split('.').pop() || '';
|
||||
const format = ['xlsx', 'xls'].includes(fileExt) ? 'Excel' : 'CSV';
|
||||
message.success(`成功解析 ${result.data.length} 条数据(${format} 格式)`);
|
||||
|
||||
// 加载参考数据用于表格行内下拉选择
|
||||
await loadReferenceData();
|
||||
updateTable();
|
||||
} catch (error: any) {
|
||||
message.error(`文件读取失败: ${error.message}`);
|
||||
} finally {
|
||||
importLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const handleClearData = () => {
|
||||
csvData.value = [];
|
||||
csvHeaders.value = [];
|
||||
currentFile.value = null;
|
||||
importTaskWizardRef.value?.reset();
|
||||
updateTable();
|
||||
message.success('已清空数据');
|
||||
};
|
||||
|
||||
const handleWizardSuccess = () => {
|
||||
csvData.value = [];
|
||||
csvHeaders.value = [];
|
||||
currentFile.value = null;
|
||||
importTaskWizardRef.value?.reset();
|
||||
updateTable();
|
||||
message.success('已创建导入任务,可继续上传新文件');
|
||||
};
|
||||
|
||||
const calculateTableHeight = () => {
|
||||
nextTick(() => {
|
||||
if (tableContainerRef.value) {
|
||||
const rect = tableContainerRef.value.getBoundingClientRect();
|
||||
const toolbarReserve = 56;
|
||||
const padding = 24;
|
||||
const availableHeight = rect.height - padding - toolbarReserve;
|
||||
tableHeight.value = Math.max(320, availableHeight);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
let resizeObserver: null | ResizeObserver = null;
|
||||
|
||||
onMounted(() => {
|
||||
calculateTableHeight();
|
||||
if (tableContainerRef.value) {
|
||||
resizeObserver = new ResizeObserver(() => {
|
||||
calculateTableHeight();
|
||||
});
|
||||
resizeObserver.observe(tableContainerRef.value);
|
||||
}
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
resizeObserver?.disconnect();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Page
|
||||
auto-content-height
|
||||
:content-padding-class="csvData.length === 0 ? 'p-4 sm:p-6' : 'p-2 sm:p-3'"
|
||||
content-class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-slate-100 dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
|
||||
>
|
||||
<div
|
||||
v-if="csvData.length === 0"
|
||||
class="mx-auto flex min-h-0 w-full max-w-3xl flex-1 flex-col items-center justify-center py-8"
|
||||
>
|
||||
<div class="mb-10 shrink-0 text-center">
|
||||
<h1
|
||||
class="mb-2 text-3xl font-black tracking-tight text-slate-800 dark:text-[hsl(0deg_0%_95%)] sm:text-4xl"
|
||||
>
|
||||
广告费导入中心
|
||||
</h1>
|
||||
<p
|
||||
class="text-sm font-medium text-slate-500 dark:text-[hsl(240deg_5%_64.9%)] sm:text-base"
|
||||
>
|
||||
请上传 CSV / Excel 格式的广告费原始数据
|
||||
</p>
|
||||
</div>
|
||||
<div
|
||||
class="relative w-full overflow-hidden rounded-[2rem] border border-white/50 bg-white/45 p-6 dark:border-[hsl(240deg_3.7%_22%/50%)] dark:bg-[hsl(222.34deg_10.43%_12.27%/80%)] shadow-[0_25px_50px_-12px_rgba(0,0,0,0.1)] dark:shadow-none backdrop-blur-2xl sm:p-8"
|
||||
>
|
||||
<div
|
||||
class="absolute -right-10 -top-10 h-32 w-32 rounded-full bg-indigo-400 opacity-10 blur-3xl"
|
||||
>
|
||||
</div>
|
||||
<div class="relative w-full">
|
||||
<FileUploadArea
|
||||
:loading="importLoading"
|
||||
@file-selected="handleFileUpload"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else
|
||||
class="flex min-h-0 w-full min-w-0 flex-1 flex-row gap-3 overflow-hidden sm:gap-4"
|
||||
>
|
||||
<section
|
||||
class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-2xl border border-slate-200/80 bg-white/90 shadow-sm dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%/90%)]"
|
||||
>
|
||||
<div
|
||||
class="flex shrink-0 flex-wrap items-center justify-between gap-3 border-b border-slate-100 px-4 py-3 dark:border-[hsl(240deg_3.7%_22%)]"
|
||||
>
|
||||
<div class="min-w-0">
|
||||
<h2
|
||||
class="mb-0.5 text-lg font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]"
|
||||
>
|
||||
数据预览
|
||||
</h2>
|
||||
<p
|
||||
class="m-0 text-xs text-slate-500 dark:text-[hsl(240deg_5%_64.9%)] sm:text-sm"
|
||||
>
|
||||
共 {{ csvData.length }} 条 · 右侧配置导入任务
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex shrink-0 flex-wrap items-center justify-end gap-2">
|
||||
<Button size="small" @click="handleClearData">清空数据</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
ref="tableContainerRef"
|
||||
class="flex min-h-0 flex-1 flex-col overflow-hidden p-3 sm:p-4"
|
||||
>
|
||||
<Grid />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<aside
|
||||
class="flex min-h-0 w-[min(100%,440px)] shrink-0 flex-col self-stretch overflow-hidden sm:w-[400px] lg:w-[440px]"
|
||||
>
|
||||
<div class="flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||
<ImportTaskWizard
|
||||
ref="importTaskWizardRef"
|
||||
v-model:preview-data="csvData"
|
||||
@success="handleWizardSuccess"
|
||||
/>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</Page>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
:deep(.vxe-grid) {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
:deep(.vxe-grid--body-wrapper) {
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
}
|
||||
</style>
|
||||
@@ -1,172 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
|
||||
import { createIconifyIcon } from '@vben/icons';
|
||||
|
||||
import { message, Spin } from 'ant-design-vue';
|
||||
|
||||
defineOptions({ name: 'FileUploadArea' });
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
loading?: boolean;
|
||||
}>(),
|
||||
{
|
||||
loading: false,
|
||||
},
|
||||
);
|
||||
|
||||
const emit = defineEmits<Emits>();
|
||||
|
||||
// 创建图标组件
|
||||
const UploadIcon = createIconifyIcon('lucide:upload');
|
||||
const LoaderIcon = createIconifyIcon('lucide:loader-2');
|
||||
|
||||
// Emits
|
||||
interface Emits {
|
||||
(e: 'fileSelected', file: File): void;
|
||||
}
|
||||
|
||||
// 响应式数据
|
||||
const isDragOver = ref(false);
|
||||
const fileInputRef = ref<HTMLInputElement>();
|
||||
|
||||
// 文件验证
|
||||
const validateFile = (file: File): boolean => {
|
||||
const ext = file.name.toLowerCase().split('.').pop() || '';
|
||||
const allowedExts = ['csv', 'xlsx', 'xls'];
|
||||
if (!allowedExts.includes(ext)) {
|
||||
message.error('只能上传 CSV 或 Excel 格式的文件!');
|
||||
return false;
|
||||
}
|
||||
|
||||
const isLt10M = file.size / 1024 / 1024 < 10;
|
||||
if (!isLt10M) {
|
||||
message.error('文件大小不能超过10MB!');
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
// 处理文件
|
||||
const processFile = (file: File) => {
|
||||
if (props.loading) return;
|
||||
if (!validateFile(file)) return;
|
||||
emit('fileSelected', file);
|
||||
};
|
||||
|
||||
// 拖拽处理
|
||||
const handleDragOver = (e: DragEvent) => {
|
||||
e.preventDefault();
|
||||
isDragOver.value = true;
|
||||
};
|
||||
|
||||
const handleDragLeave = (e: DragEvent) => {
|
||||
e.preventDefault();
|
||||
isDragOver.value = false;
|
||||
};
|
||||
|
||||
const handleDrop = (e: DragEvent) => {
|
||||
e.preventDefault();
|
||||
isDragOver.value = false;
|
||||
|
||||
const files = e.dataTransfer?.files;
|
||||
if (files && files.length > 0) {
|
||||
const file = files[0];
|
||||
if (file) {
|
||||
processFile(file);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 文件选择处理
|
||||
const triggerFileInput = () => {
|
||||
fileInputRef.value?.click();
|
||||
};
|
||||
|
||||
const handleFileSelect = (e: Event) => {
|
||||
const target = e.target as HTMLInputElement;
|
||||
const files = target.files;
|
||||
if (files && files.length > 0) {
|
||||
const file = files[0];
|
||||
if (file) {
|
||||
processFile(file);
|
||||
}
|
||||
}
|
||||
// 清空input值,允许重复选择同一文件
|
||||
target.value = '';
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Spin :spinning="loading" tip="正在解析文件...">
|
||||
<div
|
||||
class="rounded-lg border-2 border-dashed border-gray-300 dark:border-[hsl(240deg_3.7%_22%)] p-8 text-center transition-colors cursor-pointer"
|
||||
:class="{
|
||||
'border-blue-500 bg-blue-50 dark:bg-[hsl(240deg_3.7%_15.9%/20%)]': isDragOver && !loading,
|
||||
'cursor-not-allowed opacity-60': loading,
|
||||
}"
|
||||
@dragover.prevent="!loading && handleDragOver($event)"
|
||||
@dragleave.prevent="!loading && handleDragLeave($event)"
|
||||
@drop.prevent="!loading && handleDrop($event)"
|
||||
@click="!loading && triggerFileInput()"
|
||||
>
|
||||
<div class="space-y-4">
|
||||
<div class="relative mx-auto h-12 w-12">
|
||||
<UploadIcon
|
||||
v-if="!loading"
|
||||
class="h-12 w-12 text-gray-400 dark:text-[hsl(240deg_5%_64.9%)]"
|
||||
:class="{ 'text-blue-500': isDragOver }"
|
||||
/>
|
||||
<LoaderIcon v-else class="h-12 w-12 animate-spin text-blue-500" />
|
||||
</div>
|
||||
<div>
|
||||
<p
|
||||
class="text-lg font-medium"
|
||||
:class="loading ? 'text-gray-500 dark:text-[hsl(240deg_5%_64.9%)]' : 'text-gray-700 dark:text-[hsl(0deg_0%_95%)]'"
|
||||
>
|
||||
{{
|
||||
loading
|
||||
? '正在解析文件,请稍候...'
|
||||
: '拖拽 CSV 或 Excel 文件到此处或点击上传'
|
||||
}}
|
||||
</p>
|
||||
<p v-if="!loading" class="text-sm text-gray-500 dark:text-[hsl(240deg_5%_64.9%)]">
|
||||
支持 .csv / .xlsx / .xls 格式,最大 10MB
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<input
|
||||
ref="fileInputRef"
|
||||
type="file"
|
||||
accept=".csv,.xlsx,.xls"
|
||||
style="display: none"
|
||||
:disabled="loading"
|
||||
@change="handleFileSelect"
|
||||
/>
|
||||
</div>
|
||||
</Spin>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 拖拽区域样式 */
|
||||
.border-dashed {
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.border-dashed:hover {
|
||||
border-color: #1890ff !important;
|
||||
background-color: #f0f8ff !important;
|
||||
}
|
||||
|
||||
:deep(.border-dashed:hover) {
|
||||
border-color: #1890ff !important;
|
||||
background-color: #f0f8ff !important;
|
||||
}
|
||||
|
||||
html.dark .border-dashed:hover {
|
||||
border-color: hsl(240deg 3.7% 40%) !important;
|
||||
background-color: hsl(240deg 3.7% 15.9% / 15%) !important;
|
||||
}
|
||||
</style>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,518 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { VxeGridProps } from '#/adapter/vxe-table';
|
||||
|
||||
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
|
||||
|
||||
import { useDebounceFn } from '@vueuse/core';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
import { Button, message } from 'ant-design-vue';
|
||||
|
||||
import { useVbenVxeGrid } from '#/adapter/vxe-table';
|
||||
|
||||
import ImportTaskWizard from './components/ImportTaskWizard.vue';
|
||||
import FileUploadArea from './components/FileUploadArea.vue';
|
||||
import { parseFileToRawData } from './utils/fileParser';
|
||||
|
||||
defineOptions({ name: 'DataImport' });
|
||||
|
||||
// 响应式数据
|
||||
const csvData = ref<any[]>([]);
|
||||
const csvHeaders = ref<string[]>([]);
|
||||
const importLoading = ref(false);
|
||||
const currentFile = ref<File | null>(null);
|
||||
const tableContainerRef = ref<HTMLElement>();
|
||||
const tableHeight = ref<number>(600);
|
||||
|
||||
const importTaskWizardRef = ref<InstanceType<typeof ImportTaskWizard>>();
|
||||
|
||||
/** 与向导中「SKU 编码」字段映射绑定的 CSV 表头,用于左侧表格该列可编辑 */
|
||||
const skuCodeCsvHeader = ref<string | undefined>();
|
||||
const skuMissingCount = ref(0);
|
||||
/** SKU 编码为空的行在 csvData 中的全局下标(0-based) */
|
||||
const skuMissingRowIndices = ref<Set<number>>(new Set());
|
||||
/** 与表格分页条 pageSize 同步,用于计算空缺所在页 */
|
||||
const tablePageSize = ref(50);
|
||||
/** 「下一处空缺」循环游标,-1 表示尚未开始循环 */
|
||||
const missingCycleCursor = ref(-1);
|
||||
|
||||
// 动态生成Grid列配置
|
||||
const gridColumns = computed(() => {
|
||||
if (csvHeaders.value.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const columns: VxeGridProps<any>['columns'] = [
|
||||
{
|
||||
type: 'seq' as const,
|
||||
title: '序号',
|
||||
width: 80,
|
||||
fixed: 'left' as const,
|
||||
},
|
||||
];
|
||||
|
||||
csvHeaders.value.forEach((header) => {
|
||||
const isSkuCol =
|
||||
!!skuCodeCsvHeader.value && header === skuCodeCsvHeader.value;
|
||||
columns.push({
|
||||
field: header,
|
||||
title: header,
|
||||
minWidth: isSkuCol ? 180 : 150,
|
||||
showOverflow: 'tooltip' as const,
|
||||
...(isSkuCol ? { editRender: { name: 'input' as const } } : {}),
|
||||
});
|
||||
});
|
||||
|
||||
return columns;
|
||||
});
|
||||
|
||||
const gridOptions: VxeGridProps<any> = {
|
||||
columns: [],
|
||||
height: tableHeight.value,
|
||||
border: true,
|
||||
stripe: true,
|
||||
rowConfig: { isHover: true },
|
||||
showOverflow: true,
|
||||
size: 'small',
|
||||
data: [],
|
||||
editConfig: {
|
||||
mode: 'cell',
|
||||
trigger: 'click',
|
||||
},
|
||||
pagerConfig: {
|
||||
enabled: true,
|
||||
pageSize: 50,
|
||||
pageSizes: [10, 20, 50, 100],
|
||||
layouts: [
|
||||
'PrevJump',
|
||||
'PrevPage',
|
||||
'Number',
|
||||
'NextPage',
|
||||
'NextJump',
|
||||
'Sizes',
|
||||
'FullJump',
|
||||
'Total',
|
||||
] as (
|
||||
| 'FullJump'
|
||||
| 'NextJump'
|
||||
| 'NextPage'
|
||||
| 'Number'
|
||||
| 'PrevJump'
|
||||
| 'PrevPage'
|
||||
| 'Sizes'
|
||||
| 'Total'
|
||||
)[],
|
||||
},
|
||||
proxyConfig: {
|
||||
ajax: {
|
||||
query: async ({ page }) => {
|
||||
if (csvData.value.length === 0) {
|
||||
return {
|
||||
items: [],
|
||||
total: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const currentPage = page.currentPage || 1;
|
||||
const pageSize = page.pageSize || 50;
|
||||
const startIndex = (currentPage - 1) * pageSize;
|
||||
const endIndex = startIndex + pageSize;
|
||||
|
||||
const pageData = csvData.value.slice(startIndex, endIndex);
|
||||
// 供 rowClassName 识别全局行号(与 csvData 下标一致)
|
||||
pageData.forEach((row, i) => {
|
||||
(row as Record<string, unknown>).__srcRowIndex = startIndex + i;
|
||||
});
|
||||
|
||||
return {
|
||||
items: pageData,
|
||||
total: csvData.value.length,
|
||||
};
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const debouncedWizardSpecSync = useDebounceFn(() => {
|
||||
importTaskWizardRef.value?.onPreviewSpecCodeCellSaved?.();
|
||||
}, 400);
|
||||
|
||||
function rowClassNameForSpecMissing(params: { row?: Record<string, unknown> }) {
|
||||
const idx = params.row?.__srcRowIndex;
|
||||
if (typeof idx !== 'number') return '';
|
||||
return skuMissingRowIndices.value.has(idx) ? 'order-import-row--sku-missing' : '';
|
||||
}
|
||||
|
||||
const gridEvents = {
|
||||
editClosed(params: { column?: { field?: string } }) {
|
||||
const field = params.column?.field;
|
||||
if (!field || !skuCodeCsvHeader.value) return;
|
||||
if (field === skuCodeCsvHeader.value) {
|
||||
debouncedWizardSpecSync();
|
||||
}
|
||||
},
|
||||
pageChange(params: { pageSize?: number; currentPage?: number }) {
|
||||
if (params.pageSize && params.pageSize > 0) {
|
||||
tablePageSize.value = params.pageSize;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
const [Grid, gridApi] = useVbenVxeGrid({
|
||||
gridOptions,
|
||||
gridEvents,
|
||||
});
|
||||
|
||||
const updateTable = () => {
|
||||
gridApi.setGridOptions({
|
||||
columns: gridColumns.value,
|
||||
height: tableHeight.value,
|
||||
rowClassName: rowClassNameForSpecMissing,
|
||||
});
|
||||
gridApi.reload();
|
||||
};
|
||||
|
||||
watch(
|
||||
tableHeight,
|
||||
(newHeight) => {
|
||||
gridApi.setGridOptions({
|
||||
height: newHeight,
|
||||
});
|
||||
},
|
||||
{ immediate: false },
|
||||
);
|
||||
|
||||
const syncWizardOpen = () => {
|
||||
if (csvData.value.length === 0 || csvHeaders.value.length === 0) {
|
||||
return;
|
||||
}
|
||||
nextTick(() => {
|
||||
importTaskWizardRef.value?.open(
|
||||
[...csvHeaders.value],
|
||||
currentFile.value ?? undefined,
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
function onSkuCodeColumnChange(header: string | undefined) {
|
||||
skuCodeCsvHeader.value = header;
|
||||
updateTable();
|
||||
}
|
||||
|
||||
function onSkuMissingAfterPrecheck(payload: { count: number; indices: number[] }) {
|
||||
skuMissingCount.value = payload.count;
|
||||
skuMissingRowIndices.value = new Set(payload.indices);
|
||||
missingCycleCursor.value = -1;
|
||||
// 必须用 query 而非 reload:reload 会重置分页到第 1 页,用户在其它页补SKU 编码时会被突然拉回首页
|
||||
if (csvData.value.length > 0) {
|
||||
void gridApi.query({});
|
||||
}
|
||||
}
|
||||
|
||||
/** 取 VxeGrid 内部的 VxeTable 实例(用于 scrollToRow 等仅表格支持的方法) */
|
||||
function getVxeInnerTable(grid: any) {
|
||||
return grid?.$refs?.refTable ?? grid?.$refs?.xTable ?? null;
|
||||
}
|
||||
|
||||
/** 等两帧再滚,避免 loadData 后 DOM 尚未稳定 */
|
||||
function nextPaint() {
|
||||
return new Promise<void>((resolve) => {
|
||||
requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 滚动到指定数据行(scrollToRow 返回 Promise;第二参为列 field 时同时横向滚到「SKU 编码」列)
|
||||
* 虚拟滚动场景 vxe 内部会延时二次校正,这里再补一次延迟滚动。
|
||||
*/
|
||||
async function scrollGridToDataRow(row: Record<string, unknown>) {
|
||||
const grid = gridApi.grid as any;
|
||||
const field = skuCodeCsvHeader.value;
|
||||
const candidates = [grid, getVxeInnerTable(grid)].filter(Boolean);
|
||||
|
||||
for (const inst of candidates) {
|
||||
if (inst && typeof inst.scrollToRow === 'function') {
|
||||
try {
|
||||
await inst.scrollToRow(row, field || undefined);
|
||||
return;
|
||||
} catch {
|
||||
// 尝试下一个实例
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 跳转到包含该全局行号的分页并滚动到该行 */
|
||||
async function goToRowIndex(globalRowIndex: number) {
|
||||
if (globalRowIndex < 0 || globalRowIndex >= csvData.value.length) return;
|
||||
const ps = tablePageSize.value;
|
||||
const targetPage = Math.floor(globalRowIndex / ps) + 1;
|
||||
const grid = gridApi.grid as any;
|
||||
if (!grid?.getProxyInfo || typeof grid.commitProxy !== 'function') {
|
||||
message.warning('表格尚未就绪,请稍后重试');
|
||||
return;
|
||||
}
|
||||
const row = csvData.value[globalRowIndex] as Record<string, unknown> | undefined;
|
||||
if (!row) return;
|
||||
|
||||
try {
|
||||
const proxy = grid.getProxyInfo();
|
||||
if (proxy?.pager) {
|
||||
proxy.pager.currentPage = targetPage;
|
||||
proxy.pager.pageSize = ps;
|
||||
}
|
||||
await grid.commitProxy('query');
|
||||
await nextTick();
|
||||
await nextPaint();
|
||||
await scrollGridToDataRow(row);
|
||||
// 与 vxe 虚拟列表二次对齐时机接近,避免首屏未滚到位
|
||||
window.setTimeout(() => {
|
||||
void scrollGridToDataRow(row);
|
||||
}, 400);
|
||||
} catch (e) {
|
||||
console.error('跳转表格分页失败:', e);
|
||||
message.warning('跳转分页失败,请手动翻页查找');
|
||||
}
|
||||
}
|
||||
|
||||
function jumpToFirstSpecMissing() {
|
||||
const sorted = [...skuMissingRowIndices.value].sort((a, b) => a - b);
|
||||
if (sorted.length === 0) {
|
||||
message.info('当前没有空缺的SKU 编码');
|
||||
return;
|
||||
}
|
||||
missingCycleCursor.value = 0;
|
||||
void goToRowIndex(sorted[0]!);
|
||||
}
|
||||
|
||||
function jumpToNextSpecMissing() {
|
||||
const sorted = [...skuMissingRowIndices.value].sort((a, b) => a - b);
|
||||
if (sorted.length === 0) {
|
||||
message.info('当前没有空缺的SKU 编码');
|
||||
return;
|
||||
}
|
||||
missingCycleCursor.value = (missingCycleCursor.value + 1) % sorted.length;
|
||||
void goToRowIndex(sorted[missingCycleCursor.value]!);
|
||||
}
|
||||
|
||||
const handleFileUpload = async (file: File) => {
|
||||
importLoading.value = true;
|
||||
try {
|
||||
const result = await parseFileToRawData(file);
|
||||
|
||||
if (result.errors.length > 0) {
|
||||
message.warning(result.errors.join('; '));
|
||||
}
|
||||
|
||||
if (result.data.length === 0) {
|
||||
message.error('CSV文件没有有效数据');
|
||||
return;
|
||||
}
|
||||
|
||||
csvData.value = result.data;
|
||||
csvHeaders.value = result.headers;
|
||||
currentFile.value = file;
|
||||
|
||||
updateTable();
|
||||
nextTick(() => {
|
||||
calculateTableHeight();
|
||||
});
|
||||
syncWizardOpen();
|
||||
|
||||
const fileExt = file.name.toLowerCase().split('.').pop() || '';
|
||||
const format = ['xlsx', 'xls'].includes(fileExt) ? 'Excel' : 'CSV';
|
||||
message.success(`成功解析 ${result.data.length} 条数据(${format} 格式)`);
|
||||
} catch (error: any) {
|
||||
message.error(`文件读取失败: ${error.message}`);
|
||||
} finally {
|
||||
importLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const handleClearData = () => {
|
||||
csvData.value = [];
|
||||
csvHeaders.value = [];
|
||||
currentFile.value = null;
|
||||
skuCodeCsvHeader.value = undefined;
|
||||
skuMissingCount.value = 0;
|
||||
skuMissingRowIndices.value = new Set();
|
||||
missingCycleCursor.value = -1;
|
||||
importTaskWizardRef.value?.reset();
|
||||
updateTable();
|
||||
message.success('已清空数据');
|
||||
};
|
||||
|
||||
const handleWizardSuccess = () => {
|
||||
csvData.value = [];
|
||||
csvHeaders.value = [];
|
||||
currentFile.value = null;
|
||||
skuCodeCsvHeader.value = undefined;
|
||||
skuMissingCount.value = 0;
|
||||
skuMissingRowIndices.value = new Set();
|
||||
missingCycleCursor.value = -1;
|
||||
updateTable();
|
||||
message.success('已创建导入任务,可继续上传新文件');
|
||||
};
|
||||
|
||||
const calculateTableHeight = () => {
|
||||
nextTick(() => {
|
||||
if (tableContainerRef.value) {
|
||||
const rect = tableContainerRef.value.getBoundingClientRect();
|
||||
const toolbarReserve = 56;
|
||||
const padding = 24;
|
||||
const availableHeight = rect.height - padding - toolbarReserve;
|
||||
tableHeight.value = Math.max(320, availableHeight);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
watch(
|
||||
() => csvData.value.length,
|
||||
(len) => {
|
||||
if (len > 0) {
|
||||
nextTick(() => calculateTableHeight());
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
let resizeObserver: null | ResizeObserver = null;
|
||||
|
||||
onMounted(() => {
|
||||
calculateTableHeight();
|
||||
if (tableContainerRef.value) {
|
||||
resizeObserver = new ResizeObserver(() => {
|
||||
calculateTableHeight();
|
||||
});
|
||||
resizeObserver.observe(tableContainerRef.value);
|
||||
}
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
resizeObserver?.disconnect();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Page
|
||||
auto-content-height
|
||||
:content-padding-class="csvData.length === 0 ? 'p-4 sm:p-6' : 'p-2 sm:p-3'"
|
||||
content-class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-slate-100 dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
|
||||
>
|
||||
<!-- 未上传:居中上传 -->
|
||||
<div
|
||||
v-if="csvData.length === 0"
|
||||
class="mx-auto flex min-h-0 w-full max-w-3xl flex-1 flex-col items-center justify-center py-8"
|
||||
>
|
||||
<div class="mb-10 shrink-0 text-center">
|
||||
<h1
|
||||
class="mb-2 text-3xl font-black tracking-tight text-slate-800 dark:text-[hsl(0deg_0%_95%)] sm:text-4xl"
|
||||
>
|
||||
订单导入中心
|
||||
</h1>
|
||||
<p class="text-sm font-medium text-slate-500 dark:text-[hsl(240deg_5%_64.9%)] sm:text-base">
|
||||
请上传 CSV / Excel 格式的订单原始数据
|
||||
</p>
|
||||
</div>
|
||||
<div
|
||||
class="relative w-full overflow-hidden rounded-[2rem] border border-white/50 bg-white/45 p-6 dark:border-[hsl(240deg_3.7%_22%/50%)] dark:bg-[hsl(222.34deg_10.43%_12.27%/80%)] shadow-[0_25px_50px_-12px_rgba(0,0,0,0.1)] dark:shadow-none backdrop-blur-2xl sm:p-8"
|
||||
>
|
||||
<div
|
||||
class="absolute -right-10 -top-10 h-32 w-32 rounded-full bg-indigo-400 opacity-10 blur-3xl"
|
||||
></div>
|
||||
<div class="relative w-full">
|
||||
<FileUploadArea
|
||||
:loading="importLoading"
|
||||
@file-selected="handleFileUpload"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 已上传:左表右配置(flex-1 + min-h-0 约束在布局内容高度内,避免撑开外层滚动) -->
|
||||
<div
|
||||
v-else
|
||||
class="flex min-h-0 w-full min-w-0 flex-1 flex-row gap-3 overflow-hidden sm:gap-4"
|
||||
>
|
||||
<section
|
||||
class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-2xl border border-slate-200/80 bg-white/90 shadow-sm dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%/90%)]"
|
||||
>
|
||||
<div
|
||||
class="flex shrink-0 flex-wrap items-center justify-between gap-3 border-b border-slate-100 px-4 py-3 dark:border-[hsl(240deg_3.7%_22%)]"
|
||||
>
|
||||
<div class="min-w-0">
|
||||
<h2 class="mb-0.5 text-lg font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
|
||||
数据预览
|
||||
</h2>
|
||||
<p class="m-0 text-xs text-slate-500 dark:text-[hsl(240deg_5%_64.9%)] sm:text-sm">
|
||||
共 {{ csvData.length }} 条 · 右侧配置导入任务
|
||||
<template v-if="skuMissingCount > 0">
|
||||
·
|
||||
<span class="font-medium text-amber-600 dark:text-amber-400">
|
||||
SKU 编码待补 {{ skuMissingCount }} 行(点击本表对应列表格填写)
|
||||
</span>
|
||||
</template>
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex shrink-0 flex-wrap items-center justify-end gap-2">
|
||||
<template v-if="skuMissingCount > 0">
|
||||
<Button size="small" type="primary" @click="jumpToFirstSpecMissing">
|
||||
第一处空缺
|
||||
</Button>
|
||||
<Button size="small" @click="jumpToNextSpecMissing">下一处空缺</Button>
|
||||
</template>
|
||||
<Button size="small" @click="handleClearData">清空数据</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
ref="tableContainerRef"
|
||||
class="flex min-h-0 flex-1 flex-col overflow-hidden p-3 sm:p-4"
|
||||
>
|
||||
<Grid />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<aside
|
||||
class="flex min-h-0 w-[min(100%,440px)] shrink-0 flex-col self-stretch overflow-hidden sm:w-[400px] lg:w-[440px]"
|
||||
>
|
||||
<!-- 单独一层 flex-1,避免多根子组件时侧栏被内容撑出视口 -->
|
||||
<div class="flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||
<ImportTaskWizard
|
||||
ref="importTaskWizardRef"
|
||||
v-model:preview-data="csvData"
|
||||
@sku-code-column-change="onSkuCodeColumnChange"
|
||||
@sku-missing-after-precheck="onSkuMissingAfterPrecheck"
|
||||
@success="handleWizardSuccess"
|
||||
/>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</Page>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
:deep(.vxe-grid) {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
:deep(.vxe-grid--body-wrapper) {
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
/* SKU 编码为空的行:整行高亮,便于分页中辨认 */
|
||||
:deep(tr.order-import-row--sku-missing) {
|
||||
background-color: rgb(254 243 199) !important;
|
||||
}
|
||||
:deep(tr.order-import-row--sku-missing:hover) {
|
||||
background-color: rgb(253 230 138) !important;
|
||||
}
|
||||
.dark :deep(tr.order-import-row--sku-missing) {
|
||||
background-color: rgb(120 53 15 / 0.45) !important;
|
||||
}
|
||||
.dark :deep(tr.order-import-row--sku-missing:hover) {
|
||||
background-color: rgb(120 53 15 / 0.6) !important;
|
||||
}
|
||||
</style>
|
||||
@@ -1,84 +0,0 @@
|
||||
/**
|
||||
* CSV数据解析工具
|
||||
* 完全动态解析,不预设任何字段
|
||||
*/
|
||||
|
||||
import Papa from 'papaparse';
|
||||
|
||||
export interface CSVParseResult {
|
||||
/** 解析成功的数据 */
|
||||
data: any[];
|
||||
/** 解析错误 */
|
||||
errors: string[];
|
||||
/** 表头(保持CSV文件中的顺序) */
|
||||
headers: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析CSV文件为原始数据(完全动态,保持字段顺序)
|
||||
*/
|
||||
export async function parseCSVToRawData(file: File): Promise<CSVParseResult> {
|
||||
const errors: string[] = [];
|
||||
const data: any[] = [];
|
||||
let headers: string[] = [];
|
||||
|
||||
// 尝试多种编码格式
|
||||
const encodings = ['GBK', 'utf8', 'GB2312'];
|
||||
let result: null | Papa.ParseResult<any> = null;
|
||||
|
||||
for (const encoding of encodings) {
|
||||
try {
|
||||
result = await new Promise<Papa.ParseResult<any>>((resolve, reject) => {
|
||||
Papa.parse(file, {
|
||||
header: true,
|
||||
skipEmptyLines: true,
|
||||
encoding: encoding as any,
|
||||
complete: (results) => {
|
||||
resolve(results);
|
||||
},
|
||||
error: (error) => {
|
||||
reject(error);
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
// 检查是否成功解析出中文内容
|
||||
if (result.data && result.data.length > 0) {
|
||||
const firstRow = result.data[0];
|
||||
const hasChineseContent = Object.values(firstRow).some(
|
||||
(value) => typeof value === 'string' && /[\u4E00-\u9FA5]/.test(value),
|
||||
);
|
||||
|
||||
if (hasChineseContent) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (!result) {
|
||||
errors.push('无法解析CSV文件,请检查文件格式和编码');
|
||||
return { data, errors, headers };
|
||||
}
|
||||
|
||||
if (result.errors.length > 0) {
|
||||
errors.push(
|
||||
`CSV解析错误: ${result.errors.map((e) => e.message).join(', ')}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (!result.data || result.data.length === 0) {
|
||||
errors.push('CSV文件为空或没有有效数据');
|
||||
return { data, errors, headers };
|
||||
}
|
||||
|
||||
// 获取表头(保持CSV文件中的顺序)
|
||||
headers = result.meta.fields || [];
|
||||
|
||||
// 直接使用原始数据,完全保持CSV文件的字段顺序和数据顺序
|
||||
data.push(...result.data);
|
||||
|
||||
return { data, errors, headers };
|
||||
}
|
||||
@@ -1,214 +0,0 @@
|
||||
/**
|
||||
* 文件数据解析工具(支持 CSV 和 Excel)
|
||||
*/
|
||||
|
||||
import Papa from 'papaparse';
|
||||
import * as XLSX from 'xlsx';
|
||||
|
||||
export interface FileParseOptions {
|
||||
/** 为 true 时保留仅部分单元格为空的行(推广费导入需统计金额为空等失败行) */
|
||||
preserveEmptyRows?: boolean;
|
||||
}
|
||||
|
||||
export interface FileParseResult {
|
||||
/** 解析成功的数据 */
|
||||
data: any[];
|
||||
/** 解析错误 */
|
||||
errors: string[];
|
||||
/** 表头(保持文件中的顺序) */
|
||||
headers: string[];
|
||||
}
|
||||
|
||||
function isExcelFile(filename: string): boolean {
|
||||
const ext = filename.toLowerCase().split('.').pop() || '';
|
||||
return ext === 'xlsx' || ext === 'xls';
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 CSV 文件为原始数据
|
||||
*/
|
||||
async function parseCSVFile(
|
||||
file: File,
|
||||
options?: FileParseOptions,
|
||||
): Promise<FileParseResult> {
|
||||
const errors: string[] = [];
|
||||
const data: any[] = [];
|
||||
let headers: string[] = [];
|
||||
|
||||
// 尝试多种编码格式
|
||||
const encodings = ['GBK', 'utf8', 'GB2312'];
|
||||
let result: Papa.ParseResult<any> | null = null;
|
||||
|
||||
for (const encoding of encodings) {
|
||||
try {
|
||||
result = await new Promise<Papa.ParseResult<any>>((resolve, reject) => {
|
||||
Papa.parse(file, {
|
||||
header: true,
|
||||
skipEmptyLines: options?.preserveEmptyRows ? false : true,
|
||||
encoding: encoding as any,
|
||||
complete: (results) => {
|
||||
resolve(results);
|
||||
},
|
||||
error: (error) => {
|
||||
reject(error);
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
// 检查是否成功解析出中文内容
|
||||
if (result.data && result.data.length > 0) {
|
||||
const firstRow = result.data[0];
|
||||
const hasChineseContent = Object.values(firstRow).some(
|
||||
(value) => typeof value === 'string' && /[\u4E00-\u9FA5]/.test(value),
|
||||
);
|
||||
|
||||
if (hasChineseContent) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (!result) {
|
||||
errors.push('无法解析 CSV 文件,请检查文件格式和编码');
|
||||
return { data, errors, headers };
|
||||
}
|
||||
|
||||
if (result.errors.length > 0) {
|
||||
errors.push(
|
||||
`CSV 解析错误: ${result.errors.map((e) => e.message).join(', ')}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (!result.data || result.data.length === 0) {
|
||||
errors.push('CSV 文件为空或没有有效数据');
|
||||
return { data, errors, headers };
|
||||
}
|
||||
|
||||
headers = result.meta.fields || [];
|
||||
data.push(...result.data);
|
||||
|
||||
return { data, errors, headers };
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 Excel 文件为原始数据
|
||||
*/
|
||||
async function parseExcelFile(
|
||||
file: File,
|
||||
options?: FileParseOptions,
|
||||
): Promise<FileParseResult> {
|
||||
const errors: string[] = [];
|
||||
const data: any[] = [];
|
||||
let headers: string[] = [];
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const reader = new FileReader();
|
||||
|
||||
reader.onload = (e) => {
|
||||
try {
|
||||
const arrayBuffer = e.target?.result;
|
||||
if (!arrayBuffer) {
|
||||
errors.push('Excel 文件读取失败');
|
||||
resolve({ data, errors, headers });
|
||||
return;
|
||||
}
|
||||
|
||||
const workbook = XLSX.read(arrayBuffer, { type: 'array', cellDates: true });
|
||||
|
||||
// 默认取第一个 sheet
|
||||
const sheetName = workbook.SheetNames[0];
|
||||
if (!sheetName) {
|
||||
errors.push('Excel 文件中没有工作表');
|
||||
resolve({ data, errors, headers });
|
||||
return;
|
||||
}
|
||||
|
||||
const sheet = workbook.Sheets[sheetName];
|
||||
|
||||
if (!sheet) {
|
||||
errors.push('Excel 文件读取失败:未找到有效工作表');
|
||||
resolve({ data, errors, headers });
|
||||
return;
|
||||
}
|
||||
|
||||
// 转换为 JSON(header: 1 表示第一行作为表头)
|
||||
const jsonData = XLSX.utils.sheet_to_json(sheet, {
|
||||
header: 1,
|
||||
defval: '',
|
||||
blankrows: false,
|
||||
}) as any[][];
|
||||
|
||||
if (jsonData.length === 0) {
|
||||
errors.push('Excel 文件为空或没有有效数据');
|
||||
resolve({ data, errors, headers });
|
||||
return;
|
||||
}
|
||||
|
||||
// 第一行是表头
|
||||
headers = (jsonData[0] || []).map((h) => String(h ?? '').trim());
|
||||
|
||||
// 其余行是数据
|
||||
for (let i = 1; i < jsonData.length; i++) {
|
||||
const row = jsonData[i];
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
!options?.preserveEmptyRows &&
|
||||
row.every((cell) => cell === '' || cell == null)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const rowData: Record<string, any> = {};
|
||||
headers.forEach((header, idx) => {
|
||||
let value = row[idx];
|
||||
// XLSX 读取日期会返回 Date 对象,转成字符串
|
||||
if (value instanceof Date) {
|
||||
const y = value.getFullYear();
|
||||
const m = String(value.getMonth() + 1).padStart(2, '0');
|
||||
const d = String(value.getDate()).padStart(2, '0');
|
||||
value = `${y}-${m}-${d}`;
|
||||
}
|
||||
rowData[header] = value != null ? String(value).trim() : '';
|
||||
});
|
||||
data.push(rowData);
|
||||
}
|
||||
|
||||
resolve({ data, errors, headers });
|
||||
} catch (err: any) {
|
||||
errors.push(`Excel 解析失败: ${err?.message || '未知错误'}`);
|
||||
resolve({ data, errors, headers });
|
||||
}
|
||||
};
|
||||
|
||||
reader.onerror = () => {
|
||||
errors.push('Excel 文件读取失败');
|
||||
resolve({ data, errors, headers });
|
||||
};
|
||||
|
||||
reader.readAsArrayBuffer(file);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析文件为原始数据(自动根据扩展名选择解析器)
|
||||
*/
|
||||
export async function parseFileToRawData(
|
||||
file: File,
|
||||
options?: FileParseOptions,
|
||||
): Promise<FileParseResult> {
|
||||
if (isExcelFile(file.name)) {
|
||||
return parseExcelFile(file, options);
|
||||
}
|
||||
return parseCSVFile(file, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated 请使用 parseFileToRawData
|
||||
*/
|
||||
export async function parseCSVToRawData(file: File): Promise<FileParseResult> {
|
||||
return parseCSVFile(file);
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
import Papa from 'papaparse';
|
||||
import * as XLSX from 'xlsx';
|
||||
|
||||
export function buildPatchedFileName(fileName: string) {
|
||||
const dot = fileName.lastIndexOf('.');
|
||||
if (dot < 0) return `${fileName}_patched`;
|
||||
return `${fileName.slice(0, dot)}_patched${fileName.slice(dot)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 headers + rows 重建一个“补录后”的文件,并返回新的 File 对象
|
||||
* - CSV:使用 papaparse 重新生成,并添加 BOM 保证中文兼容
|
||||
* - Excel:使用 xlsx 生成新的 workbook(默认一个 sheet:Sheet1)
|
||||
*/
|
||||
export function createPatchedFile(
|
||||
sourceFile: File,
|
||||
headers: string[],
|
||||
rows: any[],
|
||||
): File {
|
||||
const ext = sourceFile.name.toLowerCase().split('.').pop() || '';
|
||||
const filename = buildPatchedFileName(sourceFile.name);
|
||||
|
||||
if (ext === 'csv') {
|
||||
const csvText = Papa.unparse(rows, { columns: headers });
|
||||
const blob = new Blob([`\uFEFF${csvText}`], {
|
||||
type: 'text/csv;charset=utf-8',
|
||||
});
|
||||
return new File([blob], filename, { type: 'text/csv;charset=utf-8' });
|
||||
}
|
||||
|
||||
const aoa = [
|
||||
headers,
|
||||
...rows.map((row) => headers.map((header) => row[header] ?? '')),
|
||||
];
|
||||
const workbook = XLSX.utils.book_new();
|
||||
const worksheet = XLSX.utils.aoa_to_sheet(aoa);
|
||||
XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
|
||||
|
||||
const wbType = ext === 'xls' ? 'xls' : 'xlsx';
|
||||
const buffer = XLSX.write(workbook, {
|
||||
type: 'array',
|
||||
bookType: wbType,
|
||||
});
|
||||
|
||||
const blob = new Blob([buffer], {
|
||||
type:
|
||||
ext === 'xls'
|
||||
? 'application/vnd.ms-excel'
|
||||
: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
});
|
||||
return new File([blob], filename, { type: blob.type });
|
||||
}
|
||||
Reference in New Issue
Block a user