diff --git a/ecom-dmb-backend/sql/ec_design.sql b/ecom-dmb-backend/sql/ec_design.sql index 727295c8..9b1741ab 100644 --- a/ecom-dmb-backend/sql/ec_design.sql +++ b/ecom-dmb-backend/sql/ec_design.sql @@ -166,6 +166,8 @@ CREATE TABLE `ec_order` ( -- ---------------------------- -- 订单状态表 +-- 说明:各统计维度独立开关(0否 1是),替代原 auto_statistics / is_refund。 +-- 概览、导出等按维度筛选订单状态时分别读取对应字段;任一为 1 的状态会进入「待拉取订单」并集。 -- ---------------------------- DROP TABLE IF EXISTS `ec_order_status`; CREATE TABLE `ec_order_status` ( @@ -175,8 +177,11 @@ CREATE TABLE `ec_order_status` ( `description` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '状态描述', `color` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '状态颜色(十六进制)', `sort_order` int NOT NULL DEFAULT 0 COMMENT '排序', - `auto_statistics` tinyint NOT NULL DEFAULT 1 COMMENT '是否自动参与统计 0不参与 1参与', - `is_refund` tinyint NOT NULL DEFAULT 0 COMMENT '是否为退款状态 0否 1是', + `include_sales_amount` tinyint NOT NULL DEFAULT 0 COMMENT '是否计入销售额/单量等统计 0否 1是', + `include_product_cost` tinyint NOT NULL DEFAULT 0 COMMENT '是否计入商品成本统计 0否 1是', + `include_freight_cost` tinyint NOT NULL DEFAULT 0 COMMENT '是否计入运费成本统计 0否 1是', + `include_other_cost` tinyint NOT NULL DEFAULT 0 COMMENT '是否计入其他成本统计 0否 1是', + `include_refund` tinyint NOT NULL DEFAULT 0 COMMENT '是否计入退款金额统计 0否 1是', `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', `create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人ID', @@ -185,10 +190,8 @@ CREATE TABLE `ec_order_status` ( UNIQUE INDEX `uk_company_status_name`(`company_id` ASC, `status_name` ASC) USING BTREE, INDEX `idx_company_id`(`company_id` ASC) USING BTREE, INDEX `idx_sort_order`(`sort_order` ASC) USING BTREE, - INDEX `idx_auto_statistics`(`auto_statistics` ASC) USING BTREE, INDEX `fk_ec_order_status_creator`(`create_by` ASC) USING BTREE, INDEX `fk_ec_order_status_updater`(`update_by` ASC) USING BTREE, - INDEX `idx_is_refund`(`is_refund` ASC) USING BTREE, CONSTRAINT `fk_ec_order_status_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_ec_order_status_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `fk_ec_order_status_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE diff --git a/ecom-dmb-backend/sql/migration/V20260604__ec_order_status_stat_dimensions.sql b/ecom-dmb-backend/sql/migration/V20260604__ec_order_status_stat_dimensions.sql new file mode 100644 index 00000000..03aa4517 --- /dev/null +++ b/ecom-dmb-backend/sql/migration/V20260604__ec_order_status_stat_dimensions.sql @@ -0,0 +1,23 @@ +-- 订单状态表:移除「自动参与统计」「是否退款」,改为五个独立统计维度(0/1) +-- 兼容旧数据:原 auto_statistics=1 则四项成本/销售额维度置 1;原 is_refund=1 则退款维度置 1 + +ALTER TABLE `ec_order_status` + ADD COLUMN `include_sales_amount` tinyint NOT NULL DEFAULT 0 COMMENT '是否计入销售额/单量等统计 0否 1是' AFTER `sort_order`, + ADD COLUMN `include_product_cost` tinyint NOT NULL DEFAULT 0 COMMENT '是否计入商品成本统计 0否 1是' AFTER `include_sales_amount`, + ADD COLUMN `include_freight_cost` tinyint NOT NULL DEFAULT 0 COMMENT '是否计入运费成本统计 0否 1是' AFTER `include_product_cost`, + ADD COLUMN `include_other_cost` tinyint NOT NULL DEFAULT 0 COMMENT '是否计入其他成本统计 0否 1是' AFTER `include_freight_cost`, + ADD COLUMN `include_refund` tinyint NOT NULL DEFAULT 0 COMMENT '是否计入退款金额统计 0否 1是' AFTER `include_other_cost`; + +UPDATE `ec_order_status` +SET + `include_sales_amount` = IF(`auto_statistics` = 1, 1, 0), + `include_product_cost` = IF(`auto_statistics` = 1, 1, 0), + `include_freight_cost` = IF(`auto_statistics` = 1, 1, 0), + `include_other_cost` = IF(`auto_statistics` = 1, 1, 0), + `include_refund` = IF(`is_refund` = 1, 1, 0); + +ALTER TABLE `ec_order_status` + DROP INDEX `idx_auto_statistics`, + DROP INDEX `idx_is_refund`, + DROP COLUMN `auto_statistics`, + DROP COLUMN `is_refund`; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/ProductSpecImportHelper.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/ProductSpecImportHelper.java index 377eb08e..36af5b13 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/ProductSpecImportHelper.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/ProductSpecImportHelper.java @@ -464,7 +464,11 @@ public class ProductSpecImportHelper { orderStatus.setStatusName(trimmed); orderStatus.setDescription("自动创建的状态"); orderStatus.setSortOrder(0); - orderStatus.setAutoStatistics(1); + orderStatus.setIncludeSalesAmount(1); + orderStatus.setIncludeProductCost(1); + orderStatus.setIncludeFreightCost(1); + orderStatus.setIncludeOtherCost(1); + orderStatus.setIncludeRefund(0); orderStatus.setCreateBy(createBy); orderStatusService.save(orderStatus); diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/model/dto/CreateOrderStatusDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/model/dto/CreateOrderStatusDTO.java index e1d77733..8892dc30 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/model/dto/CreateOrderStatusDTO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/model/dto/CreateOrderStatusDTO.java @@ -2,7 +2,6 @@ package top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.dto; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; -import jakarta.validation.constraints.NotNull; import lombok.Data; /** @@ -37,17 +36,19 @@ public class CreateOrderStatusDTO { @Schema(description = "排序", example = "1") private Integer sortOrder; - /** - * 是否自动参与统计 0不参与 1参与 - */ - @Schema(description = "是否自动参与统计", example = "1", requiredMode = Schema.RequiredMode.REQUIRED) - @NotNull(message = "是否自动参与统计不能为空") - private Integer autoStatistics; + @Schema(description = "是否计入销售额/单量等统计 0否 1是", example = "1") + private Integer includeSalesAmount; - /** - * 是否为退款状态 0否 1是 - */ - @Schema(description = "是否为退款状态", example = "0") - private Integer isRefund; + @Schema(description = "是否计入商品成本统计 0否 1是", example = "1") + private Integer includeProductCost; + + @Schema(description = "是否计入运费成本统计 0否 1是", example = "1") + private Integer includeFreightCost; + + @Schema(description = "是否计入其他成本统计 0否 1是", example = "1") + private Integer includeOtherCost; + + @Schema(description = "是否计入退款金额统计 0否 1是", example = "0") + private Integer includeRefund; } diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/model/dto/PatchOrderStatusDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/model/dto/PatchOrderStatusDTO.java index 3241707d..3b691f73 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/model/dto/PatchOrderStatusDTO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/model/dto/PatchOrderStatusDTO.java @@ -10,15 +10,18 @@ import lombok.Data; @Schema(description = "部分更新订单状态DTO") public class PatchOrderStatusDTO { - /** - * 是否自动参与统计 0不参与 1参与 - */ - @Schema(description = "是否自动参与统计", example = "1") - private Integer autoStatistics; + @Schema(description = "是否计入销售额/单量等统计 0否 1是", example = "1") + private Integer includeSalesAmount; - /** - * 是否为退款状态 0否 1是 - */ - @Schema(description = "是否为退款状态", example = "0") - private Integer isRefund; + @Schema(description = "是否计入商品成本统计 0否 1是", example = "1") + private Integer includeProductCost; + + @Schema(description = "是否计入运费成本统计 0否 1是", example = "1") + private Integer includeFreightCost; + + @Schema(description = "是否计入其他成本统计 0否 1是", example = "1") + private Integer includeOtherCost; + + @Schema(description = "是否计入退款金额统计 0否 1是", example = "0") + private Integer includeRefund; } diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/model/dto/UpdateOrderStatusDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/model/dto/UpdateOrderStatusDTO.java index 5b0bfcf0..052ec865 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/model/dto/UpdateOrderStatusDTO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/model/dto/UpdateOrderStatusDTO.java @@ -37,17 +37,24 @@ public class UpdateOrderStatusDTO { @Schema(description = "排序", example = "1") private Integer sortOrder; - /** - * 是否自动参与统计 0不参与 1参与 - */ - @Schema(description = "是否自动参与统计", example = "1", requiredMode = Schema.RequiredMode.REQUIRED) - @NotNull(message = "是否自动参与统计不能为空") - private Integer autoStatistics; + @Schema(description = "是否计入销售额/单量等统计 0否 1是", example = "1", requiredMode = Schema.RequiredMode.REQUIRED) + @NotNull(message = "includeSalesAmount 不能为空") + private Integer includeSalesAmount; - /** - * 是否为退款状态 0否 1是 - */ - @Schema(description = "是否为退款状态", example = "0") - private Integer isRefund; + @Schema(description = "是否计入商品成本统计 0否 1是", example = "1", requiredMode = Schema.RequiredMode.REQUIRED) + @NotNull(message = "includeProductCost 不能为空") + private Integer includeProductCost; + + @Schema(description = "是否计入运费成本统计 0否 1是", example = "1", requiredMode = Schema.RequiredMode.REQUIRED) + @NotNull(message = "includeFreightCost 不能为空") + private Integer includeFreightCost; + + @Schema(description = "是否计入其他成本统计 0否 1是", example = "1", requiredMode = Schema.RequiredMode.REQUIRED) + @NotNull(message = "includeOtherCost 不能为空") + private Integer includeOtherCost; + + @Schema(description = "是否计入退款金额统计 0否 1是", example = "0", requiredMode = Schema.RequiredMode.REQUIRED) + @NotNull(message = "includeRefund 不能为空") + private Integer includeRefund; } diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/model/po/OrderStatusPO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/model/po/OrderStatusPO.java index dd42115a..c4beaaba 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/model/po/OrderStatusPO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/model/po/OrderStatusPO.java @@ -51,16 +51,34 @@ public class OrderStatusPO { private Integer sortOrder; /** - * 是否自动参与统计 0不参与 1参与 + * 是否计入销售额/单量等统计 0否 1是 */ - @TableField("auto_statistics") - private Integer autoStatistics; + @TableField("include_sales_amount") + private Integer includeSalesAmount; /** - * 是否为退款状态 0否 1是 + * 是否计入商品成本统计 0否 1是 */ - @TableField("is_refund") - private Integer isRefund; + @TableField("include_product_cost") + private Integer includeProductCost; + + /** + * 是否计入运费成本统计 0否 1是 + */ + @TableField("include_freight_cost") + private Integer includeFreightCost; + + /** + * 是否计入其他成本统计 0否 1是 + */ + @TableField("include_other_cost") + private Integer includeOtherCost; + + /** + * 是否计入退款金额统计 0否 1是 + */ + @TableField("include_refund") + private Integer includeRefund; /** * 创建时间 diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/model/vo/OrderStatusVO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/model/vo/OrderStatusVO.java index ee544a03..8b72f3a5 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/model/vo/OrderStatusVO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/model/vo/OrderStatusVO.java @@ -48,17 +48,20 @@ public class OrderStatusVO { @Schema(description = "排序", example = "1") private Integer sortOrder; - /** - * 是否自动参与统计 0不参与 1参与 - */ - @Schema(description = "是否自动参与统计", example = "1") - private Integer autoStatistics; + @Schema(description = "是否计入销售额/单量等统计 0否 1是", example = "1") + private Integer includeSalesAmount; - /** - * 是否为退款状态 0否 1是 - */ - @Schema(description = "是否为退款状态", example = "0") - private Integer isRefund; + @Schema(description = "是否计入商品成本统计 0否 1是", example = "1") + private Integer includeProductCost; + + @Schema(description = "是否计入运费成本统计 0否 1是", example = "1") + private Integer includeFreightCost; + + @Schema(description = "是否计入其他成本统计 0否 1是", example = "1") + private Integer includeOtherCost; + + @Schema(description = "是否计入退款金额统计 0否 1是", example = "0") + private Integer includeRefund; /** * 创建时间 diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/service/OrderStatusService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/service/OrderStatusService.java index 515b073e..b9da2ee4 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/service/OrderStatusService.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/service/OrderStatusService.java @@ -33,7 +33,7 @@ public interface OrderStatusService extends IService { OrderStatusVO updateOrderStatus(UpdateOrderStatusDTO updateOrderStatusDTO, Long id); /** - * 部分更新订单状态(仅更新 autoStatistics 和 isRefund) + * 部分更新订单状态(仅更新各统计维度开关) * * @param patchDTO 部分更新DTO * @param id 订单状态ID diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/service/impl/OrderStatusServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/service/impl/OrderStatusServiceImpl.java index 342bebcb..1bd098c6 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/service/impl/OrderStatusServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/service/impl/OrderStatusServiceImpl.java @@ -59,12 +59,7 @@ public class OrderStatusServiceImpl extends ServiceImpl list = orderStatusService.list( + new LambdaQueryWrapper() + .eq(OrderStatusPO::getCompanyId, companyId)); + return OrderStatusStatSets.from(list); + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/support/OrderStatusStatSets.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/support/OrderStatusStatSets.java new file mode 100644 index 00000000..c4b5f1ba --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/status/support/OrderStatusStatSets.java @@ -0,0 +1,173 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.order.status.support; + +import lombok.Getter; +import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO; +import top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.po.OrderStatusPO; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * 订单状态在各统计维度上的生效集合(由 {@link OrderStatusPO} 列表解析)。 + */ +@Getter +public final class OrderStatusStatSets { + + private final List unionStatusIds; + private final Set salesIds; + private final Set productCostIds; + private final Set freightCostIds; + private final Set otherCostIds; + private final Set refundIds; + + private OrderStatusStatSets(List unionStatusIds, + Set salesIds, + Set productCostIds, + Set freightCostIds, + Set otherCostIds, + Set refundIds) { + this.unionStatusIds = unionStatusIds; + this.salesIds = salesIds; + this.productCostIds = productCostIds; + this.freightCostIds = freightCostIds; + this.otherCostIds = otherCostIds; + this.refundIds = refundIds; + } + + public static OrderStatusStatSets from(List statuses) { + Set union = new HashSet<>(); + Set sales = new HashSet<>(); + Set productCost = new HashSet<>(); + Set freightCost = new HashSet<>(); + Set otherCost = new HashSet<>(); + Set refund = new HashSet<>(); + for (OrderStatusPO s : statuses) { + Long id = s.getId(); + if (id == null) { + continue; + } + boolean any = false; + if (isOn(s.getIncludeSalesAmount())) { + sales.add(id); + any = true; + } + if (isOn(s.getIncludeProductCost())) { + productCost.add(id); + any = true; + } + if (isOn(s.getIncludeFreightCost())) { + freightCost.add(id); + any = true; + } + if (isOn(s.getIncludeOtherCost())) { + otherCost.add(id); + any = true; + } + if (isOn(s.getIncludeRefund())) { + refund.add(id); + any = true; + } + if (any) { + union.add(id); + } + } + List unionList = new ArrayList<>(union); + Collections.sort(unionList); + return new OrderStatusStatSets( + Collections.unmodifiableList(unionList), + Collections.unmodifiableSet(sales), + Collections.unmodifiableSet(productCost), + Collections.unmodifiableSet(freightCost), + Collections.unmodifiableSet(otherCost), + Collections.unmodifiableSet(refund)); + } + + private static boolean isOn(Integer v) { + return Objects.equals(v, 1); + } + + public boolean isUnionEmpty() { + return unionStatusIds.isEmpty(); + } + + public boolean includesSales(Long statusId) { + return statusId != null && salesIds.contains(statusId); + } + + public boolean includesProductCost(Long statusId) { + return statusId != null && productCostIds.contains(statusId); + } + + public boolean includesFreightCost(Long statusId) { + return statusId != null && freightCostIds.contains(statusId); + } + + public boolean includesOtherCost(Long statusId) { + return statusId != null && otherCostIds.contains(statusId); + } + + public boolean includesRefund(Long statusId) { + return statusId != null && refundIds.contains(statusId); + } + + public List getRefundStatusIds() { + return refundIds.stream().sorted().collect(Collectors.toList()); + } + + public static int quantity(OrderPO order) { + Integer q = order.getQuantity(); + return q != null && q > 0 ? q : 1; + } + + public BigDecimal receivedForSales(OrderPO order) { + return includesSales(order.getStatusId()) + ? nz(order.getReceivedAmount()) + : BigDecimal.ZERO; + } + + public BigDecimal productCostForStats(OrderPO order) { + if (!includesProductCost(order.getStatusId())) { + return BigDecimal.ZERO; + } + BigDecimal c = nz(order.getProductCost()); + return c.multiply(BigDecimal.valueOf(quantity(order))); + } + + public BigDecimal freightCostForStats(OrderPO order) { + if (!includesFreightCost(order.getStatusId())) { + return BigDecimal.ZERO; + } + BigDecimal c = nz(order.getShippingCost()); + return c.multiply(BigDecimal.valueOf(quantity(order))); + } + + public BigDecimal otherCostForStats(OrderPO order) { + if (!includesOtherCost(order.getStatusId())) { + return BigDecimal.ZERO; + } + BigDecimal c = nz(order.getOtherCost()); + return c.multiply(BigDecimal.valueOf(quantity(order))); + } + + public BigDecimal totalCostForStats(OrderPO order) { + return productCostForStats(order) + .add(freightCostForStats(order)) + .add(otherCostForStats(order)); + } + + public BigDecimal receivedForRefund(OrderPO order) { + return includesRefund(order.getStatusId()) + ? nz(order.getReceivedAmount()) + : BigDecimal.ZERO; + } + + private static BigDecimal nz(BigDecimal v) { + return v != null ? v : BigDecimal.ZERO; + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/CompanyOverviewServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/CompanyOverviewServiceImpl.java index 1f7716c1..c2acbdbf 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/CompanyOverviewServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/CompanyOverviewServiceImpl.java @@ -11,8 +11,7 @@ import top.xyquan.ecomdmbbackend.modules.ecom.promotion.mapper.PromotionFeeMappe import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CompanyOverviewQueryDTO; 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.status.model.po.OrderStatusPO; -import top.xyquan.ecomdmbbackend.modules.ecom.order.status.service.OrderStatusService; +import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatResolver; 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.monthlytarget.mapper.ShopMonthlyTargetMapper; @@ -55,7 +54,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService { private final BrushOrderMapper brushOrderMapper; private final ShopMonthlyTargetMapper shopMonthlyTargetMapper; private final ShopService shopService; - private final OrderStatusService orderStatusService; + private final OrderStatusStatResolver orderStatusStatResolver; private final ProductMapper productMapper; private final ProductSpecMapper productSpecMapper; private final CategoryService categoryService; @@ -67,7 +66,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService { BrushOrderMapper brushOrderMapper, ShopMonthlyTargetMapper shopMonthlyTargetMapper, ShopService shopService, - OrderStatusService orderStatusService, + OrderStatusStatResolver orderStatusStatResolver, ProductMapper productMapper, ProductSpecMapper productSpecMapper, CategoryService categoryService, @@ -78,7 +77,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService { this.brushOrderMapper = brushOrderMapper; this.shopMonthlyTargetMapper = shopMonthlyTargetMapper; this.shopService = shopService; - this.orderStatusService = orderStatusService; + this.orderStatusStatResolver = orderStatusStatResolver; this.productMapper = productMapper; this.productSpecMapper = productSpecMapper; this.categoryService = categoryService; @@ -813,13 +812,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService { * 获取退款状态ID(通过 is_refund 字段查询) */ private List getRefundStatusIds() { - Long companyId = currentUserContext.getCurrentCompanyId(); - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(OrderStatusPO::getCompanyId, companyId) - .eq(OrderStatusPO::getIsRefund, 1) - .select(OrderStatusPO::getId); - List statusList = orderStatusService.list(wrapper); - return statusList.stream().map(OrderStatusPO::getId).collect(Collectors.toList()); + return orderStatusStatResolver.resolve(currentUserContext.getCurrentCompanyId()).getRefundStatusIds(); } /** 订单行上的 product_spec_id → 商品 id */ @@ -1077,14 +1070,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService { } private List getAutoStatisticsStatusIds(Long companyId) { - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(OrderStatusPO::getCompanyId, companyId) - .eq(OrderStatusPO::getAutoStatistics, 1) - .select(OrderStatusPO::getId); - List statusList = orderStatusService.list(wrapper); - return statusList.stream() - .map(OrderStatusPO::getId) - .collect(Collectors.toList()); + return orderStatusStatResolver.resolve(companyId).getUnionStatusIds(); } /** diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/ExportStatusRangeHelper.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/ExportStatusRangeHelper.java index a91fa06d..ae7340cf 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/ExportStatusRangeHelper.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/ExportStatusRangeHelper.java @@ -1,14 +1,12 @@ package top.xyquan.ecomdmbbackend.modules.ecom.overview.service.impl; -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import org.springframework.stereotype.Component; import top.xyquan.ecomdmbbackend.common.exception.BusinessException; -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.support.OrderStatusStatResolver; +import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets; import java.time.LocalDate; import java.util.List; -import java.util.stream.Collectors; /** * 导出共用的日期区间与订单状态 ID 解析 @@ -16,10 +14,10 @@ import java.util.stream.Collectors; @Component public class ExportStatusRangeHelper { - private final OrderStatusService orderStatusService; + private final OrderStatusStatResolver orderStatusStatResolver; - public ExportStatusRangeHelper(OrderStatusService orderStatusService) { - this.orderStatusService = orderStatusService; + public ExportStatusRangeHelper(OrderStatusStatResolver orderStatusStatResolver) { + this.orderStatusStatResolver = orderStatusStatResolver; } public LocalDate[] parseDateRange(List dateRange) { @@ -34,21 +32,18 @@ public class ExportStatusRangeHelper { return new LocalDate[]{start, end}; } + /** + * 任一会参与统计的维度为 1 的订单状态 ID(用于拉取订单并集) + */ public List getAutoStatusIds(Long companyId) { - List statusList = orderStatusService.list( - new LambdaQueryWrapper() - .eq(OrderStatusPO::getCompanyId, companyId) - .eq(OrderStatusPO::getAutoStatistics, 1) - .select(OrderStatusPO::getId)); - return statusList.stream().map(OrderStatusPO::getId).collect(Collectors.toList()); + return orderStatusStatResolver.resolve(companyId).getUnionStatusIds(); } public List getRefundStatusIds(Long companyId) { - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(OrderStatusPO::getCompanyId, companyId) - .eq(OrderStatusPO::getIsRefund, 1) - .select(OrderStatusPO::getId); - List statusList = orderStatusService.list(wrapper); - return statusList.stream().map(OrderStatusPO::getId).collect(Collectors.toList()); + return orderStatusStatResolver.resolve(companyId).getRefundStatusIds(); + } + + public OrderStatusStatSets resolveStat(Long companyId) { + return orderStatusStatResolver.resolve(companyId); } } diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/ShopOverviewStatisticsServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/ShopOverviewStatisticsServiceImpl.java index ab83882a..d24ddae5 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/ShopOverviewStatisticsServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/ShopOverviewStatisticsServiceImpl.java @@ -11,8 +11,8 @@ import top.xyquan.ecomdmbbackend.modules.ecom.promotion.mapper.PromotionFeeMappe import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.ShopOverviewQueryDTO; 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.status.model.po.OrderStatusPO; -import top.xyquan.ecomdmbbackend.modules.ecom.order.status.service.OrderStatusService; +import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatResolver; +import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets; 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.ProductSpecPO; @@ -56,7 +56,7 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics private final ShopService shopService; private final ProductService productService; private final ProductSpecMapper productSpecMapper; - private final OrderStatusService orderStatusService; + private final OrderStatusStatResolver orderStatusStatResolver; private final CategoryService categoryService; public ShopOverviewStatisticsServiceImpl(CurrentUserContext currentUserContext, @@ -67,7 +67,7 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics ShopService shopService, ProductService productService, ProductSpecMapper productSpecMapper, - OrderStatusService orderStatusService, + OrderStatusStatResolver orderStatusStatResolver, CategoryService categoryService) { this.currentUserContext = currentUserContext; this.orderMapper = orderMapper; @@ -77,7 +77,7 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics this.shopService = shopService; this.productService = productService; this.productSpecMapper = productSpecMapper; - this.orderStatusService = orderStatusService; + this.orderStatusStatResolver = orderStatusStatResolver; this.categoryService = categoryService; } @@ -104,7 +104,8 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics LocalDateTime startDateTime = startDate.atStartOfDay(); LocalDateTime endDateTime = endDate.atTime(23, 59, 59); - List autoStatisticsStatusIds = getAutoStatisticsStatusIds(companyId); + OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId); + List unionStatusIds = stat.getUnionStatusIds(); // 验证店铺是否存在 ShopPO shop = shopService.getById(queryDTO.getShopId()); @@ -118,8 +119,8 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics .eq(OrderPO::getShopId, queryDTO.getShopId()) .ge(OrderPO::getOrderTime, startDateTime) .le(OrderPO::getOrderTime, endDateTime); - if (!autoStatisticsStatusIds.isEmpty()) { - orderWrapper.in(OrderPO::getStatusId, autoStatisticsStatusIds); + if (!unionStatusIds.isEmpty()) { + orderWrapper.in(OrderPO::getStatusId, unionStatusIds); } else { orderWrapper.isNull(OrderPO::getId); } @@ -141,9 +142,6 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics .le(BrushOrderPO::getBrushTime, endDateTime); List brushOrders = brushOrderMapper.selectList(brushWrapper); - // 获取所有退款状态ID列表 - List refundStatusIds = getRefundStatusIds(); - // 计算上月同期数据(用于增长百分比) LocalDate lastMonthStartDate = startDate.minusMonths(1); LocalDate lastMonthEndDate = endDate.minusMonths(1); @@ -155,8 +153,8 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics .eq(OrderPO::getShopId, queryDTO.getShopId()) .ge(OrderPO::getOrderTime, lastMonthStartDateTime) .le(OrderPO::getOrderTime, lastMonthEndDateTime); - if (!autoStatisticsStatusIds.isEmpty()) { - lastMonthOrderWrapper.in(OrderPO::getStatusId, autoStatisticsStatusIds); + if (!unionStatusIds.isEmpty()) { + lastMonthOrderWrapper.in(OrderPO::getStatusId, unionStatusIds); } else { lastMonthOrderWrapper.isNull(OrderPO::getId); } @@ -171,15 +169,15 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics overviewVO.setShopName(shopEntity.getName()); } - // 1. 计算店铺总销售额 + // 1. 计算店铺总销售额(按状态「计入销售额」维度) BigDecimal totalSalesAmount = orders.stream() - .map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO) + .map(stat::receivedForSales) .reduce(BigDecimal.ZERO, BigDecimal::add); overviewVO.setTotalSalesAmount(totalSalesAmount); // 2. 计算较上月同期增长百分比 BigDecimal lastMonthSalesAmount = lastMonthOrders.stream() - .map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO) + .map(stat::receivedForSales) .reduce(BigDecimal.ZERO, BigDecimal::add); BigDecimal monthOverMonthGrowth = BigDecimal.ZERO; if (lastMonthSalesAmount.compareTo(BigDecimal.ZERO) > 0) { @@ -191,18 +189,14 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics } overviewVO.setMonthOverMonthGrowth(monthOverMonthGrowth); - // 3. 计算店铺总单量 - int totalOrderCount = orders.size(); + // 3. 计算店铺总单量(按状态「计入销售额」维度计单) + int totalOrderCount = (int) orders.stream().filter(o -> stat.includesSales(o.getStatusId())).count(); overviewVO.setTotalOrderCount(totalOrderCount); - // 3.1 退款金额、客单价(概览页与导出汇总表共用) - BigDecimal refundAmountAgg = BigDecimal.ZERO; - if (!refundStatusIds.isEmpty()) { - refundAmountAgg = orders.stream() - .filter(o -> refundStatusIds.contains(o.getStatusId())) - .map(o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - } + // 3.1 退款金额、客单价(按状态「计入退款」维度) + BigDecimal refundAmountAgg = orders.stream() + .map(stat::receivedForRefund) + .reduce(BigDecimal.ZERO, BigDecimal::add); overviewVO.setRefundAmount(refundAmountAgg); BigDecimal averageOrderValue = BigDecimal.ZERO; if (totalOrderCount > 0) { @@ -225,7 +219,7 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics overviewVO.setAverageFeeRatio(averageFeeRatio); // 6. 计算店铺总净利(税后)和总税额 - BigDecimal totalProfitBeforeTax = calculateTotalProfit(orders); + BigDecimal totalProfitBeforeTax = calculateTotalProfit(orders, stat); overviewVO.setTotalProfitBeforeTax(totalProfitBeforeTax); BigDecimal totalSalesTaxAmount = totalSalesAmount.multiply(taxRate); BigDecimal totalNetProfitAfterTax = totalProfitBeforeTax.subtract(totalSalesTaxAmount); @@ -236,24 +230,24 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics calculateTargetData(overviewVO, companyId, queryDTO.getShopId(), startDate, endDate, totalSalesAmount, totalOrderCount); // 8. 汇总ROI和总税后盈亏 - BigDecimal totalROI = calculateTotalROI(orders, promotionFees, brushOrders, refundStatusIds); + BigDecimal totalROI = calculateTotalROI(orders, promotionFees, brushOrders, stat); overviewVO.setTotalROI(totalROI); overviewVO.setTotalProfitAfterTax(totalNetProfitAfterTax); // 9. 计算趋势分析数据 - ShopOverviewStatisticsVO.TrendData salesAmountTrend = calculateSalesAmountTrend(orders, startDate, endDate); - ShopOverviewStatisticsVO.TrendData orderCountTrend = calculateOrderCountTrend(orders, startDate, endDate); + ShopOverviewStatisticsVO.TrendData salesAmountTrend = calculateSalesAmountTrend(orders, startDate, endDate, stat); + ShopOverviewStatisticsVO.TrendData orderCountTrend = calculateOrderCountTrend(orders, startDate, endDate, stat); overviewVO.setSalesAmountTrend(salesAmountTrend); overviewVO.setOrderCountTrend(orderCountTrend); // 10. 多商品数据横向汇总 ShopOverviewStatisticsVO.ProductOverview productOverview = calculateProductComparisons( - orders, promotionFees, brushOrders, refundStatusIds); + orders, promotionFees, brushOrders, stat); overviewVO.setProductOverview(productOverview); // 11. 品类多维度数据汇总 ShopOverviewStatisticsVO.CategoryOverview categoryOverview = calculateCategoryComparisons( - orders, promotionFees, brushOrders, refundStatusIds); + orders, promotionFees, brushOrders, stat); overviewVO.setCategoryOverview(categoryOverview); return overviewVO; @@ -262,17 +256,9 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics /** * 计算总利润(税前) */ - private BigDecimal calculateTotalProfit(List orders) { + private BigDecimal calculateTotalProfit(List orders, OrderStatusStatSets stat) { return orders.stream() - .map(order -> { - BigDecimal receivedAmount = order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO; - BigDecimal productCost = order.getProductCost() != null ? order.getProductCost() : BigDecimal.ZERO; - BigDecimal shippingCost = order.getShippingCost() != null ? order.getShippingCost() : BigDecimal.ZERO; - BigDecimal otherCost = order.getOtherCost() != null ? order.getOtherCost() : BigDecimal.ZERO; - Integer quantity = order.getQuantity() != null ? order.getQuantity() : 1; - BigDecimal totalCost = productCost.add(shippingCost).add(otherCost).multiply(new BigDecimal(quantity)); - return receivedAmount.subtract(totalCost); - }) + .map(order -> stat.receivedForSales(order).subtract(stat.totalCostForStats(order))) .reduce(BigDecimal.ZERO, BigDecimal::add); } @@ -335,13 +321,12 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics * 计算汇总ROI */ private BigDecimal calculateTotalROI(List orders, List promotionFees, - List brushOrders, List refundStatusIds) { + List brushOrders, OrderStatusStatSets stat) { BigDecimal totalSales = orders.stream() - .map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO) + .map(stat::receivedForSales) .reduce(BigDecimal.ZERO, BigDecimal::add); BigDecimal totalRefund = orders.stream() - .filter(order -> !refundStatusIds.isEmpty() && refundStatusIds.contains(order.getStatusId())) - .map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO) + .map(stat::receivedForRefund) .reduce(BigDecimal.ZERO, BigDecimal::add); BigDecimal totalPromotionFee = promotionFees.stream() .map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO) @@ -393,7 +378,7 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics */ private ShopOverviewStatisticsVO.ProductOverview calculateProductComparisons( List orders, List promotionFees, - List brushOrders, List refundStatusIds) { + List brushOrders, OrderStatusStatSets stat) { List comparisons = new ArrayList<>(); Map specToProduct = orderSpecIdToProductIdMap(orders); @@ -413,7 +398,7 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics .map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO) .reduce(BigDecimal.ZERO, BigDecimal::add); BigDecimal totalSalesAmount = orders.stream() - .map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO) + .map(stat::receivedForSales) .reduce(BigDecimal.ZERO, BigDecimal::add); for (Map.Entry> entry : ordersByProduct.entrySet()) { @@ -431,14 +416,15 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics // 计算各项指标 BigDecimal salesAmount = productOrders.stream() - .map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO) + .map(stat::receivedForSales) .reduce(BigDecimal.ZERO, BigDecimal::add); - int orderCount = productOrders.size(); + int orderCount = (int) productOrders.stream() + .filter(o -> stat.includesSales(o.getStatusId())) + .count(); BigDecimal refundAmount = productOrders.stream() - .filter(order -> !refundStatusIds.isEmpty() && refundStatusIds.contains(order.getStatusId())) - .map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO) + .map(stat::receivedForRefund) .reduce(BigDecimal.ZERO, BigDecimal::add); BigDecimal brushFee = brushOrdersByProduct.getOrDefault(productId, new ArrayList<>()).stream() @@ -454,32 +440,20 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics // 计算商品成本 BigDecimal productCost = productOrders.stream() - .map(order -> { - BigDecimal cost = order.getProductCost() != null ? order.getProductCost() : BigDecimal.ZERO; - Integer quantity = order.getQuantity() != null ? order.getQuantity() : 1; - return cost.multiply(new BigDecimal(quantity)); - }) + .map(stat::productCostForStats) .reduce(BigDecimal.ZERO, BigDecimal::add); // 计算运费成本 BigDecimal shippingCost = productOrders.stream() - .map(order -> { - BigDecimal cost = order.getShippingCost() != null ? order.getShippingCost() : BigDecimal.ZERO; - Integer quantity = order.getQuantity() != null ? order.getQuantity() : 1; - return cost.multiply(new BigDecimal(quantity)); - }) + .map(stat::freightCostForStats) .reduce(BigDecimal.ZERO, BigDecimal::add); // 计算其他成本 BigDecimal otherCost = productOrders.stream() - .map(order -> { - BigDecimal cost = order.getOtherCost() != null ? order.getOtherCost() : BigDecimal.ZERO; - Integer quantity = order.getQuantity() != null ? order.getQuantity() : 1; - return cost.multiply(new BigDecimal(quantity)); - }) + .map(stat::otherCostForStats) .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal totalCost = calculateProductTotalCost(productOrders); + BigDecimal totalCost = calculateProductTotalCost(productOrders, stat); BigDecimal profitBeforeTax = salesAmount.subtract(totalCost).subtract(refundAmount); // 销售额4%税额 @@ -597,31 +571,25 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics /** * 计算商品总成本(订单成本) */ - private BigDecimal calculateProductTotalCost(List orders) { + private BigDecimal calculateProductTotalCost(List orders, OrderStatusStatSets stat) { return orders.stream() - .map(order -> { - BigDecimal productCost = order.getProductCost() != null ? order.getProductCost() : BigDecimal.ZERO; - BigDecimal shippingCost = order.getShippingCost() != null ? order.getShippingCost() : BigDecimal.ZERO; - BigDecimal otherCost = order.getOtherCost() != null ? order.getOtherCost() : BigDecimal.ZERO; - Integer quantity = order.getQuantity() != null ? order.getQuantity() : 1; - return productCost.add(shippingCost).add(otherCost).multiply(new BigDecimal(quantity)); - }) + .map(stat::totalCostForStats) .reduce(BigDecimal.ZERO, BigDecimal::add); } /** * 计算销售额趋势分析 */ - private ShopOverviewStatisticsVO.TrendData calculateSalesAmountTrend(List orders, LocalDate startDate, LocalDate endDate) { + private ShopOverviewStatisticsVO.TrendData calculateSalesAmountTrend(List orders, LocalDate startDate, + LocalDate endDate, OrderStatusStatSets stat) { ShopOverviewStatisticsVO.TrendData trendData = new ShopOverviewStatisticsVO.TrendData(); // 按日期分组订单数据 Map> ordersByDate = orders.stream() .collect(Collectors.groupingBy(order -> order.getOrderTime().toLocalDate())); - // 计算总销售额 BigDecimal total = orders.stream() - .map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO) + .map(stat::receivedForSales) .reduce(BigDecimal.ZERO, BigDecimal::add); trendData.setTotal(total); @@ -640,7 +608,7 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics item.setDate(date); List dayOrders = ordersByDate.getOrDefault(date, new ArrayList<>()); BigDecimal dayAmount = dayOrders.stream() - .map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO) + .map(stat::receivedForSales) .reduce(BigDecimal.ZERO, BigDecimal::add); item.setValue(dayAmount); return item; @@ -655,15 +623,15 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics /** * 计算单量趋势分析 */ - private ShopOverviewStatisticsVO.TrendData calculateOrderCountTrend(List orders, LocalDate startDate, LocalDate endDate) { + private ShopOverviewStatisticsVO.TrendData calculateOrderCountTrend(List orders, LocalDate startDate, + LocalDate endDate, OrderStatusStatSets stat) { ShopOverviewStatisticsVO.TrendData trendData = new ShopOverviewStatisticsVO.TrendData(); // 按日期分组订单数据 Map> ordersByDate = orders.stream() .collect(Collectors.groupingBy(order -> order.getOrderTime().toLocalDate())); - // 计算总单量 - int totalCount = orders.size(); + int totalCount = (int) orders.stream().filter(o -> stat.includesSales(o.getStatusId())).count(); trendData.setTotal(new BigDecimal(totalCount)); // 生成日期范围内的所有日期列表 @@ -680,7 +648,7 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics ShopOverviewStatisticsVO.TrendDataItem item = new ShopOverviewStatisticsVO.TrendDataItem(); item.setDate(date); List dayOrders = ordersByDate.getOrDefault(date, new ArrayList<>()); - int dayCount = dayOrders.size(); + int dayCount = (int) dayOrders.stream().filter(o -> stat.includesSales(o.getStatusId())).count(); item.setValue(new BigDecimal(dayCount)); return item; }) @@ -691,38 +659,12 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics return trendData; } - /** - * 获取退款状态ID(通过 is_refund 字段查询) - */ - private List getRefundStatusIds() { - Long companyId = currentUserContext.getCurrentCompanyId(); - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(OrderStatusPO::getCompanyId, companyId) - .eq(OrderStatusPO::getIsRefund, 1) - .select(OrderStatusPO::getId); - List statusList = orderStatusService.list(wrapper); - return statusList.stream() - .map(OrderStatusPO::getId) - .collect(Collectors.toList()); - } - - private List getAutoStatisticsStatusIds(Long companyId) { - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(OrderStatusPO::getCompanyId, companyId) - .eq(OrderStatusPO::getAutoStatistics, 1) - .select(OrderStatusPO::getId); - List statusList = orderStatusService.list(wrapper); - return statusList.stream() - .map(OrderStatusPO::getId) - .collect(Collectors.toList()); - } - /** * 计算品类多维度数据汇总 */ private ShopOverviewStatisticsVO.CategoryOverview calculateCategoryComparisons( List orders, List promotionFees, - List brushOrders, List refundStatusIds) { + List brushOrders, OrderStatusStatSets stat) { // 构建商品ID->品类ID的映射 Map productCategoryMap = new HashMap<>(); @@ -760,7 +702,7 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics .map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO) .reduce(BigDecimal.ZERO, BigDecimal::add); BigDecimal totalSalesAmount = orders.stream() - .map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO) + .map(stat::receivedForSales) .reduce(BigDecimal.ZERO, BigDecimal::add); // 按品类聚合 @@ -770,14 +712,13 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics List catOrders = entry.getValue(); BigDecimal salesAmount = catOrders.stream() - .map(o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO) + .map(stat::receivedForSales) .reduce(BigDecimal.ZERO, BigDecimal::add); - int orderCount = catOrders.size(); + int orderCount = (int) catOrders.stream().filter(o -> stat.includesSales(o.getStatusId())).count(); BigDecimal refundAmount = catOrders.stream() - .filter(o -> !refundStatusIds.isEmpty() && refundStatusIds.contains(o.getStatusId())) - .map(o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO) + .map(stat::receivedForRefund) .reduce(BigDecimal.ZERO, BigDecimal::add); // 推广费按销售额比例 @@ -787,27 +728,17 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics salesAmount.divide(totalSalesAmount, 4, RoundingMode.HALF_UP)); } - // 成本聚合 BigDecimal productCost = catOrders.stream() - .map(o -> { - BigDecimal cost = o.getProductCost() != null ? o.getProductCost() : BigDecimal.ZERO; - Integer qty = o.getQuantity() != null ? o.getQuantity() : 1; - return cost.multiply(new BigDecimal(qty)); - }).reduce(BigDecimal.ZERO, BigDecimal::add); + .map(stat::productCostForStats) + .reduce(BigDecimal.ZERO, BigDecimal::add); BigDecimal shippingCost = catOrders.stream() - .map(o -> { - BigDecimal cost = o.getShippingCost() != null ? o.getShippingCost() : BigDecimal.ZERO; - Integer qty = o.getQuantity() != null ? o.getQuantity() : 1; - return cost.multiply(new BigDecimal(qty)); - }).reduce(BigDecimal.ZERO, BigDecimal::add); + .map(stat::freightCostForStats) + .reduce(BigDecimal.ZERO, BigDecimal::add); BigDecimal otherCost = catOrders.stream() - .map(o -> { - BigDecimal cost = o.getOtherCost() != null ? o.getOtherCost() : BigDecimal.ZERO; - Integer qty = o.getQuantity() != null ? o.getQuantity() : 1; - return cost.multiply(new BigDecimal(qty)); - }).reduce(BigDecimal.ZERO, BigDecimal::add); + .map(stat::otherCostForStats) + .reduce(BigDecimal.ZERO, BigDecimal::add); BigDecimal totalCost = productCost.add(shippingCost).add(otherCost); BigDecimal profitBeforeTax = salesAmount.subtract(totalCost).subtract(refundAmount); diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/product/overview/service/impl/ProductOverviewServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/product/overview/service/impl/ProductOverviewServiceImpl.java index f31c59bb..13a8ce49 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/product/overview/service/impl/ProductOverviewServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/product/overview/service/impl/ProductOverviewServiceImpl.java @@ -5,8 +5,8 @@ import org.springframework.stereotype.Service; import top.xyquan.ecomdmbbackend.common.exception.BusinessException; import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO; -import top.xyquan.ecomdmbbackend.modules.ecom.order.status.mapper.OrderStatusMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.po.OrderStatusPO; +import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatResolver; +import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets; 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.mapper.ProductSpecMapper; @@ -37,7 +37,7 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { private final CurrentUserContext currentUserContext; private final OrderMapper orderMapper; private final PromotionFeeMapper promotionFeeMapper; - private final OrderStatusMapper orderStatusMapper; + private final OrderStatusStatResolver orderStatusStatResolver; private final ProductService productService; private final ProductSpecMapper productSpecMapper; private final ShopMonthlyTargetMapper shopMonthlyTargetMapper; @@ -45,14 +45,14 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { public ProductOverviewServiceImpl(CurrentUserContext currentUserContext, OrderMapper orderMapper, PromotionFeeMapper promotionFeeMapper, - OrderStatusMapper orderStatusMapper, + OrderStatusStatResolver orderStatusStatResolver, ProductService productService, ProductSpecMapper productSpecMapper, ShopMonthlyTargetMapper shopMonthlyTargetMapper) { this.currentUserContext = currentUserContext; this.orderMapper = orderMapper; this.promotionFeeMapper = promotionFeeMapper; - this.orderStatusMapper = orderStatusMapper; + this.orderStatusStatResolver = orderStatusStatResolver; this.productService = productService; this.productSpecMapper = productSpecMapper; this.shopMonthlyTargetMapper = shopMonthlyTargetMapper; @@ -83,7 +83,8 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { ? queryDTO.getTaxRate() : new BigDecimal("0.04"); - List autoStatisticsStatusIds = getAutoStatisticsStatusIds(companyId); + OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId); + List unionStatusIds = stat.getUnionStatusIds(); // 查询订单数据 LambdaQueryWrapper orderWrapper = new LambdaQueryWrapper<>(); @@ -92,8 +93,8 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { queryDTO.getProductId()) .ge(OrderPO::getOrderTime, startDateTime) .le(OrderPO::getOrderTime, endDateTime); - if (!autoStatisticsStatusIds.isEmpty()) { - orderWrapper.in(OrderPO::getStatusId, autoStatisticsStatusIds); + if (!unionStatusIds.isEmpty()) { + orderWrapper.in(OrderPO::getStatusId, unionStatusIds); } else { orderWrapper.isNull(OrderPO::getId); } @@ -117,9 +118,6 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { promotionFees = promotionFeeMapper.selectList(promoWrapper); } - // 获取退款状态ID - Set refundStatusIds = getRefundStatusIds(companyId); - // 查询上月同期数据(用于环比计算) long dayCount = ChronoUnit.DAYS.between(startDate, endDate) + 1; LocalDate lastStartDate = startDate.minusDays(dayCount); @@ -133,8 +131,8 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { queryDTO.getProductId()) .ge(OrderPO::getOrderTime, lastStartTime) .le(OrderPO::getOrderTime, lastEndTime); - if (!autoStatisticsStatusIds.isEmpty()) { - lastPeriodWrapper.in(OrderPO::getStatusId, autoStatisticsStatusIds); + if (!unionStatusIds.isEmpty()) { + lastPeriodWrapper.in(OrderPO::getStatusId, unionStatusIds); } else { lastPeriodWrapper.isNull(OrderPO::getId); } @@ -146,22 +144,17 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { vo.setProductName(product.getName()); // ---------- KPI 汇总指标 ---------- - // 总销售额 + // 总销售额(按状态「计入销售额」维度) BigDecimal totalSalesAmount = orders.stream() - .map(o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO) + .map(stat::receivedForSales) .reduce(BigDecimal.ZERO, BigDecimal::add); vo.setTotalSalesAmount(totalSalesAmount); - // 总订单量(按平台订单号去重) - long totalOrderCount = orders.stream() - .map(OrderPO::getPlatformOrderNo) - .filter(no -> no != null && !no.isEmpty()) - .distinct() + // 总订单量(按状态「计入销售额」维度计单,与店铺概览一致) + int totalOrderCount = (int) orders.stream() + .filter(o -> stat.includesSales(o.getStatusId())) .count(); - if (totalOrderCount == 0) { - totalOrderCount = orders.size(); - } - vo.setTotalOrderCount((int) totalOrderCount); + vo.setTotalOrderCount(totalOrderCount); // 汇总客单价 BigDecimal avgOrderValue = totalOrderCount > 0 @@ -169,16 +162,15 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { : BigDecimal.ZERO; vo.setAverageOrderValue(avgOrderValue); - // 总退款金额(退款状态订单的实收金额) + // 总退款金额(按状态「计入退款」维度的实收金额) BigDecimal totalRefundAmount = orders.stream() - .filter(o -> refundStatusIds.contains(o.getStatusId())) - .map(o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO) + .map(stat::receivedForRefund) .reduce(BigDecimal.ZERO, BigDecimal::add); vo.setRefundAmount(totalRefundAmount); - // 总成本(含数量) + // 总成本(商品/运费/其他成本按各维度开关,含数量) BigDecimal totalCostAmount = orders.stream() - .map(this::calcOrderCost) + .map(stat::totalCostForStats) .reduce(BigDecimal.ZERO, BigDecimal::add); vo.setAverageFeeRatio(null); // 由 spec 维度均化,待后面补充 @@ -199,9 +191,10 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { vo.setAverageFeeRatio(avgFeeRatio.multiply(new BigDecimal("100")) .setScale(2, RoundingMode.HALF_UP)); // 转为百分比 - // 税前盈亏 = 销售额 - 成本 - 推广费 - BigDecimal totalProfitBeforeTax = totalSalesAmount - .subtract(totalCostAmount) + // 税前盈亏 = Σ(计入销售额的实收 - 按维度统计的成本) - 推广费 + BigDecimal totalProfitBeforeTax = orders.stream() + .map(o -> stat.receivedForSales(o).subtract(stat.totalCostForStats(o))) + .reduce(BigDecimal.ZERO, BigDecimal::add) .subtract(totalPromotionFee); vo.setTotalProfitBeforeTax(totalProfitBeforeTax); @@ -215,17 +208,16 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { vo.setTotalProfitAfterTax(totalProfitAfterTax); vo.setTotalNetProfitAfterTax(totalProfitAfterTax); - // ROI = (销售额 - 成本) / 推广费 + // ROI = (销售额 - 退款金额) / 推广费(与店铺概览 calculateSalesROI 口径一致) BigDecimal totalROI = totalPromotionFee.compareTo(BigDecimal.ZERO) > 0 - ? totalSalesAmount.subtract(totalCostAmount) - .divide(totalPromotionFee, 2, RoundingMode.HALF_UP) - .multiply(new BigDecimal("100")) + ? totalSalesAmount.subtract(totalRefundAmount) + .divide(totalPromotionFee, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO; vo.setTotalROI(totalROI); // ---------- 环比增长(上月同期) ---------- BigDecimal lastPeriodSales = lastPeriodOrders.stream() - .map(o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO) + .map(stat::receivedForSales) .reduce(BigDecimal.ZERO, BigDecimal::add); BigDecimal monthOverMonthGrowth = BigDecimal.ZERO; if (lastPeriodSales.compareTo(BigDecimal.ZERO) > 0) { @@ -268,7 +260,7 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { vo.setSalesAmountAchievementRate(salesRate); } if (totalTargetOrderCount != null && totalTargetOrderCount > 0) { - BigDecimal orderRate = BigDecimal.valueOf(totalOrderCount) + BigDecimal orderRate = BigDecimal.valueOf((long) totalOrderCount) .divide(BigDecimal.valueOf(totalTargetOrderCount), 4, RoundingMode.HALF_UP) .multiply(new BigDecimal("100")) .setScale(2, RoundingMode.HALF_UP); @@ -278,29 +270,17 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { // ---------- 趋势数据 ---------- vo.setSalesAmountTrend(buildTrend(orders, dateList -> dateList.stream() - .map(o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO) + .map(stat::receivedForSales) .reduce(BigDecimal.ZERO, BigDecimal::add), startDate, endDate)); - vo.setOrderCountTrend(buildOrderCountTrend(orders, startDate, endDate)); + vo.setOrderCountTrend(buildOrderCountTrend(orders, stat, startDate, endDate)); // ---------- 规格销售汇总 ---------- - vo.setSpecSummaries(buildSpecSummary(orders, promotionFees, refundStatusIds, taxRate, shopIds)); + vo.setSpecSummaries(buildSpecSummary(orders, promotionFees, stat, taxRate, shopIds)); return vo; } - /** - * 计算单笔订单总成本(含数量) - */ - private BigDecimal calcOrderCost(OrderPO order) { - BigDecimal productCost = order.getProductCost() != null ? order.getProductCost() : BigDecimal.ZERO; - BigDecimal shippingCost = order.getShippingCost() != null ? order.getShippingCost() : BigDecimal.ZERO; - BigDecimal otherCost = order.getOtherCost() != null ? order.getOtherCost() : BigDecimal.ZERO; - int quantity = order.getQuantity() != null ? order.getQuantity() : 1; - return productCost.add(shippingCost).add(otherCost) - .multiply(BigDecimal.valueOf(quantity)); - } - /** * 构建销售趋势 */ @@ -337,6 +317,7 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { * 构建订单数趋势 */ private ProductOverviewVO.TrendData buildOrderCountTrend(List orders, + OrderStatusStatSets stat, LocalDate startDate, LocalDate endDate) { Map> ordersByDate = orders.stream() .collect(Collectors.groupingBy(o -> o.getOrderTime().toLocalDate())); @@ -345,13 +326,9 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { LocalDate current = startDate; while (!current.isAfter(endDate)) { List dayOrders = ordersByDate.getOrDefault(current, List.of()); - // 按平台订单号去重 long count = dayOrders.stream() - .map(OrderPO::getPlatformOrderNo) - .filter(no -> no != null && !no.isEmpty()) - .distinct() + .filter(o -> stat.includesSales(o.getStatusId())) .count(); - if (count == 0) count = dayOrders.size(); ProductOverviewVO.TrendDataItem item = new ProductOverviewVO.TrendDataItem(); item.setDate(current); @@ -360,9 +337,8 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { current = current.plusDays(1); } - BigDecimal total = BigDecimal.valueOf(dailyList.stream() - .mapToLong(i -> i.getValue().longValue()) - .sum()); + long sumDaily = dailyList.stream().mapToLong(i -> i.getValue().longValue()).sum(); + BigDecimal total = BigDecimal.valueOf(sumDaily); ProductOverviewVO.TrendData trend = new ProductOverviewVO.TrendData(); trend.setTotal(total); @@ -375,7 +351,7 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { */ private ProductOverviewVO.SpecSummary buildSpecSummary(List orders, List promotionFees, - Set refundStatusIds, + OrderStatusStatSets stat, BigDecimal taxRate, List shopIds) { // 查询商品所有规格 @@ -426,18 +402,15 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { List specOrders = entry.getValue(); ProductSpecPO spec = specMap.get(specId); - // 该规格的销售额 + // 该规格的销售额(计入销售额维度) BigDecimal salesAmount = specOrders.stream() - .map(o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO) + .map(stat::receivedForSales) .reduce(BigDecimal.ZERO, BigDecimal::add); - // 该规格的订单量(去重) - long orderCount = specOrders.stream() - .map(OrderPO::getPlatformOrderNo) - .filter(no -> no != null && !no.isEmpty()) - .distinct() + // 该规格的订单量(计入销售额维度计单) + int orderCount = (int) specOrders.stream() + .filter(o -> stat.includesSales(o.getStatusId())) .count(); - if (orderCount == 0) orderCount = specOrders.size(); // 总件数 int quantity = specOrders.stream() @@ -445,38 +418,35 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { .reduce(0, Integer::sum); // 客单价 - BigDecimal avgOV = BigDecimal.valueOf(orderCount).compareTo(BigDecimal.ZERO) > 0 + BigDecimal avgOV = orderCount > 0 ? salesAmount.divide(BigDecimal.valueOf(orderCount), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO; - // 商品成本 + // 商品 / 运费 / 其他成本(各维度开关 + 数量,与店铺商品对比一致) BigDecimal productCostTotal = specOrders.stream() - .map(o -> { - BigDecimal pc = o.getProductCost() != null ? o.getProductCost() : BigDecimal.ZERO; - int qty = o.getQuantity() != null ? o.getQuantity() : 1; - return pc.multiply(BigDecimal.valueOf(qty)); - }) + .map(stat::productCostForStats) .reduce(BigDecimal.ZERO, BigDecimal::add); - - // 运费 + 其他成本 BigDecimal shippingCostTotal = specOrders.stream() - .map(o -> o.getShippingCost() != null ? o.getShippingCost() : BigDecimal.ZERO) + .map(stat::freightCostForStats) .reduce(BigDecimal.ZERO, BigDecimal::add); BigDecimal otherCostTotal = specOrders.stream() - .map(o -> o.getOtherCost() != null ? o.getOtherCost() : BigDecimal.ZERO) + .map(stat::otherCostForStats) .reduce(BigDecimal.ZERO, BigDecimal::add); - // 退款金额 + BigDecimal totalCostStat = specOrders.stream() + .map(stat::totalCostForStats) + .reduce(BigDecimal.ZERO, BigDecimal::add); + + // 退款金额(计入退款维度) BigDecimal refundAmount = specOrders.stream() - .filter(o -> refundStatusIds.contains(o.getStatusId())) - .map(o -> o.getReceivedAmount() != null ? o.getReceivedAmount() : BigDecimal.ZERO) + .map(stat::receivedForRefund) .reduce(BigDecimal.ZERO, BigDecimal::add); // 推广费分摊(按该规格订单数占所有订单数比例) int totalOrderCountAll = orders.size(); BigDecimal specPromotionFee = BigDecimal.ZERO; if (totalOrderCountAll > 0) { - BigDecimal proportion = BigDecimal.valueOf(orderCount) + BigDecimal proportion = BigDecimal.valueOf((long) orderCount) .divide(BigDecimal.valueOf(totalOrderCountAll), 4, RoundingMode.HALF_UP); BigDecimal totalPromo = shopPromotionFeeMap.values().stream() .reduce(BigDecimal.ZERO, BigDecimal::add); @@ -489,22 +459,20 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { ? specPromotionFee.divide(salesAmount, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO; - // 税前盈亏 + // 税前盈亏(与店铺商品对比:销售额 - 总成本 - 退款金额 - 推广费) BigDecimal profitBeforeTax = salesAmount - .subtract(productCostTotal) - .subtract(shippingCostTotal) - .subtract(otherCostTotal) + .subtract(totalCostStat) + .subtract(refundAmount) .subtract(specPromotionFee); // 税额 BigDecimal salesTaxAmount = salesAmount.multiply(taxRate) .setScale(2, RoundingMode.HALF_UP); - // ROI + // ROI = (销售额 - 退款) / 推广费 BigDecimal roi = specPromotionFee.compareTo(BigDecimal.ZERO) > 0 - ? salesAmount.subtract(productCostTotal) - .divide(specPromotionFee, 2, RoundingMode.HALF_UP) - .multiply(new BigDecimal("100")) + ? salesAmount.subtract(refundAmount) + .divide(specPromotionFee, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO; // 税后盈亏 @@ -515,13 +483,13 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { item.setSpecName(spec != null ? spec.getName() : "未知规格"); item.setSpecCode(spec != null ? spec.getSpecCode() : null); item.setSalesAmount(salesAmount); - item.setOrderCount((int) orderCount); + item.setOrderCount(orderCount); item.setQuantity(quantity); item.setAverageOrderValue(avgOV); item.setProductCost(productCostTotal); item.setShippingCost(shippingCostTotal); item.setOtherCost(otherCostTotal); - item.setTotalCost(productCostTotal.add(shippingCostTotal).add(otherCostTotal)); + item.setTotalCost(totalCostStat); item.setRefundAmount(refundAmount); item.setPromotionFee(specPromotionFee); item.setFeeRatio(feeRatio.multiply(new BigDecimal("100")) @@ -571,19 +539,18 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { .setScale(2, RoundingMode.HALF_UP)); BigDecimal totalProfitBT = total.getSalesAmount() - .subtract(total.getProductCost()) - .subtract(total.getShippingCost()) - .subtract(total.getOtherCost()) + .subtract(total.getTotalCost()) + .subtract(total.getRefundAmount()) .subtract(total.getPromotionFee()); total.setProfitBeforeTax(totalProfitBT); BigDecimal totalSalesTax = totalSalesAmt.multiply(taxRate).setScale(2, RoundingMode.HALF_UP); total.setSalesTaxAmount(totalSalesTax); + BigDecimal totalRefundForRoi = total.getRefundAmount(); BigDecimal totalRoi = totalPromoFee.compareTo(BigDecimal.ZERO) > 0 - ? totalSalesAmt.subtract(total.getProductCost()) - .divide(totalPromoFee, 2, RoundingMode.HALF_UP) - .multiply(new BigDecimal("100")) + ? totalSalesAmt.subtract(totalRefundForRoi) + .divide(totalPromoFee, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO; total.setRoi(totalRoi); @@ -618,30 +585,4 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { summary.setTotal(total); return summary; } - - /** - * 获取参与统计的订单状态ID列表 - */ - private List getAutoStatisticsStatusIds(Long companyId) { - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(OrderStatusPO::getCompanyId, companyId) - .eq(OrderStatusPO::getAutoStatistics, 1) - .select(OrderStatusPO::getId); - return orderStatusMapper.selectList(wrapper).stream() - .map(OrderStatusPO::getId) - .collect(Collectors.toList()); - } - - /** - * 获取退款状态ID集合 - */ - private Set getRefundStatusIds(Long companyId) { - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(OrderStatusPO::getCompanyId, companyId) - .eq(OrderStatusPO::getIsRefund, 1) - .select(OrderStatusPO::getId); - return orderStatusMapper.selectList(wrapper).stream() - .map(OrderStatusPO::getId) - .collect(Collectors.toSet()); - } } diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/order-status/apis.ts b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/order-status/apis.ts index b3cacd20..63bbaf59 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/order-status/apis.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/order-status/apis.ts @@ -30,11 +30,11 @@ export async function updateOrderStatusApi( } /** - * 部分更新订单状态(仅自动统计和退款状态) + * 部分更新订单状态(统计维度开关,字段可选) */ export async function patchOrderStatusApi( id: number, - data: { autoStatistics?: number; isRefund?: number }, + data: OrderStatusDTO.Patch, ) { return requestClient.request( `/ec/order-status/update/${id}`, diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/order-status/types/types.dto.ts b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/order-status/types/types.dto.ts index 9e1859c4..5c409e63 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/order-status/types/types.dto.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/order-status/types/types.dto.ts @@ -13,10 +13,16 @@ export namespace OrderStatusDTO { color?: string; /** 排序 */ sortOrder?: number; - /** 自动统计 0不参与 1参与 */ - autoStatistics: number; - /** 是否为退款状态 0否 1是 */ - isRefund?: number; + /** 是否计入销售额/单量等统计 0否 1是 */ + includeSalesAmount?: number; + /** 是否计入商品成本统计 0否 1是 */ + includeProductCost?: number; + /** 是否计入运费成本统计 0否 1是 */ + includeFreightCost?: number; + /** 是否计入其他成本统计 0否 1是 */ + includeOtherCost?: number; + /** 是否计入退款金额统计 0否 1是 */ + includeRefund?: number; } /** 更新订单状态参数 */ @@ -29,9 +35,24 @@ export namespace OrderStatusDTO { color?: string; /** 排序 */ sortOrder?: number; - /** 自动统计 0不参与 1参与 */ - autoStatistics: number; - /** 是否为退款状态 0否 1是 */ - isRefund?: number; + /** 是否计入销售额/单量等统计 0否 1是 */ + includeSalesAmount: number; + /** 是否计入商品成本统计 0否 1是 */ + includeProductCost: number; + /** 是否计入运费成本统计 0否 1是 */ + includeFreightCost: number; + /** 是否计入其他成本统计 0否 1是 */ + includeOtherCost: number; + /** 是否计入退款金额统计 0否 1是 */ + includeRefund: number; + } + + /** PATCH 部分更新(任意字段可选,与后端 PatchOrderStatusDTO 对齐) */ + export interface Patch { + includeSalesAmount?: number; + includeProductCost?: number; + includeFreightCost?: number; + includeOtherCost?: number; + includeRefund?: number; } } diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/order-status/types/types.vo.ts b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/order-status/types/types.vo.ts index 19f51e72..ce06221b 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/order-status/types/types.vo.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/order-status/types/types.vo.ts @@ -17,10 +17,16 @@ export namespace OrderStatusVO { color?: string; /** 排序 */ sortOrder?: number; - /** 自动统计 0不参与 1参与 */ - autoStatistics: number; - /** 是否为退款状态 0否 1是 */ - isRefund?: number; + /** 是否计入销售额/单量等统计 0否 1是 */ + includeSalesAmount: number; + /** 是否计入商品成本统计 0否 1是 */ + includeProductCost: number; + /** 是否计入运费成本统计 0否 1是 */ + includeFreightCost: number; + /** 是否计入其他成本统计 0否 1是 */ + includeOtherCost: number; + /** 是否计入退款金额统计 0否 1是 */ + includeRefund: number; /** 创建时间 */ createTime: string; /** 更新时间 */ diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/ecommerce/config/order-status-config/components/OrderStatusCard.vue b/ecom-dmb-frontend/apps/web-antd/src/views/ecommerce/config/order-status-config/components/OrderStatusCard.vue new file mode 100644 index 00000000..f3a86716 --- /dev/null +++ b/ecom-dmb-frontend/apps/web-antd/src/views/ecommerce/config/order-status-config/components/OrderStatusCard.vue @@ -0,0 +1,241 @@ + + + + + diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/ecommerce/config/order-status-config/components/OrderStatusFormModal.vue b/ecom-dmb-frontend/apps/web-antd/src/views/ecommerce/config/order-status-config/components/OrderStatusFormModal.vue index ebb91584..f298c0f6 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/views/ecommerce/config/order-status-config/components/OrderStatusFormModal.vue +++ b/ecom-dmb-frontend/apps/web-antd/src/views/ecommerce/config/order-status-config/components/OrderStatusFormModal.vue @@ -20,10 +20,18 @@ const emit = defineEmits<{ success: []; }>(); +const STAT_DEFAULTS = { + includeSalesAmount: 1, + includeProductCost: 1, + includeFreightCost: 1, + includeOtherCost: 1, + includeRefund: 0, +} as const; + // 创建 vben modal const [Modal, modalApi] = useVbenModal({ draggable: true, - class: 'w-[500px]', + class: 'w-[640px]', onCancel() { close(); }, @@ -49,9 +57,8 @@ const formData = ref>({ statusName: '', description: '', color: '', - autoStatistics: 1, sortOrder: 0, - isRefund: 0, + ...STAT_DEFAULTS, }); // 表单验证规则 @@ -63,6 +70,10 @@ const rules = { // 表单引用 const formRef = ref(); +function toStatNumber(v: number | undefined, fallback: number) { + return v === 0 || v === 1 ? v : fallback; +} + // 打开模态框 function open(edit: boolean, record?: OrderStatusVO.Info) { isEdit.value = edit; @@ -76,17 +87,34 @@ function open(edit: boolean, record?: OrderStatusVO.Info) { statusName: record.statusName, description: record.description || '', color: record.color || '', - autoStatistics: record.autoStatistics, sortOrder: record.sortOrder || 0, - isRefund: record.isRefund || 0, + includeSalesAmount: toStatNumber( + record.includeSalesAmount, + STAT_DEFAULTS.includeSalesAmount, + ), + includeProductCost: toStatNumber( + record.includeProductCost, + STAT_DEFAULTS.includeProductCost, + ), + includeFreightCost: toStatNumber( + record.includeFreightCost, + STAT_DEFAULTS.includeFreightCost, + ), + includeOtherCost: toStatNumber( + record.includeOtherCost, + STAT_DEFAULTS.includeOtherCost, + ), + includeRefund: toStatNumber( + record.includeRefund, + STAT_DEFAULTS.includeRefund, + ), } : { statusName: '', description: '', color: '', - autoStatistics: 1, sortOrder: 0, - isRefund: 0, + ...STAT_DEFAULTS, }; } @@ -108,27 +136,31 @@ async function handleSubmit() { await formRef.value?.validate(); loading.value = true; + const dims = { + includeSalesAmount: formData.value.includeSalesAmount!, + includeProductCost: formData.value.includeProductCost!, + includeFreightCost: formData.value.includeFreightCost!, + includeOtherCost: formData.value.includeOtherCost!, + includeRefund: formData.value.includeRefund!, + }; + if (isEdit.value && currentRecord.value) { - // 更新订单状态 const updateData: OrderStatusDTO.Update = { statusName: formData.value.statusName!, description: formData.value.description, color: formData.value.color, - autoStatistics: formData.value.autoStatistics!, sortOrder: formData.value.sortOrder, - isRefund: formData.value.isRefund, + ...dims, }; await updateOrderStatusApi(currentRecord.value.id, updateData); message.success('更新订单状态成功'); } else { - // 创建订单状态 const createData: OrderStatusDTO.Create = { statusName: formData.value.statusName!, description: formData.value.description, color: formData.value.color, - autoStatistics: formData.value.autoStatistics!, sortOrder: formData.value.sortOrder, - isRefund: formData.value.isRefund, + ...dims, }; await createOrderStatusApi(createData); message.success('创建订单状态成功'); @@ -216,27 +248,58 @@ defineExpose({ :min="0" /> + - +
+ 统计维度(0/1) +
+
+ + + + + + + + + + + + +
- - - - diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/ecommerce/config/order-status-config/index.vue b/ecom-dmb-frontend/apps/web-antd/src/views/ecommerce/config/order-status-config/index.vue index 9530a539..aaf3183b 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/views/ecommerce/config/order-status-config/index.vue +++ b/ecom-dmb-frontend/apps/web-antd/src/views/ecommerce/config/order-status-config/index.vue @@ -1,294 +1,379 @@ + + + +