diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/mapper/OrderMapper.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/mapper/OrderMapper.java index 1904a6fd..b81fb540 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/mapper/OrderMapper.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/mapper/OrderMapper.java @@ -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 { List selectOrphanOrderStatDatesBySpecCode( @Param("companyId") Long companyId, @Param("specCode") String specCode); + + /** 列表分页:走时间索引的 COUNT */ + long countOrderList(OrderListQueryParam param); + + /** 列表分页:先查 id 再回表,避免大结果集 filesort */ + List selectOrderListIds(OrderListQueryParam param); } diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/model/dto/OrderFilterDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/model/dto/OrderFilterDTO.java index ba6c22b5..c332030e 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/model/dto/OrderFilterDTO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/model/dto/OrderFilterDTO.java @@ -21,9 +21,9 @@ public class OrderFilterDTO { private Long shopId; /** - * 平台订单号(模糊查询) + * 平台订单号:无 %/_ 时按前缀匹配(可走索引);含通配符时全模糊 */ - @Schema(description = "平台订单号(模糊查询)", example = "TB2024") + @Schema(description = "平台订单号(默认前缀匹配;含%/_ 时全模糊)", example = "TB2024") private String platformOrderNo; /** diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/model/dto/OrderListQueryParam.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/model/dto/OrderListQueryParam.java new file mode 100644 index 00000000..12abe978 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/model/dto/OrderListQueryParam.java @@ -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; +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/service/impl/OrderServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/service/impl/OrderServiceImpl.java index 3cb4e899..836bed25 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/service/impl/OrderServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/service/impl/OrderServiceImpl.java @@ -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 implemen */ @Override public PageResultVO getOrderPage(PageQueryDTO pageQueryDTO) { - // 从token中获取公司ID Long companyId = currentUserContext.getCurrentCompanyId(); - - // 创建分页对象 - Page page = new Page<>(pageQueryDTO.getPage(), pageQueryDTO.getPageSize()); - - // 构建查询条件 - LambdaQueryWrapper 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 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 pageResult = this.page(page, wrapper); + List ids = baseMapper.selectOrderListIds(query); + if (ids.isEmpty()) { + return PageResultVO.create(Collections.emptyList(), total, page, pageSize); + } - // 转换为VO - List voList = pageResult.getRecords().stream() - .map(this::convertToVO) + List rows = listByIds(ids); + Map rowMap = rows.stream() + .collect(Collectors.toMap(OrderPO::getId, Function.identity(), (a, b) -> a)); + List ordered = ids.stream() + .map(rowMap::get) + .filter(Objects::nonNull) .collect(Collectors.toList()); - // 构建分页结果 - return PageResultVO.create(voList, pageResult.getTotal(), pageQueryDTO.getPage(), pageQueryDTO.getPageSize()); + List voList = convertToVOBatch(ordered); + return PageResultVO.create(voList, total, page, pageSize); } /** @@ -449,51 +415,101 @@ public class OrderServiceImpl extends ServiceImpl 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 convertToVOBatch(List orders) { + if (orders == null || orders.isEmpty()) { + return Collections.emptyList(); + } + + Set statusIds = new HashSet<>(); + Set shopIds = new HashSet<>(); + Set 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 statusMap = statusIds.isEmpty() + ? Map.of() + : orderStatusService.listByIds(statusIds).stream() + .collect(Collectors.toMap(OrderStatusPO::getId, Function.identity(), (a, b) -> a)); + Map shopMap = shopIds.isEmpty() + ? Map.of() + : shopService.listByIds(shopIds).stream() + .collect(Collectors.toMap(ShopPO::getId, Function.identity(), (a, b) -> a)); + Map 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 productIds = specMap.values().stream() + .map(ProductSpecPO::getProductId) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); + Map productMap = productIds.isEmpty() + ? Map.of() + : productService.listByIds(productIds).stream() + .collect(Collectors.toMap(ProductPO::getId, Function.identity(), (a, b) -> a)); + + List 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 diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/support/OrderPageQuerySupport.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/support/OrderPageQuerySupport.java new file mode 100644 index 00000000..27312bdb --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/support/OrderPageQuerySupport.java @@ -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 ALLOWED_SORT_COLUMNS = Set.of( + "order_time", "id", "received_amount", "shop_id", "status_id", "create_time" + ); + + private static final Map 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 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 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(); + } +} diff --git a/ecom-dmb-backend/src/main/resources/mapper/order/OrderMapper.xml b/ecom-dmb-backend/src/main/resources/mapper/order/OrderMapper.xml new file mode 100644 index 00000000..bb040087 --- /dev/null +++ b/ecom-dmb-backend/src/main/resources/mapper/order/OrderMapper.xml @@ -0,0 +1,73 @@ + + + + + + ec_order + + + FORCE INDEX (idx_company_shop_time) + + + FORCE INDEX (idx_company_order_time) + + + + + + WHERE company_id = #{companyId} + + AND shop_id = #{shopId} + + + + + AND platform_order_no LIKE CONCAT(#{platformOrderNo}, '%') + + + AND platform_order_no LIKE CONCAT('%', #{platformOrderNo}, '%') + + + + + AND status_id = #{statusId} + + + AND received_amount >= #{minReceivedAmount} + + + AND received_amount <= #{maxReceivedAmount} + + + AND order_time >= #{startOrderTime} + + + AND order_time <= #{endOrderTime} + + + AND import_task_id = #{importTaskId} + + + AND confirm = #{confirm} + + + AND product_spec_id IN ( + SELECT id FROM ec_product_spec WHERE product_id = #{productId} + ) + + + + + + + diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/order/types/types.dto.ts b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/order/types/types.dto.ts index e29164f7..b4fd5322 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/order/types/types.dto.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/order/types/types.dto.ts @@ -75,7 +75,7 @@ export namespace OrderDTO { export interface Filters { /** 店铺ID */ shopId?: number; - /** 平台订单号(模糊查询) */ + /** 平台订单号(默认前缀匹配;含 %/_ 时全模糊) */ platformOrderNo?: string; /** 订单状态ID */ statusId?: number; diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/ecommerce/order/index.vue b/ecom-dmb-frontend/apps/web-antd/src/views/ecommerce/order/index.vue index 163d1566..db21d634 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/views/ecommerce/order/index.vue +++ b/ecom-dmb-frontend/apps/web-antd/src/views/ecommerce/order/index.vue @@ -80,16 +80,57 @@ const productSearchKeyword = ref(''); const productLoaded = ref(false); let productSearchTimer: null | ReturnType = null; -// 搜索表单 +/** 与后端 OrderPageQuerySupport 对齐 */ +const DEFAULT_LIST_DAYS = 30; +const MAX_LIST_DAYS = 366; + +function buildDefaultOrderTimeRange() { + const end = dayjs().endOf('day'); + const start = dayjs() + .subtract(DEFAULT_LIST_DAYS - 1, 'day') + .startOf('day'); + return { + start: start.format('YYYY-MM-DD HH:mm:ss'), + end: end.format('YYYY-MM-DD HH:mm:ss'), + range: [start, end] as [dayjs.Dayjs, dayjs.Dayjs], + }; +} + +const defaultOrderTime = buildDefaultOrderTimeRange(); + +// 搜索表单(默认近 30 天,避免无时间范围扫全表) const searchForm = ref({ platformOrderNo: '', shopId: undefined as number | undefined, statusId: undefined as number | undefined, - startOrderTime: undefined as string | undefined, - endOrderTime: undefined as string | undefined, + startOrderTime: defaultOrderTime.start as string | undefined, + endOrderTime: defaultOrderTime.end as string | undefined, productId: undefined as number | undefined, }); +function ensureOrderTimeFilters(): boolean { + if (!searchForm.value.startOrderTime || !searchForm.value.endOrderTime) { + const d = buildDefaultOrderTimeRange(); + searchForm.value.startOrderTime = d.start; + searchForm.value.endOrderTime = d.end; + } + const start = dayjs(searchForm.value.startOrderTime); + const end = dayjs(searchForm.value.endOrderTime); + if (!start.isValid() || !end.isValid()) { + message.warning('请选择有效的下单时间范围'); + return false; + } + if (end.isBefore(start)) { + message.warning('下单结束时间不能早于开始时间'); + return false; + } + if (end.diff(start, 'day') + 1 > MAX_LIST_DAYS) { + message.warning(`下单时间跨度不能超过 ${MAX_LIST_DAYS} 天,请缩小范围`); + return false; + } + return true; +} + // 当前排序状态 const currentSort = ref(null); @@ -347,6 +388,9 @@ const gridOptions: VxeGridProps = { ajax: { query: async ({ page, form }) => { try { + if (!ensureOrderTimeFilters()) { + return { items: [], total: 0 }; + } loading.value = true; // 从表单获取搜索参数 const searchParams = form || {}; @@ -403,7 +447,7 @@ const formOptions = computed(() => ({ { component: 'Input', componentProps: { - placeholder: '请输入平台订单号(回车搜索)', + placeholder: '平台订单号(前缀匹配,回车搜索)', onChange: (e: any) => { searchForm.value.platformOrderNo = e.target.value; }, @@ -483,29 +527,40 @@ const formOptions = computed(() => ({ }, { component: 'RangePicker', + defaultValue: defaultOrderTime.range, componentProps: { placeholder: ['下单开始时间', '下单结束时间'], - allowClear: true, + allowClear: false, showTime: { format: 'HH:mm:ss' }, format: 'YYYY-MM-DD HH:mm:ss', style: { width: '100%' }, onChange: (val: any) => { - searchForm.value.startOrderTime = val && val[0] - ? (val[0] as dayjs.Dayjs).format('YYYY-MM-DD HH:mm:ss') - : undefined; - searchForm.value.endOrderTime = val && val[1] - ? (val[1] as dayjs.Dayjs).format('YYYY-MM-DD HH:mm:ss') - : undefined; + if (!val || !val[0] || !val[1]) { + const d = buildDefaultOrderTimeRange(); + searchForm.value.startOrderTime = d.start; + searchForm.value.endOrderTime = d.end; + } else { + searchForm.value.startOrderTime = (val[0] as dayjs.Dayjs).format( + 'YYYY-MM-DD HH:mm:ss', + ); + searchForm.value.endOrderTime = (val[1] as dayjs.Dayjs).format( + 'YYYY-MM-DD HH:mm:ss', + ); + } gridReloadRef.value?.(); }, }, fieldName: 'orderTimeRange', label: '下单时间', + rules: 'required', }, ], showDefaultActions: true, collapsed: true, collapsedRows: 2, + defaultValues: { + orderTimeRange: defaultOrderTime.range, + }, })); // 刷新表格数据 @@ -618,9 +673,9 @@ function handleModalSuccess() { refreshTable(); } -// 初始化 +// 初始化:保证表单与 searchForm 时间一致 onMounted(async () => { - // 店铺、订单状态、商品选择器改为点击时懒加载,不再预加载 + ensureOrderTimeFilters(); });