ec_order: 去掉 product_id,改为冗余 spec_code 字段

- 迁移SQL: V20260603__ec_order_drop_product_id_add_spec_code.sql
- Order 实体/DTO/VO: product_id → spec_code,字段联路调整
- OrderImportProcessor / OrderServiceImpl: 适配新字段
- 各 Overview Service: 更新订单关联逻辑
- 前端: OrderFormModal / index / types 同步适配
This commit is contained in:
小蟑螂
2026-05-03 23:06:20 +08:00
parent 8adffcc7e9
commit 63e54279c0
16 changed files with 230 additions and 105 deletions
+2 -3
View File
@@ -123,8 +123,8 @@ CREATE TABLE `ec_order` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '订单ID', `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '订单ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID', `company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
`shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID', `shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID',
`product_id` bigint UNSIGNED NOT NULL COMMENT '商品ID',
`product_spec_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '商品规格ID', `product_spec_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '商品规格ID',
`spec_code` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '规格编码(冗余,便于查询)',
`status_id` bigint UNSIGNED NOT NULL COMMENT '订单状态ID', `status_id` bigint UNSIGNED NOT NULL COMMENT '订单状态ID',
`platform_order_no` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '平台订单号', `platform_order_no` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '平台订单号',
`link_product_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '链接商品名称', `link_product_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '链接商品名称',
@@ -147,8 +147,8 @@ CREATE TABLE `ec_order` (
INDEX `idx_company_shop_time`(`company_id` ASC, `shop_id` ASC, `order_time` ASC) USING BTREE, INDEX `idx_company_shop_time`(`company_id` ASC, `shop_id` ASC, `order_time` ASC) USING BTREE,
INDEX `idx_status_id`(`status_id` ASC) USING BTREE, INDEX `idx_status_id`(`status_id` ASC) USING BTREE,
INDEX `idx_platform_order_no`(`platform_order_no` ASC) USING BTREE, INDEX `idx_platform_order_no`(`platform_order_no` ASC) USING BTREE,
INDEX `idx_product_id`(`product_id` ASC) USING BTREE,
INDEX `idx_product_spec_id`(`product_spec_id` ASC) USING BTREE, INDEX `idx_product_spec_id`(`product_spec_id` ASC) USING BTREE,
INDEX `idx_spec_code`(`spec_code` ASC) USING BTREE,
INDEX `idx_import_task_id`(`import_task_id` ASC) USING BTREE, INDEX `idx_import_task_id`(`import_task_id` ASC) USING BTREE,
INDEX `idx_confirm`(`confirm` ASC) USING BTREE, INDEX `idx_confirm`(`confirm` ASC) USING BTREE,
INDEX `fk_ec_order_creator`(`create_by` ASC) USING BTREE, INDEX `fk_ec_order_creator`(`create_by` ASC) USING BTREE,
@@ -158,7 +158,6 @@ CREATE TABLE `ec_order` (
CONSTRAINT `fk_ec_order_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_ec_order_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ec_order_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `fk_ec_order_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_ec_order_import_task` FOREIGN KEY (`import_task_id`) REFERENCES `ec_import_tasks` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `fk_ec_order_import_task` FOREIGN KEY (`import_task_id`) REFERENCES `ec_import_tasks` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_ec_order_product` FOREIGN KEY (`product_id`) REFERENCES `ec_product` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ec_order_product_spec` FOREIGN KEY (`product_spec_id`) REFERENCES `ec_product_spec` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `fk_ec_order_product_spec` FOREIGN KEY (`product_spec_id`) REFERENCES `ec_product_spec` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_ec_order_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_ec_order_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ec_order_status` FOREIGN KEY (`status_id`) REFERENCES `ec_order_status` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE, CONSTRAINT `fk_ec_order_status` FOREIGN KEY (`status_id`) REFERENCES `ec_order_status` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE,
@@ -0,0 +1,17 @@
-- ec_order:去掉 product_id,增加冗余 spec_code 并建索引
ALTER TABLE ec_order
ADD COLUMN spec_code varchar(100) NULL COMMENT '规格编码(冗余)' AFTER product_spec_id;
UPDATE ec_order o
INNER JOIN ec_product_spec s ON o.product_spec_id = s.id
SET o.spec_code = s.spec_code
WHERE o.product_spec_id IS NOT NULL;
ALTER TABLE ec_order DROP FOREIGN KEY fk_ec_order_product;
ALTER TABLE ec_order DROP INDEX idx_product_id;
ALTER TABLE ec_order DROP COLUMN product_id;
CREATE INDEX idx_spec_code ON ec_order (spec_code);
@@ -939,7 +939,7 @@ public class OrderImportProcessor {
String specCode = dto.getPlatformOrderNo() != null ? null : null; // DTO中无specCode,需从record重新获取 String specCode = dto.getPlatformOrderNo() != null ? null : null; // DTO中无specCode,需从record重新获取
// 重新从 CSVRecord 获取 specCode(Worker 不能直接访问 CSVRecordParser) // 重新从 CSVRecord 获取 specCode(Worker 不能直接访问 CSVRecordParser)
// 方案:从 DTO 中取,或者在 parseOrderFromCSV 时预存 // 方案:从 DTO 中取,或者在 parseOrderFromCSV 时预存
// 由于 parseOrderFromCSV 已填充了 productId/specId,此处只处理找不到的情况 // 由于 parseOrderFromCSV 已填充了 productSpecId 等,此处只处理找不到的情况
if (dto.getProductSpecId() == null) { if (dto.getProductSpecId() == null) {
// 重新获取关键字段 // 重新获取关键字段
@@ -1008,8 +1008,9 @@ public class OrderImportProcessor {
throw new BusinessException("无法创建商品规格"); throw new BusinessException("无法创建商品规格");
} }
dto.setProductId(productSpec.getProductId()); dto.setShopRelationProductId(productSpec.getProductId());
dto.setProductSpecId(productSpec.getId()); dto.setProductSpecId(productSpec.getId());
dto.setSpecCode(productSpec.getSpecCode());
dto.setConfirm(isNewSpecCreated ? 0 : 1); dto.setConfirm(isNewSpecCreated ? 0 : 1);
// linkProductName / linkSpecName fallback // linkProductName / linkSpecName fallback
@@ -1227,8 +1228,8 @@ public class OrderImportProcessor {
|| fieldMapping.containsKey("link_product_name") || fieldMapping.containsKey("link_product_name")
|| fieldMapping.containsKey("link_spec_name"); || fieldMapping.containsKey("link_spec_name");
if (compareProductBlock) { if (compareProductBlock) {
if (!Objects.equals(db.getProductId(), incoming.getProductId())) return false;
if (!Objects.equals(db.getProductSpecId(), incoming.getProductSpecId())) return false; if (!Objects.equals(db.getProductSpecId(), incoming.getProductSpecId())) return false;
if (!normStrEq(db.getSpecCode(), incoming.getSpecCode())) return false;
if (!normStrEq(db.getLinkProductName(), incoming.getLinkProductName())) return false; if (!normStrEq(db.getLinkProductName(), incoming.getLinkProductName())) return false;
if (!normStrEq(db.getLinkSpecName(), incoming.getLinkSpecName())) return false; if (!normStrEq(db.getLinkSpecName(), incoming.getLinkSpecName())) return false;
} }
@@ -1296,8 +1297,8 @@ public class OrderImportProcessor {
c.setShopId(o.getShopId()); c.setShopId(o.getShopId());
c.setPlatformOrderNo(o.getPlatformOrderNo()); c.setPlatformOrderNo(o.getPlatformOrderNo());
c.setStatusId(o.getStatusId()); c.setStatusId(o.getStatusId());
c.setProductId(o.getProductId());
c.setProductSpecId(o.getProductSpecId()); c.setProductSpecId(o.getProductSpecId());
c.setSpecCode(o.getSpecCode());
c.setLinkProductName(o.getLinkProductName()); c.setLinkProductName(o.getLinkProductName());
c.setLinkSpecName(o.getLinkSpecName()); c.setLinkSpecName(o.getLinkSpecName());
c.setQuantity(o.getQuantity()); c.setQuantity(o.getQuantity());
@@ -1590,8 +1591,8 @@ public class OrderImportProcessor {
order.setShopId(dto.getShopId()); order.setShopId(dto.getShopId());
order.setPlatformOrderNo(dto.getPlatformOrderNo()); order.setPlatformOrderNo(dto.getPlatformOrderNo());
order.setStatusId(dto.getStatusId()); order.setStatusId(dto.getStatusId());
order.setProductId(dto.getProductId());
order.setProductSpecId(dto.getProductSpecId()); order.setProductSpecId(dto.getProductSpecId());
order.setSpecCode(dto.getSpecCode());
order.setLinkProductName(dto.getLinkProductName()); order.setLinkProductName(dto.getLinkProductName());
order.setLinkSpecName(dto.getLinkSpecName()); order.setLinkSpecName(dto.getLinkSpecName());
order.setQuantity(dto.getQuantity()); order.setQuantity(dto.getQuantity());
@@ -1653,7 +1654,11 @@ public class OrderImportProcessor {
* 入队店铺-商品关联(主线程调用) * 入队店铺-商品关联(主线程调用)
*/ */
private void queueShopProductRelation(CreateOrderDTO orderDTO, ImportRuntimeContext context) { private void queueShopProductRelation(CreateOrderDTO orderDTO, ImportRuntimeContext context) {
String relationKey = context.buildRelationKey(orderDTO.getShopId(), orderDTO.getProductId()); Long relationPid = orderDTO.getShopRelationProductId();
if (relationPid == null) {
return;
}
String relationKey = context.buildRelationKey(orderDTO.getShopId(), relationPid);
if (context.existingRelationKeys.contains(relationKey) if (context.existingRelationKeys.contains(relationKey)
|| context.pendingRelationKeys.contains(relationKey)) { || context.pendingRelationKeys.contains(relationKey)) {
return; return;
@@ -1661,7 +1666,7 @@ public class OrderImportProcessor {
ShopProductRelationPO relation = new ShopProductRelationPO(); ShopProductRelationPO relation = new ShopProductRelationPO();
relation.setCompanyId(context.getCompanyId()); relation.setCompanyId(context.getCompanyId());
relation.setShopId(orderDTO.getShopId()); relation.setShopId(orderDTO.getShopId());
relation.setProductId(orderDTO.getProductId()); relation.setProductId(relationPid);
relation.setSortOrder(0); relation.setSortOrder(0);
relation.setCreateBy(context.getCreateBy()); relation.setCreateBy(context.getCreateBy());
context.pendingRelations.add(relation); context.pendingRelations.add(relation);
@@ -1,5 +1,6 @@
package top.xyquan.ecomdmbbackend.modules.ecom.order.model.dto; package top.xyquan.ecomdmbbackend.modules.ecom.order.model.dto;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive; import jakarta.validation.constraints.Positive;
@@ -59,17 +60,24 @@ public class CreateOrderDTO {
private Boolean orderTimeEmptyInInput; private Boolean orderTimeEmptyInInput;
/** /**
* 商品ID * 商品规格ID(下单必选,商品由规格关联)
*/ */
@Schema(description = "商品ID", example = "1", requiredMode = Schema.RequiredMode.REQUIRED) @Schema(description = "商品规格ID", example = "1", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "商品ID不能为空") @NotNull(message = "商品规格ID不能为空")
private Long productId; private Long productSpecId;
/** /**
* 商品规格ID * 规格编码(可选;未传时服务端按规格ID补全写入订单)
*/ */
@Schema(description = "商品规格ID", example = "1") @Schema(description = "规格编码", example = "SKU001")
private Long productSpecId; private String specCode;
/**
* 导入流程用:店铺-商品关联所需商品ID,不入库,不对外序列化。
*/
@JsonIgnore
@Schema(hidden = true)
private Long shopRelationProductId;
/** /**
* 链接商品名称(冗余存储) * 链接商品名称(冗余存储)
@@ -47,18 +47,18 @@ public class UpdateOrderDTO {
@NotNull(message = "下单时间不能为空") @NotNull(message = "下单时间不能为空")
private LocalDateTime orderTime; private LocalDateTime orderTime;
/**
* 商品ID
*/
@Schema(description = "商品ID", example = "1")
private Long productId;
/** /**
* 商品规格ID * 商品规格ID
*/ */
@Schema(description = "商品规格ID", example = "1") @Schema(description = "商品规格ID", example = "1")
private Long productSpecId; private Long productSpecId;
/**
* 规格编码
*/
@Schema(description = "规格编码", example = "SKU001")
private String specCode;
/** /**
* 链接商品名称(冗余存储) * 链接商品名称(冗余存储)
*/ */
@@ -45,18 +45,18 @@ public class OrderPO {
@TableField("status_id") @TableField("status_id")
private Long statusId; private Long statusId;
/**
* 商品ID
*/
@TableField("product_id")
private Long productId;
/** /**
* 商品规格ID * 商品规格ID
*/ */
@TableField("product_spec_id") @TableField("product_spec_id")
private Long productSpecId; private Long productSpecId;
/**
* 规格编码(冗余,与 ec_product_spec.spec_code 一致)
*/
@TableField("spec_code")
private String specCode;
/** /**
* 链接商品名称(冗余存储) * 链接商品名称(冗余存储)
*/ */
@@ -95,18 +95,18 @@ public class OrderVO {
@Schema(description = "更新人ID", example = "1") @Schema(description = "更新人ID", example = "1")
private Long updateBy; private Long updateBy;
/**
* 商品ID
*/
@Schema(description = "商品ID", example = "1")
private Long productId;
/** /**
* 商品规格ID * 商品规格ID
*/ */
@Schema(description = "商品规格ID", example = "1") @Schema(description = "商品规格ID", example = "1")
private Long productSpecId; private Long productSpecId;
/**
* 规格编码
*/
@Schema(description = "规格编码", example = "SKU001")
private String specCode;
/** /**
* 链接商品名称(冗余存储) * 链接商品名称(冗余存储)
*/ */
@@ -78,22 +78,15 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
throw new BusinessException("店铺不存在"); throw new BusinessException("店铺不存在");
} }
// 验证商品是否存在且属于当前公司 ProductSpecPO productSpec = productSpecService.getById(createOrderDTO.getProductSpecId());
ProductPO product = productService.getById(createOrderDTO.getProductId()); if (productSpec == null || !productSpec.getCompanyId().equals(companyId)) {
throw new BusinessException("商品规格不存在");
}
ProductPO product = productService.getById(productSpec.getProductId());
if (product == null || !product.getCompanyId().equals(companyId)) { if (product == null || !product.getCompanyId().equals(companyId)) {
throw new BusinessException("商品不存在"); throw new BusinessException("商品不存在");
} }
// 验证商品规格是否存在且属于当前公司(如果提供了规格ID)
ProductSpecPO productSpec = null;
if (createOrderDTO.getProductSpecId() != null) {
productSpec = productSpecService.getById(createOrderDTO.getProductSpecId());
if (productSpec == null || !productSpec.getCompanyId().equals(companyId) ||
!productSpec.getProductId().equals(createOrderDTO.getProductId())) {
throw new BusinessException("商品规格不存在或不属于该商品");
}
}
// 验证订单状态是否存在且属于当前公司 // 验证订单状态是否存在且属于当前公司
OrderStatusPO orderStatus = orderStatusService.getById(createOrderDTO.getStatusId()); OrderStatusPO orderStatus = orderStatusService.getById(createOrderDTO.getStatusId());
if (orderStatus == null || !orderStatus.getCompanyId().equals(companyId)) { if (orderStatus == null || !orderStatus.getCompanyId().equals(companyId)) {
@@ -116,8 +109,10 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
order.setShopId(createOrderDTO.getShopId()); order.setShopId(createOrderDTO.getShopId());
order.setPlatformOrderNo(createOrderDTO.getPlatformOrderNo()); order.setPlatformOrderNo(createOrderDTO.getPlatformOrderNo());
order.setStatusId(createOrderDTO.getStatusId()); order.setStatusId(createOrderDTO.getStatusId());
order.setProductId(createOrderDTO.getProductId());
order.setProductSpecId(createOrderDTO.getProductSpecId()); order.setProductSpecId(createOrderDTO.getProductSpecId());
String specCodeIn = createOrderDTO.getSpecCode();
order.setSpecCode(specCodeIn != null && !specCodeIn.trim().isEmpty()
? specCodeIn.trim() : productSpec.getSpecCode());
order.setLinkProductName(createOrderDTO.getLinkProductName()); order.setLinkProductName(createOrderDTO.getLinkProductName());
order.setLinkSpecName(createOrderDTO.getLinkSpecName()); order.setLinkSpecName(createOrderDTO.getLinkSpecName());
order.setQuantity(createOrderDTO.getQuantity()); order.setQuantity(createOrderDTO.getQuantity());
@@ -147,17 +142,14 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
if (shop == null || !shop.getCompanyId().equals(companyId)) { if (shop == null || !shop.getCompanyId().equals(companyId)) {
throw new BusinessException("店铺不存在"); throw new BusinessException("店铺不存在");
} }
ProductPO product = productService.getById(createOrderDTO.getProductId()); ProductSpecPO productSpec = productSpecService.getById(createOrderDTO.getProductSpecId());
if (productSpec == null || !productSpec.getCompanyId().equals(companyId)) {
throw new BusinessException("商品规格不存在");
}
ProductPO product = productService.getById(productSpec.getProductId());
if (product == null || !product.getCompanyId().equals(companyId)) { if (product == null || !product.getCompanyId().equals(companyId)) {
throw new BusinessException("商品不存在"); throw new BusinessException("商品不存在");
} }
if (createOrderDTO.getProductSpecId() != null) {
ProductSpecPO productSpec = productSpecService.getById(createOrderDTO.getProductSpecId());
if (productSpec == null || !productSpec.getCompanyId().equals(companyId)
|| !productSpec.getProductId().equals(createOrderDTO.getProductId())) {
throw new BusinessException("商品规格不存在或不属于该商品");
}
}
OrderStatusPO orderStatus = orderStatusService.getById(createOrderDTO.getStatusId()); OrderStatusPO orderStatus = orderStatusService.getById(createOrderDTO.getStatusId());
if (orderStatus == null || !orderStatus.getCompanyId().equals(companyId)) { if (orderStatus == null || !orderStatus.getCompanyId().equals(companyId)) {
throw new BusinessException("订单状态不存在"); throw new BusinessException("订单状态不存在");
@@ -175,8 +167,10 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
order.setShopId(createOrderDTO.getShopId()); order.setShopId(createOrderDTO.getShopId());
order.setPlatformOrderNo(createOrderDTO.getPlatformOrderNo()); order.setPlatformOrderNo(createOrderDTO.getPlatformOrderNo());
order.setStatusId(createOrderDTO.getStatusId()); order.setStatusId(createOrderDTO.getStatusId());
order.setProductId(createOrderDTO.getProductId());
order.setProductSpecId(createOrderDTO.getProductSpecId()); order.setProductSpecId(createOrderDTO.getProductSpecId());
String specCodeImp = createOrderDTO.getSpecCode();
order.setSpecCode(specCodeImp != null && !specCodeImp.trim().isEmpty()
? specCodeImp.trim() : productSpec.getSpecCode());
order.setLinkProductName(createOrderDTO.getLinkProductName()); order.setLinkProductName(createOrderDTO.getLinkProductName());
order.setLinkSpecName(createOrderDTO.getLinkSpecName()); order.setLinkSpecName(createOrderDTO.getLinkSpecName());
order.setQuantity(createOrderDTO.getQuantity()); order.setQuantity(createOrderDTO.getQuantity());
@@ -313,7 +307,9 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
wrapper.eq(OrderPO::getConfirm, filter.getConfirm()); wrapper.eq(OrderPO::getConfirm, filter.getConfirm());
} }
if (filter.getProductId() != null) { if (filter.getProductId() != null) {
wrapper.eq(OrderPO::getProductId, filter.getProductId()); wrapper.apply(
"EXISTS (SELECT 1 FROM ec_product_spec s WHERE s.id = ec_order.product_spec_id AND s.product_id = {0})",
filter.getProductId());
} }
} }
@@ -433,23 +429,21 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
orderVO.setShop(shopVO); orderVO.setShop(shopVO);
} }
// 设置关联商品信息 // 设置关联商品规格与商品信息(商品经规格关联)
if (order.getProductId() != null) {
ProductPO product = productService.getById(order.getProductId());
if (product != null) {
ProductVO productVO = new ProductVO();
BeanUtils.copyProperties(product, productVO);
orderVO.setProduct(productVO);
}
}
// 设置关联商品规格信息
if (order.getProductSpecId() != null) { if (order.getProductSpecId() != null) {
ProductSpecPO productSpec = productSpecService.getById(order.getProductSpecId()); ProductSpecPO productSpec = productSpecService.getById(order.getProductSpecId());
if (productSpec != null) { if (productSpec != null) {
ProductSpecVO productSpecVO = new ProductSpecVO(); ProductSpecVO productSpecVO = new ProductSpecVO();
BeanUtils.copyProperties(productSpec, productSpecVO); BeanUtils.copyProperties(productSpec, productSpecVO);
orderVO.setProductSpec(productSpecVO); orderVO.setProductSpec(productSpecVO);
if (productSpec.getProductId() != null) {
ProductPO product = productService.getById(productSpec.getProductId());
if (product != null) {
ProductVO productVO = new ProductVO();
BeanUtils.copyProperties(product, productVO);
orderVO.setProduct(productVO);
}
}
} }
} }
@@ -15,7 +15,9 @@ import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CategoryExportDTO; import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CategoryExportDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.vo.CompanyOverviewVO; import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.vo.CompanyOverviewVO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.CategoryExportExcelService; import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.CategoryExportExcelService;
import top.xyquan.ecomdmbbackend.modules.ecom.product.mapper.ProductSpecMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO; import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductSpecPO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService; import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService;
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.mapper.PromotionFeeMapper; import top.xyquan.ecomdmbbackend.modules.ecom.promotion.mapper.PromotionFeeMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.po.PromotionFeePO; import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.po.PromotionFeePO;
@@ -41,6 +43,7 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic
private final PromotionFeeMapper promotionFeeMapper; private final PromotionFeeMapper promotionFeeMapper;
private final BrushOrderMapper brushOrderMapper; private final BrushOrderMapper brushOrderMapper;
private final ProductService productService; private final ProductService productService;
private final ProductSpecMapper productSpecMapper;
private final CategoryService categoryService; private final CategoryService categoryService;
private final ExportStatusRangeHelper exportStatusRangeHelper; private final ExportStatusRangeHelper exportStatusRangeHelper;
@@ -50,6 +53,7 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic
PromotionFeeMapper promotionFeeMapper, PromotionFeeMapper promotionFeeMapper,
BrushOrderMapper brushOrderMapper, BrushOrderMapper brushOrderMapper,
ProductService productService, ProductService productService,
ProductSpecMapper productSpecMapper,
CategoryService categoryService, CategoryService categoryService,
ExportStatusRangeHelper exportStatusRangeHelper) { ExportStatusRangeHelper exportStatusRangeHelper) {
this.currentUserContext = currentUserContext; this.currentUserContext = currentUserContext;
@@ -57,6 +61,7 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic
this.promotionFeeMapper = promotionFeeMapper; this.promotionFeeMapper = promotionFeeMapper;
this.brushOrderMapper = brushOrderMapper; this.brushOrderMapper = brushOrderMapper;
this.productService = productService; this.productService = productService;
this.productSpecMapper = productSpecMapper;
this.categoryService = categoryService; this.categoryService = categoryService;
this.exportStatusRangeHelper = exportStatusRangeHelper; this.exportStatusRangeHelper = exportStatusRangeHelper;
} }
@@ -97,11 +102,22 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic
.le(BrushOrderPO::getBrushTime, endDate.atTime(23, 59, 59)); .le(BrushOrderPO::getBrushTime, endDate.atTime(23, 59, 59));
List<BrushOrderPO> brushOrders = brushOrderMapper.selectList(brushWrapper); List<BrushOrderPO> brushOrders = brushOrderMapper.selectList(brushWrapper);
List<Long> productIds = orders.stream() List<Long> specIds = orders.stream()
.map(OrderPO::getProductId) .map(OrderPO::getProductSpecId)
.filter(Objects::nonNull) .filter(Objects::nonNull)
.distinct() .distinct()
.collect(Collectors.toList()); .collect(Collectors.toList());
Map<Long, Long> specIdToProductId = new HashMap<>();
if (!specIds.isEmpty()) {
List<ProductSpecPO> specs = productSpecMapper.selectList(new LambdaQueryWrapper<ProductSpecPO>()
.in(ProductSpecPO::getId, specIds)
.select(ProductSpecPO::getId, ProductSpecPO::getProductId));
for (ProductSpecPO s : specs) {
specIdToProductId.put(s.getId(), s.getProductId());
}
}
List<Long> productIds = specIdToProductId.values().stream().filter(Objects::nonNull).distinct()
.collect(Collectors.toList());
Map<Long, Long> productCategoryMap = new HashMap<>(); Map<Long, Long> productCategoryMap = new HashMap<>();
if (!productIds.isEmpty()) { if (!productIds.isEmpty()) {
LambdaQueryWrapper<ProductPO> productWrapper = new LambdaQueryWrapper<>(); LambdaQueryWrapper<ProductPO> productWrapper = new LambdaQueryWrapper<>();
@@ -114,7 +130,9 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic
Map<Long, List<OrderPO>> ordersByCategory = orders.stream() Map<Long, List<OrderPO>> ordersByCategory = orders.stream()
.collect(Collectors.groupingBy(order -> { .collect(Collectors.groupingBy(order -> {
Long categoryId = productCategoryMap.get(order.getProductId()); Long sid = order.getProductSpecId();
Long pid = sid != null ? specIdToProductId.get(sid) : null;
Long categoryId = pid != null ? productCategoryMap.get(pid) : null;
return categoryId != null ? categoryId : -1L; return categoryId != null ? categoryId : -1L;
})); }));
@@ -23,7 +23,9 @@ import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService;
import top.xyquan.ecomdmbbackend.modules.ecom.category.model.po.CategoryPO; import top.xyquan.ecomdmbbackend.modules.ecom.category.model.po.CategoryPO;
import top.xyquan.ecomdmbbackend.modules.ecom.category.service.CategoryService; import top.xyquan.ecomdmbbackend.modules.ecom.category.service.CategoryService;
import top.xyquan.ecomdmbbackend.modules.ecom.product.mapper.ProductMapper; import top.xyquan.ecomdmbbackend.modules.ecom.product.mapper.ProductMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.product.mapper.ProductSpecMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO; import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductSpecPO;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext; import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.math.BigDecimal; import java.math.BigDecimal;
@@ -31,9 +33,11 @@ import java.math.RoundingMode;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
@@ -53,6 +57,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
private final ShopService shopService; private final ShopService shopService;
private final OrderStatusService orderStatusService; private final OrderStatusService orderStatusService;
private final ProductMapper productMapper; private final ProductMapper productMapper;
private final ProductSpecMapper productSpecMapper;
private final CategoryService categoryService; private final CategoryService categoryService;
private final PlatformMapper platformMapper; private final PlatformMapper platformMapper;
@@ -64,6 +69,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
ShopService shopService, ShopService shopService,
OrderStatusService orderStatusService, OrderStatusService orderStatusService,
ProductMapper productMapper, ProductMapper productMapper,
ProductSpecMapper productSpecMapper,
CategoryService categoryService, CategoryService categoryService,
PlatformMapper platformMapper) { PlatformMapper platformMapper) {
this.currentUserContext = currentUserContext; this.currentUserContext = currentUserContext;
@@ -74,6 +80,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
this.shopService = shopService; this.shopService = shopService;
this.orderStatusService = orderStatusService; this.orderStatusService = orderStatusService;
this.productMapper = productMapper; this.productMapper = productMapper;
this.productSpecMapper = productSpecMapper;
this.categoryService = categoryService; this.categoryService = categoryService;
this.platformMapper = platformMapper; this.platformMapper = platformMapper;
} }
@@ -813,6 +820,25 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
return statusList.stream().map(OrderStatusPO::getId).collect(Collectors.toList()); return statusList.stream().map(OrderStatusPO::getId).collect(Collectors.toList());
} }
/** 订单行上的 product_spec_id → 商品 id */
private Map<Long, Long> orderSpecIdToProductIdMap(List<OrderPO> orders) {
List<Long> specIds = orders.stream()
.map(OrderPO::getProductSpecId)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
if (specIds.isEmpty()) {
return Collections.emptyMap();
}
List<ProductSpecPO> specs = productSpecMapper.selectList(new LambdaQueryWrapper<ProductSpecPO>()
.in(ProductSpecPO::getId, specIds)
.select(ProductSpecPO::getId, ProductSpecPO::getProductId));
Map<Long, Long> map = new java.util.HashMap<>();
for (ProductSpecPO s : specs) {
map.put(s.getId(), s.getProductId());
}
return map;
}
/** /**
* Calculate category comparison data * Calculate category comparison data
@@ -829,11 +855,8 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
Map<Long, String> categoryNameMap = allCategories.stream() Map<Long, String> categoryNameMap = allCategories.stream()
.collect(Collectors.toMap(CategoryPO::getId, CategoryPO::getName)); .collect(Collectors.toMap(CategoryPO::getId, CategoryPO::getName));
// Collect all product IDs involved and batch query their category info Map<Long, Long> specIdToProductId = orderSpecIdToProductIdMap(orders);
List<Long> productIds = orders.stream() List<Long> productIds = specIdToProductId.values().stream().filter(Objects::nonNull).distinct()
.map(OrderPO::getProductId)
.filter(id -> id != null)
.distinct()
.collect(Collectors.toList()); .collect(Collectors.toList());
Map<Long, Long> productCategoryMap = new java.util.HashMap<>(); Map<Long, Long> productCategoryMap = new java.util.HashMap<>();
@@ -849,8 +872,11 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
// Group orders by category // Group orders by category
Map<Long, List<OrderPO>> ordersByCategory = orders.stream() Map<Long, List<OrderPO>> ordersByCategory = orders.stream()
.collect(Collectors.groupingBy(order -> { .collect(Collectors.groupingBy(order -> {
Long productId = order.getProductId(); Long specId = order.getProductSpecId();
if (productId == null) return -1L; Long productId = specId != null ? specIdToProductId.get(specId) : null;
if (productId == null) {
return -1L;
}
Long categoryId = productCategoryMap.get(productId); Long categoryId = productCategoryMap.get(productId);
return categoryId != null ? categoryId : -1L; return categoryId != null ? categoryId : -1L;
})); }));
@@ -13,7 +13,9 @@ import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.model.po.BrushOrderPO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO; import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.po.OrderStatusPO; import top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.po.OrderStatusPO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.service.OrderStatusService; import top.xyquan.ecomdmbbackend.modules.ecom.order.status.service.OrderStatusService;
import top.xyquan.ecomdmbbackend.modules.ecom.product.mapper.ProductSpecMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO; import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductSpecPO;
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.po.PromotionFeePO; import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.po.PromotionFeePO;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO; import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.monthlytarget.mapper.ShopMonthlyTargetMapper; import top.xyquan.ecomdmbbackend.modules.ecom.shop.monthlytarget.mapper.ShopMonthlyTargetMapper;
@@ -29,6 +31,7 @@ import java.math.RoundingMode;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@@ -52,6 +55,7 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
private final ShopMonthlyTargetMapper shopMonthlyTargetMapper; private final ShopMonthlyTargetMapper shopMonthlyTargetMapper;
private final ShopService shopService; private final ShopService shopService;
private final ProductService productService; private final ProductService productService;
private final ProductSpecMapper productSpecMapper;
private final OrderStatusService orderStatusService; private final OrderStatusService orderStatusService;
private final CategoryService categoryService; private final CategoryService categoryService;
@@ -62,6 +66,7 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
ShopMonthlyTargetMapper shopMonthlyTargetMapper, ShopMonthlyTargetMapper shopMonthlyTargetMapper,
ShopService shopService, ShopService shopService,
ProductService productService, ProductService productService,
ProductSpecMapper productSpecMapper,
OrderStatusService orderStatusService, OrderStatusService orderStatusService,
CategoryService categoryService) { CategoryService categoryService) {
this.currentUserContext = currentUserContext; this.currentUserContext = currentUserContext;
@@ -71,6 +76,7 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
this.shopMonthlyTargetMapper = shopMonthlyTargetMapper; this.shopMonthlyTargetMapper = shopMonthlyTargetMapper;
this.shopService = shopService; this.shopService = shopService;
this.productService = productService; this.productService = productService;
this.productSpecMapper = productSpecMapper;
this.orderStatusService = orderStatusService; this.orderStatusService = orderStatusService;
this.categoryService = categoryService; this.categoryService = categoryService;
} }
@@ -363,6 +369,25 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
return profit.divide(totalCost, 4, RoundingMode.HALF_UP); return profit.divide(totalCost, 4, RoundingMode.HALF_UP);
} }
private Map<Long, Long> orderSpecIdToProductIdMap(List<OrderPO> orders) {
List<Long> specIds = orders.stream()
.map(OrderPO::getProductSpecId)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
if (specIds.isEmpty()) {
return Collections.emptyMap();
}
List<ProductSpecPO> specs = productSpecMapper.selectList(new LambdaQueryWrapper<ProductSpecPO>()
.in(ProductSpecPO::getId, specIds)
.select(ProductSpecPO::getId, ProductSpecPO::getProductId));
Map<Long, Long> map = new HashMap<>();
for (ProductSpecPO s : specs) {
map.put(s.getId(), s.getProductId());
}
return map;
}
/** /**
* 计算多商品数据横向汇总 * 计算多商品数据横向汇总
*/ */
@@ -371,9 +396,12 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
List<BrushOrderPO> brushOrders, List<Long> refundStatusIds) { List<BrushOrderPO> brushOrders, List<Long> refundStatusIds) {
List<ShopOverviewStatisticsVO.ProductComparison> comparisons = new ArrayList<>(); List<ShopOverviewStatisticsVO.ProductComparison> comparisons = new ArrayList<>();
// 按商品分组订单数据 Map<Long, Long> specToProduct = orderSpecIdToProductIdMap(orders);
Map<Long, List<OrderPO>> ordersByProduct = orders.stream() Map<Long, List<OrderPO>> ordersByProduct = orders.stream()
.collect(Collectors.groupingBy(OrderPO::getProductId)); .collect(Collectors.groupingBy(o -> {
Long sid = o.getProductSpecId();
return sid != null ? specToProduct.getOrDefault(sid, -1L) : -1L;
}));
// 按商品分组刷单费数据(如果有商品ID) // 按商品分组刷单费数据(如果有商品ID)
Map<Long, List<BrushOrderPO>> brushOrdersByProduct = brushOrders.stream() Map<Long, List<BrushOrderPO>> brushOrdersByProduct = brushOrders.stream()
@@ -391,6 +419,9 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
for (Map.Entry<Long, List<OrderPO>> entry : ordersByProduct.entrySet()) { for (Map.Entry<Long, List<OrderPO>> entry : ordersByProduct.entrySet()) {
Long productId = entry.getKey(); Long productId = entry.getKey();
List<OrderPO> productOrders = entry.getValue(); List<OrderPO> productOrders = entry.getValue();
if (productId == null || productId < 0) {
continue;
}
// 获取商品信息 // 获取商品信息
ProductPO product = productService.getById(productId); ProductPO product = productService.getById(productId);
@@ -709,10 +740,13 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
categoryMap.put(c.getId(), c); categoryMap.put(c.getId(), c);
} }
Map<Long, Long> specToProduct = orderSpecIdToProductIdMap(orders);
// 按品类分组订单 // 按品类分组订单
Map<Long, List<OrderPO>> ordersByCategory = new HashMap<>(); Map<Long, List<OrderPO>> ordersByCategory = new HashMap<>();
for (OrderPO order : orders) { for (OrderPO order : orders) {
Long categoryId = productCategoryMap.get(order.getProductId()); Long sid = order.getProductSpecId();
Long pid = sid != null ? specToProduct.get(sid) : null;
Long categoryId = pid != null ? productCategoryMap.get(pid) : null;
if (categoryId == null) { if (categoryId == null) {
categoryId = 0L; // 未分类 categoryId = 0L; // 未分类
} }
@@ -86,7 +86,8 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
// 查询订单数据 // 查询订单数据
LambdaQueryWrapper<OrderPO> orderWrapper = new LambdaQueryWrapper<>(); LambdaQueryWrapper<OrderPO> orderWrapper = new LambdaQueryWrapper<>();
orderWrapper.eq(OrderPO::getCompanyId, companyId) orderWrapper.eq(OrderPO::getCompanyId, companyId)
.eq(OrderPO::getProductId, queryDTO.getProductId()) .apply("EXISTS (SELECT 1 FROM ec_product_spec s WHERE s.id = ec_order.product_spec_id AND s.product_id = {0})",
queryDTO.getProductId())
.ge(OrderPO::getOrderTime, startDateTime) .ge(OrderPO::getOrderTime, startDateTime)
.le(OrderPO::getOrderTime, endDateTime); .le(OrderPO::getOrderTime, endDateTime);
List<OrderPO> orders = orderMapper.selectList(orderWrapper); List<OrderPO> orders = orderMapper.selectList(orderWrapper);
@@ -121,7 +122,8 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
LambdaQueryWrapper<OrderPO> lastPeriodWrapper = new LambdaQueryWrapper<>(); LambdaQueryWrapper<OrderPO> lastPeriodWrapper = new LambdaQueryWrapper<>();
lastPeriodWrapper.eq(OrderPO::getCompanyId, companyId) lastPeriodWrapper.eq(OrderPO::getCompanyId, companyId)
.eq(OrderPO::getProductId, queryDTO.getProductId()) .apply("EXISTS (SELECT 1 FROM ec_product_spec s WHERE s.id = ec_order.product_spec_id AND s.product_id = {0})",
queryDTO.getProductId())
.ge(OrderPO::getOrderTime, lastStartTime) .ge(OrderPO::getOrderTime, lastStartTime)
.le(OrderPO::getOrderTime, lastEndTime); .le(OrderPO::getOrderTime, lastEndTime);
List<OrderPO> lastPeriodOrders = orderMapper.selectList(lastPeriodWrapper); List<OrderPO> lastPeriodOrders = orderMapper.selectList(lastPeriodWrapper);
@@ -369,8 +371,18 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
return buildEmptySpecSummary(); return buildEmptySpecSummary();
} }
Long productId = orders.get(0).getProductId(); OrderPO firstOrder = orders.get(0);
Long companyId = orders.get(0).getCompanyId(); Long companyId = firstOrder.getCompanyId();
Long productId = null;
if (firstOrder.getProductSpecId() != null) {
ProductSpecPO firstSpec = productSpecMapper.selectById(firstOrder.getProductSpecId());
if (firstSpec != null) {
productId = firstSpec.getProductId();
}
}
if (productId == null) {
return buildEmptySpecSummary();
}
LambdaQueryWrapper<ProductSpecPO> specWrapper = new LambdaQueryWrapper<>(); LambdaQueryWrapper<ProductSpecPO> specWrapper = new LambdaQueryWrapper<>();
specWrapper.eq(ProductSpecPO::getCompanyId, companyId) specWrapper.eq(ProductSpecPO::getCompanyId, companyId)
@@ -15,10 +15,10 @@ export namespace OrderDTO {
receivedAmount: number; receivedAmount: number;
/** 下单时间 */ /** 下单时间 */
orderTime: string; orderTime: string;
/** 商品ID */
productId: number;
/** 商品规格ID */ /** 商品规格ID */
productSpecId?: number; productSpecId: number;
/** 规格编码(可选,服务端可按规格ID补全) */
specCode?: string;
/** 链接商品名称(冗余存储) */ /** 链接商品名称(冗余存储) */
linkProductName: string; linkProductName: string;
/** 链接规格名称(冗余存储) */ /** 链接规格名称(冗余存储) */
@@ -49,10 +49,10 @@ export namespace OrderDTO {
receivedAmount: number; receivedAmount: number;
/** 下单时间 */ /** 下单时间 */
orderTime: string; orderTime: string;
/** 商品ID */
productId?: number;
/** 商品规格ID */ /** 商品规格ID */
productSpecId?: number; productSpecId?: number;
/** 规格编码 */
specCode?: string;
/** 链接商品名称(冗余存储) */ /** 链接商品名称(冗余存储) */
linkProductName?: string; linkProductName?: string;
/** 链接规格名称(冗余存储) */ /** 链接规格名称(冗余存储) */
@@ -36,10 +36,10 @@ export namespace OrderVO {
createBy?: number; createBy?: number;
/** 更新人ID */ /** 更新人ID */
updateBy?: number; updateBy?: number;
/** 商品ID */
productId: number;
/** 商品规格ID */ /** 商品规格ID */
productSpecId?: number; productSpecId?: number;
/** 规格编码 */
specCode?: string;
/** 链接商品名称(冗余存储) */ /** 链接商品名称(冗余存储) */
linkProductName: string; linkProductName: string;
/** 链接规格名称(冗余存储) */ /** 链接规格名称(冗余存储) */
@@ -8,7 +8,7 @@ import type { ProductDTO, ProductVO } from '#/api/ecommerce/product/types';
import type { ShopVO } from '#/api/ecommerce/shop/types'; import type { ShopVO } from '#/api/ecommerce/shop/types';
import type { PageQueryDTO } from '#/types/common'; import type { PageQueryDTO } from '#/types/common';
import { ref, watch } from 'vue'; import { ref } from 'vue';
import { useVbenModal } from '@vben/common-ui'; import { useVbenModal } from '@vben/common-ui';
@@ -56,7 +56,8 @@ const isEdit = ref(false);
const currentRecord = ref<null | OrderVO.Info>(null); const currentRecord = ref<null | OrderVO.Info>(null);
// 表单数据 // 表单数据
const formData = ref<Partial<OrderDTO.Create>>({ /** 表单含 UI 用 productId(选规格);提交用 productSpecId + specCode */
const formData = ref<Partial<OrderDTO.Create> & { productId?: number }>({
shopId: undefined, shopId: undefined,
platformOrderNo: '', platformOrderNo: '',
statusId: undefined as number | undefined, statusId: undefined as number | undefined,
@@ -64,6 +65,7 @@ const formData = ref<Partial<OrderDTO.Create>>({
orderTime: dayjs().format('YYYY-MM-DD HH:mm:ss'), orderTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
productId: undefined, productId: undefined,
productSpecId: undefined, productSpecId: undefined,
specCode: undefined,
linkProductName: '', linkProductName: '',
linkSpecName: '', linkSpecName: '',
quantity: 1, quantity: 1,
@@ -111,6 +113,7 @@ const rules = {
], ],
orderTime: [{ required: true, message: '请选择下单时间', trigger: 'change' }], orderTime: [{ required: true, message: '请选择下单时间', trigger: 'change' }],
productId: [{ required: true, message: '请选择商品', trigger: 'change' }], productId: [{ required: true, message: '请选择商品', trigger: 'change' }],
productSpecId: [{ required: true, message: '请选择商品规格', trigger: 'change' }],
linkProductName: [ linkProductName: [
{ required: true, message: '请输入链接商品名称', trigger: 'blur' }, { required: true, message: '请输入链接商品名称', trigger: 'blur' },
], ],
@@ -292,6 +295,7 @@ function handleProductChange(productId: number | undefined) {
specPage.value = 1; specPage.value = 1;
productSpecOptions.value = []; productSpecOptions.value = [];
formData.value.productSpecId = undefined; formData.value.productSpecId = undefined;
formData.value.specCode = undefined;
formData.value.linkSpecName = ''; formData.value.linkSpecName = '';
formData.value.productCost = 0; formData.value.productCost = 0;
formData.value.shippingCost = 0; formData.value.shippingCost = 0;
@@ -300,6 +304,7 @@ function handleProductChange(productId: number | undefined) {
} else { } else {
formData.value.linkProductName = ''; formData.value.linkProductName = '';
formData.value.productSpecId = undefined; formData.value.productSpecId = undefined;
formData.value.specCode = undefined;
formData.value.linkSpecName = ''; formData.value.linkSpecName = '';
formData.value.productCost = 0; formData.value.productCost = 0;
formData.value.shippingCost = 0; formData.value.shippingCost = 0;
@@ -316,12 +321,14 @@ function handleProductSpecChange(specId: number | undefined) {
); );
if (selectedSpec) { if (selectedSpec) {
formData.value.linkSpecName = selectedSpec.spec.name; formData.value.linkSpecName = selectedSpec.spec.name;
formData.value.specCode = selectedSpec.spec.specCode;
formData.value.productCost = selectedSpec.spec.productCost; formData.value.productCost = selectedSpec.spec.productCost;
formData.value.shippingCost = selectedSpec.spec.shippingCost || 0; formData.value.shippingCost = selectedSpec.spec.shippingCost || 0;
formData.value.otherCost = selectedSpec.spec.otherCost || 0; formData.value.otherCost = selectedSpec.spec.otherCost || 0;
} }
} else { } else {
formData.value.linkSpecName = ''; formData.value.linkSpecName = '';
formData.value.specCode = undefined;
formData.value.productCost = 0; formData.value.productCost = 0;
formData.value.shippingCost = 0; formData.value.shippingCost = 0;
formData.value.otherCost = 0; formData.value.otherCost = 0;
@@ -350,8 +357,9 @@ async function open(edit: boolean, record?: OrderVO.Info) {
orderTime: record.orderTime orderTime: record.orderTime
? dayjs(record.orderTime).format('YYYY-MM-DD HH:mm:ss') ? dayjs(record.orderTime).format('YYYY-MM-DD HH:mm:ss')
: dayjs().format('YYYY-MM-DD HH:mm:ss'), : dayjs().format('YYYY-MM-DD HH:mm:ss'),
productId: record.productId, productId: record.product?.id,
productSpecId: record.productSpecId, productSpecId: record.productSpecId,
specCode: record.specCode,
linkProductName: record.linkProductName, linkProductName: record.linkProductName,
linkSpecName: record.linkSpecName, linkSpecName: record.linkSpecName,
quantity: record.quantity, quantity: record.quantity,
@@ -369,6 +377,7 @@ async function open(edit: boolean, record?: OrderVO.Info) {
orderTime: dayjs().format('YYYY-MM-DD HH:mm:ss'), orderTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
productId: undefined, productId: undefined,
productSpecId: undefined, productSpecId: undefined,
specCode: undefined,
linkProductName: '', linkProductName: '',
linkSpecName: '', linkSpecName: '',
quantity: 1, quantity: 1,
@@ -379,16 +388,17 @@ async function open(edit: boolean, record?: OrderVO.Info) {
remark: '', remark: '',
}; };
// 如果是编辑模式且有商品ID,加载商品和规格选项 // 如果是编辑模式且有商品/规格,加载商品和规格选项
if (edit && record?.productId) { if (edit && record && (record.product?.id ?? record.productSpecId)) {
await fetchProducts(1, false); await fetchProducts(1, false);
// 确保选中的商品在选项中 // 确保选中的商品在选项中
if (!productOptions.value.some((opt) => opt.value === record.productId)) { const pid = record.product?.id;
if (pid && !productOptions.value.some((opt) => opt.value === pid)) {
productOptions.value.push({ productOptions.value.push({
label: record.linkProductName, label: record.linkProductName,
value: record.productId, value: pid,
product: { product: {
id: record.productId, id: pid,
name: record.linkProductName, name: record.linkProductName,
} as ProductVO.Info, } as ProductVO.Info,
}); });
@@ -438,8 +448,8 @@ async function handleSubmit() {
statusId: formData.value.statusId, statusId: formData.value.statusId,
receivedAmount: formData.value.receivedAmount!, receivedAmount: formData.value.receivedAmount!,
orderTime: formData.value.orderTime!, orderTime: formData.value.orderTime!,
productId: formData.value.productId,
productSpecId: formData.value.productSpecId, productSpecId: formData.value.productSpecId,
specCode: formData.value.specCode,
linkProductName: formData.value.linkProductName, linkProductName: formData.value.linkProductName,
linkSpecName: formData.value.linkSpecName, linkSpecName: formData.value.linkSpecName,
quantity: formData.value.quantity, quantity: formData.value.quantity,
@@ -459,8 +469,8 @@ async function handleSubmit() {
statusId: formData.value.statusId!, statusId: formData.value.statusId!,
receivedAmount: formData.value.receivedAmount!, receivedAmount: formData.value.receivedAmount!,
orderTime: formData.value.orderTime!, orderTime: formData.value.orderTime!,
productId: formData.value.productId!, productSpecId: formData.value.productSpecId!,
productSpecId: formData.value.productSpecId, specCode: formData.value.specCode,
linkProductName: formData.value.linkProductName!, linkProductName: formData.value.linkProductName!,
linkSpecName: formData.value.linkSpecName, linkSpecName: formData.value.linkSpecName,
quantity: formData.value.quantity!, quantity: formData.value.quantity!,
@@ -614,11 +614,13 @@ onMounted(async () => {
<div>商品编码:{{ row.product.productCode || '-' }}</div> <div>商品编码:{{ row.product.productCode || '-' }}</div>
</template> </template>
<a <a
v-if="row.product?.id"
style="color: #1890ff; cursor: pointer" style="color: #1890ff; cursor: pointer"
@click.stop="goToProductDetail(row.productId)" @click.stop="goToProductDetail(row.product.id)"
> >
{{ row.product.name }} {{ row.product.name }}
</a> </a>
<span v-else style="color: #1890ff">{{ row.product.name }}</span>
</Popover> </Popover>
<span v-else style="color: #999">暂无商品信息</span> <span v-else style="color: #999">暂无商品信息</span>
</template> </template>