perf(订单): 列表分页走时间索引与延迟关联,批量组装 VO,前端默认 30 天下单时间范围

This commit is contained in:
小蟑螂
2026-06-04 14:54:45 +08:00
parent 6d3d8c699b
commit 5a2b98b727
8 changed files with 425 additions and 112 deletions
@@ -5,6 +5,7 @@ import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.Select;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.dto.OrderListQueryParam;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.OrderShopStatDateRow;
@@ -83,4 +84,10 @@ public interface OrderMapper extends BaseMapper<OrderPO> {
List<OrderShopStatDateRow> selectOrphanOrderStatDatesBySpecCode(
@Param("companyId") Long companyId,
@Param("specCode") String specCode);
/** 列表分页:走时间索引的 COUNT */
long countOrderList(OrderListQueryParam param);
/** 列表分页:先查 id 再回表,避免大结果集 filesort */
List<Long> selectOrderListIds(OrderListQueryParam param);
}
@@ -21,9 +21,9 @@ public class OrderFilterDTO {
private Long shopId;
/**
* 平台订单号(模糊查询)
* 平台订单号:无 %/_ 时按前缀匹配(可走索引);含通配符时全模糊
*/
@Schema(description = "平台订单号(模糊查询)", example = "TB2024")
@Schema(description = "平台订单号(默认前缀匹配;含%/_ 时全模糊)", example = "TB2024")
private String platformOrderNo;
/**
@@ -0,0 +1,36 @@
package top.xyquan.ecomdmbbackend.modules.ecom.order.model.dto;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 订单列表分页查询参数(Mapper 动态 SQL,含 FORCE INDEX 提示)。
*/
@Data
public class OrderListQueryParam {
private Long companyId;
private Long shopId;
/** 平台单号:前缀匹配(无 %/_ 时) */
private String platformOrderNo;
private Boolean platformOrderNoPrefix;
private Long statusId;
private BigDecimal minReceivedAmount;
private BigDecimal maxReceivedAmount;
private LocalDateTime startOrderTime;
private LocalDateTime endOrderTime;
private Long importTaskId;
private Integer confirm;
private Long productId;
/** true → FORCE INDEX(idx_company_shop_time),否则 idx_company_order_time */
private boolean useShopTimeIndex;
/** 白名单排序片段,如 order_time DESC, id DESC */
private String orderByClause;
private long offset;
private long limit;
}
@@ -2,21 +2,19 @@ package top.xyquan.ecomdmbbackend.modules.ecom.order.service.impl;
import top.xyquan.ecomdmbbackend.common.utils.BeanCopyUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.dto.SortDTO;
import top.xyquan.ecomdmbbackend.common.utils.SortUtils;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.dto.BatchImportOrderDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.dto.CreateOrderDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.dto.OrderFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.dto.OrderListQueryParam;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.dto.UpdateOrderDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.support.OrderPageQuerySupport;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductSpecPO;
@@ -39,10 +37,13 @@ import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
@@ -312,73 +313,38 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
*/
@Override
public PageResultVO<OrderVO> getOrderPage(PageQueryDTO<OrderFilterDTO> pageQueryDTO) {
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
// 创建分页对象
Page<OrderPO> page = new Page<>(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
// 构建查询条件
LambdaQueryWrapper<OrderPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderPO::getCompanyId, companyId);
// 添加过滤条件
OrderFilterDTO filter = pageQueryDTO.getFilters();
if (filter != null) {
if (filter.getShopId() != null) {
wrapper.eq(OrderPO::getShopId, filter.getShopId());
}
if (filter.getPlatformOrderNo() != null && !filter.getPlatformOrderNo().trim().isEmpty()) {
wrapper.like(OrderPO::getPlatformOrderNo, filter.getPlatformOrderNo());
}
if (filter.getStatusId() != null) {
wrapper.eq(OrderPO::getStatusId, filter.getStatusId());
}
if (filter.getMinReceivedAmount() != null) {
wrapper.ge(OrderPO::getReceivedAmount, filter.getMinReceivedAmount());
}
if (filter.getMaxReceivedAmount() != null) {
wrapper.le(OrderPO::getReceivedAmount, filter.getMaxReceivedAmount());
}
if (filter.getStartOrderTime() != null) {
wrapper.ge(OrderPO::getOrderTime, filter.getStartOrderTime());
}
if (filter.getEndOrderTime() != null) {
wrapper.le(OrderPO::getOrderTime, filter.getEndOrderTime());
}
if (filter.getImportTaskId() != null) {
wrapper.eq(OrderPO::getImportTaskId, filter.getImportTaskId());
}
if (filter.getConfirm() != null) {
wrapper.eq(OrderPO::getConfirm, filter.getConfirm());
}
if (filter.getProductId() != null) {
wrapper.apply(
"EXISTS (SELECT 1 FROM ec_product_spec s WHERE s.id = ec_order.product_spec_id AND s.product_id = {0})",
filter.getProductId());
}
if (filter == null) {
filter = new OrderFilterDTO();
}
// 排序(支持多字段自定义排序,默认按下单时间降序 + 创建时间降序)
List<SortDTO> sorts = pageQueryDTO.getSorts();
if (sorts == null || sorts.isEmpty()) {
// 默认排序:下单时间降序,创建时间降序
wrapper.orderByDesc(OrderPO::getOrderTime)
.orderByDesc(OrderPO::getCreateTime);
} else {
SortUtils.applySorts(wrapper, OrderPO.class, sorts);
int page = pageQueryDTO.getPage() != null ? pageQueryDTO.getPage() : 1;
int pageSize = pageQueryDTO.getPageSize() != null ? pageQueryDTO.getPageSize() : 20;
OrderListQueryParam query = OrderPageQuerySupport.toQueryParam(
companyId, filter, pageQueryDTO.getSorts(), page, pageSize);
long total = baseMapper.countOrderList(query);
if (total == 0) {
return PageResultVO.create(Collections.emptyList(), 0L, page, pageSize);
}
// 执行分页查询
IPage<OrderPO> pageResult = this.page(page, wrapper);
List<Long> ids = baseMapper.selectOrderListIds(query);
if (ids.isEmpty()) {
return PageResultVO.create(Collections.emptyList(), total, page, pageSize);
}
// 转换为VO
List<OrderVO> voList = pageResult.getRecords().stream()
.map(this::convertToVO)
List<OrderPO> rows = listByIds(ids);
Map<Long, OrderPO> rowMap = rows.stream()
.collect(Collectors.toMap(OrderPO::getId, Function.identity(), (a, b) -> a));
List<OrderPO> ordered = ids.stream()
.map(rowMap::get)
.filter(Objects::nonNull)
.collect(Collectors.toList());
// 构建分页结果
return PageResultVO.create(voList, pageResult.getTotal(), pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
List<OrderVO> voList = convertToVOBatch(ordered);
return PageResultVO.create(voList, total, page, pageSize);
}
/**
@@ -449,51 +415,101 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
}
/**
* 转换为VO
* 转换为VO(单条详情等仍用逐条加载)
*/
private OrderVO convertToVO(OrderPO order) {
OrderVO orderVO = new OrderVO();
BeanCopyUtils.copyProperties(order, orderVO);
return convertToVOBatch(List.of(order)).get(0);
}
// 设置状态信息
if (order.getStatusId() != null) {
OrderStatusPO orderStatus = orderStatusService.getById(order.getStatusId());
if (orderStatus != null) {
orderVO.setStatusName(orderStatus.getStatusName());
OrderStatusVO orderStatusVO = new OrderStatusVO();
BeanCopyUtils.copyProperties(orderStatus, orderStatusVO);
orderVO.setOrderStatus(orderStatusVO);
/**
* 批量转换为 VO,关联数据一次查出,避免 N+1。
*/
private List<OrderVO> convertToVOBatch(List<OrderPO> orders) {
if (orders == null || orders.isEmpty()) {
return Collections.emptyList();
}
Set<Long> statusIds = new HashSet<>();
Set<Long> shopIds = new HashSet<>();
Set<Long> specIds = new HashSet<>();
for (OrderPO o : orders) {
if (o.getStatusId() != null) {
statusIds.add(o.getStatusId());
}
if (o.getShopId() != null) {
shopIds.add(o.getShopId());
}
if (o.getProductSpecId() != null) {
specIds.add(o.getProductSpecId());
}
}
// 设置店铺名称
ShopPO shop = shopService.getById(order.getShopId());
if (shop != null) {
orderVO.setShopName(shop.getName());
ShopVO shopVO = new ShopVO();
BeanCopyUtils.copyProperties(shop, shopVO);
orderVO.setShop(shopVO);
}
Map<Long, OrderStatusPO> statusMap = statusIds.isEmpty()
? Map.of()
: orderStatusService.listByIds(statusIds).stream()
.collect(Collectors.toMap(OrderStatusPO::getId, Function.identity(), (a, b) -> a));
Map<Long, ShopPO> shopMap = shopIds.isEmpty()
? Map.of()
: shopService.listByIds(shopIds).stream()
.collect(Collectors.toMap(ShopPO::getId, Function.identity(), (a, b) -> a));
Map<Long, ProductSpecPO> specMap = specIds.isEmpty()
? Map.of()
: productSpecService.listByIds(specIds).stream()
.collect(Collectors.toMap(ProductSpecPO::getId, Function.identity(), (a, b) -> a));
// 设置关联商品规格与商品信息(商品经规格关联)
if (order.getProductSpecId() != null) {
ProductSpecPO productSpec = productSpecService.getById(order.getProductSpecId());
if (productSpec != null) {
ProductSpecVO productSpecVO = new ProductSpecVO();
BeanCopyUtils.copyProperties(productSpec, productSpecVO);
orderVO.setProductSpec(productSpecVO);
if (productSpec.getProductId() != null) {
ProductPO product = productService.getById(productSpec.getProductId());
if (product != null) {
ProductVO productVO = new ProductVO();
BeanCopyUtils.copyProperties(product, productVO);
orderVO.setProduct(productVO);
Set<Long> productIds = specMap.values().stream()
.map(ProductSpecPO::getProductId)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
Map<Long, ProductPO> productMap = productIds.isEmpty()
? Map.of()
: productService.listByIds(productIds).stream()
.collect(Collectors.toMap(ProductPO::getId, Function.identity(), (a, b) -> a));
List<OrderVO> result = new ArrayList<>(orders.size());
for (OrderPO order : orders) {
OrderVO orderVO = new OrderVO();
BeanCopyUtils.copyProperties(order, orderVO);
if (order.getStatusId() != null) {
OrderStatusPO orderStatus = statusMap.get(order.getStatusId());
if (orderStatus != null) {
orderVO.setStatusName(orderStatus.getStatusName());
OrderStatusVO orderStatusVO = new OrderStatusVO();
BeanCopyUtils.copyProperties(orderStatus, orderStatusVO);
orderVO.setOrderStatus(orderStatusVO);
}
}
if (order.getShopId() != null) {
ShopPO shop = shopMap.get(order.getShopId());
if (shop != null) {
orderVO.setShopName(shop.getName());
ShopVO shopVO = new ShopVO();
BeanCopyUtils.copyProperties(shop, shopVO);
orderVO.setShop(shopVO);
}
}
if (order.getProductSpecId() != null) {
ProductSpecPO productSpec = specMap.get(order.getProductSpecId());
if (productSpec != null) {
ProductSpecVO productSpecVO = new ProductSpecVO();
BeanCopyUtils.copyProperties(productSpec, productSpecVO);
orderVO.setProductSpec(productSpecVO);
if (productSpec.getProductId() != null) {
ProductPO product = productMap.get(productSpec.getProductId());
if (product != null) {
ProductVO productVO = new ProductVO();
BeanCopyUtils.copyProperties(product, productVO);
orderVO.setProduct(productVO);
}
}
}
}
result.add(orderVO);
}
return orderVO;
return result;
}
@Override
@@ -0,0 +1,126 @@
package top.xyquan.ecomdmbbackend.modules.ecom.order.support;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.common.model.dto.SortDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.dto.OrderFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.dto.OrderListQueryParam;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 订单列表查询:时间范围兜底、排序白名单、索引选择。
*/
public final class OrderPageQuerySupport {
/** 未传时间时默认查最近 N 天 */
public static final int DEFAULT_LIST_DAYS = 30;
/** 列表允许的最大时间跨度 */
public static final int MAX_LIST_DAYS = 366;
private static final Set<String> ALLOWED_SORT_COLUMNS = Set.of(
"order_time", "id", "received_amount", "shop_id", "status_id", "create_time"
);
private static final Map<String, String> SORT_FIELD_TO_COLUMN = Map.of(
"orderTime", "order_time",
"id", "id",
"receivedAmount", "received_amount",
"shopId", "shop_id",
"statusId", "status_id",
"createTime", "create_time"
);
private OrderPageQuerySupport() {
}
/**
* 规范化下单时间:禁止无范围扫全表;跨度超限则拒绝。
*/
public static void normalizeOrderTimeRange(OrderFilterDTO filter) {
if (filter == null) {
throw new BusinessException("请指定下单时间范围(默认查询最近 " + DEFAULT_LIST_DAYS + " 天)");
}
LocalDateTime now = LocalDateTime.now();
if (filter.getStartOrderTime() == null && filter.getEndOrderTime() == null) {
filter.setEndOrderTime(now);
filter.setStartOrderTime(now.minusDays(DEFAULT_LIST_DAYS).withHour(0).withMinute(0).withSecond(0).withNano(0));
return;
}
if (filter.getStartOrderTime() == null) {
filter.setStartOrderTime(filter.getEndOrderTime().minusDays(DEFAULT_LIST_DAYS));
}
if (filter.getEndOrderTime() == null) {
filter.setEndOrderTime(now);
}
if (filter.getEndOrderTime().isBefore(filter.getStartOrderTime())) {
throw new BusinessException("下单结束时间不能早于开始时间");
}
long days = ChronoUnit.DAYS.between(
filter.getStartOrderTime().toLocalDate(),
filter.getEndOrderTime().toLocalDate()) + 1;
if (days > MAX_LIST_DAYS) {
throw new BusinessException("下单时间跨度不能超过 " + MAX_LIST_DAYS + " 天,请缩小范围");
}
}
public static OrderListQueryParam toQueryParam(Long companyId, OrderFilterDTO filter,
List<SortDTO> sorts, long page, long pageSize) {
normalizeOrderTimeRange(filter);
OrderListQueryParam p = new OrderListQueryParam();
p.setCompanyId(companyId);
p.setShopId(filter.getShopId());
if (filter.getPlatformOrderNo() != null && !filter.getPlatformOrderNo().trim().isEmpty()) {
String raw = filter.getPlatformOrderNo().trim();
p.setPlatformOrderNo(raw);
p.setPlatformOrderNoPrefix(!raw.contains("%") && !raw.contains("_"));
}
p.setStatusId(filter.getStatusId());
p.setMinReceivedAmount(filter.getMinReceivedAmount());
p.setMaxReceivedAmount(filter.getMaxReceivedAmount());
p.setStartOrderTime(filter.getStartOrderTime());
p.setEndOrderTime(filter.getEndOrderTime());
p.setImportTaskId(filter.getImportTaskId());
p.setConfirm(filter.getConfirm());
p.setProductId(filter.getProductId());
p.setUseShopTimeIndex(filter.getShopId() != null);
p.setOrderByClause(buildOrderByClause(sorts));
p.setOffset(Math.max(0, (page - 1) * pageSize));
p.setLimit(Math.max(1, pageSize));
return p;
}
/**
* 排序仅允许白名单字段;默认 order_time DESC, id DESC(利于走时间索引)。
*/
public static String buildOrderByClause(List<SortDTO> sorts) {
if (sorts == null || sorts.isEmpty()) {
return "order_time DESC, id DESC";
}
StringBuilder sb = new StringBuilder();
for (SortDTO sort : sorts) {
if (sort == null || sort.getField() == null || sort.getField().isBlank()) {
continue;
}
String column = SORT_FIELD_TO_COLUMN.get(sort.getField().trim());
if (column == null || !ALLOWED_SORT_COLUMNS.contains(column)) {
continue;
}
boolean asc = "asc".equalsIgnoreCase(sort.getOrder());
if (!sb.isEmpty()) {
sb.append(", ");
}
sb.append(column).append(asc ? " ASC" : " DESC");
}
if (sb.isEmpty()) {
return "order_time DESC, id DESC";
}
if (!sb.toString().contains("id ")) {
sb.append(", id DESC");
}
return sb.toString();
}
}