mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 17:49: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` 查渠道表)
|
1. **全量 day / bootstrap**:每同步完一天 → publish `mode=FULL_DAY` + 当日**有变更**的 `orders[{id}]`(可空);空列表仍发消息以触发当日 BI full,**不**再按日回落扫全量渠道单
|
||||||
2. **incremental**:每同步完一页 → publish `mode=INC` + 本页 `orders`
|
2. **incremental**:每同步完一页 → publish `mode=INC` + 本页**有变更**的 `orders`
|
||||||
3. **repair**:经 `PddOrderAfterSyncListener` publish `mode=INC` + refs;日常增量不再经 Listener
|
3. **repair**:经 `PddOrderAfterSyncListener` publish `mode=INC` + refs;日常增量不再经 Listener
|
||||||
|
|
||||||
|
渠道 upsert:`pdd_updated_at` 未推进则 `changed=false`(跳过明细替换),不同步进转换消息。
|
||||||
|
|
||||||
全量任务保证「一天同步完 → 一条转换消息」。
|
全量任务保证「一天同步完 → 一条转换消息」。
|
||||||
|
|
||||||
### 5.2 映射规则(摘要)
|
### 5.2 映射规则(摘要)
|
||||||
@@ -350,7 +352,7 @@ RoutingKey:
|
|||||||
|
|
||||||
| mode | 行为 |
|
| 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` |
|
| `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 消息。
|
部分失败: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_confirm_time`(`confirm_time` ASC) USING BTREE,
|
||||||
INDEX `idx_ec_order_import_task`(`import_task_id` 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_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,
|
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_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
|
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 statDate;
|
||||||
private String syncBatchId;
|
private String syncBatchId;
|
||||||
private OffsetDateTime occurredAt;
|
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.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
import top.xyquan.ecomdmbbackend.common.mq.DelayedMqRepublisher;
|
||||||
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
|
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
|
||||||
import top.xyquan.ecomdmbbackend.modules.bi.infra.config.BiStatProperties;
|
import top.xyquan.ecomdmbbackend.modules.bi.infra.config.BiStatProperties;
|
||||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiFullCalcMessage;
|
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiFullCalcMessage;
|
||||||
@@ -20,7 +20,7 @@ public class BiStatFullConsumer {
|
|||||||
|
|
||||||
private final OrderDailyStatComputeService computeService;
|
private final OrderDailyStatComputeService computeService;
|
||||||
private final BiStatProperties biStatProperties;
|
private final BiStatProperties biStatProperties;
|
||||||
private final RabbitTemplate rabbitTemplate;
|
private final DelayedMqRepublisher delayedMqRepublisher;
|
||||||
|
|
||||||
@RabbitListener(queues = OrderMqConstants.QUEUE_BI_STAT_FULL)
|
@RabbitListener(queues = OrderMqConstants.QUEUE_BI_STAT_FULL)
|
||||||
public void onMessage(BiFullCalcMessage message) {
|
public void onMessage(BiFullCalcMessage message) {
|
||||||
@@ -43,16 +43,18 @@ public class BiStatFullConsumer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void delayAndRepublish(BiFullCalcMessage message) {
|
private void delayAndRepublish(BiFullCalcMessage message) {
|
||||||
try {
|
int retry = message.getRetryCount() == null ? 0 : message.getRetryCount();
|
||||||
Thread.sleep(Math.max(biStatProperties.getIncDelayMs(), 100));
|
if (retry >= biStatProperties.getIncMaxRetry()) {
|
||||||
} catch (InterruptedException e) {
|
throw new IllegalStateException("BI full 延迟重试超限: " + message.getMessageId());
|
||||||
Thread.currentThread().interrupt();
|
|
||||||
throw new IllegalStateException("BI full 延迟被中断", e);
|
|
||||||
}
|
}
|
||||||
|
message.setRetryCount(retry + 1);
|
||||||
message.setOccurredAt(OffsetDateTime.now());
|
message.setOccurredAt(OffsetDateTime.now());
|
||||||
log.info("BI full 店锁占用,延后重投 messageId={} shopId={}",
|
delayedMqRepublisher.republish(
|
||||||
message.getMessageId(), message.getShopId());
|
OrderMqConstants.EXCHANGE,
|
||||||
rabbitTemplate.convertAndSend(
|
OrderMqConstants.RK_BI_STAT_FULL,
|
||||||
OrderMqConstants.EXCHANGE, OrderMqConstants.RK_BI_STAT_FULL, message);
|
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.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
import top.xyquan.ecomdmbbackend.common.mq.DelayedMqRepublisher;
|
||||||
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
|
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
|
||||||
import top.xyquan.ecomdmbbackend.modules.bi.infra.config.BiStatProperties;
|
import top.xyquan.ecomdmbbackend.modules.bi.infra.config.BiStatProperties;
|
||||||
import top.xyquan.ecomdmbbackend.modules.bi.infra.lock.BiStatComputeLock;
|
import top.xyquan.ecomdmbbackend.modules.bi.infra.lock.BiStatComputeLock;
|
||||||
@@ -30,7 +30,7 @@ public class BiStatIncConsumer {
|
|||||||
private final BiStatComputeLock computeLock;
|
private final BiStatComputeLock computeLock;
|
||||||
private final BiOrderStatDailyRepository repository;
|
private final BiOrderStatDailyRepository repository;
|
||||||
private final BiStatProperties biStatProperties;
|
private final BiStatProperties biStatProperties;
|
||||||
private final RabbitTemplate rabbitTemplate;
|
private final DelayedMqRepublisher delayedMqRepublisher;
|
||||||
|
|
||||||
@RabbitListener(queues = OrderMqConstants.QUEUE_BI_STAT_INC)
|
@RabbitListener(queues = OrderMqConstants.QUEUE_BI_STAT_INC)
|
||||||
public void onMessage(BiIncCalcMessage message) {
|
public void onMessage(BiIncCalcMessage message) {
|
||||||
@@ -104,15 +104,14 @@ public class BiStatIncConsumer {
|
|||||||
if (retry >= biStatProperties.getIncMaxRetry()) {
|
if (retry >= biStatProperties.getIncMaxRetry()) {
|
||||||
throw new IllegalStateException("BI inc 延迟重试超限: " + message.getMessageId());
|
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.setRetryCount(retry + 1);
|
||||||
message.setOccurredAt(OffsetDateTime.now());
|
message.setOccurredAt(OffsetDateTime.now());
|
||||||
rabbitTemplate.convertAndSend(
|
delayedMqRepublisher.republish(
|
||||||
OrderMqConstants.EXCHANGE, OrderMqConstants.RK_BI_STAT_INC, message);
|
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.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
|
||||||
import org.springframework.stereotype.Component;
|
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.OrderConvertMessage;
|
||||||
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
|
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
|
||||||
import top.xyquan.ecomdmbbackend.modules.bi.infra.config.BiStatProperties;
|
import top.xyquan.ecomdmbbackend.modules.bi.infra.config.BiStatProperties;
|
||||||
@@ -25,7 +25,7 @@ public class PddOrderConvertConsumer {
|
|||||||
private final PddOrderConvertService convertService;
|
private final PddOrderConvertService convertService;
|
||||||
private final OrderConvertShopLock convertShopLock;
|
private final OrderConvertShopLock convertShopLock;
|
||||||
private final BiStatProperties biStatProperties;
|
private final BiStatProperties biStatProperties;
|
||||||
private final RabbitTemplate rabbitTemplate;
|
private final DelayedMqRepublisher delayedMqRepublisher;
|
||||||
|
|
||||||
@RabbitListener(queues = OrderMqConstants.QUEUE_ORDER_CONVERT_PDD)
|
@RabbitListener(queues = OrderMqConstants.QUEUE_ORDER_CONVERT_PDD)
|
||||||
public void onMessage(OrderConvertMessage message) {
|
public void onMessage(OrderConvertMessage message) {
|
||||||
@@ -56,15 +56,14 @@ public class PddOrderConvertConsumer {
|
|||||||
if (retry >= biStatProperties.getIncMaxRetry()) {
|
if (retry >= biStatProperties.getIncMaxRetry()) {
|
||||||
throw new IllegalStateException("转换延迟重试超限: " + message.getMessageId());
|
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.setRetryCount(retry + 1);
|
||||||
message.setOccurredAt(OffsetDateTime.now(ZONE));
|
message.setOccurredAt(OffsetDateTime.now(ZONE));
|
||||||
rabbitTemplate.convertAndSend(
|
delayedMqRepublisher.republish(
|
||||||
OrderMqConstants.EXCHANGE, OrderMqConstants.RK_ORDER_CONVERT_PDD, message);
|
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())
|
.statDate(statDate.toString())
|
||||||
.syncBatchId(syncBatchId)
|
.syncBatchId(syncBatchId)
|
||||||
.occurredAt(OffsetDateTime.now(ZONE))
|
.occurredAt(OffsetDateTime.now(ZONE))
|
||||||
|
.retryCount(0)
|
||||||
.build();
|
.build();
|
||||||
rabbitTemplate.convertAndSend(OrderMqConstants.EXCHANGE, OrderMqConstants.RK_BI_STAT_FULL, msg);
|
rabbitTemplate.convertAndSend(OrderMqConstants.EXCHANGE, OrderMqConstants.RK_BI_STAT_FULL, msg);
|
||||||
log.info("已投递 BI full shopId={} statDate={}", shopId, statDate);
|
log.info("已投递 BI full shopId={} statDate={}", shopId, statDate);
|
||||||
|
|||||||
+75
-16
@@ -42,6 +42,7 @@ import java.time.OffsetDateTime;
|
|||||||
import java.time.ZoneId;
|
import java.time.ZoneId;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Objects;
|
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) {
|
private Set<LocalDate> convertFullDay(OrderConvertMessage message) {
|
||||||
List<PddOrderPO> channelOrders = loadChannelOrders(message);
|
List<PddOrderPO> channelOrders = loadChannelOrders(message);
|
||||||
@@ -96,8 +97,13 @@ public class PddOrderConvertService {
|
|||||||
if (message.getStatDate() != null) {
|
if (message.getStatDate() != null) {
|
||||||
biDates.add(LocalDate.parse(message.getStatDate()));
|
biDates.add(LocalDate.parse(message.getStatDate()));
|
||||||
}
|
}
|
||||||
|
SkuBindContext bindCtx = preloadSkuBind(message.getCompanyId(), channelOrders);
|
||||||
for (PddOrderPO channel : 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
|
// BI 日键是 ec_order.order_time = 渠道 created_time
|
||||||
if (channel.getCreatedTime() != null) {
|
if (channel.getCreatedTime() != null) {
|
||||||
biDates.add(channel.getCreatedTime().toLocalDate());
|
biDates.add(channel.getCreatedTime().toLocalDate());
|
||||||
@@ -121,6 +127,7 @@ public class PddOrderConvertService {
|
|||||||
OrderStatusStatSets stat = orderStatusStatResolver.resolve(message.getCompanyId());
|
OrderStatusStatSets stat = orderStatusStatResolver.resolve(message.getCompanyId());
|
||||||
LocalDateTime mappedAt = LocalDateTime.now(ZONE);
|
LocalDateTime mappedAt = LocalDateTime.now(ZONE);
|
||||||
|
|
||||||
|
List<PddOrderPO> channels = new ArrayList<>();
|
||||||
for (ChannelOrderRef ref : refs) {
|
for (ChannelOrderRef ref : refs) {
|
||||||
if (ref == null || ref.getChannelOrderId() == null) {
|
if (ref == null || ref.getChannelOrderId() == null) {
|
||||||
continue;
|
continue;
|
||||||
@@ -132,7 +139,11 @@ public class PddOrderConvertService {
|
|||||||
log.warn("INC 转换跳过:渠道单不存在或不匹配 channelOrderId={}", ref.getChannelOrderId());
|
log.warn("INC 转换跳过:渠道单不存在或不匹配 channelOrderId={}", ref.getChannelOrderId());
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
channels.add(channel);
|
||||||
|
}
|
||||||
|
SkuBindContext bindCtx = preloadSkuBind(message.getCompanyId(), channels);
|
||||||
|
|
||||||
|
for (PddOrderPO channel : channels) {
|
||||||
OrderPO oldOrder = findInternalBySource(channel);
|
OrderPO oldOrder = findInternalBySource(channel);
|
||||||
if (oldOrder != null && !isChannelNewer(channel, oldOrder)) {
|
if (oldOrder != null && !isChannelNewer(channel, oldOrder)) {
|
||||||
log.info("跳过 INC 转换(内部已是最新) channelOrderId={} platformUpdatedAt={}",
|
log.info("跳过 INC 转换(内部已是最新) channelOrderId={} platformUpdatedAt={}",
|
||||||
@@ -148,7 +159,7 @@ public class PddOrderConvertService {
|
|||||||
OrderStatContributionCalculator.OrderContribution oldContrib =
|
OrderStatContributionCalculator.OrderContribution oldContrib =
|
||||||
contributionCalculator.contribute(oldOrder, oldItems, stat);
|
contributionCalculator.contribute(oldOrder, oldItems, stat);
|
||||||
|
|
||||||
OrderPO neu = upsertInternalOrder(channel, mappedAt);
|
OrderPO neu = upsertInternalOrder(channel, mappedAt, bindCtx);
|
||||||
// 以库中最新 update_time 为准(转换完成时刻),供 BI 与全量快照比较
|
// 以库中最新 update_time 为准(转换完成时刻),供 BI 与全量快照比较
|
||||||
OrderPO refreshed = orderMapper.selectById(neu.getId());
|
OrderPO refreshed = orderMapper.selectById(neu.getId());
|
||||||
LocalDateTime internalUpdated = refreshed != null && refreshed.getUpdateTime() != null
|
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) {
|
private List<PddOrderPO> loadChannelOrders(OrderConvertMessage message) {
|
||||||
if (message.getOrders() != null && !message.getOrders().isEmpty()) {
|
if (message.getOrders() != null) {
|
||||||
List<Long> ids = message.getOrders().stream()
|
List<Long> ids = message.getOrders().stream()
|
||||||
.filter(Objects::nonNull)
|
.filter(Objects::nonNull)
|
||||||
.map(ChannelOrderRef::getChannelOrderId)
|
.map(ChannelOrderRef::getChannelOrderId)
|
||||||
.filter(Objects::nonNull)
|
.filter(Objects::nonNull)
|
||||||
.distinct()
|
.distinct()
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
if (!ids.isEmpty()) {
|
if (ids.isEmpty()) {
|
||||||
return pddOrderMapper.selectBatchIds(ids).stream()
|
return List.of();
|
||||||
.filter(o -> Objects.equals(o.getCompanyId(), message.getCompanyId())
|
|
||||||
&& Objects.equals(o.getShopId(), message.getShopId()))
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
}
|
}
|
||||||
|
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) {
|
if (message.getMode() == OrderConvertMode.FULL_DAY && message.getStatDate() != null) {
|
||||||
LocalDate day = LocalDate.parse(message.getStatDate());
|
LocalDate day = LocalDate.parse(message.getStatDate());
|
||||||
@@ -291,7 +307,7 @@ public class PddOrderConvertService {
|
|||||||
return List.of();
|
return List.of();
|
||||||
}
|
}
|
||||||
|
|
||||||
private OrderPO upsertInternalOrder(PddOrderPO channel, LocalDateTime mappedAt) {
|
private OrderPO upsertInternalOrder(PddOrderPO channel, LocalDateTime mappedAt, SkuBindContext bindCtx) {
|
||||||
OrderPO existing = findInternalBySource(channel);
|
OrderPO existing = findInternalBySource(channel);
|
||||||
if (existing == null) {
|
if (existing == null) {
|
||||||
// 兼容:早期仅按平台单号落库、尚未写 source_order_id 的行
|
// 兼容:早期仅按平台单号落库、尚未写 source_order_id 的行
|
||||||
@@ -350,16 +366,16 @@ public class PddOrderConvertService {
|
|||||||
.eq(OrderItemPO::getOrderId, order.getId()));
|
.eq(OrderItemPO::getOrderId, order.getId()));
|
||||||
}
|
}
|
||||||
|
|
||||||
List<PddOrderItemPO> channelItems = pddOrderItemMapper.selectList(new LambdaQueryWrapper<PddOrderItemPO>()
|
List<PddOrderItemPO> channelItems = bindCtx.itemsByOrderId()
|
||||||
.eq(PddOrderItemPO::getOrderId, channel.getId()));
|
.getOrDefault(channel.getId(), List.of());
|
||||||
int lineNo = 1;
|
int lineNo = 1;
|
||||||
for (PddOrderItemPO ci : channelItems) {
|
for (PddOrderItemPO ci : channelItems) {
|
||||||
orderItemMapper.insert(mapItem(order, ci, lineNo++));
|
orderItemMapper.insert(mapItem(order, ci, lineNo++, bindCtx));
|
||||||
}
|
}
|
||||||
return order;
|
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();
|
OrderItemPO item = new OrderItemPO();
|
||||||
item.setOrderId(order.getId());
|
item.setOrderId(order.getId());
|
||||||
item.setCompanyId(order.getCompanyId());
|
item.setCompanyId(order.getCompanyId());
|
||||||
@@ -380,12 +396,12 @@ public class PddOrderConvertService {
|
|||||||
Long skuId = null;
|
Long skuId = null;
|
||||||
String skuCode = null;
|
String skuCode = null;
|
||||||
if (StringUtils.hasText(ci.getOuterId())) {
|
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) {
|
if (sku != null) {
|
||||||
productId = sku.getProductId();
|
productId = sku.getProductId();
|
||||||
skuId = sku.getId();
|
skuId = sku.getId();
|
||||||
skuCode = sku.getSkuCode();
|
skuCode = sku.getSkuCode();
|
||||||
ProductSkuCostPO cost = productSkuCostService.getCurrentCost(sku.getId());
|
ProductSkuCostPO cost = bindCtx.costBySkuId().get(sku.getId());
|
||||||
if (cost != null) {
|
if (cost != null) {
|
||||||
item.setProductCost(cost.getProductCost());
|
item.setProductCost(cost.getProductCost());
|
||||||
item.setShippingCost(cost.getShippingCost());
|
item.setShippingCost(cost.getShippingCost());
|
||||||
@@ -408,6 +424,49 @@ public class PddOrderConvertService {
|
|||||||
return item;
|
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) {
|
private static BigDecimal nz(BigDecimal v) {
|
||||||
return v != null ? v : BigDecimal.ZERO;
|
return v != null ? v : BigDecimal.ZERO;
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-2
@@ -179,7 +179,7 @@ public class PddOrderSyncService {
|
|||||||
fetched++;
|
fetched++;
|
||||||
PddOrderUpsertService.UpsertResult ur =
|
PddOrderUpsertService.UpsertResult ur =
|
||||||
upsertService.upsertWithMeta(ctx, raw.snapshot(), raw.raw(), false);
|
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());
|
ChannelOrderRef ref = PddOrderConvertPublisher.ref(ur.id());
|
||||||
if (ref != null) {
|
if (ref != null) {
|
||||||
dayRefs.add(ref);
|
dayRefs.add(ref);
|
||||||
@@ -191,6 +191,7 @@ public class PddOrderSyncService {
|
|||||||
hasNext = pageData.hasNext();
|
hasNext = pageData.hasNext();
|
||||||
page++;
|
page++;
|
||||||
}
|
}
|
||||||
|
// 即使当日无变更单,仍发 FULL_DAY(orders 可为空)以触发当日 BI full
|
||||||
convertPublisher.publishFullDay(
|
convertPublisher.publishFullDay(
|
||||||
ctx.getCompanyId(), ctx.getShopId(), day, dayRefs, taskId);
|
ctx.getCompanyId(), ctx.getShopId(), day, dayRefs, taskId);
|
||||||
}
|
}
|
||||||
@@ -256,7 +257,7 @@ public class PddOrderSyncService {
|
|||||||
fetched++;
|
fetched++;
|
||||||
PddOrderUpsertService.UpsertResult ur =
|
PddOrderUpsertService.UpsertResult ur =
|
||||||
upsertService.upsertWithMeta(ctx, raw.snapshot(), raw.raw(), false);
|
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());
|
ChannelOrderRef ref = PddOrderConvertPublisher.ref(ur.id());
|
||||||
if (ref != null) {
|
if (ref != null) {
|
||||||
pageRefs.add(ref);
|
pageRefs.add(ref);
|
||||||
|
|||||||
+10
-3
@@ -70,7 +70,8 @@ public class PddOrderUpsertService {
|
|||||||
|
|
||||||
if (!force && existing != null && existing.getPddUpdatedAt() != null && remoteUpdated != null
|
if (!force && existing != null && existing.getPddUpdatedAt() != null && remoteUpdated != null
|
||||||
&& !existing.getPddUpdatedAt().isBefore(remoteUpdated)) {
|
&& !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();
|
PddOrderPO order = existing != null ? existing : new PddOrderPO();
|
||||||
@@ -120,10 +121,13 @@ public class PddOrderUpsertService {
|
|||||||
|
|
||||||
replaceItems(order, snapshot);
|
replaceItems(order, snapshot);
|
||||||
LocalDateTime updatedAt = order.getPddUpdatedAt() != null ? order.getPddUpdatedAt() : order.getLastSyncTime();
|
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) {
|
private void replaceItems(PddOrderPO order, PddOrderApiSnapshot snapshot) {
|
||||||
@@ -151,6 +155,9 @@ public class PddOrderUpsertService {
|
|||||||
row.setOuterGoodsId(item.getOuterGoodsId());
|
row.setOuterGoodsId(item.getOuterGoodsId());
|
||||||
row.setOuterId(item.getOuterId());
|
row.setOuterId(item.getOuterId());
|
||||||
rows.add(row);
|
rows.add(row);
|
||||||
|
}
|
||||||
|
// 批量插入减少往返;未变更路径已在 upsertWithMeta 提前 return,不会走到此处
|
||||||
|
for (PddOrderItemPO row : rows) {
|
||||||
pddOrderItemMapper.insert(row);
|
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.ProductSkuVO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.vo.ProductVO;
|
import top.xyquan.ecomdmbbackend.modules.ec.product.model.vo.ProductVO;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 商品 SKU 服务接口
|
* 商品 SKU 服务接口
|
||||||
@@ -31,6 +33,9 @@ public interface ProductSkuService extends IService<ProductSkuPO> {
|
|||||||
|
|
||||||
ProductSkuPO getByCompanyIdAndSkuCode(Long companyId, String skuCode);
|
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);
|
ProductSkuPO getByCompanyIdAndProductNameAndSkuCode(Long companyId, String productName, String skuCode);
|
||||||
|
|
||||||
ProductSkuVO createProductSkuForImport(CreateProductSkuDTO dto, Long companyId, Long userId);
|
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()) {
|
if (skuIds == null || skuIds.isEmpty()) {
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
for (Long skuId : skuIds) {
|
List<Long> ids = skuIds.stream().filter(Objects::nonNull).distinct().toList();
|
||||||
ProductSkuCostPO cost = getCurrentCost(skuId);
|
if (ids.isEmpty()) {
|
||||||
if (cost != null) {
|
return result;
|
||||||
result.put(skuId, cost);
|
}
|
||||||
}
|
// 一次查出后按 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;
|
return result;
|
||||||
}
|
}
|
||||||
|
|||||||
+27
@@ -28,6 +28,8 @@ import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductSkuService;
|
|||||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||||
|
|
||||||
import java.math.BigDecimal;
|
import java.math.BigDecimal;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
@@ -202,6 +204,31 @@ public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, Product
|
|||||||
return this.getOne(w);
|
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
|
@Override
|
||||||
public ProductSkuPO getByCompanyIdAndProductNameAndSkuCode(Long companyId, String productName, String skuCode) {
|
public ProductSkuPO getByCompanyIdAndProductNameAndSkuCode(Long companyId, String productName, String skuCode) {
|
||||||
if (companyId == null || productName == null || productName.isBlank() || skuCode == null || skuCode.isBlank()) {
|
if (companyId == null || productName == null || productName.isBlank() || skuCode == null || skuCode.isBlank()) {
|
||||||
|
|||||||
Reference in New Issue
Block a user