mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 01:59:20 +08:00
feat: 新增导入功能
This commit is contained in:
+7
@@ -20,6 +20,13 @@ public class CreateImportMappingDTO {
|
||||
@Pattern(regexp = "^(product|order)$", message = "导入类型只能是product或order")
|
||||
private String type;
|
||||
|
||||
/**
|
||||
* 映射名称
|
||||
*/
|
||||
@Schema(description = "映射名称", example = "商品导入映射模板", required = true)
|
||||
@NotBlank(message = "映射名称不能为空")
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* 字段映射(JSON格式)
|
||||
*/
|
||||
|
||||
+6
@@ -15,5 +15,11 @@ public class ImportMappingFilterDTO {
|
||||
*/
|
||||
@Schema(description = "导入类型", example = "product", allowableValues = {"product", "order"})
|
||||
private String type;
|
||||
|
||||
/**
|
||||
* 映射名称(模糊查询)
|
||||
*/
|
||||
@Schema(description = "映射名称(模糊查询)", example = "商品导入")
|
||||
private String name;
|
||||
}
|
||||
|
||||
|
||||
+6
@@ -11,6 +11,12 @@ import lombok.Data;
|
||||
@Schema(description = "更新导入映射DTO")
|
||||
public class UpdateImportMappingDTO {
|
||||
|
||||
/**
|
||||
* 映射名称
|
||||
*/
|
||||
@Schema(description = "映射名称", example = "商品导入映射模板")
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* 字段映射(JSON格式)
|
||||
*/
|
||||
|
||||
+6
@@ -23,6 +23,12 @@ public class CreateProductDTO {
|
||||
@NotBlank(message = "商品名称不能为空")
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* 商品编码
|
||||
*/
|
||||
@Schema(description = "商品编码", example = "IPHONE15PRO001")
|
||||
private String productCode;
|
||||
|
||||
/**
|
||||
* 主图图片ID
|
||||
*/
|
||||
|
||||
+2
-22
@@ -3,8 +3,6 @@ package top.xyquan.ecomdmbbackend.modules.ecom.model.dto.product;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* 商品分页查询过滤DTO
|
||||
*/
|
||||
@@ -21,24 +19,6 @@ public class ProductFilterDTO {
|
||||
/**
|
||||
* 商品编码(模糊查询)
|
||||
*/
|
||||
@Schema(description = "商品编码(模糊查询)", example = "IPHONE")
|
||||
private String specCode;
|
||||
|
||||
/**
|
||||
* 商品SKU(模糊查询)
|
||||
*/
|
||||
@Schema(description = "商品SKU(模糊查询)", example = "IPHONE15")
|
||||
private String skuCode;
|
||||
|
||||
/**
|
||||
* 成本价范围-最小值
|
||||
*/
|
||||
@Schema(description = "成本价范围-最小值", example = "1000.00")
|
||||
private BigDecimal minCostPrice;
|
||||
|
||||
/**
|
||||
* 成本价范围-最大值
|
||||
*/
|
||||
@Schema(description = "成本价范围-最大值", example = "10000.00")
|
||||
private BigDecimal maxCostPrice;
|
||||
@Schema(description = "商品编码(模糊查询)", example = "IPHONE15PRO001")
|
||||
private String productCode;
|
||||
}
|
||||
|
||||
+1
-14
@@ -25,24 +25,11 @@ public class UpdateProductDTO {
|
||||
* 商品编码
|
||||
*/
|
||||
@Schema(description = "商品编码", example = "IPHONE15PRO001")
|
||||
private String specCode;
|
||||
|
||||
/**
|
||||
* 商品SKU
|
||||
*/
|
||||
@Schema(description = "商品SKU", example = "IPHONE15PRO-128G-BLUE")
|
||||
private String skuCode;
|
||||
private String productCode;
|
||||
|
||||
/**
|
||||
* 主图图片ID
|
||||
*/
|
||||
@Schema(description = "主图图片ID", example = "1")
|
||||
private Long mainImageId;
|
||||
|
||||
/**
|
||||
* 成本价
|
||||
*/
|
||||
@Schema(description = "成本价", example = "8000.00", required = true)
|
||||
@NotNull(message = "成本价不能为空")
|
||||
private BigDecimal costPrice;
|
||||
}
|
||||
|
||||
+6
@@ -32,6 +32,12 @@ public class ImportMappingPO {
|
||||
@TableField("type")
|
||||
private String type;
|
||||
|
||||
/**
|
||||
* 映射模板名称
|
||||
*/
|
||||
@TableField("name")
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* 字段映射(JSON格式)
|
||||
*/
|
||||
|
||||
+6
@@ -32,6 +32,12 @@ public class ProductPO {
|
||||
@TableField("name")
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* 商品编码
|
||||
*/
|
||||
@TableField("product_code")
|
||||
private String productCode;
|
||||
|
||||
/**
|
||||
* 主图URL(冗余字段)
|
||||
*/
|
||||
|
||||
+6
@@ -30,6 +30,12 @@ public class ImportMappingVO {
|
||||
@Schema(description = "导入类型", example = "product")
|
||||
private String type;
|
||||
|
||||
/**
|
||||
* 映射名称
|
||||
*/
|
||||
@Schema(description = "映射名称", example = "商品导入映射模板")
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* 字段映射(JSON格式)
|
||||
*/
|
||||
|
||||
+6
@@ -31,6 +31,12 @@ public class ProductVO {
|
||||
@Schema(description = "商品名称", example = "iPhone 15 Pro")
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* 商品编码
|
||||
*/
|
||||
@Schema(description = "商品编码", example = "IPHONE15PRO001")
|
||||
private String productCode;
|
||||
|
||||
/**
|
||||
* 主图URL
|
||||
*/
|
||||
|
||||
+24
-5
@@ -47,12 +47,13 @@ public class ImportMappingServiceImpl extends ServiceImpl<ImportMappingMapper, I
|
||||
// 从token中获取公司ID
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
|
||||
// 验证同一公司、同一类型是否已存在映射(根据唯一索引)
|
||||
// 验证同一公司、同一类型、同一名称是否已存在映射(根据唯一索引)
|
||||
LambdaQueryWrapper<ImportMappingPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ImportMappingPO::getCompanyId, companyId)
|
||||
.eq(ImportMappingPO::getType, createImportMappingDTO.getType());
|
||||
.eq(ImportMappingPO::getType, createImportMappingDTO.getType())
|
||||
.eq(ImportMappingPO::getName, createImportMappingDTO.getName());
|
||||
if (this.count(wrapper) > 0) {
|
||||
throw new BusinessException("该类型的导入映射已存在,请使用更新接口");
|
||||
throw new BusinessException("该类型的导入映射名称已存在,请使用其他名称或更新接口");
|
||||
}
|
||||
|
||||
// 创建导入映射
|
||||
@@ -89,6 +90,19 @@ public class ImportMappingServiceImpl extends ServiceImpl<ImportMappingMapper, I
|
||||
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();
|
||||
BeanUtils.copyProperties(updateImportMappingDTO, importMappingPO);
|
||||
@@ -140,8 +154,13 @@ public class ImportMappingServiceImpl extends ServiceImpl<ImportMappingMapper, I
|
||||
LambdaQueryWrapper<ImportMappingPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ImportMappingPO::getCompanyId, companyId);
|
||||
|
||||
if (filter != null && StringUtils.hasText(filter.getType())) {
|
||||
wrapper.eq(ImportMappingPO::getType, filter.getType());
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
// 按创建时间倒序
|
||||
|
||||
+282
-106
@@ -39,6 +39,7 @@ import java.math.RoundingMode;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 导入任务处理器服务实现类
|
||||
@@ -46,13 +47,52 @@ import java.util.Map;
|
||||
@Service
|
||||
public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorService {
|
||||
|
||||
/**
|
||||
* 映射字段定义
|
||||
*/
|
||||
private static class MappingField {
|
||||
private Boolean required;
|
||||
private String fieldName;
|
||||
private String fieldLabel;
|
||||
private String fileFieldName;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ImportTaskProcessorServiceImpl.class);
|
||||
|
||||
private final ImportTaskService importTaskService;
|
||||
private final OrderService orderService;
|
||||
private final ProductService productService;
|
||||
private final ProductSpecService productSpecService;
|
||||
private final OrderStatusService orderStatusService;
|
||||
private final OrderStatusMapper orderStatusMapper;
|
||||
private final OrderMapper orderMapper;
|
||||
private final ProductMapper productMapper;
|
||||
@@ -72,10 +112,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
SseNotificationService sseNotificationService,
|
||||
ObjectMapper objectMapper) {
|
||||
this.importTaskService = importTaskService;
|
||||
this.orderService = orderService;
|
||||
this.productService = productService;
|
||||
this.productSpecService = productSpecService;
|
||||
this.orderStatusService = orderStatusService;
|
||||
this.orderStatusMapper = orderStatusMapper;
|
||||
this.orderMapper = orderMapper;
|
||||
this.productMapper = productMapper;
|
||||
@@ -135,7 +172,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
*/
|
||||
private void processOrderImport(ImportTaskPO task) throws IOException {
|
||||
// 解析字段映射
|
||||
Map<String, String> mapping = parseMapping(task.getMapping());
|
||||
Map<String, MappingField> mapping = parseMapping(task.getMapping());
|
||||
Long companyId = task.getCompanyId();
|
||||
|
||||
// 读取CSV文件
|
||||
@@ -242,16 +279,24 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
* 解析字段映射
|
||||
*
|
||||
* @param mappingJson 映射JSON字符串
|
||||
* @return 字段映射Map(实体字段名 -> CSV表头名)
|
||||
* @return 字段映射Map(实体字段名 -> 映射字段定义)
|
||||
*/
|
||||
private Map<String, String> parseMapping(String mappingJson) {
|
||||
private Map<String, MappingField> parseMapping(String mappingJson) {
|
||||
try {
|
||||
if (mappingJson == null || mappingJson.trim().isEmpty()) {
|
||||
throw new BusinessException("字段映射不能为空");
|
||||
}
|
||||
// 解析JSON,格式:{"specCode": "商家编码-规格维度", "specName": "商品规格", ...}
|
||||
Map<String, String> mapping = objectMapper.readValue(mappingJson, new TypeReference<Map<String, String>>() {});
|
||||
return mapping;
|
||||
// 解析JSON数组,格式:[{"required": false, "fieldName": "productName", "fieldLabel": "商品名称", "fileFieldName": "商品"}, ...]
|
||||
List<MappingField> mappingFields = objectMapper.readValue(mappingJson,
|
||||
new TypeReference<List<MappingField>>() {});
|
||||
|
||||
if (mappingFields == null || mappingFields.isEmpty()) {
|
||||
throw new BusinessException("字段映射不能为空");
|
||||
}
|
||||
|
||||
// 转换为Map,key为fieldName,value为MappingField对象
|
||||
return mappingFields.stream()
|
||||
.collect(Collectors.toMap(MappingField::getFieldName, field -> field, (v1, v2) -> v1));
|
||||
} catch (Exception e) {
|
||||
throw new BusinessException("解析字段映射失败: " + e.getMessage());
|
||||
}
|
||||
@@ -261,94 +306,145 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
* 从CSV记录解析订单数据
|
||||
*
|
||||
* @param record CSV记录
|
||||
* @param mapping 字段映射
|
||||
* @param mapping 字段映射(fieldName -> MappingField)
|
||||
* @param shopId 店铺ID
|
||||
* @param defaultStatusId 默认订单状态ID
|
||||
* @param companyId 公司ID
|
||||
* @param createBy 创建人ID
|
||||
* @return 创建订单DTO
|
||||
*/
|
||||
private CreateOrderDTO parseOrderFromCSV(CSVRecord record, Map<String, String> mapping,
|
||||
private CreateOrderDTO parseOrderFromCSV(CSVRecord record, Map<String, MappingField> mapping,
|
||||
Long shopId, Long defaultStatusId, Long companyId, Long createBy) {
|
||||
CreateOrderDTO orderDTO = new CreateOrderDTO();
|
||||
orderDTO.setShopId(shopId);
|
||||
orderDTO.setStatusId(defaultStatusId);
|
||||
|
||||
// 获取映射的CSV表头名
|
||||
String specCodeHeader = mapping.get("specCode");
|
||||
String receivedAmountHeader = mapping.get("receivedAmount");
|
||||
String orderQuantityHeader = mapping.get("orderQuantity");
|
||||
String orderStatusHeader = mapping.get("orderStatus");
|
||||
String productNameHeader = mapping.get("productName");
|
||||
String specNameHeader = mapping.get("specName");
|
||||
String platformOrderNoHeader = mapping.get("platformOrderNo");
|
||||
// 获取映射字段定义
|
||||
MappingField specCodeField = mapping.get("specCode"); // 规格编码
|
||||
MappingField receivedAmountField = mapping.get("receivedAmount"); // 商家实收金额
|
||||
MappingField productQuantityField = mapping.get("productQuantity"); // 商品数量
|
||||
MappingField orderStatusField = mapping.get("orderStatus"); // 订单状态
|
||||
MappingField productNameField = mapping.get("productName"); // 商品名称
|
||||
MappingField productCodeField = mapping.get("productCode"); // 商品编码
|
||||
MappingField specNameField = mapping.get("specName"); // 规格名称
|
||||
MappingField platformOrderNoField = mapping.get("platformOrderNo"); // 平台订单号
|
||||
|
||||
// 调试日志:记录字段映射
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("字段映射 - specCodeHeader: {}, receivedAmountHeader: {}, orderQuantityHeader: {}",
|
||||
specCodeHeader, receivedAmountHeader, orderQuantityHeader);
|
||||
logger.debug("字段映射 - specCode: {}, receivedAmount: {}, productQuantity: {}",
|
||||
specCodeField != null ? specCodeField.getFileFieldName() : null,
|
||||
receivedAmountField != null ? receivedAmountField.getFileFieldName() : null,
|
||||
productQuantityField != null ? productQuantityField.getFileFieldName() : null);
|
||||
}
|
||||
|
||||
// 必填字段验证
|
||||
String specCode = getValue(record, specCodeHeader);
|
||||
String specCode = getValue(record, specCodeField);
|
||||
if (specCode == null || specCode.trim().isEmpty()) {
|
||||
// 提供更详细的错误信息
|
||||
String availableHeaders = String.join(", ", record.getParser().getHeaderMap().keySet());
|
||||
throw new BusinessException(String.format("规格编码不能为空。映射的表头名: '%s',可用的表头: [%s],当前行的所有值: %s",
|
||||
specCodeHeader, availableHeaders, record.toMap()));
|
||||
// 检查是否为必填字段
|
||||
if (specCodeField != null && specCodeField.getRequired() != null && specCodeField.getRequired()) {
|
||||
// 提供更详细的错误信息
|
||||
String availableHeaders = String.join(", ", record.getParser().getHeaderMap().keySet());
|
||||
String fileFieldName = specCodeField.getFileFieldName();
|
||||
throw new BusinessException(String.format("规格编码不能为空。映射的表头名: '%s',可用的表头: [%s],当前行的所有值: %s",
|
||||
fileFieldName, availableHeaders, record.toMap()));
|
||||
} else if (specCodeField == null) {
|
||||
// 如果映射中没有定义该字段,但规格编码是必需的,抛出异常
|
||||
String availableHeaders = String.join(", ", record.getParser().getHeaderMap().keySet());
|
||||
throw new BusinessException(String.format("规格编码不能为空。映射中未定义该字段,可用的表头: [%s],当前行的所有值: %s",
|
||||
availableHeaders, record.toMap()));
|
||||
}
|
||||
}
|
||||
|
||||
String receivedAmountStr = getValue(record, receivedAmountHeader);
|
||||
if (receivedAmountStr == null || receivedAmountStr.trim().isEmpty()) {
|
||||
String receivedAmountStr = getValue(record, receivedAmountField);
|
||||
if ((receivedAmountStr == null || receivedAmountStr.trim().isEmpty()) &&
|
||||
receivedAmountField != null && receivedAmountField.getRequired() != null && receivedAmountField.getRequired()) {
|
||||
throw new BusinessException("商家实收金额不能为空");
|
||||
}
|
||||
|
||||
String orderQuantityStr = getValue(record, orderQuantityHeader);
|
||||
if (orderQuantityStr == null || orderQuantityStr.trim().isEmpty()) {
|
||||
throw new BusinessException("订单数量不能为空");
|
||||
String productQuantityStr = getValue(record, productQuantityField);
|
||||
if ((productQuantityStr == null || productQuantityStr.trim().isEmpty()) &&
|
||||
productQuantityField != null && productQuantityField.getRequired() != null && productQuantityField.getRequired()) {
|
||||
throw new BusinessException("商品数量不能为空");
|
||||
}
|
||||
|
||||
// 解析必填字段
|
||||
try {
|
||||
orderDTO.setReceivedAmount(new BigDecimal(receivedAmountStr.trim()));
|
||||
} catch (NumberFormatException e) {
|
||||
throw new BusinessException("商家实收金额格式错误: " + receivedAmountStr);
|
||||
if (receivedAmountStr != null && !receivedAmountStr.trim().isEmpty()) {
|
||||
try {
|
||||
orderDTO.setReceivedAmount(new BigDecimal(receivedAmountStr.trim()));
|
||||
} catch (NumberFormatException e) {
|
||||
throw new BusinessException("商家实收金额格式错误: " + receivedAmountStr);
|
||||
}
|
||||
} else if (receivedAmountField != null && receivedAmountField.getRequired() != null && receivedAmountField.getRequired()) {
|
||||
throw new BusinessException("商家实收金额不能为空");
|
||||
}
|
||||
|
||||
try {
|
||||
orderDTO.setQuantity(Integer.parseInt(orderQuantityStr.trim()));
|
||||
if (orderDTO.getQuantity() <= 0) {
|
||||
throw new BusinessException("订单数量必须大于0");
|
||||
if (productQuantityStr != null && !productQuantityStr.trim().isEmpty()) {
|
||||
try {
|
||||
orderDTO.setQuantity(Integer.parseInt(productQuantityStr.trim()));
|
||||
if (orderDTO.getQuantity() <= 0) {
|
||||
throw new BusinessException("商品数量必须大于0");
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
throw new BusinessException("商品数量格式错误: " + productQuantityStr);
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
throw new BusinessException("订单数量格式错误: " + orderQuantityStr);
|
||||
} else if (productQuantityField != null && productQuantityField.getRequired() != null && productQuantityField.getRequired()) {
|
||||
throw new BusinessException("商品数量不能为空");
|
||||
}
|
||||
|
||||
// 解析可选字段(先解析,用于后续创建商品和规格)
|
||||
String productName = null;
|
||||
if (productNameHeader != null) {
|
||||
productName = getValue(record, productNameHeader);
|
||||
productName = productName != null ? productName.trim() : null;
|
||||
}
|
||||
String productName = getValue(record, productNameField);
|
||||
productName = productName != null ? productName.trim() : null;
|
||||
|
||||
String specName = null;
|
||||
if (specNameHeader != null) {
|
||||
specName = getValue(record, specNameHeader);
|
||||
specName = specName != null ? specName.trim() : null;
|
||||
}
|
||||
String productCode = getValue(record, productCodeField);
|
||||
productCode = productCode != null ? productCode.trim() : null;
|
||||
|
||||
String specName = getValue(record, specNameField);
|
||||
specName = specName != null ? specName.trim() : null;
|
||||
|
||||
// 通过规格编码查找商品规格
|
||||
// 首先通过规格编码查找商品规格
|
||||
ProductSpecPO productSpec = findProductSpecBySpecCode(specCode.trim(), companyId);
|
||||
|
||||
// 如果找不到规格,但有商品名称和规格名称,则自动创建商品和规格
|
||||
// 如果找不到规格,则尝试通过商品编码或商品名称查找商品,然后创建规格
|
||||
if (productSpec == null) {
|
||||
if (productName != null && !productName.isEmpty() &&
|
||||
specName != null && !specName.isEmpty()) {
|
||||
logger.info("未找到规格编码 '{}',但提供了商品名称 '{}' 和规格名称 '{}',将自动创建商品和规格",
|
||||
ProductPO product = null;
|
||||
|
||||
// 优先使用商品编码查找商品
|
||||
if (productCode != null && !productCode.isEmpty()) {
|
||||
product = findProductByProductCode(productCode, companyId);
|
||||
if (product != null) {
|
||||
logger.info("未找到规格编码 '{}',但通过商品编码 '{}' 找到了商品 '{}' (ID: {})",
|
||||
specCode, productCode, product.getName(), product.getId());
|
||||
}
|
||||
}
|
||||
|
||||
// 如果商品编码查找失败,使用商品名称精准查找商品
|
||||
if (product == null && productName != null && !productName.isEmpty()) {
|
||||
product = findProductByName(productName, companyId);
|
||||
if (product != null) {
|
||||
logger.info("未找到规格编码 '{}',但通过商品名称 '{}' 找到了商品 (ID: {})",
|
||||
specCode, productName, product.getId());
|
||||
}
|
||||
}
|
||||
|
||||
// 如果找到了商品,创建规格
|
||||
if (product != null) {
|
||||
if (specName == null || specName.isEmpty()) {
|
||||
throw new BusinessException("未找到规格编码对应的商品规格: " + specCode +
|
||||
",且未提供规格名称,无法创建规格");
|
||||
}
|
||||
logger.info("为商品 '{}' (ID: {}) 创建规格 '{}' (编码: {})",
|
||||
product.getName(), product.getId(), specName, specCode);
|
||||
productSpec = createSpecForProduct(companyId, product.getId(), specName, specCode.trim(), createBy);
|
||||
}
|
||||
// 如果没有找到商品,但有商品名称和规格名称,则自动创建商品和规格
|
||||
else if (productName != null && !productName.isEmpty() &&
|
||||
specName != null && !specName.isEmpty()) {
|
||||
logger.info("未找到规格编码 '{}',也未找到商品,将自动创建商品 '{}' 和规格 '{}'",
|
||||
specCode, productName, specName);
|
||||
productSpec = createProductAndSpecIfNotExists(companyId, productName, specName, specCode.trim(), createBy);
|
||||
productSpec = createProductAndSpecIfNotExists(companyId, productName, productCode, specName, specCode.trim(), createBy);
|
||||
} else {
|
||||
throw new BusinessException("未找到规格编码对应的商品规格: " + specCode +
|
||||
(productCode == null || productCode.isEmpty() ? "" : ",商品编码 '" + productCode + "' 未找到商品") +
|
||||
(productName == null || productName.isEmpty() ? ",且未提供商品名称" : "") +
|
||||
(specName == null || specName.isEmpty() ? ",且未提供规格名称" : ""));
|
||||
}
|
||||
@@ -373,23 +469,23 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
orderDTO.setSpecName(productSpec.getName());
|
||||
}
|
||||
|
||||
if (platformOrderNoHeader != null) {
|
||||
String platformOrderNo = getValue(record, platformOrderNoHeader);
|
||||
orderDTO.setPlatformOrderNo(platformOrderNo != null ? platformOrderNo.trim() : null);
|
||||
String platformOrderNo = getValue(record, platformOrderNoField);
|
||||
if (platformOrderNo != null && !platformOrderNo.trim().isEmpty()) {
|
||||
orderDTO.setPlatformOrderNo(platformOrderNo.trim());
|
||||
}
|
||||
|
||||
// 计算销售单价(商家实收金额 / 数量)
|
||||
orderDTO.setUnitPrice(orderDTO.getReceivedAmount()
|
||||
.divide(new BigDecimal(orderDTO.getQuantity()), 2, RoundingMode.HALF_UP));
|
||||
if (orderDTO.getReceivedAmount() != null && orderDTO.getQuantity() != null && orderDTO.getQuantity() > 0) {
|
||||
orderDTO.setUnitPrice(orderDTO.getReceivedAmount()
|
||||
.divide(new BigDecimal(orderDTO.getQuantity()), 2, RoundingMode.HALF_UP));
|
||||
}
|
||||
|
||||
// 解析订单状态(如果提供了映射)
|
||||
if (orderStatusHeader != null) {
|
||||
String orderStatusName = getValue(record, orderStatusHeader);
|
||||
if (orderStatusName != null && !orderStatusName.trim().isEmpty()) {
|
||||
Long statusId = findOrderStatusByName(orderStatusName.trim(), companyId);
|
||||
if (statusId != null) {
|
||||
orderDTO.setStatusId(statusId);
|
||||
}
|
||||
String orderStatusName = getValue(record, orderStatusField);
|
||||
if (orderStatusName != null && !orderStatusName.trim().isEmpty()) {
|
||||
Long statusId = findOrderStatusByName(orderStatusName.trim(), companyId);
|
||||
if (statusId != null) {
|
||||
orderDTO.setStatusId(statusId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -403,6 +499,21 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
* 从CSV记录获取值
|
||||
*
|
||||
* @param record CSV记录
|
||||
* @param mappingField 映射字段定义
|
||||
* @return 值
|
||||
*/
|
||||
private String getValue(CSVRecord record, MappingField mappingField) {
|
||||
if (mappingField == null || mappingField.getFileFieldName() == null || mappingField.getFileFieldName().trim().isEmpty()) {
|
||||
logger.debug("映射字段为空或文件字段名为空,无法获取值");
|
||||
return null;
|
||||
}
|
||||
return getValue(record, mappingField.getFileFieldName());
|
||||
}
|
||||
|
||||
/**
|
||||
* 从CSV记录获取值(重载方法,兼容旧代码)
|
||||
*
|
||||
* @param record CSV记录
|
||||
* @param header 表头名称
|
||||
* @return 值
|
||||
*/
|
||||
@@ -451,19 +562,100 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
}
|
||||
|
||||
/**
|
||||
* 如果商品和规格不存在,则创建它们
|
||||
* 通过规格编码查找无果则确定为规格不存在,再通过商品名称来判断有没有该商品
|
||||
* 复用ProductService.createProduct和ProductSpecService.createProductSpec的业务逻辑
|
||||
* 通过商品编码查找商品
|
||||
*
|
||||
* @param productCode 商品编码
|
||||
* @param companyId 公司ID
|
||||
* @return 商品
|
||||
*/
|
||||
private ProductPO findProductByProductCode(String productCode, Long companyId) {
|
||||
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ProductPO> wrapper =
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
|
||||
wrapper.eq(ProductPO::getProductCode, productCode)
|
||||
.eq(ProductPO::getCompanyId, companyId);
|
||||
return productMapper.selectOne(wrapper);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过商品名称查找商品(精准匹配)
|
||||
*
|
||||
* @param productName 商品名称
|
||||
* @param companyId 公司ID
|
||||
* @return 商品
|
||||
*/
|
||||
private ProductPO findProductByName(String productName, Long companyId) {
|
||||
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ProductPO> wrapper =
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
|
||||
wrapper.eq(ProductPO::getName, productName)
|
||||
.eq(ProductPO::getCompanyId, companyId);
|
||||
return productMapper.selectOne(wrapper);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为已存在的商品创建规格
|
||||
*
|
||||
* @param companyId 公司ID
|
||||
* @param productId 商品ID
|
||||
* @param specName 规格名称
|
||||
* @param specCode 规格编码
|
||||
* @param createBy 创建人ID
|
||||
* @return 商品规格
|
||||
*/
|
||||
private ProductSpecPO createSpecForProduct(Long companyId, Long productId, String specName, String specCode, Long createBy) {
|
||||
// 验证商品是否存在
|
||||
ProductPO existingProduct = productMapper.selectById(productId);
|
||||
if (existingProduct == null || !existingProduct.getCompanyId().equals(companyId)) {
|
||||
throw new BusinessException("商品不存在");
|
||||
}
|
||||
|
||||
// 验证规格名称是否重复
|
||||
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ProductSpecPO> specCheckWrapper =
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
|
||||
specCheckWrapper.eq(ProductSpecPO::getProductId, productId)
|
||||
.eq(ProductSpecPO::getName, specName)
|
||||
.eq(ProductSpecPO::getCompanyId, companyId);
|
||||
if (productSpecService.count(specCheckWrapper) > 0) {
|
||||
throw new BusinessException("规格名称已存在");
|
||||
}
|
||||
|
||||
// 验证规格编码是否重复
|
||||
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ProductSpecPO> specCodeCheckWrapper =
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
|
||||
specCodeCheckWrapper.eq(ProductSpecPO::getSpecCode, specCode)
|
||||
.eq(ProductSpecPO::getCompanyId, companyId);
|
||||
if (productSpecService.count(specCodeCheckWrapper) > 0) {
|
||||
throw new BusinessException("规格编码已存在");
|
||||
}
|
||||
|
||||
// 创建商品规格
|
||||
ProductSpecPO productSpec = new ProductSpecPO();
|
||||
productSpec.setCompanyId(companyId);
|
||||
productSpec.setProductId(productId);
|
||||
productSpec.setName(specName);
|
||||
productSpec.setSpecCode(specCode);
|
||||
productSpec.setCostPrice(BigDecimal.ZERO); // 默认成本价为0,后续可以手动更新
|
||||
productSpec.setCreateBy(createBy);
|
||||
productSpecService.save(productSpec);
|
||||
logger.info("为商品 (ID: {}) 创建规格: {} (编码: {}, ID: {})", productId, specName, specCode, productSpec.getId());
|
||||
|
||||
return productSpec;
|
||||
}
|
||||
|
||||
/**
|
||||
* 如果商品和规格不存在,则创建它们
|
||||
* 通过规格编码查找无果则确定为规格不存在,再通过商品编码或商品名称来判断有没有该商品
|
||||
* 复用ProductService.createProduct和ProductSpecService.createProductSpec的业务逻辑
|
||||
*
|
||||
* @param companyId 公司ID
|
||||
* @param productName 商品名称
|
||||
* @param productCode 商品编码(可选)
|
||||
* @param specName 规格名称
|
||||
* @param specCode 规格编码
|
||||
* @param createBy 创建人ID
|
||||
* @return 商品规格
|
||||
*/
|
||||
private ProductSpecPO createProductAndSpecIfNotExists(Long companyId, String productName,
|
||||
String specName, String specCode, Long createBy) {
|
||||
String productCode, String specName, String specCode, Long createBy) {
|
||||
// 1. 通过商品名称查找商品(复用ProductService.getProductByName的逻辑)
|
||||
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ProductPO> productWrapper =
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
|
||||
@@ -491,10 +683,22 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
product = new ProductPO();
|
||||
product.setCompanyId(companyId);
|
||||
product.setName(productName);
|
||||
if (productCode != null && !productCode.isEmpty()) {
|
||||
// 验证商品编码是否重复
|
||||
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ProductPO> codeCheckWrapper =
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
|
||||
codeCheckWrapper.eq(ProductPO::getProductCode, productCode)
|
||||
.eq(ProductPO::getCompanyId, companyId);
|
||||
if (productMapper.selectCount(codeCheckWrapper) > 0) {
|
||||
throw new BusinessException("商品编码已存在: " + productCode);
|
||||
}
|
||||
product.setProductCode(productCode);
|
||||
}
|
||||
product.setCreateBy(createBy);
|
||||
productMapper.insert(product);
|
||||
productId = product.getId();
|
||||
logger.info("自动创建商品: {} (ID: {})", productName, productId);
|
||||
logger.info("自动创建商品: {} (ID: {})" + (productCode != null && !productCode.isEmpty() ? ", 商品编码: " + productCode : ""),
|
||||
productName, productId);
|
||||
}
|
||||
} else {
|
||||
productId = product.getId();
|
||||
@@ -502,35 +706,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
}
|
||||
|
||||
// 2. 创建商品规格(复用ProductSpecService.createProductSpec的逻辑)
|
||||
// 注意:规格编码查找无果,所以这里直接创建
|
||||
// 验证商品是否存在(复用createProductSpec的逻辑)
|
||||
ProductPO existingProduct = productMapper.selectById(productId);
|
||||
if (existingProduct == null || !existingProduct.getCompanyId().equals(companyId)) {
|
||||
throw new BusinessException("商品不存在");
|
||||
}
|
||||
|
||||
// 验证规格名称是否重复(复用createProductSpec的逻辑)
|
||||
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ProductSpecPO> specCheckWrapper =
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
|
||||
specCheckWrapper.eq(ProductSpecPO::getProductId, productId)
|
||||
.eq(ProductSpecPO::getName, specName)
|
||||
.eq(ProductSpecPO::getCompanyId, companyId);
|
||||
if (productSpecService.count(specCheckWrapper) > 0) {
|
||||
throw new BusinessException("规格名称已存在");
|
||||
}
|
||||
|
||||
// 创建商品规格(复用createProductSpec的逻辑)
|
||||
ProductSpecPO productSpec = new ProductSpecPO();
|
||||
productSpec.setCompanyId(companyId);
|
||||
productSpec.setProductId(productId);
|
||||
productSpec.setName(specName);
|
||||
productSpec.setSpecCode(specCode);
|
||||
productSpec.setCostPrice(BigDecimal.ZERO); // 默认成本价为0,后续可以手动更新
|
||||
productSpec.setCreateBy(createBy);
|
||||
productSpecService.save(productSpec);
|
||||
logger.info("自动创建商品规格: {} (编码: {}, ID: {})", specName, specCode, productSpec.getId());
|
||||
|
||||
return productSpec;
|
||||
return createSpecForProduct(companyId, productId, specName, specCode, createBy);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+23
-3
@@ -35,10 +35,30 @@ public class ImportTaskQueueServiceImpl implements ImportTaskQueueService {
|
||||
@Override
|
||||
public void publishImportTask(Long taskId) {
|
||||
try {
|
||||
// 获取任务信息
|
||||
ImportTaskPO task = importTaskService.getById(taskId);
|
||||
// 获取任务信息,由于是在事务提交后调用,可能需要短暂等待
|
||||
ImportTaskPO task = null;
|
||||
int retryCount = 0;
|
||||
int maxRetries = 5;
|
||||
|
||||
while (task == null && retryCount < maxRetries) {
|
||||
task = importTaskService.getById(taskId);
|
||||
if (task == null) {
|
||||
retryCount++;
|
||||
if (retryCount < maxRetries) {
|
||||
// 等待一小段时间后重试(事务可能刚提交,数据库可能还没完全同步)
|
||||
try {
|
||||
Thread.sleep(50); // 等待50毫秒
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
logger.warn("等待任务查询时被中断", e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (task == null) {
|
||||
logger.error("导入任务不存在,taskId: {}", taskId);
|
||||
logger.error("导入任务不存在,taskId: {},已重试{}次", taskId, maxRetries);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
+11
-2
@@ -7,6 +7,7 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
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;
|
||||
@@ -61,8 +62,16 @@ public class ImportTaskServiceImpl extends ServiceImpl<ImportTaskMapper, ImportT
|
||||
|
||||
this.save(importTaskPO);
|
||||
|
||||
// 发布任务到Redis队列
|
||||
importTaskQueueService.publishImportTask(importTaskPO.getId());
|
||||
// 在事务提交后再发布任务到Redis队列,确保数据已提交到数据库
|
||||
Long taskId = importTaskPO.getId();
|
||||
TransactionSynchronizationManager.registerSynchronization(
|
||||
new org.springframework.transaction.support.TransactionSynchronization() {
|
||||
@Override
|
||||
public void afterCommit() {
|
||||
importTaskQueueService.publishImportTask(taskId);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// 转换为VO返回
|
||||
return convertToVO(importTaskPO);
|
||||
|
||||
+20
@@ -63,6 +63,14 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
||||
throw new BusinessException("商品名称已存在");
|
||||
}
|
||||
|
||||
// 验证商品编码是否重复(如果不为空)
|
||||
if (createProductDTO.getProductCode() != null && !createProductDTO.getProductCode().trim().isEmpty()) {
|
||||
LambdaQueryWrapper<ProductPO> codeWrapper = new LambdaQueryWrapper<>();
|
||||
codeWrapper.eq(ProductPO::getProductCode, createProductDTO.getProductCode().trim());
|
||||
if (this.count(codeWrapper) > 0) {
|
||||
throw new BusinessException("商品编码已存在");
|
||||
}
|
||||
}
|
||||
|
||||
// 创建商品
|
||||
ProductPO product = new ProductPO();
|
||||
@@ -133,6 +141,15 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
||||
throw new BusinessException("商品名称已存在");
|
||||
}
|
||||
|
||||
// 验证商品编码是否重复(如果不为空,排除当前商品)
|
||||
if (updateProductDTO.getProductCode() != null && !updateProductDTO.getProductCode().trim().isEmpty()) {
|
||||
LambdaQueryWrapper<ProductPO> codeWrapper = new LambdaQueryWrapper<>();
|
||||
codeWrapper.eq(ProductPO::getProductCode, updateProductDTO.getProductCode().trim())
|
||||
.ne(ProductPO::getId, id);
|
||||
if (this.count(codeWrapper) > 0) {
|
||||
throw new BusinessException("商品编码已存在");
|
||||
}
|
||||
}
|
||||
|
||||
// 更新商品
|
||||
ProductPO product = new ProductPO();
|
||||
@@ -202,6 +219,9 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
||||
if (filter.getName() != null && !filter.getName().trim().isEmpty()) {
|
||||
wrapper.like(ProductPO::getName, filter.getName());
|
||||
}
|
||||
if (filter.getProductCode() != null && !filter.getProductCode().trim().isEmpty()) {
|
||||
wrapper.like(ProductPO::getProductCode, filter.getProductCode());
|
||||
}
|
||||
}
|
||||
|
||||
// 排序
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
-- 为导入映射表添加名称字段并修改唯一约束
|
||||
-- 执行时间:2025-12-03
|
||||
|
||||
-- 1. 添加名称字段
|
||||
ALTER TABLE `ec_import_mappings`
|
||||
ADD COLUMN `name` varchar(20) NOT NULL COMMENT '映射名称' AFTER `type`;
|
||||
|
||||
-- 2. 为现有数据设置默认名称(根据类型设置,确保唯一性)
|
||||
UPDATE `ec_import_mappings` SET `name` = CONCAT('商品导入映射-', DATE_FORMAT(create_time, '%Y%m%d')) WHERE `type` = 'product';
|
||||
UPDATE `ec_import_mappings` SET `name` = CONCAT('订单导入映射-', DATE_FORMAT(create_time, '%Y%m%d')) WHERE `type` = 'order';
|
||||
|
||||
-- 3. 删除旧的唯一约束(如果存在)
|
||||
ALTER TABLE `ec_import_mappings` DROP INDEX IF EXISTS `uniq_company_type`;
|
||||
|
||||
-- 4. 添加新的唯一约束(公司ID、导入类型、名称)
|
||||
ALTER TABLE `ec_import_mappings`
|
||||
ADD UNIQUE KEY `uniq_company_type_name` (`company_id`, `type`, `name`);
|
||||
|
||||
@@ -26,6 +26,7 @@ CREATE TABLE `ec_product` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '商品ID',
|
||||
`company_id` BIGINT UNSIGNED NOT NULL COMMENT '公司ID',
|
||||
`name` VARCHAR(255) NOT NULL COMMENT '商品名称',
|
||||
`product_code` VARCHAR(100) DEFAULT NULL COMMENT '商品编码',
|
||||
`main_image` VARCHAR(500) DEFAULT NULL COMMENT '主图URL(冗余字段)',
|
||||
`main_image_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '主图图片ID',
|
||||
`create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
@@ -34,6 +35,7 @@ CREATE TABLE `ec_product` (
|
||||
`update_by` BIGINT UNSIGNED DEFAULT NULL COMMENT '更新人ID',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_company_id` (`company_id`),
|
||||
UNIQUE KEY `uk_product_code` (`product_code`),
|
||||
KEY `fk_ec_product_main_image` (`main_image_id`),
|
||||
KEY `fk_ec_product_creator` (`create_by`),
|
||||
KEY `fk_ec_product_updater` (`update_by`),
|
||||
@@ -225,14 +227,15 @@ 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') NOT NULL COMMENT '导入类型(product-商品 order-订单)',
|
||||
`mapping` json NOT NULL COMMENT '{"商品名称":"name","价格(元)":"price"}',
|
||||
`name` varchar(20) 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 DEFAULT NULL COMMENT '创建人ID',
|
||||
`update_by` bigint unsigned DEFAULT NULL COMMENT '更新人ID',
|
||||
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uniq_company_type` (`company_id`, `type`),
|
||||
UNIQUE KEY `uniq_company_type_name` (`company_id`, `type`, `name`),
|
||||
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
|
||||
|
||||
@@ -7,12 +7,16 @@ export namespace ImportMappingDTO {
|
||||
export interface CreateImportMappingDTO {
|
||||
/** 导入类型(product-商品 order-订单) */
|
||||
type: string;
|
||||
/** 映射名称 */
|
||||
name: string;
|
||||
/** 字段映射(JSON格式) */
|
||||
mapping: string;
|
||||
}
|
||||
|
||||
/** 更新导入映射参数 */
|
||||
export interface UpdateImportMappingDTO {
|
||||
/** 映射名称 */
|
||||
name?: string;
|
||||
/** 字段映射(JSON格式) */
|
||||
mapping: string;
|
||||
}
|
||||
@@ -21,5 +25,7 @@ export namespace ImportMappingDTO {
|
||||
export interface ImportMappingFilterDTO {
|
||||
/** 导入类型(product-商品 order-订单) */
|
||||
type?: string;
|
||||
/** 映射名称(模糊查询) */
|
||||
name?: string;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,8 @@ export namespace ImportMappingVO {
|
||||
companyId?: number;
|
||||
/** 导入类型(product-商品 order-订单) */
|
||||
type: string;
|
||||
/** 映射名称 */
|
||||
name: string;
|
||||
/** 字段映射(JSON格式) */
|
||||
mapping: string;
|
||||
/** 创建时间 */
|
||||
|
||||
@@ -2,8 +2,13 @@ import type { ImportTaskDTO, ImportTaskVO } from './types';
|
||||
|
||||
import type { PageQueryDTO, PageResultVO } from '#/types/common';
|
||||
|
||||
import { useAppConfig } from '@vben/hooks';
|
||||
import { useAccessStore } from '@vben/stores';
|
||||
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
|
||||
|
||||
/**
|
||||
* 导入任务管理API
|
||||
*/
|
||||
@@ -31,3 +36,191 @@ export async function getImportTaskPageApi(
|
||||
params,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* SSE连接管理器(使用fetch API支持自定义请求头)
|
||||
*/
|
||||
class SseConnection {
|
||||
private abortController: AbortController | null = null;
|
||||
private accessStore: ReturnType<typeof useAccessStore>;
|
||||
private listeners: Map<string, Set<(event: MessageEvent) => void>> =
|
||||
new Map();
|
||||
private readyState: number = EventSource.CLOSED;
|
||||
|
||||
constructor() {
|
||||
this.accessStore = useAccessStore();
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加事件监听器
|
||||
*/
|
||||
addEventListener(eventType: string, handler: (event: MessageEvent) => void) {
|
||||
if (!this.listeners.has(eventType)) {
|
||||
this.listeners.set(eventType, new Set());
|
||||
}
|
||||
this.listeners.get(eventType)!.add(handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* 建立SSE连接(使用fetch API)
|
||||
*/
|
||||
connect(): void {
|
||||
if (this.abortController) {
|
||||
this.disconnect();
|
||||
}
|
||||
|
||||
const token = this.accessStore.accessToken;
|
||||
if (!token) {
|
||||
console.error('无法建立SSE连接:token不存在');
|
||||
return;
|
||||
}
|
||||
|
||||
const url = `${apiURL}/ec/import-task/sse/connect`;
|
||||
this.abortController = new AbortController();
|
||||
this.readyState = EventSource.CONNECTING;
|
||||
|
||||
fetch(url, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
Accept: 'text/event-stream',
|
||||
},
|
||||
signal: this.abortController.signal,
|
||||
})
|
||||
.then((response) => {
|
||||
if (!response.ok) {
|
||||
throw new Error(`SSE连接失败: ${response.status}`);
|
||||
}
|
||||
|
||||
this.readyState = EventSource.OPEN;
|
||||
|
||||
const reader = response.body?.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
if (!reader) {
|
||||
throw new Error('无法获取响应流');
|
||||
}
|
||||
|
||||
// 读取流数据
|
||||
const readStream = () => {
|
||||
reader
|
||||
.read()
|
||||
.then(({ done, value }) => {
|
||||
if (done) {
|
||||
this.readyState = EventSource.CLOSED;
|
||||
return;
|
||||
}
|
||||
|
||||
const chunk = decoder.decode(value, { stream: true });
|
||||
this.parseSSE(chunk);
|
||||
readStream();
|
||||
})
|
||||
.catch((error) => {
|
||||
if (error.name !== 'AbortError') {
|
||||
console.error('读取SSE流失败:', error);
|
||||
this.readyState = EventSource.CLOSED;
|
||||
this.dispatchEvent(
|
||||
'error',
|
||||
new MessageEvent('error', { data: error }),
|
||||
);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
readStream();
|
||||
})
|
||||
.catch((error) => {
|
||||
if (error.name !== 'AbortError') {
|
||||
console.error('建立SSE连接失败:', error);
|
||||
this.readyState = EventSource.CLOSED;
|
||||
this.dispatchEvent(
|
||||
'error',
|
||||
new MessageEvent('error', { data: error }),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 断开连接
|
||||
*/
|
||||
disconnect() {
|
||||
if (this.abortController) {
|
||||
this.abortController.abort();
|
||||
this.abortController = null;
|
||||
this.readyState = EventSource.CLOSED;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取连接状态
|
||||
*/
|
||||
getReadyState(): number {
|
||||
return this.readyState;
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除事件监听器
|
||||
*/
|
||||
removeEventListener(
|
||||
eventType: string,
|
||||
handler: (event: MessageEvent) => void,
|
||||
) {
|
||||
const handlers = this.listeners.get(eventType);
|
||||
if (handlers) {
|
||||
handlers.delete(handler);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 分发事件
|
||||
*/
|
||||
private dispatchEvent(eventType: string, event: MessageEvent) {
|
||||
const handlers = this.listeners.get(eventType);
|
||||
if (handlers) {
|
||||
handlers.forEach((handler) => {
|
||||
try {
|
||||
handler(event);
|
||||
} catch (error) {
|
||||
console.error('事件处理器执行失败:', error);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析SSE数据
|
||||
*/
|
||||
private parseSSE(chunk: string) {
|
||||
const lines = chunk.split('\n');
|
||||
let eventType = 'message';
|
||||
let data = '';
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('event:')) {
|
||||
eventType = line.slice(6).trim();
|
||||
} else if (line.startsWith('data:')) {
|
||||
data += `${line.slice(5).trim()}\n`;
|
||||
} else if (
|
||||
line === '' && // 空行表示一个完整的消息
|
||||
data
|
||||
) {
|
||||
const event = new MessageEvent(eventType, {
|
||||
data: data.trim(),
|
||||
});
|
||||
this.dispatchEvent(eventType, event);
|
||||
this.dispatchEvent('message', event);
|
||||
data = '';
|
||||
eventType = 'message';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 建立SSE连接
|
||||
* @returns SseConnection实例
|
||||
*/
|
||||
export function createSseConnection(): SseConnection {
|
||||
return new SseConnection();
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@ export namespace ProductDTO {
|
||||
export interface Create {
|
||||
/** 商品名称 */
|
||||
name: string;
|
||||
/** 商品编码 */
|
||||
productCode?: string;
|
||||
/** 主图图片ID */
|
||||
mainImageId?: number;
|
||||
/** 商品规格列表(可选) */
|
||||
@@ -18,6 +20,8 @@ export namespace ProductDTO {
|
||||
/** 商品名称 */
|
||||
name: string;
|
||||
/** 商品编码 */
|
||||
productCode?: string;
|
||||
/** 商品编码 */
|
||||
specCode?: string;
|
||||
/** 商品SKU */
|
||||
skuCode?: string;
|
||||
@@ -64,6 +68,8 @@ export namespace ProductDTO {
|
||||
/** 商品名称(模糊查询) */
|
||||
name?: string;
|
||||
/** 商品编码(模糊查询) */
|
||||
productCode?: string;
|
||||
/** 商品编码(模糊查询) */
|
||||
specCode?: string;
|
||||
/** 商品SKU(模糊查询) */
|
||||
skuCode?: string;
|
||||
|
||||
@@ -11,6 +11,8 @@ export namespace ProductVO {
|
||||
companyId: number;
|
||||
/** 商品名称 */
|
||||
name: string;
|
||||
/** 商品编码 */
|
||||
productCode?: string;
|
||||
/** 主图URL(冗余字段) */
|
||||
mainImage?: string;
|
||||
/** 主图图片ID */
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
<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>
|
||||
@@ -0,0 +1,234 @@
|
||||
<script setup lang="ts">
|
||||
import type { ImportTaskVO } from '#/api/ecommerce/import-task';
|
||||
|
||||
import { computed, onMounted, onUnmounted, 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();
|
||||
}
|
||||
|
||||
// 组件挂载时初始化
|
||||
onMounted(() => {
|
||||
importTaskStore.init();
|
||||
});
|
||||
|
||||
// 组件卸载时清理
|
||||
onUnmounted(() => {
|
||||
// 如果没有进行中的任务,断开SSE连接
|
||||
if (!importTaskStore.hasActiveTasks) {
|
||||
importTaskStore.disconnectSse();
|
||||
}
|
||||
});
|
||||
</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 class="text-xs text-gray-400">
|
||||
类型: {{ item.type === 'order' ? '订单导入' : '商品导入' }}
|
||||
</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>
|
||||
@@ -1,7 +1,7 @@
|
||||
<script lang="ts" setup>
|
||||
import type { NotificationItem } from '@vben/layouts';
|
||||
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { computed, onMounted, ref, watch } from 'vue';
|
||||
|
||||
import { AuthenticationLoginExpiredModal } from '@vben/common-ui';
|
||||
import { VBEN_DOC_URL, VBEN_GITHUB_URL } from '@vben/constants';
|
||||
@@ -17,9 +17,10 @@ import { preferences } from '@vben/preferences';
|
||||
import { useAccessStore, useUserStore } from '@vben/stores';
|
||||
import { openWindow } from '@vben/utils';
|
||||
|
||||
import ImportTaskButton from '#/components/ImportTaskButton.vue';
|
||||
import SwitchAccountModal from '#/components/SwitchAccountModal.vue';
|
||||
import { $t } from '#/locales';
|
||||
import { useAuthStore } from '#/store';
|
||||
import { useAuthStore, useImportTaskStore } from '#/store';
|
||||
import LoginForm from '#/views/_core/authentication/login.vue';
|
||||
|
||||
const notifications = ref<NotificationItem[]>([
|
||||
@@ -56,11 +57,17 @@ const notifications = ref<NotificationItem[]>([
|
||||
const userStore = useUserStore();
|
||||
const authStore = useAuthStore();
|
||||
const accessStore = useAccessStore();
|
||||
const importTaskStore = useImportTaskStore();
|
||||
const { destroyWatermark, updateWatermark } = useWatermark();
|
||||
const showDot = computed(() =>
|
||||
notifications.value.some((item) => !item.isRead),
|
||||
);
|
||||
|
||||
// 初始化导入任务store
|
||||
onMounted(() => {
|
||||
importTaskStore.init();
|
||||
});
|
||||
|
||||
// 切换账户模态框引用
|
||||
const switchAccountModalRef = ref();
|
||||
|
||||
@@ -155,6 +162,9 @@ watch(
|
||||
@logout="handleLogout"
|
||||
/>
|
||||
</template>
|
||||
<template #header-right-90>
|
||||
<ImportTaskButton />
|
||||
</template>
|
||||
<template #notification>
|
||||
<Notification
|
||||
:dot="showDot"
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
import type { ImportTaskVO } from '#/api/ecommerce/import-task';
|
||||
import type { PageQueryDTO } from '#/types/common';
|
||||
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
import { defineStore } from 'pinia';
|
||||
|
||||
import {
|
||||
createSseConnection,
|
||||
getImportTaskPageApi,
|
||||
} from '#/api/ecommerce/import-task';
|
||||
|
||||
/**
|
||||
* 导入任务管理 Store
|
||||
*/
|
||||
export const useImportTaskStore = defineStore('import-task', () => {
|
||||
// 任务列表
|
||||
const tasks = ref<ImportTaskVO.ImportTaskInfoVO[]>([]);
|
||||
|
||||
// 分页信息
|
||||
const pagination = ref({
|
||||
current: 1,
|
||||
pageSize: 10,
|
||||
total: 0,
|
||||
});
|
||||
|
||||
// SSE连接
|
||||
const sseConnection = ref<null | ReturnType<typeof createSseConnection>>(
|
||||
null,
|
||||
);
|
||||
const sseConnected = ref(false);
|
||||
|
||||
// 加载状态
|
||||
const loading = ref(false);
|
||||
|
||||
// 控制下拉菜单打开状态
|
||||
const shouldOpenDropdown = ref(false);
|
||||
|
||||
// 计算属性:是否有进行中的任务
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新任务状态(通过SSE接收到的更新)
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 建立SSE连接
|
||||
* @returns Promise,连接建立成功后resolve
|
||||
*/
|
||||
function connectSse(): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
// 如果已经连接且已连接成功,直接resolve
|
||||
if (sseConnection.value && sseConnected.value) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
// 如果已经连接但未成功,先关闭
|
||||
if (sseConnection.value) {
|
||||
disconnectSse();
|
||||
}
|
||||
|
||||
try {
|
||||
const connection = createSseConnection();
|
||||
sseConnection.value = connection;
|
||||
sseConnected.value = false;
|
||||
|
||||
let timeoutId: null | ReturnType<typeof setTimeout> = null;
|
||||
|
||||
// 监听连接成功事件
|
||||
const connectedHandler = (event: MessageEvent) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
if (data.type === 'connected') {
|
||||
sseConnected.value = true;
|
||||
connection.removeEventListener('message', connectedHandler);
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
resolve();
|
||||
}
|
||||
} catch {
|
||||
// 忽略解析错误,继续等待
|
||||
}
|
||||
};
|
||||
|
||||
// 监听连接错误
|
||||
const errorHandler = (_event: MessageEvent) => {
|
||||
connection.removeEventListener('message', connectedHandler);
|
||||
connection.removeEventListener('error', errorHandler);
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
reject(new Error('SSE连接失败'));
|
||||
};
|
||||
|
||||
connection.addEventListener('message', connectedHandler);
|
||||
connection.addEventListener('error', errorHandler);
|
||||
|
||||
// 设置超时,避免无限等待
|
||||
timeoutId = setTimeout(() => {
|
||||
if (!sseConnected.value) {
|
||||
connection.removeEventListener('message', connectedHandler);
|
||||
connection.removeEventListener('error', errorHandler);
|
||||
reject(new Error('SSE连接超时'));
|
||||
}
|
||||
}, 10_000); // 10秒超时
|
||||
|
||||
connection.connect();
|
||||
|
||||
// 连接成功(如果不在等待连接,则正常处理)
|
||||
connection.addEventListener('message', (event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
if (data.type === 'connected') {
|
||||
sseConnected.value = true;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('解析SSE消息失败:', error);
|
||||
}
|
||||
});
|
||||
|
||||
// 接收任务进度更新
|
||||
connection.addEventListener('task_progress', (event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
if (data.type === 'task_progress' && data.task) {
|
||||
updateTask(data.task);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('解析任务进度消息失败:', error);
|
||||
}
|
||||
});
|
||||
|
||||
// 所有任务完成
|
||||
connection.addEventListener('all_tasks_completed', () => {
|
||||
try {
|
||||
// 刷新任务列表
|
||||
fetchTasks(true);
|
||||
} catch (error) {
|
||||
console.error('刷新任务列表失败:', error);
|
||||
}
|
||||
});
|
||||
|
||||
// 连接错误
|
||||
connection.addEventListener('error', (event) => {
|
||||
console.error('SSE连接错误:', event);
|
||||
sseConnected.value = false;
|
||||
// 如果连接关闭,尝试重连
|
||||
if (connection.getReadyState() === EventSource.CLOSED) {
|
||||
// 延迟重连,避免频繁重连
|
||||
setTimeout(() => {
|
||||
if (hasActiveTasks.value) {
|
||||
connectSse();
|
||||
}
|
||||
}, 5000);
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('建立SSE连接失败:', error);
|
||||
sseConnected.value = false;
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 断开SSE连接
|
||||
*/
|
||||
function disconnectSse() {
|
||||
if (sseConnection.value) {
|
||||
sseConnection.value.disconnect();
|
||||
sseConnection.value = null;
|
||||
sseConnected.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化:获取第一页任务
|
||||
*/
|
||||
async function init() {
|
||||
await fetchTasks(true);
|
||||
|
||||
// 如果有进行中的任务,建立SSE连接
|
||||
if (hasActiveTasks.value && !sseConnection.value) {
|
||||
connectSse();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置store
|
||||
*/
|
||||
function $reset() {
|
||||
tasks.value = [];
|
||||
pagination.value = {
|
||||
current: 1,
|
||||
pageSize: 10,
|
||||
total: 0,
|
||||
};
|
||||
disconnectSse();
|
||||
loading.value = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开下拉菜单
|
||||
*/
|
||||
function openDropdown() {
|
||||
shouldOpenDropdown.value = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭下拉菜单
|
||||
*/
|
||||
function closeDropdown() {
|
||||
shouldOpenDropdown.value = false;
|
||||
}
|
||||
|
||||
return {
|
||||
tasks,
|
||||
pagination,
|
||||
sseConnection,
|
||||
sseConnected,
|
||||
loading,
|
||||
shouldOpenDropdown,
|
||||
hasActiveTasks,
|
||||
activeTaskCount,
|
||||
fetchTasks,
|
||||
updateTask,
|
||||
connectSse,
|
||||
disconnectSse,
|
||||
init,
|
||||
openDropdown,
|
||||
closeDropdown,
|
||||
$reset,
|
||||
};
|
||||
});
|
||||
@@ -1 +1,2 @@
|
||||
export * from './auth';
|
||||
export * from './import-task';
|
||||
|
||||
+293
-12
@@ -1,5 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
import type { ImportFieldDefVO } from '#/api/ecommerce/import-field-def';
|
||||
import type {
|
||||
ImportMappingDTO,
|
||||
ImportMappingVO,
|
||||
} from '#/api/ecommerce/import-mapping';
|
||||
import type { ImportTaskDTO } from '#/api/ecommerce/import-task';
|
||||
import type { ShopVO } from '#/api/shop/shop/types';
|
||||
|
||||
@@ -7,12 +11,37 @@ import { computed, ref } from 'vue';
|
||||
|
||||
import { useVbenModal } from '@vben/common-ui';
|
||||
|
||||
import { Button, Form, message, Select, Spin, Steps } from 'ant-design-vue';
|
||||
import {
|
||||
Button,
|
||||
Form,
|
||||
Input,
|
||||
message,
|
||||
Select,
|
||||
Spin,
|
||||
Steps,
|
||||
} from 'ant-design-vue';
|
||||
|
||||
import { getFieldDefsByTypeApi } from '#/api/ecommerce/import-field-def';
|
||||
import {
|
||||
createImportMappingApi,
|
||||
getImportMappingPageApi,
|
||||
} from '#/api/ecommerce/import-mapping';
|
||||
import { createImportTaskApi } from '#/api/ecommerce/import-task';
|
||||
import { uploadFileApi } from '#/api/media/file';
|
||||
import { getShopPageApi } from '#/api/shop/shop';
|
||||
import { useImportTaskStore } from '#/store';
|
||||
|
||||
// 定义映射项数据结构
|
||||
interface FieldMappingItem {
|
||||
/** 数据库字段名 */
|
||||
fieldName: string;
|
||||
/** 中文字段名 */
|
||||
fieldLabel: string;
|
||||
/** 文件字段名(CSV列名) */
|
||||
fileFieldName?: string;
|
||||
/** 是否必填 */
|
||||
required: boolean;
|
||||
}
|
||||
|
||||
defineOptions({ name: 'CreateImportTaskModal' });
|
||||
|
||||
@@ -54,9 +83,35 @@ const fieldMappings = ref<
|
||||
>
|
||||
>({});
|
||||
|
||||
// 映射模板相关
|
||||
const mappingTemplates = ref<ImportMappingVO.ImportMappingInfoVO[]>([]);
|
||||
const selectedTemplateId = ref<number | undefined>();
|
||||
const templateLoading = ref(false);
|
||||
const savingTemplate = ref(false);
|
||||
const templateName = ref('');
|
||||
|
||||
// 创建保存模板的 vben modal
|
||||
const [SaveTemplateModal, saveTemplateModalApi] = useVbenModal({
|
||||
draggable: true,
|
||||
class: 'w-[500px]',
|
||||
title: '保存映射模板',
|
||||
showCancelButton: true,
|
||||
showConfirmButton: true,
|
||||
confirmText: '保存',
|
||||
cancelText: '取消',
|
||||
onConfirm: handleConfirmSaveTemplate,
|
||||
onCancel() {
|
||||
templateName.value = '';
|
||||
saveTemplateModalApi.close();
|
||||
},
|
||||
});
|
||||
|
||||
// 表单引用
|
||||
const formRef = ref();
|
||||
|
||||
// 导入任务store
|
||||
const importTaskStore = useImportTaskStore();
|
||||
|
||||
// 计算属性:必填字段是否都已绑定
|
||||
const canGoToNextStep = computed(() => {
|
||||
if (currentStep.value === 0) {
|
||||
@@ -167,6 +222,153 @@ const fetchFieldDefs = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
// 获取映射模板列表
|
||||
const fetchMappingTemplates = async () => {
|
||||
try {
|
||||
templateLoading.value = true;
|
||||
const result = await getImportMappingPageApi({
|
||||
page: 1,
|
||||
pageSize: 100,
|
||||
filters: {
|
||||
type: 'order',
|
||||
},
|
||||
});
|
||||
mappingTemplates.value = result.records || [];
|
||||
} 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) {
|
||||
return;
|
||||
}
|
||||
|
||||
const template = mappingTemplates.value.find((t) => t.id === templateId);
|
||||
if (!template) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// 解析模板的 mapping JSON
|
||||
const mappingItems: FieldMappingItem[] = JSON.parse(template.mapping);
|
||||
|
||||
// 根据模板填充字段映射
|
||||
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) {
|
||||
// 检查 CSV 表头中是否存在该字段名
|
||||
const matched = csvHeaders.value.find(
|
||||
(header) => header === templateItem.fileFieldName,
|
||||
);
|
||||
if (matched) {
|
||||
mappedHeader = matched;
|
||||
}
|
||||
}
|
||||
|
||||
mappings[fieldDef.id] = {
|
||||
fieldDef,
|
||||
mappedHeader,
|
||||
};
|
||||
});
|
||||
|
||||
fieldMappings.value = mappings;
|
||||
message.success('已应用映射模板');
|
||||
} catch (error) {
|
||||
console.error('应用映射模板失败:', error);
|
||||
message.error('应用映射模板失败,模板格式可能不正确');
|
||||
}
|
||||
};
|
||||
|
||||
// 打开保存模板模态框
|
||||
const handleSaveTemplate = () => {
|
||||
// 验证是否有映射数据
|
||||
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.id];
|
||||
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,
|
||||
}));
|
||||
|
||||
const createData: ImportMappingDTO.CreateImportMappingDTO = {
|
||||
type: 'order',
|
||||
name: templateName.value.trim(),
|
||||
mapping: JSON.stringify(mappingItems),
|
||||
};
|
||||
|
||||
await createImportMappingApi(createData);
|
||||
message.success('保存映射模板成功');
|
||||
templateName.value = '';
|
||||
saveTemplateModalApi.close();
|
||||
// 刷新模板列表
|
||||
await fetchMappingTemplates();
|
||||
// 清空选中的模板
|
||||
selectedTemplateId.value = undefined;
|
||||
} catch (error: any) {
|
||||
console.error('保存映射模板失败:', error);
|
||||
message.error(error?.message || '保存映射模板失败');
|
||||
} finally {
|
||||
savingTemplate.value = false;
|
||||
saveTemplateModalApi.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
// 下一步
|
||||
const handleNext = () => {
|
||||
if (currentStep.value === 0) {
|
||||
@@ -178,6 +380,10 @@ const handleNext = () => {
|
||||
if (fieldDefs.value.length === 0) {
|
||||
fetchFieldDefs();
|
||||
}
|
||||
// 加载映射模板列表
|
||||
if (mappingTemplates.value.length === 0) {
|
||||
fetchMappingTemplates();
|
||||
}
|
||||
} else if (currentStep.value === 1) {
|
||||
// 验证必填字段
|
||||
const requiredFields = fieldDefs.value.filter((f) => f.required);
|
||||
@@ -218,29 +424,56 @@ const handleCreateTask = async () => {
|
||||
try {
|
||||
loading.value = true;
|
||||
|
||||
// 确保SSE连接已建立(如果还没有连接,先建立连接)
|
||||
if (!importTaskStore.sseConnection || !importTaskStore.sseConnected) {
|
||||
message.loading('正在建立连接...', 0);
|
||||
try {
|
||||
await importTaskStore.connectSse();
|
||||
message.destroy();
|
||||
} catch (error: any) {
|
||||
message.destroy();
|
||||
message.error(
|
||||
error?.message || '建立SSE连接失败,无法实时接收任务进度',
|
||||
);
|
||||
// 即使连接失败,也允许继续创建任务
|
||||
}
|
||||
}
|
||||
|
||||
// 先上传文件
|
||||
message.loading('正在上传文件...', 0);
|
||||
const fileInfo = await uploadFileApi(selectedFile.value);
|
||||
message.destroy();
|
||||
|
||||
// 构建字段映射 JSON
|
||||
const mapping: Record<string, string> = {};
|
||||
Object.values(fieldMappings.value).forEach((m) => {
|
||||
if (m.mappedHeader) {
|
||||
mapping[m.fieldDef.fieldName] = m.mappedHeader;
|
||||
}
|
||||
});
|
||||
// 构建字段映射 JSON(基于 ImportFieldDefInfoVO 结构)
|
||||
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 createData: ImportTaskDTO.CreateImportTaskDTO = {
|
||||
shopId: selectedShopId.value!,
|
||||
type: 'order',
|
||||
fileName: selectedFile.value.name,
|
||||
filePath: fileInfo.url,
|
||||
mapping: JSON.stringify(mapping),
|
||||
mapping: JSON.stringify(mappingItems),
|
||||
};
|
||||
|
||||
await createImportTaskApi(createData);
|
||||
const task = await createImportTaskApi(createData);
|
||||
message.success('创建导入任务成功');
|
||||
|
||||
// 更新store中的任务列表
|
||||
importTaskStore.updateTask(task);
|
||||
|
||||
// 刷新任务列表
|
||||
await importTaskStore.fetchTasks(true);
|
||||
|
||||
// 创建成功后,自动展开任务下拉菜单
|
||||
importTaskStore.openDropdown();
|
||||
|
||||
// 创建成功后,重置状态并关闭
|
||||
currentStep.value = 0;
|
||||
selectedShopId.value = undefined;
|
||||
@@ -354,8 +587,41 @@ const shopOptions = computed(() => {
|
||||
|
||||
<!-- 第二步:字段映射 -->
|
||||
<div v-if="currentStep === 1" class="py-4">
|
||||
<div class="mb-4 text-sm text-gray-600">
|
||||
请为每个订单字段选择对应的CSV列,必填字段必须绑定
|
||||
<div class="mb-4 flex items-center justify-between">
|
||||
<div class="text-sm text-gray-600">
|
||||
请为每个订单字段选择对应的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">
|
||||
暂无模板
|
||||
</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">
|
||||
({{ new Date(template.createTime).toLocaleDateString() }})
|
||||
</span>
|
||||
</Select.Option>
|
||||
</Select>
|
||||
<Button @click="handleSaveTemplate">保存为模板</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="max-h-[400px] space-y-4 overflow-y-auto">
|
||||
<div
|
||||
@@ -452,6 +718,21 @@ const shopOptions = computed(() => {
|
||||
</div>
|
||||
</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>
|
||||
</Modal>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -89,6 +89,14 @@ const handleManageSpecs = (product: ProductVO.Info) => {
|
||||
{{ product.name }}
|
||||
</div>
|
||||
|
||||
<!-- 商品编码 -->
|
||||
<div
|
||||
v-if="product.productCode"
|
||||
class="mb-2 text-xs text-gray-500 dark:text-gray-400"
|
||||
>
|
||||
编码: {{ product.productCode }}
|
||||
</div>
|
||||
|
||||
<!-- 规格信息预览 -->
|
||||
<div
|
||||
v-if="product.specs && product.specs.length > 0"
|
||||
|
||||
+22
-6
@@ -66,6 +66,7 @@ const imageLoadError = ref(false); // 图片加载错误状态
|
||||
// 表单数据
|
||||
const formData = ref({
|
||||
name: '',
|
||||
productCode: '',
|
||||
specCode: '',
|
||||
skuCode: '',
|
||||
mainImageId: undefined as number | undefined,
|
||||
@@ -93,6 +94,7 @@ function initFormData() {
|
||||
const productData = currentProductData.value as any;
|
||||
formData.value = {
|
||||
name: currentProductData.value.name || '',
|
||||
productCode: currentProductData.value.productCode || '',
|
||||
specCode: productData.specCode || '',
|
||||
skuCode: productData.skuCode || '',
|
||||
mainImageId: undefined,
|
||||
@@ -105,6 +107,7 @@ function initFormData() {
|
||||
// 创建模式 - 如果有传入的productData,则使用它来初始化表单
|
||||
formData.value = {
|
||||
name: currentProductData.value?.name || '',
|
||||
productCode: currentProductData.value?.productCode || '',
|
||||
specCode: '',
|
||||
skuCode: '',
|
||||
mainImageId: undefined,
|
||||
@@ -174,15 +177,21 @@ async function handleSubmit() {
|
||||
'id' in currentProductData.value &&
|
||||
currentProductData.value.id
|
||||
) {
|
||||
await updateProductApi(
|
||||
currentProductData.value.id,
|
||||
submitData as ProductDTO.Update,
|
||||
);
|
||||
const updateData: ProductDTO.Update = {
|
||||
name: submitData.name,
|
||||
productCode: submitData.productCode || undefined,
|
||||
specCode: submitData.specCode || undefined,
|
||||
skuCode: submitData.skuCode || undefined,
|
||||
mainImageId: submitData.mainImageId,
|
||||
costPrice: submitData.costPrice,
|
||||
};
|
||||
await updateProductApi(currentProductData.value.id, updateData);
|
||||
message.success('更新成功');
|
||||
} else {
|
||||
// 创建模式:统一使用创建接口,规格信息作为可选字段
|
||||
const createData: ProductDTO.Create = {
|
||||
name: submitData.name,
|
||||
productCode: submitData.productCode || undefined,
|
||||
mainImageId: submitData.mainImageId,
|
||||
...(specs.value.length > 0 && { specs: specs.value }),
|
||||
};
|
||||
@@ -512,8 +521,15 @@ onUnmounted(() => {
|
||||
<Input v-model:value="formData.name" placeholder="请输入商品名称" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item v-if="isEdit" label="商品编码" name="specCode">
|
||||
<Input v-model:value="formData.specCode" placeholder="请输入商品编码" />
|
||||
<Form.Item label="商品编码" name="productCode">
|
||||
<Input
|
||||
v-model:value="formData.productCode"
|
||||
placeholder="请输入商品编码"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item v-if="isEdit" label="规格编码" name="specCode">
|
||||
<Input v-model:value="formData.specCode" placeholder="请输入规格编码" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item v-if="isEdit" label="商品SKU" name="skuCode">
|
||||
|
||||
@@ -31,6 +31,7 @@ const productGridViewRef = ref<null | { refreshTable: () => void }>(null);
|
||||
// 搜索表单
|
||||
const searchForm = ref({
|
||||
name: '',
|
||||
productCode: '',
|
||||
specCode: '',
|
||||
skuCode: '',
|
||||
minCostPrice: undefined as number | undefined,
|
||||
|
||||
+17
-1
@@ -30,6 +30,7 @@ const props = defineProps<{
|
||||
maxCostPrice?: number;
|
||||
minCostPrice?: number;
|
||||
name: string;
|
||||
productCode: string;
|
||||
skuCode: string;
|
||||
specCode: string;
|
||||
};
|
||||
@@ -54,6 +55,7 @@ const scrollContainerRef = ref<HTMLElement | null>(null);
|
||||
// 本地搜索表单副本(用于 v-model)
|
||||
const localSearchForm = ref({
|
||||
name: props.searchForm.name,
|
||||
productCode: props.searchForm.productCode,
|
||||
specCode: props.searchForm.specCode,
|
||||
skuCode: props.searchForm.skuCode,
|
||||
minCostPrice: props.searchForm.minCostPrice,
|
||||
@@ -66,12 +68,14 @@ watch(
|
||||
(newForm) => {
|
||||
if (
|
||||
localSearchForm.value.name !== newForm.name ||
|
||||
localSearchForm.value.productCode !== newForm.productCode ||
|
||||
localSearchForm.value.specCode !== newForm.specCode ||
|
||||
localSearchForm.value.skuCode !== newForm.skuCode ||
|
||||
localSearchForm.value.minCostPrice !== newForm.minCostPrice ||
|
||||
localSearchForm.value.maxCostPrice !== newForm.maxCostPrice
|
||||
) {
|
||||
localSearchForm.value.name = newForm.name;
|
||||
localSearchForm.value.productCode = newForm.productCode;
|
||||
localSearchForm.value.specCode = newForm.specCode;
|
||||
localSearchForm.value.skuCode = newForm.skuCode;
|
||||
localSearchForm.value.minCostPrice = newForm.minCostPrice;
|
||||
@@ -92,6 +96,7 @@ watch(
|
||||
(newForm) => {
|
||||
if (
|
||||
props.searchForm.name !== newForm.name ||
|
||||
props.searchForm.productCode !== newForm.productCode ||
|
||||
props.searchForm.specCode !== newForm.specCode ||
|
||||
props.searchForm.skuCode !== newForm.skuCode ||
|
||||
props.searchForm.minCostPrice !== newForm.minCostPrice ||
|
||||
@@ -114,6 +119,7 @@ const loadProductList = async (reset = false) => {
|
||||
pageSize: pageSize.value,
|
||||
filters: {
|
||||
name: localSearchForm.value.name || undefined,
|
||||
productCode: localSearchForm.value.productCode || undefined,
|
||||
specCode: localSearchForm.value.specCode || undefined,
|
||||
skuCode: localSearchForm.value.skuCode || undefined,
|
||||
minCostPrice: localSearchForm.value.minCostPrice,
|
||||
@@ -157,6 +163,7 @@ const handleSearch = () => {
|
||||
const handleReset = () => {
|
||||
localSearchForm.value = {
|
||||
name: '',
|
||||
productCode: '',
|
||||
specCode: '',
|
||||
skuCode: '',
|
||||
minCostPrice: undefined,
|
||||
@@ -235,13 +242,22 @@ onUnmounted(() => {
|
||||
</Form.Item>
|
||||
<Form.Item label="商品编码" class="mb-0">
|
||||
<Input
|
||||
v-model:value="localSearchForm.specCode"
|
||||
v-model:value="localSearchForm.productCode"
|
||||
placeholder="请输入商品编码"
|
||||
style="width: 150px"
|
||||
allow-clear
|
||||
@press-enter="handleSearch"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item label="规格编码" class="mb-0">
|
||||
<Input
|
||||
v-model:value="localSearchForm.specCode"
|
||||
placeholder="请输入规格编码"
|
||||
style="width: 150px"
|
||||
allow-clear
|
||||
@press-enter="handleSearch"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item label="商品SKU" class="mb-0">
|
||||
<Input
|
||||
v-model:value="localSearchForm.skuCode"
|
||||
|
||||
+21
-1
@@ -17,6 +17,7 @@ const props = defineProps<{
|
||||
maxCostPrice?: number;
|
||||
minCostPrice?: number;
|
||||
name: string;
|
||||
productCode: string;
|
||||
skuCode: string;
|
||||
specCode: string;
|
||||
};
|
||||
@@ -35,6 +36,7 @@ const loading = ref(false);
|
||||
// 本地搜索表单副本(用于 v-model)
|
||||
const localSearchForm = ref({
|
||||
name: props.searchForm.name,
|
||||
productCode: props.searchForm.productCode,
|
||||
specCode: props.searchForm.specCode,
|
||||
skuCode: props.searchForm.skuCode,
|
||||
minCostPrice: props.searchForm.minCostPrice,
|
||||
@@ -47,12 +49,14 @@ watch(
|
||||
(newForm) => {
|
||||
if (
|
||||
localSearchForm.value.name !== newForm.name ||
|
||||
localSearchForm.value.productCode !== newForm.productCode ||
|
||||
localSearchForm.value.specCode !== newForm.specCode ||
|
||||
localSearchForm.value.skuCode !== newForm.skuCode ||
|
||||
localSearchForm.value.minCostPrice !== newForm.minCostPrice ||
|
||||
localSearchForm.value.maxCostPrice !== newForm.maxCostPrice
|
||||
) {
|
||||
localSearchForm.value.name = newForm.name;
|
||||
localSearchForm.value.productCode = newForm.productCode;
|
||||
localSearchForm.value.specCode = newForm.specCode;
|
||||
localSearchForm.value.skuCode = newForm.skuCode;
|
||||
localSearchForm.value.minCostPrice = newForm.minCostPrice;
|
||||
@@ -69,6 +73,7 @@ watch(
|
||||
(newForm) => {
|
||||
if (
|
||||
props.searchForm.name !== newForm.name ||
|
||||
props.searchForm.productCode !== newForm.productCode ||
|
||||
props.searchForm.specCode !== newForm.specCode ||
|
||||
props.searchForm.skuCode !== newForm.skuCode ||
|
||||
props.searchForm.minCostPrice !== newForm.minCostPrice ||
|
||||
@@ -99,6 +104,12 @@ const gridOptions: VxeGridProps<any> = {
|
||||
minWidth: 200,
|
||||
showOverflow: 'tooltip' as const,
|
||||
},
|
||||
{
|
||||
field: 'productCode',
|
||||
title: '商品编码',
|
||||
minWidth: 150,
|
||||
showOverflow: 'tooltip' as const,
|
||||
},
|
||||
{
|
||||
title: '规格数量',
|
||||
minWidth: 100,
|
||||
@@ -166,6 +177,7 @@ const gridOptions: VxeGridProps<any> = {
|
||||
pageSize: page.pageSize,
|
||||
filters: {
|
||||
name: localSearchForm.value.name || undefined,
|
||||
productCode: localSearchForm.value.productCode || undefined,
|
||||
specCode: localSearchForm.value.specCode || undefined,
|
||||
skuCode: localSearchForm.value.skuCode || undefined,
|
||||
minCostPrice: localSearchForm.value.minCostPrice,
|
||||
@@ -208,9 +220,17 @@ const formOptions = computed(() => ({
|
||||
componentProps: {
|
||||
placeholder: '请输入商品编码',
|
||||
},
|
||||
fieldName: 'specCode',
|
||||
fieldName: 'productCode',
|
||||
label: '商品编码',
|
||||
},
|
||||
{
|
||||
component: 'Input',
|
||||
componentProps: {
|
||||
placeholder: '请输入规格编码',
|
||||
},
|
||||
fieldName: 'specCode',
|
||||
label: '规格编码',
|
||||
},
|
||||
{
|
||||
component: 'Input',
|
||||
componentProps: {
|
||||
|
||||
Reference in New Issue
Block a user