mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
feat: 优化订单转换效率
This commit is contained in:
@@ -317,10 +317,12 @@ RoutingKey:
|
||||
|
||||
投递策略(固定):
|
||||
|
||||
1. **全量 day / bootstrap**:每同步完一天 → publish `mode=FULL_DAY` + 当日 `orders[{id, updateTime}]`(列表可空则消费者按 `shopId+statDate` 查渠道表)
|
||||
2. **incremental**:每同步完一页 → publish `mode=INC` + 本页 `orders`
|
||||
1. **全量 day / bootstrap**:每同步完一天 → publish `mode=FULL_DAY` + 当日**有变更**的 `orders[{id}]`(可空);空列表仍发消息以触发当日 BI full,**不**再按日回落扫全量渠道单
|
||||
2. **incremental**:每同步完一页 → publish `mode=INC` + 本页**有变更**的 `orders`
|
||||
3. **repair**:经 `PddOrderAfterSyncListener` publish `mode=INC` + refs;日常增量不再经 Listener
|
||||
|
||||
渠道 upsert:`pdd_updated_at` 未推进则 `changed=false`(跳过明细替换),不同步进转换消息。
|
||||
|
||||
全量任务保证「一天同步完 → 一条转换消息」。
|
||||
|
||||
### 5.2 映射规则(摘要)
|
||||
@@ -350,7 +352,7 @@ RoutingKey:
|
||||
|
||||
| mode | 行为 |
|
||||
|------|------|
|
||||
| `FULL_DAY` | 开事务批量转换(按消息渠道主键或店+成交日查渠道表)→ 写 `ec_order.platform_updated_at` ← 渠道 `pdd_updated_at` → 发 **一条** `bi.stat.full`(**不**再写转换侧 Redis 快照) |
|
||||
| `FULL_DAY` | 开事务批量转换:消息带 `orders`(含空)只按 id 加载;`orders==null` 的旧消息才按店+成交日查。仅渠道新于内部的单写入;批内预加载 SKU/成本 → 写 `platform_updated_at` → 发 `bi.stat.full`(含成交日,即使当日零变更) |
|
||||
| `INC` | 逐单按 `channelOrderId` 查渠道镜像;内部用 `platform_code + source_order_id` 定位:无单则新增;有单则仅当 `channel.pdd_updated_at` **严格晚于** `ec_order.platform_updated_at` 时覆盖转换;用转换前后贡献差算出 delta,按受影响 `statDate` 各发一条 `bi.stat.inc`;`internalOrderUpdateTime` = 转换后 `ec_order.update_time` |
|
||||
|
||||
部分失败:FULL_DAY 不发 full 消息,转换消息进重试/DLQ;INC 仅对实际转换成功的订单发 inc 消息。
|
||||
|
||||
@@ -67,6 +67,7 @@ CREATE TABLE `ec_order` (
|
||||
INDEX `idx_ec_order_confirm_time`(`confirm_time` ASC) USING BTREE,
|
||||
INDEX `idx_ec_order_import_task`(`import_task_id` ASC) USING BTREE,
|
||||
INDEX `idx_ec_order_source`(`source` ASC, `source_order_id` ASC) USING BTREE,
|
||||
INDEX `idx_ec_order_company_platform_source`(`company_id` ASC, `platform_code` ASC, `source_order_id` ASC) USING BTREE COMMENT '转换按来源镜像定位',
|
||||
INDEX `idx_ec_order_confirm`(`confirm` ASC) USING BTREE,
|
||||
CONSTRAINT `fk_ec_order_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
CONSTRAINT `fk_ec_order_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
-- 内部订单按来源镜像定位:findInternalBySource(company_id, platform_code, source_order_id)
|
||||
ALTER TABLE `ec_order`
|
||||
ADD INDEX `idx_ec_order_company_platform_source` (`company_id`, `platform_code`, `source_order_id`)
|
||||
COMMENT '同步转换按来源镜像定位内部单';
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package top.xyquan.ecomdmbbackend.common.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.TaskScheduler;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
|
||||
|
||||
@Configuration
|
||||
public class SchedulingConfig {
|
||||
|
||||
@Bean
|
||||
public TaskScheduler taskScheduler() {
|
||||
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
|
||||
scheduler.setPoolSize(4);
|
||||
scheduler.setThreadNamePrefix("mq-delay-");
|
||||
scheduler.setRemoveOnCancelPolicy(true);
|
||||
scheduler.initialize();
|
||||
return scheduler;
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package top.xyquan.ecomdmbbackend.common.mq;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.scheduling.TaskScheduler;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* 锁冲突等场景延后重投 MQ:用调度线程延迟,不阻塞 listener 消费线程。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class DelayedMqRepublisher {
|
||||
|
||||
private final RabbitTemplate rabbitTemplate;
|
||||
private final TaskScheduler taskScheduler;
|
||||
|
||||
public void republish(String exchange, String routingKey, Object message, long delayMs) {
|
||||
long delay = Math.max(delayMs, 100L);
|
||||
Instant when = Instant.now().plusMillis(delay);
|
||||
taskScheduler.schedule(() -> {
|
||||
try {
|
||||
rabbitTemplate.convertAndSend(exchange, routingKey, message);
|
||||
} catch (Exception e) {
|
||||
log.error("延迟重投 MQ 失败 exchange={} rk={}", exchange, routingKey, e);
|
||||
}
|
||||
}, when);
|
||||
}
|
||||
}
|
||||
+2
@@ -21,4 +21,6 @@ public class BiFullCalcMessage {
|
||||
private String statDate;
|
||||
private String syncBatchId;
|
||||
private OffsetDateTime occurredAt;
|
||||
/** 锁冲突延迟重投次数 */
|
||||
private Integer retryCount;
|
||||
}
|
||||
|
||||
+13
-11
@@ -3,8 +3,8 @@ package top.xyquan.ecomdmbbackend.modules.bi.orderstat.consumer;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.DelayedMqRepublisher;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.infra.config.BiStatProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiFullCalcMessage;
|
||||
@@ -20,7 +20,7 @@ public class BiStatFullConsumer {
|
||||
|
||||
private final OrderDailyStatComputeService computeService;
|
||||
private final BiStatProperties biStatProperties;
|
||||
private final RabbitTemplate rabbitTemplate;
|
||||
private final DelayedMqRepublisher delayedMqRepublisher;
|
||||
|
||||
@RabbitListener(queues = OrderMqConstants.QUEUE_BI_STAT_FULL)
|
||||
public void onMessage(BiFullCalcMessage message) {
|
||||
@@ -43,16 +43,18 @@ public class BiStatFullConsumer {
|
||||
}
|
||||
|
||||
private void delayAndRepublish(BiFullCalcMessage message) {
|
||||
try {
|
||||
Thread.sleep(Math.max(biStatProperties.getIncDelayMs(), 100));
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException("BI full 延迟被中断", e);
|
||||
int retry = message.getRetryCount() == null ? 0 : message.getRetryCount();
|
||||
if (retry >= biStatProperties.getIncMaxRetry()) {
|
||||
throw new IllegalStateException("BI full 延迟重试超限: " + message.getMessageId());
|
||||
}
|
||||
message.setRetryCount(retry + 1);
|
||||
message.setOccurredAt(OffsetDateTime.now());
|
||||
log.info("BI full 店锁占用,延后重投 messageId={} shopId={}",
|
||||
message.getMessageId(), message.getShopId());
|
||||
rabbitTemplate.convertAndSend(
|
||||
OrderMqConstants.EXCHANGE, OrderMqConstants.RK_BI_STAT_FULL, message);
|
||||
delayedMqRepublisher.republish(
|
||||
OrderMqConstants.EXCHANGE,
|
||||
OrderMqConstants.RK_BI_STAT_FULL,
|
||||
message,
|
||||
biStatProperties.getIncDelayMs());
|
||||
log.info("BI full 店锁占用,已安排延迟重投 messageId={} shopId={} retry={}",
|
||||
message.getMessageId(), message.getShopId(), message.getRetryCount());
|
||||
}
|
||||
}
|
||||
|
||||
+9
-10
@@ -3,8 +3,8 @@ package top.xyquan.ecomdmbbackend.modules.bi.orderstat.consumer;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.DelayedMqRepublisher;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.infra.config.BiStatProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.infra.lock.BiStatComputeLock;
|
||||
@@ -30,7 +30,7 @@ public class BiStatIncConsumer {
|
||||
private final BiStatComputeLock computeLock;
|
||||
private final BiOrderStatDailyRepository repository;
|
||||
private final BiStatProperties biStatProperties;
|
||||
private final RabbitTemplate rabbitTemplate;
|
||||
private final DelayedMqRepublisher delayedMqRepublisher;
|
||||
|
||||
@RabbitListener(queues = OrderMqConstants.QUEUE_BI_STAT_INC)
|
||||
public void onMessage(BiIncCalcMessage message) {
|
||||
@@ -104,15 +104,14 @@ public class BiStatIncConsumer {
|
||||
if (retry >= biStatProperties.getIncMaxRetry()) {
|
||||
throw new IllegalStateException("BI inc 延迟重试超限: " + message.getMessageId());
|
||||
}
|
||||
try {
|
||||
Thread.sleep(Math.max(biStatProperties.getIncDelayMs(), 100));
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException("BI inc 延迟被中断", e);
|
||||
}
|
||||
message.setRetryCount(retry + 1);
|
||||
message.setOccurredAt(OffsetDateTime.now());
|
||||
rabbitTemplate.convertAndSend(
|
||||
OrderMqConstants.EXCHANGE, OrderMqConstants.RK_BI_STAT_INC, message);
|
||||
delayedMqRepublisher.republish(
|
||||
OrderMqConstants.EXCHANGE,
|
||||
OrderMqConstants.RK_BI_STAT_INC,
|
||||
message,
|
||||
biStatProperties.getIncDelayMs());
|
||||
log.info("BI inc 店锁占用,已安排延迟重投 messageId={} shopId={} retry={}",
|
||||
message.getMessageId(), message.getShopId(), message.getRetryCount());
|
||||
}
|
||||
}
|
||||
|
||||
+9
-10
@@ -3,8 +3,8 @@ package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.consumer;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.DelayedMqRepublisher;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderConvertMessage;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.infra.config.BiStatProperties;
|
||||
@@ -25,7 +25,7 @@ public class PddOrderConvertConsumer {
|
||||
private final PddOrderConvertService convertService;
|
||||
private final OrderConvertShopLock convertShopLock;
|
||||
private final BiStatProperties biStatProperties;
|
||||
private final RabbitTemplate rabbitTemplate;
|
||||
private final DelayedMqRepublisher delayedMqRepublisher;
|
||||
|
||||
@RabbitListener(queues = OrderMqConstants.QUEUE_ORDER_CONVERT_PDD)
|
||||
public void onMessage(OrderConvertMessage message) {
|
||||
@@ -56,15 +56,14 @@ public class PddOrderConvertConsumer {
|
||||
if (retry >= biStatProperties.getIncMaxRetry()) {
|
||||
throw new IllegalStateException("转换延迟重试超限: " + message.getMessageId());
|
||||
}
|
||||
try {
|
||||
Thread.sleep(Math.max(biStatProperties.getIncDelayMs(), 100));
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException("转换延迟被中断", e);
|
||||
}
|
||||
message.setRetryCount(retry + 1);
|
||||
message.setOccurredAt(OffsetDateTime.now(ZONE));
|
||||
rabbitTemplate.convertAndSend(
|
||||
OrderMqConstants.EXCHANGE, OrderMqConstants.RK_ORDER_CONVERT_PDD, message);
|
||||
delayedMqRepublisher.republish(
|
||||
OrderMqConstants.EXCHANGE,
|
||||
OrderMqConstants.RK_ORDER_CONVERT_PDD,
|
||||
message,
|
||||
biStatProperties.getIncDelayMs());
|
||||
log.info("转换店锁占用,已安排延迟重投 messageId={} shopId={} retry={}",
|
||||
message.getMessageId(), message.getShopId(), message.getRetryCount());
|
||||
}
|
||||
}
|
||||
|
||||
+1
@@ -36,6 +36,7 @@ public class PddBiCalcPublisher {
|
||||
.statDate(statDate.toString())
|
||||
.syncBatchId(syncBatchId)
|
||||
.occurredAt(OffsetDateTime.now(ZONE))
|
||||
.retryCount(0)
|
||||
.build();
|
||||
rabbitTemplate.convertAndSend(OrderMqConstants.EXCHANGE, OrderMqConstants.RK_BI_STAT_FULL, msg);
|
||||
log.info("已投递 BI full shopId={} statDate={}", shopId, statDate);
|
||||
|
||||
+75
-16
@@ -42,6 +42,7 @@ import java.time.OffsetDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
@@ -87,7 +88,7 @@ public class PddOrderConvertService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 仅做库写入;返回需全量重算的 BI 统计日(成交日 + 本批订单 order_time/created_time 涉及日)。
|
||||
* 仅做库写入;返回需全量重算的 BI 统计日(成交日 + 本批实际转换订单 order_time 涉及日)。
|
||||
*/
|
||||
private Set<LocalDate> convertFullDay(OrderConvertMessage message) {
|
||||
List<PddOrderPO> channelOrders = loadChannelOrders(message);
|
||||
@@ -96,8 +97,13 @@ public class PddOrderConvertService {
|
||||
if (message.getStatDate() != null) {
|
||||
biDates.add(LocalDate.parse(message.getStatDate()));
|
||||
}
|
||||
SkuBindContext bindCtx = preloadSkuBind(message.getCompanyId(), channelOrders);
|
||||
for (PddOrderPO channel : channelOrders) {
|
||||
upsertInternalOrder(channel, mappedAt);
|
||||
OrderPO existing = findInternalBySource(channel);
|
||||
if (existing != null && !isChannelNewer(channel, existing)) {
|
||||
continue;
|
||||
}
|
||||
upsertInternalOrder(channel, mappedAt, bindCtx);
|
||||
// BI 日键是 ec_order.order_time = 渠道 created_time
|
||||
if (channel.getCreatedTime() != null) {
|
||||
biDates.add(channel.getCreatedTime().toLocalDate());
|
||||
@@ -121,6 +127,7 @@ public class PddOrderConvertService {
|
||||
OrderStatusStatSets stat = orderStatusStatResolver.resolve(message.getCompanyId());
|
||||
LocalDateTime mappedAt = LocalDateTime.now(ZONE);
|
||||
|
||||
List<PddOrderPO> channels = new ArrayList<>();
|
||||
for (ChannelOrderRef ref : refs) {
|
||||
if (ref == null || ref.getChannelOrderId() == null) {
|
||||
continue;
|
||||
@@ -132,7 +139,11 @@ public class PddOrderConvertService {
|
||||
log.warn("INC 转换跳过:渠道单不存在或不匹配 channelOrderId={}", ref.getChannelOrderId());
|
||||
continue;
|
||||
}
|
||||
channels.add(channel);
|
||||
}
|
||||
SkuBindContext bindCtx = preloadSkuBind(message.getCompanyId(), channels);
|
||||
|
||||
for (PddOrderPO channel : channels) {
|
||||
OrderPO oldOrder = findInternalBySource(channel);
|
||||
if (oldOrder != null && !isChannelNewer(channel, oldOrder)) {
|
||||
log.info("跳过 INC 转换(内部已是最新) channelOrderId={} platformUpdatedAt={}",
|
||||
@@ -148,7 +159,7 @@ public class PddOrderConvertService {
|
||||
OrderStatContributionCalculator.OrderContribution oldContrib =
|
||||
contributionCalculator.contribute(oldOrder, oldItems, stat);
|
||||
|
||||
OrderPO neu = upsertInternalOrder(channel, mappedAt);
|
||||
OrderPO neu = upsertInternalOrder(channel, mappedAt, bindCtx);
|
||||
// 以库中最新 update_time 为准(转换完成时刻),供 BI 与全量快照比较
|
||||
OrderPO refreshed = orderMapper.selectById(neu.getId());
|
||||
LocalDateTime internalUpdated = refreshed != null && refreshed.getUpdateTime() != null
|
||||
@@ -258,20 +269,25 @@ public class PddOrderConvertService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* orders != null(含空列表):只按 id 加载,不回落到按日全量(避免「当日无变更」仍扫全天渠道单)。
|
||||
* orders == null:兼容旧消息,按成交日拉渠道单。
|
||||
*/
|
||||
private List<PddOrderPO> loadChannelOrders(OrderConvertMessage message) {
|
||||
if (message.getOrders() != null && !message.getOrders().isEmpty()) {
|
||||
if (message.getOrders() != null) {
|
||||
List<Long> ids = message.getOrders().stream()
|
||||
.filter(Objects::nonNull)
|
||||
.map(ChannelOrderRef::getChannelOrderId)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
if (!ids.isEmpty()) {
|
||||
return pddOrderMapper.selectBatchIds(ids).stream()
|
||||
.filter(o -> Objects.equals(o.getCompanyId(), message.getCompanyId())
|
||||
&& Objects.equals(o.getShopId(), message.getShopId()))
|
||||
.collect(Collectors.toList());
|
||||
if (ids.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
return pddOrderMapper.selectBatchIds(ids).stream()
|
||||
.filter(o -> Objects.equals(o.getCompanyId(), message.getCompanyId())
|
||||
&& Objects.equals(o.getShopId(), message.getShopId()))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
if (message.getMode() == OrderConvertMode.FULL_DAY && message.getStatDate() != null) {
|
||||
LocalDate day = LocalDate.parse(message.getStatDate());
|
||||
@@ -291,7 +307,7 @@ public class PddOrderConvertService {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
private OrderPO upsertInternalOrder(PddOrderPO channel, LocalDateTime mappedAt) {
|
||||
private OrderPO upsertInternalOrder(PddOrderPO channel, LocalDateTime mappedAt, SkuBindContext bindCtx) {
|
||||
OrderPO existing = findInternalBySource(channel);
|
||||
if (existing == null) {
|
||||
// 兼容:早期仅按平台单号落库、尚未写 source_order_id 的行
|
||||
@@ -350,16 +366,16 @@ public class PddOrderConvertService {
|
||||
.eq(OrderItemPO::getOrderId, order.getId()));
|
||||
}
|
||||
|
||||
List<PddOrderItemPO> channelItems = pddOrderItemMapper.selectList(new LambdaQueryWrapper<PddOrderItemPO>()
|
||||
.eq(PddOrderItemPO::getOrderId, channel.getId()));
|
||||
List<PddOrderItemPO> channelItems = bindCtx.itemsByOrderId()
|
||||
.getOrDefault(channel.getId(), List.of());
|
||||
int lineNo = 1;
|
||||
for (PddOrderItemPO ci : channelItems) {
|
||||
orderItemMapper.insert(mapItem(order, ci, lineNo++));
|
||||
orderItemMapper.insert(mapItem(order, ci, lineNo++, bindCtx));
|
||||
}
|
||||
return order;
|
||||
}
|
||||
|
||||
private OrderItemPO mapItem(OrderPO order, PddOrderItemPO ci, int lineNo) {
|
||||
private OrderItemPO mapItem(OrderPO order, PddOrderItemPO ci, int lineNo, SkuBindContext bindCtx) {
|
||||
OrderItemPO item = new OrderItemPO();
|
||||
item.setOrderId(order.getId());
|
||||
item.setCompanyId(order.getCompanyId());
|
||||
@@ -380,12 +396,12 @@ public class PddOrderConvertService {
|
||||
Long skuId = null;
|
||||
String skuCode = null;
|
||||
if (StringUtils.hasText(ci.getOuterId())) {
|
||||
ProductSkuPO sku = productSkuService.getByCompanyIdAndSkuCode(order.getCompanyId(), ci.getOuterId().trim());
|
||||
ProductSkuPO sku = bindCtx.skuByCode().get(ci.getOuterId().trim());
|
||||
if (sku != null) {
|
||||
productId = sku.getProductId();
|
||||
skuId = sku.getId();
|
||||
skuCode = sku.getSkuCode();
|
||||
ProductSkuCostPO cost = productSkuCostService.getCurrentCost(sku.getId());
|
||||
ProductSkuCostPO cost = bindCtx.costBySkuId().get(sku.getId());
|
||||
if (cost != null) {
|
||||
item.setProductCost(cost.getProductCost());
|
||||
item.setShippingCost(cost.getShippingCost());
|
||||
@@ -408,6 +424,49 @@ public class PddOrderConvertService {
|
||||
return item;
|
||||
}
|
||||
|
||||
/** 批内预加载渠道明细 + SKU + 当前成本,消除逐行 N+1。 */
|
||||
private SkuBindContext preloadSkuBind(Long companyId, List<PddOrderPO> channels) {
|
||||
if (channels == null || channels.isEmpty()) {
|
||||
return SkuBindContext.empty();
|
||||
}
|
||||
List<Long> channelIds = channels.stream()
|
||||
.map(PddOrderPO::getId)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.toList();
|
||||
if (channelIds.isEmpty()) {
|
||||
return SkuBindContext.empty();
|
||||
}
|
||||
List<PddOrderItemPO> allItems = pddOrderItemMapper.selectList(new LambdaQueryWrapper<PddOrderItemPO>()
|
||||
.in(PddOrderItemPO::getOrderId, channelIds));
|
||||
Map<Long, List<PddOrderItemPO>> itemsByOrderId = allItems.stream()
|
||||
.collect(Collectors.groupingBy(PddOrderItemPO::getOrderId));
|
||||
|
||||
Set<String> codes = new HashSet<>();
|
||||
for (PddOrderItemPO item : allItems) {
|
||||
if (StringUtils.hasText(item.getOuterId())) {
|
||||
codes.add(item.getOuterId().trim());
|
||||
}
|
||||
}
|
||||
Map<String, ProductSkuPO> skuByCode = productSkuService.listByCompanyIdAndSkuCodes(companyId, codes);
|
||||
Set<Long> skuIds = skuByCode.values().stream()
|
||||
.map(ProductSkuPO::getId)
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.toSet());
|
||||
Map<Long, ProductSkuCostPO> costs = productSkuCostService.getCurrentCosts(skuIds);
|
||||
return new SkuBindContext(itemsByOrderId, skuByCode, costs);
|
||||
}
|
||||
|
||||
private record SkuBindContext(
|
||||
Map<Long, List<PddOrderItemPO>> itemsByOrderId,
|
||||
Map<String, ProductSkuPO> skuByCode,
|
||||
Map<Long, ProductSkuCostPO> costBySkuId
|
||||
) {
|
||||
static SkuBindContext empty() {
|
||||
return new SkuBindContext(Map.of(), Map.of(), Map.of());
|
||||
}
|
||||
}
|
||||
|
||||
private static BigDecimal nz(BigDecimal v) {
|
||||
return v != null ? v : BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
+3
-2
@@ -179,7 +179,7 @@ public class PddOrderSyncService {
|
||||
fetched++;
|
||||
PddOrderUpsertService.UpsertResult ur =
|
||||
upsertService.upsertWithMeta(ctx, raw.snapshot(), raw.raw(), false);
|
||||
if (ur != null && ur.id() != null) {
|
||||
if (ur != null && ur.id() != null && ur.changed()) {
|
||||
ChannelOrderRef ref = PddOrderConvertPublisher.ref(ur.id());
|
||||
if (ref != null) {
|
||||
dayRefs.add(ref);
|
||||
@@ -191,6 +191,7 @@ public class PddOrderSyncService {
|
||||
hasNext = pageData.hasNext();
|
||||
page++;
|
||||
}
|
||||
// 即使当日无变更单,仍发 FULL_DAY(orders 可为空)以触发当日 BI full
|
||||
convertPublisher.publishFullDay(
|
||||
ctx.getCompanyId(), ctx.getShopId(), day, dayRefs, taskId);
|
||||
}
|
||||
@@ -256,7 +257,7 @@ public class PddOrderSyncService {
|
||||
fetched++;
|
||||
PddOrderUpsertService.UpsertResult ur =
|
||||
upsertService.upsertWithMeta(ctx, raw.snapshot(), raw.raw(), false);
|
||||
if (ur != null && ur.id() != null) {
|
||||
if (ur != null && ur.id() != null && ur.changed()) {
|
||||
ChannelOrderRef ref = PddOrderConvertPublisher.ref(ur.id());
|
||||
if (ref != null) {
|
||||
pageRefs.add(ref);
|
||||
|
||||
+10
-3
@@ -70,7 +70,8 @@ public class PddOrderUpsertService {
|
||||
|
||||
if (!force && existing != null && existing.getPddUpdatedAt() != null && remoteUpdated != null
|
||||
&& !existing.getPddUpdatedAt().isBefore(remoteUpdated)) {
|
||||
return new UpsertResult(existing.getId(), existing.getPddUpdatedAt());
|
||||
// 平台更新时间未推进:跳过写库与明细替换,标记未变更供同步侧过滤转换投递
|
||||
return new UpsertResult(existing.getId(), existing.getPddUpdatedAt(), false);
|
||||
}
|
||||
|
||||
PddOrderPO order = existing != null ? existing : new PddOrderPO();
|
||||
@@ -120,10 +121,13 @@ public class PddOrderUpsertService {
|
||||
|
||||
replaceItems(order, snapshot);
|
||||
LocalDateTime updatedAt = order.getPddUpdatedAt() != null ? order.getPddUpdatedAt() : order.getLastSyncTime();
|
||||
return new UpsertResult(order.getId(), updatedAt);
|
||||
return new UpsertResult(order.getId(), updatedAt, true);
|
||||
}
|
||||
|
||||
public record UpsertResult(Long id, LocalDateTime pddUpdatedAt) {
|
||||
/**
|
||||
* @param changed true=本次写入/覆盖了渠道镜像;false=因平台更新时间未推进而跳过
|
||||
*/
|
||||
public record UpsertResult(Long id, LocalDateTime pddUpdatedAt, boolean changed) {
|
||||
}
|
||||
|
||||
private void replaceItems(PddOrderPO order, PddOrderApiSnapshot snapshot) {
|
||||
@@ -151,6 +155,9 @@ public class PddOrderUpsertService {
|
||||
row.setOuterGoodsId(item.getOuterGoodsId());
|
||||
row.setOuterId(item.getOuterId());
|
||||
rows.add(row);
|
||||
}
|
||||
// 批量插入减少往返;未变更路径已在 upsertWithMeta 提前 return,不会走到此处
|
||||
for (PddOrderItemPO row : rows) {
|
||||
pddOrderItemMapper.insert(row);
|
||||
}
|
||||
}
|
||||
|
||||
+5
@@ -10,7 +10,9 @@ import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductSkuPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.vo.ProductSkuVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.vo.ProductVO;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 商品 SKU 服务接口
|
||||
@@ -31,6 +33,9 @@ public interface ProductSkuService extends IService<ProductSkuPO> {
|
||||
|
||||
ProductSkuPO getByCompanyIdAndSkuCode(Long companyId, String skuCode);
|
||||
|
||||
/** 按公司 + SKU 编码批量查询,key 为 skuCode */
|
||||
Map<String, ProductSkuPO> listByCompanyIdAndSkuCodes(Long companyId, Collection<String> skuCodes);
|
||||
|
||||
ProductSkuPO getByCompanyIdAndProductNameAndSkuCode(Long companyId, String productName, String skuCode);
|
||||
|
||||
ProductSkuVO createProductSkuForImport(CreateProductSkuDTO dto, Long companyId, Long userId);
|
||||
|
||||
+10
-5
@@ -40,11 +40,16 @@ public class ProductSkuCostServiceImpl extends ServiceImpl<ProductSkuCostMapper,
|
||||
if (skuIds == null || skuIds.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
for (Long skuId : skuIds) {
|
||||
ProductSkuCostPO cost = getCurrentCost(skuId);
|
||||
if (cost != null) {
|
||||
result.put(skuId, cost);
|
||||
}
|
||||
List<Long> ids = skuIds.stream().filter(Objects::nonNull).distinct().toList();
|
||||
if (ids.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
// 一次查出后按 sku 取 effective_from 最新一条,避免 N+1
|
||||
List<ProductSkuCostPO> rows = list(new LambdaQueryWrapper<ProductSkuCostPO>()
|
||||
.in(ProductSkuCostPO::getSkuId, ids)
|
||||
.orderByDesc(ProductSkuCostPO::getEffectiveFrom));
|
||||
for (ProductSkuCostPO row : rows) {
|
||||
result.putIfAbsent(row.getSkuId(), row);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
+27
@@ -28,6 +28,8 @@ import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductSkuService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -202,6 +204,31 @@ public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, Product
|
||||
return this.getOne(w);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, ProductSkuPO> listByCompanyIdAndSkuCodes(Long companyId, Collection<String> skuCodes) {
|
||||
Map<String, ProductSkuPO> result = new HashMap<>();
|
||||
if (companyId == null || skuCodes == null || skuCodes.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
List<String> codes = skuCodes.stream()
|
||||
.filter(c -> c != null && !c.isBlank())
|
||||
.map(String::trim)
|
||||
.distinct()
|
||||
.toList();
|
||||
if (codes.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
List<ProductSkuPO> rows = this.list(new LambdaQueryWrapper<ProductSkuPO>()
|
||||
.eq(ProductSkuPO::getCompanyId, companyId)
|
||||
.in(ProductSkuPO::getSkuCode, codes));
|
||||
for (ProductSkuPO sku : rows) {
|
||||
if (sku.getSkuCode() != null) {
|
||||
result.putIfAbsent(sku.getSkuCode(), sku);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProductSkuPO getByCompanyIdAndProductNameAndSkuCode(Long companyId, String productName, String skuCode) {
|
||||
if (companyId == null || productName == null || productName.isBlank() || skuCode == null || skuCode.isBlank()) {
|
||||
|
||||
Reference in New Issue
Block a user