refactor(ecom): 订单状态统计规则从单一开关升级为多维度独立控制

- ec_order_status 表 auto_statistics 拆分为四个独立字段:include_sales_amount / include_product_cost / include_freight_cost / include_other_cost / include_refund
- CompanyOverviewServiceImpl / ShopOverviewStatisticsServiceImpl / ProductOverviewServiceImpl / ExportStatusRangeHelper 全部改为按各维度独立统计
- OrderStatus PO/DTO/VO 层字段更新,Service 层校验逻辑同步调整
- ProductSpecImportHelper 导入逻辑适配新字段
- 前端订单状态配置页适配新字段及展示
- 新增 OrderStatusCard.vue 卡片组件
- 更新 ec_design.sql 设计文档
This commit is contained in:
小蟑螂
2026-05-05 21:09:46 +08:00
parent a1953d5447
commit c6025a7c2c
22 changed files with 1173 additions and 616 deletions
+7 -4
View File
@@ -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
@@ -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`;
@@ -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);
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
/**
* 创建时间
@@ -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;
/**
* 创建时间
@@ -33,7 +33,7 @@ public interface OrderStatusService extends IService<OrderStatusPO> {
OrderStatusVO updateOrderStatus(UpdateOrderStatusDTO updateOrderStatusDTO, Long id);
/**
* 部分更新订单状态(仅更新 autoStatistics 和 isRefund)
* 部分更新订单状态(仅更新各统计维度开关)
*
* @param patchDTO 部分更新DTO
* @param id 订单状态ID
@@ -59,12 +59,7 @@ public class OrderStatusServiceImpl extends ServiceImpl<OrderStatusMapper, Order
if (orderStatus.getSortOrder() == null) {
orderStatus.setSortOrder(0);
}
if (orderStatus.getAutoStatistics() == null) {
orderStatus.setAutoStatistics(1);
}
if (orderStatus.getIsRefund() == null) {
orderStatus.setIsRefund(0);
}
applyStatDefaultsForCreate(orderStatus);
// 设置创建人ID
orderStatus.setCreateBy(currentUserContext.getCurrentUserId());
@@ -121,7 +116,7 @@ public class OrderStatusServiceImpl extends ServiceImpl<OrderStatusMapper, Order
}
/**
* 部分更新订单状态(仅更新 autoStatistics 和 isRefund)
* 部分更新订单状态(仅更新各统计维度开关)
*
* @param patchDTO 部分更新DTO
* @param id 订单状态ID
@@ -138,12 +133,20 @@ public class OrderStatusServiceImpl extends ServiceImpl<OrderStatusMapper, Order
throw new BusinessException("订单状态不存在");
}
// 只更新传入的字段
if (patchDTO.getAutoStatistics() != null) {
existingStatus.setAutoStatistics(patchDTO.getAutoStatistics());
if (patchDTO.getIncludeSalesAmount() != null) {
existingStatus.setIncludeSalesAmount(patchDTO.getIncludeSalesAmount());
}
if (patchDTO.getIsRefund() != null) {
existingStatus.setIsRefund(patchDTO.getIsRefund());
if (patchDTO.getIncludeProductCost() != null) {
existingStatus.setIncludeProductCost(patchDTO.getIncludeProductCost());
}
if (patchDTO.getIncludeFreightCost() != null) {
existingStatus.setIncludeFreightCost(patchDTO.getIncludeFreightCost());
}
if (patchDTO.getIncludeOtherCost() != null) {
existingStatus.setIncludeOtherCost(patchDTO.getIncludeOtherCost());
}
if (patchDTO.getIncludeRefund() != null) {
existingStatus.setIncludeRefund(patchDTO.getIncludeRefund());
}
existingStatus.setUpdateBy(currentUserContext.getCurrentUserId());
@@ -228,5 +231,24 @@ public class OrderStatusServiceImpl extends ServiceImpl<OrderStatusMapper, Order
BeanUtils.copyProperties(orderStatus, vo);
return vo;
}
/** 创建时未传的统计开关默认:前四项参与(等同原 auto_statistics=1),退款不参与 */
private void applyStatDefaultsForCreate(OrderStatusPO p) {
if (p.getIncludeSalesAmount() == null) {
p.setIncludeSalesAmount(1);
}
if (p.getIncludeProductCost() == null) {
p.setIncludeProductCost(1);
}
if (p.getIncludeFreightCost() == null) {
p.setIncludeFreightCost(1);
}
if (p.getIncludeOtherCost() == null) {
p.setIncludeOtherCost(1);
}
if (p.getIncludeRefund() == null) {
p.setIncludeRefund(0);
}
}
}
@@ -0,0 +1,31 @@
package top.xyquan.ecomdmbbackend.modules.ecom.order.status.support;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Component;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.po.OrderStatusPO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.service.OrderStatusService;
import java.util.List;
/**
* 加载当前公司的订单状态并解析为 {@link OrderStatusStatSets}。
*/
@Component
public class OrderStatusStatResolver {
private final OrderStatusService orderStatusService;
public OrderStatusStatResolver(OrderStatusService orderStatusService) {
this.orderStatusService = orderStatusService;
}
public OrderStatusStatSets resolve(Long companyId) {
if (companyId == null) {
return OrderStatusStatSets.from(List.of());
}
List<OrderStatusPO> list = orderStatusService.list(
new LambdaQueryWrapper<OrderStatusPO>()
.eq(OrderStatusPO::getCompanyId, companyId));
return OrderStatusStatSets.from(list);
}
}
@@ -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<Long> unionStatusIds;
private final Set<Long> salesIds;
private final Set<Long> productCostIds;
private final Set<Long> freightCostIds;
private final Set<Long> otherCostIds;
private final Set<Long> refundIds;
private OrderStatusStatSets(List<Long> unionStatusIds,
Set<Long> salesIds,
Set<Long> productCostIds,
Set<Long> freightCostIds,
Set<Long> otherCostIds,
Set<Long> refundIds) {
this.unionStatusIds = unionStatusIds;
this.salesIds = salesIds;
this.productCostIds = productCostIds;
this.freightCostIds = freightCostIds;
this.otherCostIds = otherCostIds;
this.refundIds = refundIds;
}
public static OrderStatusStatSets from(List<OrderStatusPO> statuses) {
Set<Long> union = new HashSet<>();
Set<Long> sales = new HashSet<>();
Set<Long> productCost = new HashSet<>();
Set<Long> freightCost = new HashSet<>();
Set<Long> otherCost = new HashSet<>();
Set<Long> 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<Long> 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<Long> 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;
}
}
@@ -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<Long> getRefundStatusIds() {
Long companyId = currentUserContext.getCurrentCompanyId();
LambdaQueryWrapper<OrderStatusPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderStatusPO::getCompanyId, companyId)
.eq(OrderStatusPO::getIsRefund, 1)
.select(OrderStatusPO::getId);
List<OrderStatusPO> 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<Long> getAutoStatisticsStatusIds(Long companyId) {
LambdaQueryWrapper<OrderStatusPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderStatusPO::getCompanyId, companyId)
.eq(OrderStatusPO::getAutoStatistics, 1)
.select(OrderStatusPO::getId);
List<OrderStatusPO> statusList = orderStatusService.list(wrapper);
return statusList.stream()
.map(OrderStatusPO::getId)
.collect(Collectors.toList());
return orderStatusStatResolver.resolve(companyId).getUnionStatusIds();
}
/**
@@ -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<LocalDate> dateRange) {
@@ -34,21 +32,18 @@ public class ExportStatusRangeHelper {
return new LocalDate[]{start, end};
}
/**
* 任一会参与统计的维度为 1 的订单状态 ID(用于拉取订单并集)
*/
public List<Long> getAutoStatusIds(Long companyId) {
List<OrderStatusPO> statusList = orderStatusService.list(
new LambdaQueryWrapper<OrderStatusPO>()
.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<Long> getRefundStatusIds(Long companyId) {
LambdaQueryWrapper<OrderStatusPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderStatusPO::getCompanyId, companyId)
.eq(OrderStatusPO::getIsRefund, 1)
.select(OrderStatusPO::getId);
List<OrderStatusPO> 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);
}
}
@@ -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<Long> autoStatisticsStatusIds = getAutoStatisticsStatusIds(companyId);
OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId);
List<Long> 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<BrushOrderPO> brushOrders = brushOrderMapper.selectList(brushWrapper);
// 获取所有退款状态ID列表
List<Long> 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<OrderPO> orders) {
private BigDecimal calculateTotalProfit(List<OrderPO> 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<OrderPO> orders, List<PromotionFeePO> promotionFees,
List<BrushOrderPO> brushOrders, List<Long> refundStatusIds) {
List<BrushOrderPO> 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<OrderPO> orders, List<PromotionFeePO> promotionFees,
List<BrushOrderPO> brushOrders, List<Long> refundStatusIds) {
List<BrushOrderPO> brushOrders, OrderStatusStatSets stat) {
List<ShopOverviewStatisticsVO.ProductComparison> comparisons = new ArrayList<>();
Map<Long, Long> 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<Long, List<OrderPO>> 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<OrderPO> orders) {
private BigDecimal calculateProductTotalCost(List<OrderPO> 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<OrderPO> orders, LocalDate startDate, LocalDate endDate) {
private ShopOverviewStatisticsVO.TrendData calculateSalesAmountTrend(List<OrderPO> orders, LocalDate startDate,
LocalDate endDate, OrderStatusStatSets stat) {
ShopOverviewStatisticsVO.TrendData trendData = new ShopOverviewStatisticsVO.TrendData();
// 按日期分组订单数据
Map<LocalDate, List<OrderPO>> 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<OrderPO> 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<OrderPO> orders, LocalDate startDate, LocalDate endDate) {
private ShopOverviewStatisticsVO.TrendData calculateOrderCountTrend(List<OrderPO> orders, LocalDate startDate,
LocalDate endDate, OrderStatusStatSets stat) {
ShopOverviewStatisticsVO.TrendData trendData = new ShopOverviewStatisticsVO.TrendData();
// 按日期分组订单数据
Map<LocalDate, List<OrderPO>> 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<OrderPO> 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<Long> getRefundStatusIds() {
Long companyId = currentUserContext.getCurrentCompanyId();
LambdaQueryWrapper<OrderStatusPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderStatusPO::getCompanyId, companyId)
.eq(OrderStatusPO::getIsRefund, 1)
.select(OrderStatusPO::getId);
List<OrderStatusPO> statusList = orderStatusService.list(wrapper);
return statusList.stream()
.map(OrderStatusPO::getId)
.collect(Collectors.toList());
}
private List<Long> getAutoStatisticsStatusIds(Long companyId) {
LambdaQueryWrapper<OrderStatusPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderStatusPO::getCompanyId, companyId)
.eq(OrderStatusPO::getAutoStatistics, 1)
.select(OrderStatusPO::getId);
List<OrderStatusPO> statusList = orderStatusService.list(wrapper);
return statusList.stream()
.map(OrderStatusPO::getId)
.collect(Collectors.toList());
}
/**
* 计算品类多维度数据汇总
*/
private ShopOverviewStatisticsVO.CategoryOverview calculateCategoryComparisons(
List<OrderPO> orders, List<PromotionFeePO> promotionFees,
List<BrushOrderPO> brushOrders, List<Long> refundStatusIds) {
List<BrushOrderPO> brushOrders, OrderStatusStatSets stat) {
// 构建商品ID->品类ID的映射
Map<Long, Long> 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<OrderPO> 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);
@@ -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<Long> autoStatisticsStatusIds = getAutoStatisticsStatusIds(companyId);
OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId);
List<Long> unionStatusIds = stat.getUnionStatusIds();
// 查询订单数据
LambdaQueryWrapper<OrderPO> 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<Long> 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<OrderPO> orders,
OrderStatusStatSets stat,
LocalDate startDate, LocalDate endDate) {
Map<LocalDate, List<OrderPO>> 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<OrderPO> 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<OrderPO> orders,
List<PromotionFeePO> promotionFees,
Set<Long> refundStatusIds,
OrderStatusStatSets stat,
BigDecimal taxRate,
List<Long> shopIds) {
// 查询商品所有规格
@@ -426,18 +402,15 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
List<OrderPO> 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<Long> getAutoStatisticsStatusIds(Long companyId) {
LambdaQueryWrapper<OrderStatusPO> 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<Long> getRefundStatusIds(Long companyId) {
LambdaQueryWrapper<OrderStatusPO> 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());
}
}
@@ -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<OrderStatusVO.Info>(
`/ec/order-status/update/${id}`,
@@ -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;
}
}
@@ -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;
/** 更新时间 */
@@ -0,0 +1,241 @@
<script lang="ts" setup>
import type { OrderStatusVO } from '#/api/ecommerce/order-status';
import { patchOrderStatusApi } from '#/api/ecommerce/order-status';
import { createIconifyIcon } from '@vben/icons';
import { Button, Card, message, Popconfirm, Switch } from 'ant-design-vue';
const props = defineProps<{
status: OrderStatusVO.Info;
}>();
const emit = defineEmits<{
delete: [OrderStatusVO.Info];
edit: [OrderStatusVO.Info];
/** 成功时携带 PATCH 返回的最新 VO;失败时不传,由父级决定是否重新拉列表 */
patched: [vo?: OrderStatusVO.Info];
}>();
const EditIcon = createIconifyIcon('lucide:pencil');
const TrashIcon = createIconifyIcon('lucide:trash-2');
type StatKey = keyof Pick<
OrderStatusVO.Info,
| 'includeSalesAmount'
| 'includeProductCost'
| 'includeFreightCost'
| 'includeOtherCost'
| 'includeRefund'
>;
/** 后端 / JSON 可能为 0、1、'0'、'1';Switch 在 checkedValue=1 时须用 0|1 绑定 :checked,不能绑 boolean */
function dim01(v: unknown): 0 | 1 {
if (v === 1 || v === '1' || v === true) return 1;
return 0;
}
async function handleDimChange(key: StatKey, next: unknown) {
const val = dim01(next);
if (dim01(props.status[key]) === val) return;
try {
const updated = await patchOrderStatusApi(props.status.id, { [key]: val });
message.success('更新成功');
if (updated && typeof updated === 'object' && 'id' in updated) {
emit('patched', updated as OrderStatusVO.Info);
} else {
emit('patched');
}
} catch {
message.error('更新失败');
emit('patched');
}
}
</script>
<template>
<Card
hoverable
:body-style="{ padding: 0 }"
class="order-status-card group h-full"
>
<div class="card-head">
<div class="flex min-w-0 flex-1 items-center gap-2">
<span
class="max-w-[70%] truncate text-base font-semibold text-slate-800 dark:text-[hsl(0deg_0%_95%)]"
>
{{ status.statusName }}
</span>
<span
v-if="status.sortOrder != null"
class="shrink-0 rounded-md bg-slate-100 px-2 py-0.5 text-xs text-slate-500 dark:bg-[hsl(240deg_3.7%_22%)] dark:text-[hsl(240deg_5%_64.9%)]"
>
排序 {{ status.sortOrder }}
</span>
</div>
<div class="flex shrink-0 items-center gap-1 opacity-80 transition-opacity group-hover:opacity-100">
<Button type="text" size="small" @click="emit('edit', status)">
<EditIcon class="h-4 w-4" />
</Button>
<Popconfirm title="确定删除该订单状态?" @confirm="emit('delete', status)">
<Button type="text" size="small" danger>
<TrashIcon class="h-4 w-4" />
</Button>
</Popconfirm>
</div>
</div>
<!-- 布局与 OrderStatusFormModal 中 Form 区块对齐(只读展示 + 维度开关) -->
<div class="card-body">
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
<div class="min-w-0">
<div class="mb-1 text-sm text-muted-foreground">状态名称</div>
<div class="text-sm font-medium text-foreground">
{{ status.statusName }}
</div>
</div>
<div class="min-w-0">
<div class="mb-1 text-sm text-muted-foreground">状态描述</div>
<p
class="desc-preview whitespace-pre-wrap text-sm text-foreground/90"
>
{{ status.description || '—' }}
</p>
</div>
</div>
<div class="mb-2 mt-4 text-sm font-medium text-foreground">
统计维度
</div>
<div class="grid grid-cols-1 gap-x-4 gap-y-2 sm:grid-cols-2">
<div
class="stat-dim-row stat-dim--sales flex items-center justify-between gap-2 rounded-lg border border-slate-100 border-l-[3px] border-l-blue-500 bg-blue-50/70 px-3 py-2 dark:border-[hsl(240deg_3.7%_22%)] dark:border-l-sky-400 dark:bg-sky-950/25"
>
<span class="text-sm text-muted-foreground">计入销售额 / 单量</span>
<Switch
:checked="dim01(status.includeSalesAmount)"
:checked-value="1"
:un-checked-value="0"
checked-children="计入"
un-checked-children="不计入"
@update:checked="(v: unknown) => handleDimChange('includeSalesAmount', v)"
/>
</div>
<div
class="stat-dim-row stat-dim--product flex items-center justify-between gap-2 rounded-lg border border-slate-100 border-l-[3px] border-l-emerald-500 bg-emerald-50/70 px-3 py-2 dark:border-[hsl(240deg_3.7%_22%)] dark:border-l-emerald-400 dark:bg-emerald-950/25"
>
<span class="text-sm text-muted-foreground">计入商品成本</span>
<Switch
:checked="dim01(status.includeProductCost)"
:checked-value="1"
:un-checked-value="0"
checked-children="计入"
un-checked-children="不计入"
@update:checked="(v: unknown) => handleDimChange('includeProductCost', v)"
/>
</div>
<div
class="stat-dim-row stat-dim--freight flex items-center justify-between gap-2 rounded-lg border border-slate-100 border-l-[3px] border-l-amber-500 bg-amber-50/70 px-3 py-2 dark:border-[hsl(240deg_3.7%_22%)] dark:border-l-amber-400 dark:bg-amber-950/25"
>
<span class="text-sm text-muted-foreground">计入运费成本</span>
<Switch
:checked="dim01(status.includeFreightCost)"
:checked-value="1"
:un-checked-value="0"
checked-children="计入"
un-checked-children="不计入"
@update:checked="(v: unknown) => handleDimChange('includeFreightCost', v)"
/>
</div>
<div
class="stat-dim-row stat-dim--other flex items-center justify-between gap-2 rounded-lg border border-slate-100 border-l-[3px] border-l-violet-500 bg-violet-50/70 px-3 py-2 dark:border-[hsl(240deg_3.7%_22%)] dark:border-l-violet-400 dark:bg-violet-950/25"
>
<span class="text-sm text-muted-foreground">计入其他成本</span>
<Switch
:checked="dim01(status.includeOtherCost)"
:checked-value="1"
:un-checked-value="0"
checked-children="计入"
un-checked-children="不计入"
@update:checked="(v: unknown) => handleDimChange('includeOtherCost', v)"
/>
</div>
<div
class="stat-dim-row stat-dim--refund flex items-center justify-between gap-2 rounded-lg border border-slate-100 border-l-[3px] border-l-rose-500 bg-rose-50/70 px-3 py-2 sm:col-span-2 dark:border-[hsl(240deg_3.7%_22%)] dark:border-l-rose-400 dark:bg-rose-950/25"
>
<span class="text-sm text-muted-foreground">计入退款金额</span>
<Switch
:checked="dim01(status.includeRefund)"
:checked-value="1"
:un-checked-value="0"
checked-children="计入"
un-checked-children="不计入"
@update:checked="(v: unknown) => handleDimChange('includeRefund', v)"
/>
</div>
</div>
</div>
</Card>
</template>
<style scoped lang="scss">
.order-status-card {
border-radius: 12px;
overflow: hidden;
border: 1px solid #d7e1ee;
background: linear-gradient(180deg, #ffffff 0%, #f7fbff 100%);
box-shadow:
0 14px 34px rgb(15 23 42 / 9%),
0 2px 10px rgb(15 23 42 / 5%);
transition: all 0.2s ease;
&:hover {
transform: translateY(-2px);
border-color: #b8c8de;
box-shadow:
0 20px 38px rgb(15 23 42 / 14%),
0 6px 14px rgb(15 23 42 / 9%);
}
.card-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 14px 16px;
border-bottom: 1px solid #dde6f2;
background: linear-gradient(180deg, rgb(237 245 255 / 95%) 0%, #ffffff 100%);
}
.card-body {
padding: 16px 18px 18px;
}
/* 各维度 Switch 开启态与行主题色一致 */
.stat-dim--sales :deep(.ant-switch-checked) {
background: #1677ff !important;
}
.stat-dim--product :deep(.ant-switch-checked) {
background: #16a34a !important;
}
.stat-dim--freight :deep(.ant-switch-checked) {
background: #d97706 !important;
}
.stat-dim--other :deep(.ant-switch-checked) {
background: #7c3aed !important;
}
.stat-dim--refund :deep(.ant-switch-checked) {
background: #e11d48 !important;
}
}
/* 右侧描述区:多行截断,避免把卡片撑得过高 */
.desc-preview {
display: -webkit-box;
-webkit-line-clamp: 5;
line-clamp: 5;
-webkit-box-orient: vertical;
overflow: hidden;
word-break: break-word;
}
</style>
@@ -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<Partial<OrderStatusDTO.Create>>({
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"
/>
</Form.Item>
</div>
<Form.Item label="自动统计" name="autoStatistics">
<div class="mb-2 text-sm font-medium text-foreground">
统计维度(0/1)
</div>
<div class="grid grid-cols-2 gap-x-4 gap-y-2">
<Form.Item label="计入销售额 / 单量" name="includeSalesAmount">
<Switch
v-model:checked="formData.autoStatistics"
v-model:checked="formData.includeSalesAmount"
:checked-value="1"
:un-checked-value="0"
checked-children="参与"
un-checked-children="不参与"
checked-children="计入"
un-checked-children="不计入"
/>
</Form.Item>
<Form.Item label="计入商品成本" name="includeProductCost">
<Switch
v-model:checked="formData.includeProductCost"
:checked-value="1"
:un-checked-value="0"
checked-children="计入"
un-checked-children="不计入"
/>
</Form.Item>
<Form.Item label="计入运费成本" name="includeFreightCost">
<Switch
v-model:checked="formData.includeFreightCost"
:checked-value="1"
:un-checked-value="0"
checked-children="计入"
un-checked-children="不计入"
/>
</Form.Item>
<Form.Item label="计入其他成本" name="includeOtherCost">
<Switch
v-model:checked="formData.includeOtherCost"
:checked-value="1"
:un-checked-value="0"
checked-children="计入"
un-checked-children="不计入"
/>
</Form.Item>
<Form.Item label="计入退款金额" name="includeRefund" class="col-span-2">
<Switch
v-model:checked="formData.includeRefund"
:checked-value="1"
:un-checked-value="0"
checked-children="计入"
un-checked-children="不计入"
/>
</Form.Item>
</div>
<Form.Item label="是否为退款状态" name="isRefund">
<Switch
v-model:checked="formData.isRefund"
:checked-value="1"
:un-checked-value="0"
checked-children="是"
un-checked-children="否"
/>
</Form.Item>
</Form>
</Modal>
</template>
@@ -1,294 +1,379 @@
<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { OrderStatusVO } from '#/api/ecommerce/order-status';
import { computed, ref } from 'vue';
import { computed, nextTick, onMounted, ref } from 'vue';
import { Waterfall } from 'vue-waterfall-plugin-next';
import 'vue-waterfall-plugin-next/dist/style.css';
import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import { Button, message, Popconfirm, Space, Switch, Tag } from 'ant-design-vue';
import { Button, Card, Empty, message, Spin } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { useVbenForm } from '#/adapter/form';
import {
deleteOrderStatusApi,
getAllOrderStatusListApi,
patchOrderStatusApi,
} from '#/api/ecommerce/order-status';
import OrderStatusCard from './components/OrderStatusCard.vue';
import OrderStatusFormModal from './components/OrderStatusFormModal.vue';
defineOptions({ name: 'OrderStatusConfig' });
// 创建图标组件
/** 列表与筛选统一为 0 | 1,避免接口字符串与 Switch 受控值不一致 */
function dim01(v: unknown): 0 | 1 {
if (v === 1 || v === '1' || v === true) return 1;
return 0;
}
function normalizeOrderStatus(s: OrderStatusVO.Info): OrderStatusVO.Info {
return {
...s,
includeSalesAmount: dim01(s.includeSalesAmount),
includeProductCost: dim01(s.includeProductCost),
includeFreightCost: dim01(s.includeFreightCost),
includeOtherCost: dim01(s.includeOtherCost),
includeRefund: dim01(s.includeRefund),
};
}
const PlusIcon = createIconifyIcon('lucide:plus');
// 响应式数据
const loading = ref(false);
const orderStatusFormModalRef = ref();
const waterfallRef = ref();
// VbenVxeGrid 表格配置
const gridOptions: VxeGridProps<any> = {
columns: [
{
type: 'seq' as const,
width: 80,
title: '序号',
},
{
title: '状态名称',
minWidth: 'auto',
slots: { default: 'statusName' },
},
{
field: 'description',
title: '状态描述',
minWidth: 'auto',
showOverflow: 'tooltip' as const,
},
const searchForm = ref({
statusName: '',
includeSalesAmount: undefined as number | undefined,
});
{
title: '自动统计',
minWidth: 'auto',
slots: { default: 'autoStatistics' },
},
{
title: '退款状态',
minWidth: 'auto',
slots: { default: 'refundStatus' },
},
{
field: 'createTime',
title: '创建时间',
minWidth: 'auto',
},
{
field: 'updateTime',
title: '更新时间',
minWidth: 'auto',
},
{
title: '操作',
minWidth: 'auto',
fixed: 'right' as const,
slots: { default: 'action' },
},
],
height: 'auto',
border: true,
stripe: true,
rowConfig: { isHover: true },
showOverflow: true,
size: 'small',
toolbarConfig: {
custom: true,
refresh: true,
zoom: true,
},
data: [],
pagerConfig: {
enabled: false,
},
// 配置远程加载
proxyConfig: {
ajax: {
query: async () => {
try {
loading.value = true;
const data = await getAllOrderStatusListApi();
return {
items: data,
total: data.length,
};
} catch (error) {
console.error('获取订单状态列表失败:', error);
message.error('获取订单状态列表失败');
return {
items: [],
total: 0,
};
} finally {
loading.value = false;
}
},
const searchFormSubmitRef = ref<null | (() => Promise<unknown>)>(null);
const [SearchForm, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
},
};
// 搜索表单配置
const gridReloadRef = ref<(() => void) | null>(null);
const formOptions = computed(() => ({
handleReset: handleSearchFormReset,
handleSubmit: handleSearchFormSubmit,
layout: 'horizontal',
schema: [
{
component: 'Input',
componentProps: {
placeholder: '请输入状态名称(回车搜索)',
onPressEnter: () => gridReloadRef.value?.(),
placeholder: '状态名称(回车搜索)',
allowClear: true,
onPressEnter: () => void searchFormSubmitRef.value?.(),
},
defaultValue: '',
fieldName: 'statusName',
label: '状态名称',
},
{
component: 'Select',
componentProps: {
placeholder: '请选择是否自动统计',
options: [
{ label: '参与自动统计', value: 1 },
{ label: '不参与自动统计', value: 0 },
],
placeholder: '是否计入销售额',
allowClear: true,
onChange: () => gridReloadRef.value?.(),
options: [
{ label: '计入销售额', value: 1 },
{ label: '不计入销售额', value: 0 },
],
},
fieldName: 'autoStatistics',
label: '自动统计',
fieldName: 'includeSalesAmount',
label: '销售额统计',
},
],
showCollapseButton: false,
showDefaultActions: true,
collapsed: true,
collapsedRows: 1,
}));
// 创建 VbenVxeGrid 实例
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
formOptions: formOptions.value,
showSearchForm: true,
tableTitle: '订单状态配置',
submitButtonOptions: {
content: '搜索',
},
resetButtonOptions: {
content: '重置',
},
submitOnEnter: true,
wrapperClass: 'grid-cols-1 md:grid-cols-2',
});
gridReloadRef.value = () => gridApi.reload();
// 刷新表格数据
function refreshTable() {
if (gridApi) {
gridApi.reload();
searchFormSubmitRef.value = () => formApi.validateAndSubmitForm();
async function handleSearchFormSubmit(values: Record<string, any>) {
searchForm.value = {
statusName: String(values.statusName ?? '').trim(),
includeSalesAmount:
values.includeSalesAmount === '' || values.includeSalesAmount === undefined
? undefined
: Number(values.includeSalesAmount),
};
}
async function handleSearchFormReset() {
await formApi.resetForm();
searchForm.value = {
statusName: '',
includeSalesAmount: undefined,
};
}
const loading = ref(false);
const orderStatusList = ref<OrderStatusVO.Info[]>([]);
const displayList = computed(() => {
let list = [...orderStatusList.value];
const { statusName, includeSalesAmount } = searchForm.value;
if (statusName) {
list = list.filter((s) => s.statusName.includes(statusName));
}
if (includeSalesAmount === 0 || includeSalesAmount === 1) {
list = list.filter((s) => dim01(s.includeSalesAmount) === includeSalesAmount);
}
list.sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0));
return list;
});
async function loadOrderStatuses() {
loading.value = true;
try {
const data = await getAllOrderStatusListApi();
orderStatusList.value = (data || []).map(normalizeOrderStatus);
} catch {
message.error('获取订单状态列表失败');
orderStatusList.value = [];
} finally {
loading.value = false;
}
}
// 处理添加订单状态
function handleAdd() {
orderStatusFormModalRef.value?.open(false);
}
// 处理编辑订单状态
function handleEdit(record: OrderStatusVO.Info) {
orderStatusFormModalRef.value?.open(true, record);
}
// 处理删除订单状态
async function handleDelete(record: OrderStatusVO.Info) {
try {
await deleteOrderStatusApi(record.id);
message.success('删除成功');
refreshTable();
} catch (error) {
console.error('删除订单状态失败:', error);
message.error('删除订单状态失败');
await loadOrderStatuses();
await handleWaterfallLayout();
} catch {
message.error('删除失败');
}
}
// 处理模态框成功
function handleModalSuccess() {
refreshTable();
async function handleModalSuccess() {
await loadOrderStatuses();
await handleWaterfallLayout();
}
// 处理自动统计开关切换
async function handleAutoStatisticsChange(row: OrderStatusVO.Info, checked: any) {
const val = !!checked;
try {
await patchOrderStatusApi(row.id, { autoStatistics: val ? 1 : 0 });
message.success('更新成功');
refreshTable();
} catch (error) {
console.error('更新自动统计失败:', error);
message.error('更新自动统计失败');
refreshTable(); // 恢复原状态
/** 用 PATCH 返回体就地更新一条,避免再请求列表;找不到 id 时再全量拉取 */
async function mergeOrderStatusFromPatch(vo: OrderStatusVO.Info) {
const n = normalizeOrderStatus(vo);
const idx = orderStatusList.value.findIndex(
(s) => Number(s.id) === Number(n.id),
);
if (idx === -1) {
await loadOrderStatuses();
return;
}
const next = [...orderStatusList.value];
next[idx] = n;
orderStatusList.value = next;
}
// 处理退款状态开关切换
async function handleIsRefundChange(row: OrderStatusVO.Info, checked: any) {
const val = !!checked;
try {
await patchOrderStatusApi(row.id, { isRefund: val ? 1 : 0 });
message.success('更新成功');
refreshTable();
} catch (error) {
console.error('更新退款状态失败:', error);
message.error('更新退款状态失败');
refreshTable(); // 恢复原状态
async function handlePatched(vo?: OrderStatusVO.Info) {
if (vo) {
await mergeOrderStatusFromPatch(vo);
} else {
await loadOrderStatuses();
}
await handleWaterfallLayout();
}
async function handleWaterfallLayout() {
await nextTick();
await nextTick();
waterfallRef.value?.renderer?.();
}
onMounted(() => {
loadOrderStatuses();
});
</script>
<template>
<Page title="订单状态配置" auto-content-height>
<Page
title="订单状态配置"
auto-content-height
content-class="flex min-h-0 flex-1 flex-col bg-[#f8fafc] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
header-class="order-status-page-header"
>
<template #description>
<div class="text-foreground/80 mt-2">
管理订单状态类型,包括状态名称、描述和自动统计
<div class="text-foreground/80 mt-2 max-w-4xl">
管理订单状态及五个统计维度:销售额/单量、商品成本、运费成本、其他成本、退款金额;仅开启的维度会进入全店/店铺/商品概览与导出等统计。
</div>
</template>
<!-- VbenVxeGrid 表格 -->
<Grid :loading="loading">
<!-- 工具栏工具 -->
<template #toolbar-tools>
<Space>
<Button type="primary" @click="handleAdd">
<PlusIcon />
添加状态
</Button>
</Space>
</template>
<!-- 状态名称列(带颜色) -->
<template #statusName="{ row }: { row: OrderStatusVO.Info }">
<Tag
v-if="row.color"
:color="row.color"
type="outline"
class="font-bold"
<div class="flex min-h-0 flex-1 flex-col dark:bg-[hsl(222.34deg_10.43%_12.27%)]">
<div class="flex min-h-0 flex-1 flex-col">
<Card
class="order-status-search mb-4 shrink-0 rounded-2xl border border-slate-200 bg-white/90 shadow-[0_4px_12px_rgba(0,0,0,0.03)] dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)] dark:shadow-none"
:body-style="{ padding: '16px' }"
>
{{ row.statusName }}
</Tag>
<span v-else>{{ row.statusName }}</span>
</template>
<SearchForm />
</Card>
<!-- 自动统计列 -->
<template #autoStatistics="{ row }: { row: OrderStatusVO.Info }">
<Switch
:checked="row.autoStatistics === 1"
size="small"
@change="(checked) => handleAutoStatisticsChange(row, checked)"
/>
</template>
<!-- 退款状态列 -->
<template #refundStatus="{ row }: { row: OrderStatusVO.Info }">
<Switch
:checked="row.isRefund === 1"
size="small"
@change="(checked) => handleIsRefundChange(row, checked)"
/>
</template>
<!-- 操作列 -->
<template #action="{ row }: { row: any }">
<Space>
<Button size="small" @click="handleEdit(row)"> 编辑 </Button>
<Popconfirm
title="确定要删除这个订单状态吗?"
@confirm="handleDelete(row)"
<div class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
<Card
class="order-status-grid flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-2xl border border-slate-200 bg-white/90 shadow-[0_4px_12px_rgba(0,0,0,0.03)] dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)] dark:shadow-none"
:body-style="{
padding: '16px',
display: 'flex',
flexDirection: 'column',
flex: '1 1 0',
minHeight: 0,
overflow: 'hidden',
}"
>
<Button size="small" danger> 删除 </Button>
</Popconfirm>
</Space>
</template>
</Grid>
<div class="mb-3 flex shrink-0 items-center justify-between gap-3">
<span class="text-sm text-gray-500 dark:text-[hsl(240deg_5%_64.9%)]">
共 {{ displayList.length }} 个状态(全部 {{ orderStatusList.length }} 个)
</span>
<Button type="primary" @click="handleAdd">
<PlusIcon class="mr-2 h-4 w-4" />
添加状态
</Button>
</div>
<div
class="order-status-scroll flex min-h-0 min-w-0 flex-1 flex-col overflow-y-auto"
>
<Spin :spinning="loading && orderStatusList.length === 0">
<div
v-if="!loading && displayList.length === 0"
class="flex min-h-[200px] items-center justify-center py-8"
>
<Empty description="暂无订单状态" />
</div>
<Waterfall
v-else-if="displayList.length > 0"
ref="waterfallRef"
:list="displayList"
row-key="id"
:horizontalOrder="true"
:width="420"
:breakpoints="{
2000: { rowPerView: 3 },
1400: { rowPerView: 2 },
900: { rowPerView: 2 },
600: { rowPerView: 1 },
}"
:gutter="20"
class="order-status-waterfall"
>
<template #default="{ item }">
<div class="w-full pb-1">
<OrderStatusCard
:status="item as OrderStatusVO.Info"
@edit="handleEdit"
@delete="handleDelete"
@patched="(v) => handlePatched(v)"
/>
</div>
</template>
</Waterfall>
</Spin>
</div>
</Card>
</div>
</div>
</div>
<!-- 订单状态表单模态框 -->
<OrderStatusFormModal
ref="orderStatusFormModalRef"
@success="handleModalSuccess"
/>
</Page>
</template>
<style scoped>
.order-status-waterfall {
background-color: transparent !important;
}
@media (max-width: 640px) {
:deep(.order-status-page-header) {
flex-direction: column;
align-items: stretch;
gap: 10px;
}
:deep(.order-status-page-header > div:first-child) {
width: 100%;
}
:deep(.order-status-page-header > div:last-child) {
width: 100%;
}
}
</style>
<style>
html.dark .order-status-search.ant-card,
html.dark .order-status-grid.ant-card {
background-color: hsl(var(--card)) !important;
border-color: hsl(var(--border)) !important;
}
html.dark .order-status-search.ant-card .ant-card-body,
html.dark .order-status-grid.ant-card .ant-card-body {
background-color: hsl(var(--card)) !important;
}
html.dark .order-status-search .ant-form-item-label > label {
color: hsl(var(--muted-foreground));
}
html.dark .order-status-search .ant-input,
html.dark .order-status-search .ant-input-affix-wrapper,
html.dark .order-status-search .ant-select-selector {
background-color: hsl(var(--input-background)) !important;
border-color: hsl(var(--border)) !important;
color: hsl(var(--foreground)) !important;
}
html.dark .order-status-search .ant-btn-default {
background-color: hsl(var(--secondary));
border-color: hsl(var(--border));
color: hsl(var(--foreground));
}
html.dark .order-status-scroll .ant-empty-description {
color: hsl(var(--muted-foreground));
}
/* 订单状态卡片深色(与商品卡同思路) */
html.dark .order-status-card {
border-color: hsl(240deg 3.7% 22%) !important;
background: linear-gradient(
180deg,
hsl(222.34deg 10.43% 14%) 0%,
hsl(222.34deg 10.43% 12.27%) 100%
) !important;
box-shadow: 0 8px 24px rgb(0 0 0 / 35%) !important;
}
html.dark .order-status-card .card-head {
border-bottom-color: hsl(240deg 3.7% 22%) !important;
background: linear-gradient(
180deg,
hsl(222deg 14% 16%) 0%,
hsl(222.34deg 10.43% 12.27%) 100%
) !important;
}
</style>