feat: 完成拼多多订单同步,订单转换,bi计算三层设计

This commit is contained in:
2026-08-10 15:02:31 +08:00
parent b66b48036d
commit dafbe5820b
61 changed files with 4228 additions and 191 deletions
@@ -0,0 +1,20 @@
package top.xyquan.ecomdmbbackend.common.mq;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 渠道订单引用:镜像表主键。
* 转换侧按 id 查渠道镜像;内部单用 platform_code + source_order_id 定位。
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ChannelOrderRef {
/** 渠道镜像订单主键(如 channel_pdd_order.id) */
private Long channelOrderId;
}
@@ -0,0 +1,30 @@
package top.xyquan.ecomdmbbackend.common.mq;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.OffsetDateTime;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class OrderConvertMessage {
private String messageId;
private Long companyId;
private Long shopId;
private String platform;
private OrderConvertMode mode;
/** FULL_DAY 必填:成交自然日 yyyy-MM-dd */
private String statDate;
/** 渠道镜像订单主键列表(增量按页必带;全量日可带,空则按店+成交日查渠道表) */
private List<ChannelOrderRef> orders;
private String syncBatchId;
private Long taskId;
private OffsetDateTime occurredAt;
private Integer retryCount;
}
@@ -0,0 +1,9 @@
package top.xyquan.ecomdmbbackend.common.mq;
/**
* 订单转换消息模式:全量日与增量共用同一转换队列。
*/
public enum OrderConvertMode {
FULL_DAY,
INC
}
@@ -0,0 +1,32 @@
package top.xyquan.ecomdmbbackend.common.mq;
/**
* 订单同步 / 转换 / BI 管线 MQ 常量。
*/
public final class OrderMqConstants {
public static final String EXCHANGE = "ecom.order.topic";
public static final String RK_ORDER_SYNC_PDD_FULL = "order.sync.pdd.full";
public static final String QUEUE_ORDER_SYNC_PDD_FULL = "order.sync.pdd.full";
public static final String QUEUE_ORDER_SYNC_PDD_FULL_DLQ = "order.sync.pdd.full.dlq";
public static final String RK_ORDER_SYNC_PDD_INC = "order.sync.pdd.inc";
public static final String QUEUE_ORDER_SYNC_PDD_INC = "order.sync.pdd.inc";
public static final String QUEUE_ORDER_SYNC_PDD_INC_DLQ = "order.sync.pdd.inc.dlq";
public static final String RK_ORDER_CONVERT_PDD = "order.convert.pdd";
public static final String QUEUE_ORDER_CONVERT_PDD = "order.convert.pdd";
public static final String QUEUE_ORDER_CONVERT_PDD_DLQ = "order.convert.pdd.dlq";
public static final String RK_BI_STAT_FULL = "bi.stat.full";
public static final String QUEUE_BI_STAT_FULL = "bi.stat.full";
public static final String QUEUE_BI_STAT_FULL_DLQ = "bi.stat.full.dlq";
public static final String RK_BI_STAT_INC = "bi.stat.inc";
public static final String QUEUE_BI_STAT_INC = "bi.stat.inc";
public static final String QUEUE_BI_STAT_INC_DLQ = "bi.stat.inc.dlq";
private OrderMqConstants() {
}
}
@@ -0,0 +1,42 @@
package top.xyquan.ecomdmbbackend.modules.bi.infra.config;
import org.bson.types.Decimal128;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.convert.ReadingConverter;
import org.springframework.data.convert.WritingConverter;
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
import java.math.BigDecimal;
import java.util.List;
/**
* BigDecimal 存 Decimal128,避免默认写成字符串导致 $inc / 数值运算失败。
*/
@Configuration
public class BiMongoConversionsConfig {
@Bean
public MongoCustomConversions mongoCustomConversions() {
return new MongoCustomConversions(List.of(
new BigDecimalToDecimal128Converter(),
new Decimal128ToBigDecimalConverter()));
}
@WritingConverter
static class BigDecimalToDecimal128Converter implements Converter<BigDecimal, Decimal128> {
@Override
public Decimal128 convert(BigDecimal source) {
return new Decimal128(source);
}
}
@ReadingConverter
static class Decimal128ToBigDecimalConverter implements Converter<Decimal128, BigDecimal> {
@Override
public BigDecimal convert(Decimal128 source) {
return source.bigDecimalValue();
}
}
}
@@ -0,0 +1,20 @@
package top.xyquan.ecomdmbbackend.modules.bi.infra.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "ecom.bi.stat")
public class BiStatProperties {
/** 全量计算锁 TTL(秒) */
private long lockTtlSeconds = 600;
/** 增量遇全量进行中时延迟毫秒 */
private long incDelayMs = 5000;
/** 增量延迟最大重试次数 */
private int incMaxRetry = 20;
}
@@ -0,0 +1,145 @@
package top.xyquan.ecomdmbbackend.modules.bi.infra.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
@Configuration
public class RabbitBiConfig {
@Bean
public MessageConverter jacksonMessageConverter() {
return new Jackson2JsonMessageConverter();
}
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory, MessageConverter jacksonMessageConverter) {
RabbitTemplate template = new RabbitTemplate(connectionFactory);
template.setMessageConverter(jacksonMessageConverter);
return template;
}
@Bean
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(
ConnectionFactory connectionFactory, MessageConverter jacksonMessageConverter) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setMessageConverter(jacksonMessageConverter);
return factory;
}
@Bean
public TopicExchange orderTopicExchange() {
return new TopicExchange(OrderMqConstants.EXCHANGE, true, false);
}
@Bean
public Queue orderConvertPddQueue() {
return QueueBuilder.durable(OrderMqConstants.QUEUE_ORDER_CONVERT_PDD)
.withArgument("x-dead-letter-exchange", "")
.withArgument("x-dead-letter-routing-key", OrderMqConstants.QUEUE_ORDER_CONVERT_PDD_DLQ)
.build();
}
@Bean
public Queue orderConvertPddDlq() {
return QueueBuilder.durable(OrderMqConstants.QUEUE_ORDER_CONVERT_PDD_DLQ).build();
}
@Bean
public Binding orderConvertPddBinding(Queue orderConvertPddQueue, TopicExchange orderTopicExchange) {
return BindingBuilder.bind(orderConvertPddQueue)
.to(orderTopicExchange)
.with(OrderMqConstants.RK_ORDER_CONVERT_PDD);
}
@Bean
public Queue biStatFullQueue() {
return QueueBuilder.durable(OrderMqConstants.QUEUE_BI_STAT_FULL)
.withArgument("x-dead-letter-exchange", "")
.withArgument("x-dead-letter-routing-key", OrderMqConstants.QUEUE_BI_STAT_FULL_DLQ)
.build();
}
@Bean
public Queue biStatFullDlq() {
return QueueBuilder.durable(OrderMqConstants.QUEUE_BI_STAT_FULL_DLQ).build();
}
@Bean
public Binding biStatFullBinding(Queue biStatFullQueue, TopicExchange orderTopicExchange) {
return BindingBuilder.bind(biStatFullQueue)
.to(orderTopicExchange)
.with(OrderMqConstants.RK_BI_STAT_FULL);
}
@Bean
public Queue biStatIncQueue() {
return QueueBuilder.durable(OrderMqConstants.QUEUE_BI_STAT_INC)
.withArgument("x-dead-letter-exchange", "")
.withArgument("x-dead-letter-routing-key", OrderMqConstants.QUEUE_BI_STAT_INC_DLQ)
.build();
}
@Bean
public Queue biStatIncDlq() {
return QueueBuilder.durable(OrderMqConstants.QUEUE_BI_STAT_INC_DLQ).build();
}
@Bean
public Binding biStatIncBinding(Queue biStatIncQueue, TopicExchange orderTopicExchange) {
return BindingBuilder.bind(biStatIncQueue)
.to(orderTopicExchange)
.with(OrderMqConstants.RK_BI_STAT_INC);
}
@Bean
public Queue orderSyncPddFullQueue() {
return QueueBuilder.durable(OrderMqConstants.QUEUE_ORDER_SYNC_PDD_FULL)
.withArgument("x-dead-letter-exchange", "")
.withArgument("x-dead-letter-routing-key", OrderMqConstants.QUEUE_ORDER_SYNC_PDD_FULL_DLQ)
.build();
}
@Bean
public Queue orderSyncPddFullDlq() {
return QueueBuilder.durable(OrderMqConstants.QUEUE_ORDER_SYNC_PDD_FULL_DLQ).build();
}
@Bean
public Binding orderSyncPddFullBinding(Queue orderSyncPddFullQueue, TopicExchange orderTopicExchange) {
return BindingBuilder.bind(orderSyncPddFullQueue)
.to(orderTopicExchange)
.with(OrderMqConstants.RK_ORDER_SYNC_PDD_FULL);
}
@Bean
public Queue orderSyncPddIncQueue() {
return QueueBuilder.durable(OrderMqConstants.QUEUE_ORDER_SYNC_PDD_INC)
.withArgument("x-dead-letter-exchange", "")
.withArgument("x-dead-letter-routing-key", OrderMqConstants.QUEUE_ORDER_SYNC_PDD_INC_DLQ)
.build();
}
@Bean
public Queue orderSyncPddIncDlq() {
return QueueBuilder.durable(OrderMqConstants.QUEUE_ORDER_SYNC_PDD_INC_DLQ).build();
}
@Bean
public Binding orderSyncPddIncBinding(Queue orderSyncPddIncQueue, TopicExchange orderTopicExchange) {
return BindingBuilder.bind(orderSyncPddIncQueue)
.to(orderTopicExchange)
.with(OrderMqConstants.RK_ORDER_SYNC_PDD_INC);
}
}
@@ -0,0 +1,87 @@
package top.xyquan.ecomdmbbackend.modules.bi.infra.lock;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import top.xyquan.ecomdmbbackend.modules.bi.infra.config.BiStatProperties;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
/**
* BI 同店串行锁(全量/增量共用)。
* 全量抢锁时登记会话 snapshotTime(事务快照开启时刻),供进行中的增量跳过/延后;
* 持久化的「最新全量快照时间」以 Mongo 文档 dbSnapshotTime 为准。
*/
@Component
@RequiredArgsConstructor
public class BiStatComputeLock {
private static final String LOCK_PREFIX = "bi:stat:lock:";
private final StringRedisTemplate stringRedisTemplate;
private final BiStatProperties biStatProperties;
/** 同店串行:key = companyId:shopId */
public Optional<Session> tryLock(Long companyId, Long shopId, Instant snapshotTimeOrNull) {
String key = lockKey(companyId, shopId);
String token = UUID.randomUUID().toString();
long ttl = Math.max(biStatProperties.getLockTtlSeconds(), 60);
Boolean ok = stringRedisTemplate.opsForValue()
.setIfAbsent(key + ":hold", token, Duration.ofSeconds(ttl));
if (!Boolean.TRUE.equals(ok)) {
return Optional.empty();
}
Map<String, String> meta = new HashMap<>();
meta.put("token", token);
if (snapshotTimeOrNull != null) {
meta.put("snapshotTime", String.valueOf(snapshotTimeOrNull.toEpochMilli()));
}
stringRedisTemplate.opsForHash().putAll(key, meta);
stringRedisTemplate.expire(key, Duration.ofSeconds(ttl));
return Optional.of(new Session(key, token, snapshotTimeOrNull));
}
public Optional<Instant> peekSessionSnapshot(Long companyId, Long shopId) {
Object v = stringRedisTemplate.opsForHash().get(lockKey(companyId, shopId), "snapshotTime");
return parseInstant(v);
}
public boolean isLocked(Long companyId, Long shopId) {
return Boolean.TRUE.equals(stringRedisTemplate.hasKey(lockKey(companyId, shopId) + ":hold"));
}
public void unlock(Session session) {
if (session == null) {
return;
}
String holdKey = session.key() + ":hold";
String current = stringRedisTemplate.opsForValue().get(holdKey);
if (session.token().equals(current)) {
stringRedisTemplate.delete(holdKey);
stringRedisTemplate.delete(session.key());
}
}
private static String lockKey(Long companyId, Long shopId) {
return LOCK_PREFIX + companyId + ":" + shopId;
}
private static Optional<Instant> parseInstant(Object v) {
if (v == null) {
return Optional.empty();
}
try {
return Optional.of(Instant.ofEpochMilli(Long.parseLong(v.toString())));
} catch (NumberFormatException e) {
return Optional.empty();
}
}
public record Session(String key, String token, Instant snapshotTime) {
}
}
@@ -0,0 +1,24 @@
package top.xyquan.ecomdmbbackend.modules.bi.messaging;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.OffsetDateTime;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class BiFullCalcMessage {
private String messageId;
private Long companyId;
private Long shopId;
private String platformCode;
/** yyyy-MM-dd */
private String statDate;
private String syncBatchId;
private OffsetDateTime occurredAt;
}
@@ -0,0 +1,38 @@
package top.xyquan.ecomdmbbackend.modules.bi.messaging;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.OffsetDateTime;
import java.util.List;
/**
* 增量计算消息:转换侧算好各维度加减量,BI 侧按快照决定跳过或累加。
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class BiIncCalcMessage {
private String messageId;
private Long companyId;
private Long shopId;
private String platformCode;
/** yyyy-MM-dd */
private String statDate;
/**
* 转换完成时内部订单的更新时间(ec_order.update_time / last_mapped_time)。
* BI 与 Mongo 文档 dbSnapshotTime(最新一次全量事务快照开启时间)比较:≤ 快照则跳过。
*/
private OffsetDateTime internalOrderUpdateTime;
private Long orderId;
private Long channelOrderId;
private BiStatMetricDelta shopDelta;
private List<BiProductStatDelta> productDeltas;
private List<BiSpecStatDelta> specDeltas;
private OffsetDateTime occurredAt;
private Integer retryCount;
}
@@ -0,0 +1,17 @@
package top.xyquan.ecomdmbbackend.modules.bi.messaging;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class BiProductStatDelta {
private Long productId;
private Long categoryId;
private BiStatMetricDelta metrics;
}
@@ -0,0 +1,17 @@
package top.xyquan.ecomdmbbackend.modules.bi.messaging;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class BiSpecStatDelta {
private Long productId;
private Long productSpecId;
private BiStatMetricDelta metrics;
}
@@ -0,0 +1,100 @@
package top.xyquan.ecomdmbbackend.modules.bi.messaging;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
/** 单维度指标增量(可正可负) */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class BiStatMetricDelta {
private BigDecimal salesAmount;
private Integer salesOrderCount;
private Integer salesQuantitySum;
private BigDecimal gmvAmount;
private Integer gmvOrderCount;
private Integer gmvQuantitySum;
private BigDecimal refundAmount;
private BigDecimal productCost;
private BigDecimal freightCost;
private BigDecimal otherCost;
public static BiStatMetricDelta zeros() {
return BiStatMetricDelta.builder()
.salesAmount(BigDecimal.ZERO)
.salesOrderCount(0)
.salesQuantitySum(0)
.gmvAmount(BigDecimal.ZERO)
.gmvOrderCount(0)
.gmvQuantitySum(0)
.refundAmount(BigDecimal.ZERO)
.productCost(BigDecimal.ZERO)
.freightCost(BigDecimal.ZERO)
.otherCost(BigDecimal.ZERO)
.build();
}
public BiStatMetricDelta negate() {
return BiStatMetricDelta.builder()
.salesAmount(nz(salesAmount).negate())
.salesOrderCount(-(salesOrderCount == null ? 0 : salesOrderCount))
.salesQuantitySum(-(salesQuantitySum == null ? 0 : salesQuantitySum))
.gmvAmount(nz(gmvAmount).negate())
.gmvOrderCount(-(gmvOrderCount == null ? 0 : gmvOrderCount))
.gmvQuantitySum(-(gmvQuantitySum == null ? 0 : gmvQuantitySum))
.refundAmount(nz(refundAmount).negate())
.productCost(nz(productCost).negate())
.freightCost(nz(freightCost).negate())
.otherCost(nz(otherCost).negate())
.build();
}
public BiStatMetricDelta plus(BiStatMetricDelta o) {
if (o == null) {
return this;
}
return BiStatMetricDelta.builder()
.salesAmount(nz(salesAmount).add(nz(o.salesAmount)))
.salesOrderCount(nzi(salesOrderCount) + nzi(o.salesOrderCount))
.salesQuantitySum(nzi(salesQuantitySum) + nzi(o.salesQuantitySum))
.gmvAmount(nz(gmvAmount).add(nz(o.gmvAmount)))
.gmvOrderCount(nzi(gmvOrderCount) + nzi(o.gmvOrderCount))
.gmvQuantitySum(nzi(gmvQuantitySum) + nzi(o.gmvQuantitySum))
.refundAmount(nz(refundAmount).add(nz(o.refundAmount)))
.productCost(nz(productCost).add(nz(o.productCost)))
.freightCost(nz(freightCost).add(nz(o.freightCost)))
.otherCost(nz(otherCost).add(nz(o.otherCost)))
.build();
}
public BiStatMetricDelta minus(BiStatMetricDelta o) {
return plus(o == null ? null : o.negate());
}
public boolean isAllZero() {
return nz(salesAmount).signum() == 0
&& nzi(salesOrderCount) == 0
&& nzi(salesQuantitySum) == 0
&& nz(gmvAmount).signum() == 0
&& nzi(gmvOrderCount) == 0
&& nzi(gmvQuantitySum) == 0
&& nz(refundAmount).signum() == 0
&& nz(productCost).signum() == 0
&& nz(freightCost).signum() == 0
&& nz(otherCost).signum() == 0;
}
private static BigDecimal nz(BigDecimal v) {
return v != null ? v : BigDecimal.ZERO;
}
private static int nzi(Integer v) {
return v != null ? v : 0;
}
}
@@ -0,0 +1,58 @@
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.OrderMqConstants;
import top.xyquan.ecomdmbbackend.modules.bi.infra.config.BiStatProperties;
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiFullCalcMessage;
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.service.OrderDailyStatComputeService;
import java.time.LocalDate;
import java.time.OffsetDateTime;
@Slf4j
@Component
@RequiredArgsConstructor
public class BiStatFullConsumer {
private final OrderDailyStatComputeService computeService;
private final BiStatProperties biStatProperties;
private final RabbitTemplate rabbitTemplate;
@RabbitListener(queues = OrderMqConstants.QUEUE_BI_STAT_FULL)
public void onMessage(BiFullCalcMessage message) {
if (message == null || message.getCompanyId() == null || message.getShopId() == null
|| message.getStatDate() == null) {
log.warn("BI full 消息非法: {}", message);
return;
}
LocalDate statDate = LocalDate.parse(message.getStatDate());
log.info("收到 BI 全量计算 messageId={} shopId={} statDate={}",
message.getMessageId(), message.getShopId(), statDate);
boolean ok = computeService.tryComputeFull(
message.getCompanyId(),
message.getShopId(),
statDate,
message.getPlatformCode());
if (!ok) {
delayAndRepublish(message);
}
}
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);
}
message.setOccurredAt(OffsetDateTime.now());
log.info("BI full 店锁占用,延后重投 messageId={} shopId={}",
message.getMessageId(), message.getShopId());
rabbitTemplate.convertAndSend(
OrderMqConstants.EXCHANGE, OrderMqConstants.RK_BI_STAT_FULL, message);
}
}
@@ -0,0 +1,118 @@
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.OrderMqConstants;
import top.xyquan.ecomdmbbackend.modules.bi.infra.config.BiStatProperties;
import top.xyquan.ecomdmbbackend.modules.bi.infra.lock.BiStatComputeLock;
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiIncCalcMessage;
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyShopDoc;
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.repository.BiOrderStatDailyRepository;
import java.time.Instant;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.util.Optional;
/**
* BI 增量:与同店全量串行。
* 比较消息中的内部订单更新时间 vs Mongo 文档最新全量快照时间(dbSnapshotTime);
* 在快照内(≤)跳过,在外(>)才 $inc。全量进行中则按会话快照同样规则跳过或延后。
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class BiStatIncConsumer {
private final BiStatComputeLock computeLock;
private final BiOrderStatDailyRepository repository;
private final BiStatProperties biStatProperties;
private final RabbitTemplate rabbitTemplate;
@RabbitListener(queues = OrderMqConstants.QUEUE_BI_STAT_INC)
public void onMessage(BiIncCalcMessage message) {
if (message == null || message.getCompanyId() == null || message.getShopId() == null
|| message.getStatDate() == null || message.getInternalOrderUpdateTime() == null) {
log.warn("BI inc 消息非法: {}", message);
return;
}
LocalDate statDate = LocalDate.parse(message.getStatDate());
Instant internalUpdated = message.getInternalOrderUpdateTime().toInstant();
// 全量进行中:同店串行;内部更新时间已在会话快照内则跳过,否则等全量结束后再比文档
if (computeLock.isLocked(message.getCompanyId(), message.getShopId())) {
Optional<Instant> sessionSnapshot =
computeLock.peekSessionSnapshot(message.getCompanyId(), message.getShopId());
if (sessionSnapshot.isPresent() && !internalUpdated.isAfter(sessionSnapshot.get())) {
log.info("BI inc 跳过(全量会话快照内) messageId={} shopId={} statDate={}",
message.getMessageId(), message.getShopId(), statDate);
return;
}
delayAndRepublish(message);
return;
}
Optional<BiOrderStatDailyShopDoc> shopDoc =
repository.findShop(message.getCompanyId(), message.getShopId(), statDate);
if (withinFullSnapshot(shopDoc, internalUpdated)) {
log.info("BI inc 跳过(文档全量快照内) messageId={} shopId={} statDate={}",
message.getMessageId(), message.getShopId(), statDate);
return;
}
Optional<BiStatComputeLock.Session> session =
computeLock.tryLock(message.getCompanyId(), message.getShopId(), null);
if (session.isEmpty()) {
delayAndRepublish(message);
return;
}
try {
shopDoc = repository.findShop(message.getCompanyId(), message.getShopId(), statDate);
if (withinFullSnapshot(shopDoc, internalUpdated)) {
log.info("BI inc 跳过(抢锁后文档全量快照内) shopId={} statDate={}",
message.getShopId(), statDate);
return;
}
repository.applyIncDeltas(
message.getCompanyId(),
message.getShopId(),
message.getPlatformCode(),
statDate,
message.getShopDelta(),
message.getProductDeltas(),
message.getSpecDeltas());
log.info("BI inc delta 已累加 shopId={} statDate={} orderId={}",
message.getShopId(), statDate, message.getOrderId());
} finally {
computeLock.unlock(session.get());
}
}
/** 内部订单更新时间 ≤ 文档最新全量快照时间 → 已包含在全量结果中 */
private static boolean withinFullSnapshot(Optional<BiOrderStatDailyShopDoc> shopDoc,
Instant internalUpdated) {
return shopDoc.isPresent()
&& shopDoc.get().getDbSnapshotTime() != null
&& !internalUpdated.isAfter(shopDoc.get().getDbSnapshotTime());
}
private void delayAndRepublish(BiIncCalcMessage message) {
int retry = message.getRetryCount() == null ? 0 : message.getRetryCount();
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);
}
}
@@ -0,0 +1,47 @@
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.CompoundIndexes;
import org.springframework.data.mongodb.core.mapping.Document;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
@Data
@Document(collection = "bi_order_stat_daily_product")
@CompoundIndexes({
@CompoundIndex(
name = "uk_company_shop_prod_cat_date",
def = "{'companyId':1,'shopId':1,'productId':1,'categoryId':1,'statDate':1}",
unique = true)
})
public class BiOrderStatDailyProductDoc {
@Id
private String id;
private Long companyId;
private Long shopId;
private Long productId;
private Long categoryId;
private LocalDate statDate;
private BigDecimal salesAmount = BigDecimal.ZERO;
private Integer salesOrderCount = 0;
private Integer salesQuantitySum = 0;
private BigDecimal gmvAmount = BigDecimal.ZERO;
private Integer gmvOrderCount = 0;
private Integer gmvQuantitySum = 0;
private BigDecimal refundAmount = BigDecimal.ZERO;
private BigDecimal productCost = BigDecimal.ZERO;
private BigDecimal freightCost = BigDecimal.ZERO;
private BigDecimal otherCost = BigDecimal.ZERO;
private Integer statVersion = 0;
private Instant dbSnapshotTime;
private Instant computedAt;
private String computeMode;
}
@@ -0,0 +1,45 @@
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.CompoundIndexes;
import org.springframework.data.mongodb.core.mapping.Document;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
@Data
@Document(collection = "bi_order_stat_daily_shop")
@CompoundIndexes({
@CompoundIndex(name = "uk_company_shop_date", def = "{'companyId':1,'shopId':1,'statDate':1}", unique = true),
@CompoundIndex(name = "idx_company_date", def = "{'companyId':1,'statDate':1}")
})
public class BiOrderStatDailyShopDoc {
@Id
private String id;
private Long companyId;
private Long shopId;
private String platformCode;
private LocalDate statDate;
private BigDecimal salesAmount = BigDecimal.ZERO;
private Integer salesOrderCount = 0;
private Integer salesQuantitySum = 0;
private BigDecimal gmvAmount = BigDecimal.ZERO;
private Integer gmvOrderCount = 0;
private Integer gmvQuantitySum = 0;
private BigDecimal refundAmount = BigDecimal.ZERO;
private BigDecimal productCost = BigDecimal.ZERO;
private BigDecimal freightCost = BigDecimal.ZERO;
private BigDecimal otherCost = BigDecimal.ZERO;
private Integer statVersion = 0;
/** 最新一次全量计算开启 MySQL 事务快照的时间;增量用内部订单更新时间与之比较 */
private Instant dbSnapshotTime;
private Instant computedAt;
private String computeMode;
}
@@ -0,0 +1,47 @@
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.CompoundIndexes;
import org.springframework.data.mongodb.core.mapping.Document;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
@Data
@Document(collection = "bi_order_stat_daily_spec")
@CompoundIndexes({
@CompoundIndex(
name = "uk_company_shop_spec_date",
def = "{'companyId':1,'shopId':1,'productSpecId':1,'statDate':1}",
unique = true)
})
public class BiOrderStatDailySpecDoc {
@Id
private String id;
private Long companyId;
private Long shopId;
private Long productId;
private Long productSpecId;
private LocalDate statDate;
private BigDecimal salesAmount = BigDecimal.ZERO;
private Integer salesOrderCount = 0;
private Integer salesQuantitySum = 0;
private BigDecimal gmvAmount = BigDecimal.ZERO;
private Integer gmvOrderCount = 0;
private Integer gmvQuantitySum = 0;
private BigDecimal refundAmount = BigDecimal.ZERO;
private BigDecimal productCost = BigDecimal.ZERO;
private BigDecimal freightCost = BigDecimal.ZERO;
private BigDecimal otherCost = BigDecimal.ZERO;
private Integer statVersion = 0;
private Instant dbSnapshotTime;
private Instant computedAt;
private String computeMode;
}
@@ -0,0 +1,247 @@
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.repository;
import lombok.RequiredArgsConstructor;
import org.bson.types.Decimal128;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiProductStatDelta;
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiSpecStatDelta;
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiStatMetricDelta;
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyProductDoc;
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyShopDoc;
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailySpecDoc;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
@Repository
@RequiredArgsConstructor
public class BiOrderStatDailyRepository {
private final MongoTemplate mongoTemplate;
public Optional<BiOrderStatDailyShopDoc> findShop(Long companyId, Long shopId, LocalDate statDate) {
Query q = Query.query(Criteria.where("companyId").is(companyId)
.and("shopId").is(shopId)
.and("statDate").is(statDate));
return Optional.ofNullable(mongoTemplate.findOne(q, BiOrderStatDailyShopDoc.class));
}
public void replaceShopDay(BiOrderStatDailyShopDoc shopDoc,
List<BiOrderStatDailyProductDoc> products,
List<BiOrderStatDailySpecDoc> specs) {
Long companyId = shopDoc.getCompanyId();
Long shopId = shopDoc.getShopId();
LocalDate statDate = shopDoc.getStatDate();
Query dayQ = Query.query(Criteria.where("companyId").is(companyId)
.and("shopId").is(shopId)
.and("statDate").is(statDate));
findShop(companyId, shopId, statDate).ifPresentOrElse(existing -> {
shopDoc.setId(existing.getId());
if (!"FULL".equals(shopDoc.getComputeMode()) && existing.getDbSnapshotTime() != null) {
shopDoc.setDbSnapshotTime(existing.getDbSnapshotTime());
}
mongoTemplate.save(shopDoc);
}, () -> mongoTemplate.insert(shopDoc));
mongoTemplate.remove(dayQ, BiOrderStatDailyProductDoc.class);
mongoTemplate.remove(dayQ, BiOrderStatDailySpecDoc.class);
if (products != null && !products.isEmpty()) {
mongoTemplate.insertAll(products);
}
if (specs != null && !specs.isEmpty()) {
mongoTemplate.insertAll(specs);
}
}
/** 将转换侧算出的增量累加到日文档(无文档则按 delta 新建)。 */
public void applyIncDeltas(Long companyId, Long shopId, String platformCode, LocalDate statDate,
BiStatMetricDelta shopDelta,
List<BiProductStatDelta> productDeltas,
List<BiSpecStatDelta> specDeltas) {
Instant now = Instant.now();
Optional<BiOrderStatDailyShopDoc> existing = findShop(companyId, shopId, statDate);
if (existing.isEmpty()) {
BiOrderStatDailyShopDoc shop = new BiOrderStatDailyShopDoc();
shop.setCompanyId(companyId);
shop.setShopId(shopId);
shop.setPlatformCode(platformCode);
shop.setStatDate(statDate);
applyMetricToShop(shop, shopDelta);
shop.setComputeMode("INC");
shop.setComputedAt(now);
mongoTemplate.insert(shop);
} else {
Query q = Query.query(Criteria.where("companyId").is(companyId)
.and("shopId").is(shopId)
.and("statDate").is(statDate));
Update u = metricIncUpdate(shopDelta);
u.set("computedAt", now).set("computeMode", "INC");
if (platformCode != null) {
u.set("platformCode", platformCode);
}
mongoTemplate.updateFirst(q, u, BiOrderStatDailyShopDoc.class);
}
if (productDeltas != null) {
for (BiProductStatDelta pd : productDeltas) {
if (pd.getMetrics() == null || pd.getMetrics().isAllZero()) {
continue;
}
long productId = pd.getProductId() != null ? pd.getProductId() : 0L;
long categoryId = pd.getCategoryId() != null ? pd.getCategoryId() : 0L;
Query pq = Query.query(Criteria.where("companyId").is(companyId)
.and("shopId").is(shopId)
.and("productId").is(productId)
.and("categoryId").is(categoryId)
.and("statDate").is(statDate));
BiOrderStatDailyProductDoc found = mongoTemplate.findOne(pq, BiOrderStatDailyProductDoc.class);
if (found == null) {
BiOrderStatDailyProductDoc doc = new BiOrderStatDailyProductDoc();
doc.setCompanyId(companyId);
doc.setShopId(shopId);
doc.setProductId(productId);
doc.setCategoryId(categoryId);
doc.setStatDate(statDate);
applyMetricToProduct(doc, pd.getMetrics());
doc.setComputeMode("INC");
doc.setComputedAt(now);
mongoTemplate.insert(doc);
} else {
Update u = metricIncUpdate(pd.getMetrics());
u.set("computedAt", now).set("computeMode", "INC");
mongoTemplate.updateFirst(pq, u, BiOrderStatDailyProductDoc.class);
}
}
}
if (specDeltas != null) {
for (BiSpecStatDelta sd : specDeltas) {
if (sd.getMetrics() == null || sd.getMetrics().isAllZero()) {
continue;
}
long productId = sd.getProductId() != null ? sd.getProductId() : 0L;
long specId = sd.getProductSpecId() != null ? sd.getProductSpecId() : 0L;
Query sq = Query.query(Criteria.where("companyId").is(companyId)
.and("shopId").is(shopId)
.and("productSpecId").is(specId)
.and("statDate").is(statDate));
BiOrderStatDailySpecDoc found = mongoTemplate.findOne(sq, BiOrderStatDailySpecDoc.class);
if (found == null) {
BiOrderStatDailySpecDoc doc = new BiOrderStatDailySpecDoc();
doc.setCompanyId(companyId);
doc.setShopId(shopId);
doc.setProductId(productId);
doc.setProductSpecId(specId);
doc.setStatDate(statDate);
applyMetricToSpec(doc, sd.getMetrics());
doc.setComputeMode("INC");
doc.setComputedAt(now);
mongoTemplate.insert(doc);
} else {
Update u = metricIncUpdate(sd.getMetrics());
u.set("computedAt", now).set("computeMode", "INC");
mongoTemplate.updateFirst(sq, u, BiOrderStatDailySpecDoc.class);
}
}
}
}
private static Update metricIncUpdate(BiStatMetricDelta d) {
Update u = new Update();
if (d == null) {
return u;
}
inc(u, "salesAmount", d.getSalesAmount());
inc(u, "salesOrderCount", d.getSalesOrderCount());
inc(u, "salesQuantitySum", d.getSalesQuantitySum());
inc(u, "gmvAmount", d.getGmvAmount());
inc(u, "gmvOrderCount", d.getGmvOrderCount());
inc(u, "gmvQuantitySum", d.getGmvQuantitySum());
inc(u, "refundAmount", d.getRefundAmount());
inc(u, "productCost", d.getProductCost());
inc(u, "freightCost", d.getFreightCost());
inc(u, "otherCost", d.getOtherCost());
return u;
}
private static void inc(Update u, String field, Number v) {
if (v == null) {
return;
}
if (v instanceof BigDecimal bd) {
if (bd.signum() == 0) {
return;
}
u.inc(field, new Decimal128(bd));
return;
}
if (v instanceof Integer i && i == 0) {
return;
}
u.inc(field, v);
}
private static void applyMetricToShop(BiOrderStatDailyShopDoc doc, BiStatMetricDelta d) {
if (d == null) {
return;
}
doc.setSalesAmount(nz(d.getSalesAmount()));
doc.setSalesOrderCount(nzi(d.getSalesOrderCount()));
doc.setSalesQuantitySum(nzi(d.getSalesQuantitySum()));
doc.setGmvAmount(nz(d.getGmvAmount()));
doc.setGmvOrderCount(nzi(d.getGmvOrderCount()));
doc.setGmvQuantitySum(nzi(d.getGmvQuantitySum()));
doc.setRefundAmount(nz(d.getRefundAmount()));
doc.setProductCost(nz(d.getProductCost()));
doc.setFreightCost(nz(d.getFreightCost()));
doc.setOtherCost(nz(d.getOtherCost()));
}
private static void applyMetricToProduct(BiOrderStatDailyProductDoc doc, BiStatMetricDelta d) {
if (d == null) {
return;
}
doc.setSalesAmount(nz(d.getSalesAmount()));
doc.setSalesOrderCount(nzi(d.getSalesOrderCount()));
doc.setSalesQuantitySum(nzi(d.getSalesQuantitySum()));
doc.setGmvAmount(nz(d.getGmvAmount()));
doc.setGmvOrderCount(nzi(d.getGmvOrderCount()));
doc.setGmvQuantitySum(nzi(d.getGmvQuantitySum()));
doc.setRefundAmount(nz(d.getRefundAmount()));
doc.setProductCost(nz(d.getProductCost()));
doc.setFreightCost(nz(d.getFreightCost()));
doc.setOtherCost(nz(d.getOtherCost()));
}
private static void applyMetricToSpec(BiOrderStatDailySpecDoc doc, BiStatMetricDelta d) {
if (d == null) {
return;
}
doc.setSalesAmount(nz(d.getSalesAmount()));
doc.setSalesOrderCount(nzi(d.getSalesOrderCount()));
doc.setSalesQuantitySum(nzi(d.getSalesQuantitySum()));
doc.setGmvAmount(nz(d.getGmvAmount()));
doc.setGmvOrderCount(nzi(d.getGmvOrderCount()));
doc.setGmvQuantitySum(nzi(d.getGmvQuantitySum()));
doc.setRefundAmount(nz(d.getRefundAmount()));
doc.setProductCost(nz(d.getProductCost()));
doc.setFreightCost(nz(d.getFreightCost()));
doc.setOtherCost(nz(d.getOtherCost()));
}
private static BigDecimal nz(BigDecimal v) {
return v != null ? v : BigDecimal.ZERO;
}
private static int nzi(Integer v) {
return v != null ? v : 0;
}
}
@@ -0,0 +1,381 @@
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import top.xyquan.ecomdmbbackend.modules.bi.infra.lock.BiStatComputeLock;
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyProductDoc;
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyShopDoc;
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailySpecDoc;
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.repository.BiOrderStatDailyRepository;
import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderItemMapper;
import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderMapper;
import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderItemPO;
import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderPO;
import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatResolver;
import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatSets;
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductMapper;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderDailyStatComputeService {
private final OrderMapper orderMapper;
private final OrderItemMapper orderItemMapper;
private final ProductMapper productMapper;
private final OrderStatusStatResolver orderStatusStatResolver;
private final BiOrderStatDailyRepository repository;
private final BiStatComputeLock computeLock;
private final PlatformTransactionManager transactionManager;
/**
* 全量:同店串行锁 + MySQL 事务一致读重算;
* 将事务快照开启时间写入 Mongo 文档 dbSnapshotTime(最新全量计算快照时间)。
*/
public boolean tryComputeFull(Long companyId, Long shopId, LocalDate statDate, String platformCode) {
// 快照时刻在抢锁时登记,供进行中的增量与会话快照比较
Instant snapshotTime = Instant.now();
Optional<BiStatComputeLock.Session> sessionOpt =
computeLock.tryLock(companyId, shopId, snapshotTime);
if (sessionOpt.isEmpty()) {
return false;
}
BiStatComputeLock.Session session = sessionOpt.get();
try {
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
TransactionTemplate tt = new TransactionTemplate(transactionManager, def);
tt.executeWithoutResult(status -> {
DayAgg agg = aggregateDay(companyId, shopId, statDate, platformCode);
persist(agg, snapshotTime, "FULL");
});
return true;
} finally {
computeLock.unlock(session);
}
}
/**
* @deprecated 增量已改为消费端 $inc delta,不再按日重算。
*/
public boolean tryComputeInc(Long companyId, Long shopId, LocalDate statDate, String platformCode) {
Optional<BiStatComputeLock.Session> sessionOpt =
computeLock.tryLock(companyId, shopId, null);
if (sessionOpt.isEmpty()) {
return false;
}
BiStatComputeLock.Session session = sessionOpt.get();
try {
DayAgg agg = aggregateDay(companyId, shopId, statDate, platformCode);
persist(agg, null, "INC");
return true;
} finally {
computeLock.unlock(session);
}
}
/** @deprecated 使用 {@link #tryComputeFull} */
public void computeFull(Long companyId, Long shopId, LocalDate statDate, String platformCode) {
if (!tryComputeFull(companyId, shopId, statDate, platformCode)) {
throw new IllegalStateException("BI 店铺计算锁占用中: " + companyId + "/" + shopId);
}
}
/** @deprecated 使用 {@link #tryComputeInc} */
public void computeInc(Long companyId, Long shopId, LocalDate statDate, String platformCode) {
if (!tryComputeInc(companyId, shopId, statDate, platformCode)) {
throw new IllegalStateException("BI 店铺计算锁占用中: " + companyId + "/" + shopId);
}
}
private DayAgg aggregateDay(Long companyId, Long shopId, LocalDate statDate, String platformCode) {
LocalDateTime start = statDate.atStartOfDay();
LocalDateTime end = statDate.plusDays(1).atStartOfDay();
List<OrderPO> orders = orderMapper.selectList(new LambdaQueryWrapper<OrderPO>()
.eq(OrderPO::getCompanyId, companyId)
.eq(OrderPO::getShopId, shopId)
.ge(OrderPO::getOrderTime, start)
.lt(OrderPO::getOrderTime, end));
OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId);
Map<Long, List<OrderItemPO>> itemsByOrder = new HashMap<>();
if (!orders.isEmpty()) {
List<Long> orderIds = orders.stream().map(OrderPO::getId).toList();
List<OrderItemPO> items = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemPO>()
.in(OrderItemPO::getOrderId, orderIds));
for (OrderItemPO item : items) {
itemsByOrder.computeIfAbsent(item.getOrderId(), k -> new ArrayList<>()).add(item);
}
}
Set<Long> productIds = itemsByOrder.values().stream()
.flatMap(List::stream)
.map(OrderItemPO::getProductId)
.filter(id -> id != null && id > 0)
.collect(Collectors.toSet());
Map<Long, Long> categoryByProduct = new HashMap<>();
if (!productIds.isEmpty()) {
List<ProductPO> products = productMapper.selectBatchIds(productIds);
for (ProductPO p : products) {
categoryByProduct.put(p.getId(), p.getCategoryId() != null ? p.getCategoryId() : 0L);
}
}
Metric shop = new Metric();
Map<String, Metric> productMap = new HashMap<>();
Map<String, Metric> specMap = new HashMap<>();
Map<String, DimKey> productKeys = new HashMap<>();
Map<String, DimKey> specKeys = new HashMap<>();
for (OrderPO order : orders) {
List<OrderItemPO> items = itemsByOrder.getOrDefault(order.getId(), List.of());
int qtySum = OrderStatusStatSets.totalQuantity(items);
if (qtySum <= 0 && items.isEmpty()) {
qtySum = 1;
}
BigDecimal pay = nz(order.getPayAmount());
boolean sales = stat.includesSales(order.getStatus());
boolean refund = stat.includesRefund(order.getStatus());
shop.gmvAmount = shop.gmvAmount.add(pay);
shop.gmvOrderCount++;
shop.gmvQuantitySum += qtySum;
if (sales) {
shop.salesAmount = shop.salesAmount.add(pay);
shop.salesOrderCount++;
shop.salesQuantitySum += qtySum;
}
if (refund) {
shop.refundAmount = shop.refundAmount.add(pay);
}
Set<String> countedProductSales = new HashSet<>();
Set<String> countedProductGmv = new HashSet<>();
Set<String> countedSpecSales = new HashSet<>();
Set<String> countedSpecGmv = new HashSet<>();
if (items.isEmpty()) {
continue;
}
for (OrderItemPO item : items) {
long productId = item.getProductId() != null ? item.getProductId() : 0L;
long categoryId = categoryByProduct.getOrDefault(productId, 0L);
long specId = item.getProductSkuId() != null ? item.getProductSkuId() : 0L;
int qty = OrderStatusStatSets.quantity(item);
BigDecimal linePay = allocateLine(pay, item, items);
String pk = companyId + ":" + shopId + ":" + productId + ":" + categoryId;
Metric pm = productMap.computeIfAbsent(pk, k -> new Metric());
productKeys.putIfAbsent(pk, new DimKey(productId, categoryId, 0L));
pm.gmvAmount = pm.gmvAmount.add(linePay);
pm.gmvQuantitySum += qty;
if (countedProductGmv.add(pk)) {
pm.gmvOrderCount++;
}
if (sales) {
pm.salesAmount = pm.salesAmount.add(linePay);
pm.salesQuantitySum += qty;
if (countedProductSales.add(pk)) {
pm.salesOrderCount++;
}
}
if (refund) {
pm.refundAmount = pm.refundAmount.add(linePay);
}
pm.productCost = pm.productCost.add(stat.productCostForStats(order, item));
pm.freightCost = pm.freightCost.add(stat.freightCostForStats(order, item));
pm.otherCost = pm.otherCost.add(stat.otherCostForStats(order, item));
String sk = companyId + ":" + shopId + ":" + specId;
Metric sm = specMap.computeIfAbsent(sk, k -> new Metric());
specKeys.putIfAbsent(sk, new DimKey(productId, 0L, specId));
sm.gmvAmount = sm.gmvAmount.add(linePay);
sm.gmvQuantitySum += qty;
if (countedSpecGmv.add(sk)) {
sm.gmvOrderCount++;
}
if (sales) {
sm.salesAmount = sm.salesAmount.add(linePay);
sm.salesQuantitySum += qty;
if (countedSpecSales.add(sk)) {
sm.salesOrderCount++;
}
}
if (refund) {
sm.refundAmount = sm.refundAmount.add(linePay);
}
sm.productCost = sm.productCost.add(stat.productCostForStats(order, item));
sm.freightCost = sm.freightCost.add(stat.freightCostForStats(order, item));
sm.otherCost = sm.otherCost.add(stat.otherCostForStats(order, item));
shop.productCost = shop.productCost.add(stat.productCostForStats(order, item));
shop.freightCost = shop.freightCost.add(stat.freightCostForStats(order, item));
shop.otherCost = shop.otherCost.add(stat.otherCostForStats(order, item));
}
}
String platform = platformCode;
if (platform == null && !orders.isEmpty()) {
platform = orders.get(0).getPlatformCode();
}
return new DayAgg(companyId, shopId, statDate, platform, shop, productMap, productKeys, specMap, specKeys);
}
private void persist(DayAgg agg, Instant snapshotTime, String mode) {
Instant now = Instant.now();
BiOrderStatDailyShopDoc shopDoc = new BiOrderStatDailyShopDoc();
shopDoc.setCompanyId(agg.companyId());
shopDoc.setShopId(agg.shopId());
shopDoc.setPlatformCode(agg.platformCode());
shopDoc.setStatDate(agg.statDate());
applyMetric(shopDoc, agg.shop());
shopDoc.setDbSnapshotTime(snapshotTime);
shopDoc.setComputedAt(now);
shopDoc.setComputeMode(mode);
List<BiOrderStatDailyProductDoc> products = new ArrayList<>();
for (Map.Entry<String, Metric> e : agg.productMap().entrySet()) {
DimKey key = agg.productKeys().get(e.getKey());
BiOrderStatDailyProductDoc doc = new BiOrderStatDailyProductDoc();
doc.setCompanyId(agg.companyId());
doc.setShopId(agg.shopId());
doc.setProductId(key.productId());
doc.setCategoryId(key.categoryId());
doc.setStatDate(agg.statDate());
applyMetric(doc, e.getValue());
doc.setDbSnapshotTime(snapshotTime);
doc.setComputedAt(now);
doc.setComputeMode(mode);
products.add(doc);
}
List<BiOrderStatDailySpecDoc> specs = new ArrayList<>();
for (Map.Entry<String, Metric> e : agg.specMap().entrySet()) {
DimKey key = agg.specKeys().get(e.getKey());
BiOrderStatDailySpecDoc doc = new BiOrderStatDailySpecDoc();
doc.setCompanyId(agg.companyId());
doc.setShopId(agg.shopId());
doc.setProductId(key.productId());
doc.setProductSpecId(key.specId());
doc.setStatDate(agg.statDate());
applyMetric(doc, e.getValue());
doc.setDbSnapshotTime(snapshotTime);
doc.setComputedAt(now);
doc.setComputeMode(mode);
specs.add(doc);
}
repository.replaceShopDay(shopDoc, products, specs);
log.info("BI 日汇聚完成 mode={} companyId={} shopId={} statDate={} ordersShopGmv={}",
mode, agg.companyId(), agg.shopId(), agg.statDate(), agg.shop().gmvOrderCount);
}
private static void applyMetric(BiOrderStatDailyShopDoc doc, Metric m) {
doc.setSalesAmount(m.salesAmount);
doc.setSalesOrderCount(m.salesOrderCount);
doc.setSalesQuantitySum(m.salesQuantitySum);
doc.setGmvAmount(m.gmvAmount);
doc.setGmvOrderCount(m.gmvOrderCount);
doc.setGmvQuantitySum(m.gmvQuantitySum);
doc.setRefundAmount(m.refundAmount);
doc.setProductCost(m.productCost);
doc.setFreightCost(m.freightCost);
doc.setOtherCost(m.otherCost);
}
private static void applyMetric(BiOrderStatDailyProductDoc doc, Metric m) {
doc.setSalesAmount(m.salesAmount);
doc.setSalesOrderCount(m.salesOrderCount);
doc.setSalesQuantitySum(m.salesQuantitySum);
doc.setGmvAmount(m.gmvAmount);
doc.setGmvOrderCount(m.gmvOrderCount);
doc.setGmvQuantitySum(m.gmvQuantitySum);
doc.setRefundAmount(m.refundAmount);
doc.setProductCost(m.productCost);
doc.setFreightCost(m.freightCost);
doc.setOtherCost(m.otherCost);
}
private static void applyMetric(BiOrderStatDailySpecDoc doc, Metric m) {
doc.setSalesAmount(m.salesAmount);
doc.setSalesOrderCount(m.salesOrderCount);
doc.setSalesQuantitySum(m.salesQuantitySum);
doc.setGmvAmount(m.gmvAmount);
doc.setGmvOrderCount(m.gmvOrderCount);
doc.setGmvQuantitySum(m.gmvQuantitySum);
doc.setRefundAmount(m.refundAmount);
doc.setProductCost(m.productCost);
doc.setFreightCost(m.freightCost);
doc.setOtherCost(m.otherCost);
}
/** 按行金额占比分摊订单实收;无行金额则均分。 */
private static BigDecimal allocateLine(BigDecimal orderPay, OrderItemPO item, List<OrderItemPO> items) {
BigDecimal totalLine = BigDecimal.ZERO;
for (OrderItemPO i : items) {
totalLine = totalLine.add(nz(i.getLineAmount()));
}
if (totalLine.compareTo(BigDecimal.ZERO) > 0) {
return orderPay.multiply(nz(item.getLineAmount())).divide(totalLine, 4, java.math.RoundingMode.HALF_UP);
}
if (items.isEmpty()) {
return orderPay;
}
return orderPay.divide(BigDecimal.valueOf(items.size()), 4, java.math.RoundingMode.HALF_UP);
}
private static BigDecimal nz(BigDecimal v) {
return v != null ? v : BigDecimal.ZERO;
}
private static final class Metric {
BigDecimal salesAmount = BigDecimal.ZERO;
int salesOrderCount;
int salesQuantitySum;
BigDecimal gmvAmount = BigDecimal.ZERO;
int gmvOrderCount;
int gmvQuantitySum;
BigDecimal refundAmount = BigDecimal.ZERO;
BigDecimal productCost = BigDecimal.ZERO;
BigDecimal freightCost = BigDecimal.ZERO;
BigDecimal otherCost = BigDecimal.ZERO;
}
private record DimKey(long productId, long categoryId, long specId) {
}
private record DayAgg(
Long companyId,
Long shopId,
LocalDate statDate,
String platformCode,
Metric shop,
Map<String, Metric> productMap,
Map<String, DimKey> productKeys,
Map<String, Metric> specMap,
Map<String, DimKey> specKeys) {
}
}
@@ -0,0 +1,206 @@
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.support;
import lombok.Builder;
import lombok.Data;
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiProductStatDelta;
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiSpecStatDelta;
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiStatMetricDelta;
import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderItemPO;
import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderPO;
import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatSets;
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductMapper;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 单笔内部订单对日汇聚的贡献(转换侧算增量 delta 用)。
*/
@Component
public class OrderStatContributionCalculator {
private final ProductMapper productMapper;
public OrderStatContributionCalculator(ProductMapper productMapper) {
this.productMapper = productMapper;
}
public OrderContribution contribute(OrderPO order, List<OrderItemPO> items, OrderStatusStatSets stat) {
if (order == null || order.getOrderTime() == null) {
return null;
}
LocalDate statDate = order.getOrderTime().toLocalDate();
List<OrderItemPO> safeItems = items != null ? items : List.of();
int qtySum = OrderStatusStatSets.totalQuantity(safeItems);
if (qtySum <= 0 && safeItems.isEmpty()) {
qtySum = 1;
}
BigDecimal pay = nz(order.getPayAmount());
boolean sales = stat.includesSales(order.getStatus());
boolean refund = stat.includesRefund(order.getStatus());
BiStatMetricDelta shop = BiStatMetricDelta.zeros();
shop.setGmvAmount(pay);
shop.setGmvOrderCount(1);
shop.setGmvQuantitySum(qtySum);
if (sales) {
shop.setSalesAmount(pay);
shop.setSalesOrderCount(1);
shop.setSalesQuantitySum(qtySum);
}
if (refund) {
shop.setRefundAmount(pay);
}
Map<String, BiStatMetricDelta> productMap = new HashMap<>();
Map<String, long[]> productKeys = new HashMap<>();
Map<String, BiStatMetricDelta> specMap = new HashMap<>();
Map<String, long[]> specKeys = new HashMap<>();
Map<Long, Long> categoryByProduct = loadCategories(safeItems);
for (OrderItemPO item : safeItems) {
long productId = item.getProductId() != null ? item.getProductId() : 0L;
long categoryId = categoryByProduct.getOrDefault(productId, 0L);
long specId = item.getProductSkuId() != null ? item.getProductSkuId() : 0L;
int qty = OrderStatusStatSets.quantity(item);
BigDecimal linePay = allocateLine(pay, item, safeItems);
String pk = productId + ":" + categoryId;
BiStatMetricDelta pm = productMap.computeIfAbsent(pk, k -> BiStatMetricDelta.zeros());
productKeys.putIfAbsent(pk, new long[]{productId, categoryId});
pm.setGmvAmount(nz(pm.getGmvAmount()).add(linePay));
pm.setGmvQuantitySum(nzi(pm.getGmvQuantitySum()) + qty);
if (sales) {
pm.setSalesAmount(nz(pm.getSalesAmount()).add(linePay));
pm.setSalesQuantitySum(nzi(pm.getSalesQuantitySum()) + qty);
}
if (refund) {
pm.setRefundAmount(nz(pm.getRefundAmount()).add(linePay));
}
BigDecimal pc = stat.productCostForStats(order, item);
BigDecimal fc = stat.freightCostForStats(order, item);
BigDecimal oc = stat.otherCostForStats(order, item);
pm.setProductCost(nz(pm.getProductCost()).add(pc));
pm.setFreightCost(nz(pm.getFreightCost()).add(fc));
pm.setOtherCost(nz(pm.getOtherCost()).add(oc));
String sk = String.valueOf(specId);
BiStatMetricDelta sm = specMap.computeIfAbsent(sk, k -> BiStatMetricDelta.zeros());
specKeys.putIfAbsent(sk, new long[]{productId, specId});
sm.setGmvAmount(nz(sm.getGmvAmount()).add(linePay));
sm.setGmvQuantitySum(nzi(sm.getGmvQuantitySum()) + qty);
if (sales) {
sm.setSalesAmount(nz(sm.getSalesAmount()).add(linePay));
sm.setSalesQuantitySum(nzi(sm.getSalesQuantitySum()) + qty);
}
if (refund) {
sm.setRefundAmount(nz(sm.getRefundAmount()).add(linePay));
}
sm.setProductCost(nz(sm.getProductCost()).add(pc));
sm.setFreightCost(nz(sm.getFreightCost()).add(fc));
sm.setOtherCost(nz(sm.getOtherCost()).add(oc));
shop.setProductCost(nz(shop.getProductCost()).add(pc));
shop.setFreightCost(nz(shop.getFreightCost()).add(fc));
shop.setOtherCost(nz(shop.getOtherCost()).add(oc));
}
// 订单计数:商品/规格维度每单计 1 次(有明细时)
if (!safeItems.isEmpty()) {
for (BiStatMetricDelta pm : productMap.values()) {
pm.setGmvOrderCount(1);
if (sales) {
pm.setSalesOrderCount(1);
}
}
for (BiStatMetricDelta sm : specMap.values()) {
sm.setGmvOrderCount(1);
if (sales) {
sm.setSalesOrderCount(1);
}
}
}
List<BiProductStatDelta> products = new ArrayList<>();
for (Map.Entry<String, BiStatMetricDelta> e : productMap.entrySet()) {
long[] k = productKeys.get(e.getKey());
products.add(BiProductStatDelta.builder()
.productId(k[0])
.categoryId(k[1])
.metrics(e.getValue())
.build());
}
List<BiSpecStatDelta> specs = new ArrayList<>();
for (Map.Entry<String, BiStatMetricDelta> e : specMap.entrySet()) {
long[] k = specKeys.get(e.getKey());
specs.add(BiSpecStatDelta.builder()
.productId(k[0])
.productSpecId(k[1])
.metrics(e.getValue())
.build());
}
return OrderContribution.builder()
.statDate(statDate)
.shop(shop)
.products(products)
.specs(specs)
.build();
}
private Map<Long, Long> loadCategories(List<OrderItemPO> items) {
Map<Long, Long> map = new HashMap<>();
List<Long> ids = items.stream()
.map(OrderItemPO::getProductId)
.filter(id -> id != null && id > 0)
.distinct()
.toList();
if (ids.isEmpty()) {
return map;
}
for (ProductPO p : productMapper.selectBatchIds(ids)) {
map.put(p.getId(), p.getCategoryId() != null ? p.getCategoryId() : 0L);
}
return map;
}
private static BigDecimal allocateLine(BigDecimal orderPay, OrderItemPO item, List<OrderItemPO> items) {
BigDecimal totalLine = BigDecimal.ZERO;
for (OrderItemPO i : items) {
totalLine = totalLine.add(nz(i.getLineAmount()));
}
if (totalLine.compareTo(BigDecimal.ZERO) > 0) {
return orderPay.multiply(nz(item.getLineAmount())).divide(totalLine, 4, RoundingMode.HALF_UP);
}
if (items.isEmpty()) {
return orderPay;
}
return orderPay.divide(BigDecimal.valueOf(items.size()), 4, RoundingMode.HALF_UP);
}
private static BigDecimal nz(BigDecimal v) {
return v != null ? v : BigDecimal.ZERO;
}
private static int nzi(Integer v) {
return v != null ? v : 0;
}
@Data
@Builder
public static class OrderContribution {
private LocalDate statDate;
private BiStatMetricDelta shop;
private List<BiProductStatDelta> products;
private List<BiSpecStatDelta> specs;
}
}
@@ -0,0 +1,70 @@
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.OrderConvertMessage;
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
import top.xyquan.ecomdmbbackend.modules.bi.infra.config.BiStatProperties;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.lock.OrderConvertShopLock;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.service.PddOrderConvertService;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.util.Optional;
@Slf4j
@Component
@RequiredArgsConstructor
public class PddOrderConvertConsumer {
private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
private final PddOrderConvertService convertService;
private final OrderConvertShopLock convertShopLock;
private final BiStatProperties biStatProperties;
private final RabbitTemplate rabbitTemplate;
@RabbitListener(queues = OrderMqConstants.QUEUE_ORDER_CONVERT_PDD)
public void onMessage(OrderConvertMessage message) {
if (message == null || message.getCompanyId() == null || message.getShopId() == null
|| message.getMode() == null) {
log.warn("转换消息非法: {}", message);
return;
}
log.info("收到转换消息 mode={} shopId={} statDate={} orders={} messageId={}",
message.getMode(), message.getShopId(), message.getStatDate(),
message.getOrders() != null ? message.getOrders().size() : 0, message.getMessageId());
Optional<OrderConvertShopLock.Session> sessionOpt = convertShopLock.tryLock(message.getShopId());
if (sessionOpt.isEmpty()) {
delayAndRepublish(message);
return;
}
OrderConvertShopLock.Session session = sessionOpt.get();
try {
convertService.convert(message);
} finally {
convertShopLock.unlock(session);
}
}
private void delayAndRepublish(OrderConvertMessage message) {
int retry = message.getRetryCount() == null ? 0 : message.getRetryCount();
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);
}
}
@@ -0,0 +1,50 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.lock;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.Optional;
import java.util.UUID;
/**
* 转换侧同店串行锁(全量日 / 增量共用一把锁)。
*/
@Component
@RequiredArgsConstructor
public class OrderConvertShopLock {
private static final String LOCK_PREFIX = "order:convert:lock:";
private static final long LOCK_TTL_SECONDS = 600;
private final StringRedisTemplate stringRedisTemplate;
public Optional<Session> tryLock(Long shopId) {
String key = LOCK_PREFIX + shopId;
String token = UUID.randomUUID().toString();
Boolean ok = stringRedisTemplate.opsForValue()
.setIfAbsent(key, token, Duration.ofSeconds(LOCK_TTL_SECONDS));
if (!Boolean.TRUE.equals(ok)) {
return Optional.empty();
}
return Optional.of(new Session(key, token));
}
public boolean isLocked(Long shopId) {
return Boolean.TRUE.equals(stringRedisTemplate.hasKey(LOCK_PREFIX + shopId));
}
public void unlock(Session session) {
if (session == null) {
return;
}
String current = stringRedisTemplate.opsForValue().get(session.key());
if (session.token().equals(current)) {
stringRedisTemplate.delete(session.key());
}
}
public record Session(String key, String token) {
}
}
@@ -0,0 +1,72 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.messaging;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiFullCalcMessage;
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiIncCalcMessage;
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiProductStatDelta;
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiSpecStatDelta;
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiStatMetricDelta;
import top.xyquan.ecomdmbbackend.modules.ec.platform.model.enums.PlatformCode;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.UUID;
@Slf4j
@Component
@RequiredArgsConstructor
public class PddBiCalcPublisher {
private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
private final RabbitTemplate rabbitTemplate;
public void publishFull(Long companyId, Long shopId, LocalDate statDate, String syncBatchId) {
BiFullCalcMessage msg = BiFullCalcMessage.builder()
.messageId(UUID.randomUUID().toString())
.companyId(companyId)
.shopId(shopId)
.platformCode(PlatformCode.PDD.getCode())
.statDate(statDate.toString())
.syncBatchId(syncBatchId)
.occurredAt(OffsetDateTime.now(ZONE))
.build();
rabbitTemplate.convertAndSend(OrderMqConstants.EXCHANGE, OrderMqConstants.RK_BI_STAT_FULL, msg);
log.info("已投递 BI full shopId={} statDate={}", shopId, statDate);
}
public void publishIncDelta(Long companyId, Long shopId, LocalDate statDate,
OffsetDateTime internalOrderUpdateTime, Long orderId, Long channelOrderId,
BiStatMetricDelta shopDelta,
List<BiProductStatDelta> productDeltas,
List<BiSpecStatDelta> specDeltas) {
if (shopDelta != null && shopDelta.isAllZero()
&& (productDeltas == null || productDeltas.isEmpty())
&& (specDeltas == null || specDeltas.isEmpty())) {
return;
}
BiIncCalcMessage msg = BiIncCalcMessage.builder()
.messageId(UUID.randomUUID().toString())
.companyId(companyId)
.shopId(shopId)
.platformCode(PlatformCode.PDD.getCode())
.statDate(statDate.toString())
.internalOrderUpdateTime(internalOrderUpdateTime)
.orderId(orderId)
.channelOrderId(channelOrderId)
.shopDelta(shopDelta)
.productDeltas(productDeltas)
.specDeltas(specDeltas)
.occurredAt(OffsetDateTime.now(ZONE))
.retryCount(0)
.build();
rabbitTemplate.convertAndSend(OrderMqConstants.EXCHANGE, OrderMqConstants.RK_BI_STAT_INC, msg);
log.info("已投递 BI inc delta shopId={} statDate={} orderId={}", shopId, statDate, orderId);
}
}
@@ -0,0 +1,74 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.messaging;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import top.xyquan.ecomdmbbackend.common.mq.ChannelOrderRef;
import top.xyquan.ecomdmbbackend.common.mq.OrderConvertMessage;
import top.xyquan.ecomdmbbackend.common.mq.OrderConvertMode;
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
import top.xyquan.ecomdmbbackend.modules.ec.platform.model.enums.PlatformCode;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.UUID;
@Slf4j
@Component
@RequiredArgsConstructor
public class PddOrderConvertPublisher {
private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
private final RabbitTemplate rabbitTemplate;
public void publishFullDay(Long companyId, Long shopId, LocalDate statDate,
List<ChannelOrderRef> orders, Long taskId) {
OrderConvertMessage msg = OrderConvertMessage.builder()
.messageId(UUID.randomUUID().toString())
.companyId(companyId)
.shopId(shopId)
.platform(PlatformCode.PDD.getCode())
.mode(OrderConvertMode.FULL_DAY)
.statDate(statDate.toString())
.orders(orders != null ? orders : List.of())
.syncBatchId(taskId != null ? taskId + ":" + statDate : "day:" + shopId + ":" + statDate)
.taskId(taskId)
.occurredAt(OffsetDateTime.now(ZONE))
.retryCount(0)
.build();
rabbitTemplate.convertAndSend(
OrderMqConstants.EXCHANGE, OrderMqConstants.RK_ORDER_CONVERT_PDD, msg);
log.info("已投递 FULL_DAY 转换消息 shopId={} statDate={} orders={}",
shopId, statDate, orders != null ? orders.size() : 0);
}
public void publishInc(Long companyId, Long shopId, List<ChannelOrderRef> orders) {
if (orders == null || orders.isEmpty()) {
return;
}
OrderConvertMessage msg = OrderConvertMessage.builder()
.messageId(UUID.randomUUID().toString())
.companyId(companyId)
.shopId(shopId)
.platform(PlatformCode.PDD.getCode())
.mode(OrderConvertMode.INC)
.orders(orders)
.occurredAt(OffsetDateTime.now(ZONE))
.retryCount(0)
.build();
rabbitTemplate.convertAndSend(
OrderMqConstants.EXCHANGE, OrderMqConstants.RK_ORDER_CONVERT_PDD, msg);
log.info("已投递 INC 转换消息 shopId={} orders={}", shopId, orders.size());
}
public static ChannelOrderRef ref(Long channelOrderId) {
if (channelOrderId == null) {
return null;
}
return ChannelOrderRef.builder().channelOrderId(channelOrderId).build();
}
}
@@ -0,0 +1,385 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.common.mq.ChannelOrderRef;
import top.xyquan.ecomdmbbackend.common.mq.OrderConvertMessage;
import top.xyquan.ecomdmbbackend.common.mq.OrderConvertMode;
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiProductStatDelta;
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiSpecStatDelta;
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiStatMetricDelta;
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.support.OrderStatContributionCalculator;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.messaging.PddBiCalcPublisher;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.support.PddOrderStatusMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.mapper.PddOrderItemMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.mapper.PddOrderMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.model.po.PddOrderItemPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.model.po.PddOrderPO;
import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderItemMapper;
import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderMapper;
import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderItemPO;
import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderPO;
import top.xyquan.ecomdmbbackend.modules.ec.order.status.model.enums.OrderStatus;
import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatResolver;
import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatSets;
import top.xyquan.ecomdmbbackend.modules.ec.platform.model.enums.PlatformCode;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductSkuCostPO;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductSkuPO;
import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductSkuCostService;
import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductSkuService;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
@Slf4j
@Service
@RequiredArgsConstructor
public class PddOrderConvertService {
private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
private final PddOrderMapper pddOrderMapper;
private final PddOrderItemMapper pddOrderItemMapper;
private final OrderMapper orderMapper;
private final OrderItemMapper orderItemMapper;
private final ProductSkuService productSkuService;
private final ProductSkuCostService productSkuCostService;
private final PddBiCalcPublisher biCalcPublisher;
private final PlatformTransactionManager transactionManager;
private final OrderStatContributionCalculator contributionCalculator;
private final OrderStatusStatResolver orderStatusStatResolver;
public void convert(OrderConvertMessage message) {
if (message.getMode() == OrderConvertMode.FULL_DAY) {
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
TransactionTemplate tt = new TransactionTemplate(transactionManager, def);
tt.executeWithoutResult(status -> convertFullDay(message));
return;
}
convertInc(message);
}
private void convertFullDay(OrderConvertMessage message) {
List<PddOrderPO> channelOrders = loadChannelOrders(message);
LocalDateTime mappedAt = LocalDateTime.now(ZONE);
for (PddOrderPO channel : channelOrders) {
upsertInternalOrder(channel, mappedAt);
}
LocalDate statDate = message.getStatDate() != null
? LocalDate.parse(message.getStatDate())
: LocalDate.now(ZONE);
biCalcPublisher.publishFull(
message.getCompanyId(), message.getShopId(), statDate, message.getSyncBatchId());
}
/**
* 增量:消息带渠道镜像主键列表;按 id 查渠道单。
* 内部单用 platform_code + source_order_id 定位:无则新增;有则仅当渠道更新时间更新时覆盖,并产出 BI delta。
*/
private void convertInc(OrderConvertMessage message) {
List<ChannelOrderRef> refs = message.getOrders() != null ? message.getOrders() : List.of();
if (refs.isEmpty()) {
return;
}
OrderStatusStatSets stat = orderStatusStatResolver.resolve(message.getCompanyId());
LocalDateTime mappedAt = LocalDateTime.now(ZONE);
for (ChannelOrderRef ref : refs) {
if (ref == null || ref.getChannelOrderId() == null) {
continue;
}
PddOrderPO channel = pddOrderMapper.selectById(ref.getChannelOrderId());
if (channel == null
|| !Objects.equals(channel.getCompanyId(), message.getCompanyId())
|| !Objects.equals(channel.getShopId(), message.getShopId())) {
log.warn("INC 转换跳过:渠道单不存在或不匹配 channelOrderId={}", ref.getChannelOrderId());
continue;
}
OrderPO oldOrder = findInternalBySource(channel);
if (oldOrder != null && !isChannelNewer(channel, oldOrder)) {
log.info("跳过 INC 转换(内部已是最新) channelOrderId={} platformUpdatedAt={}",
channel.getId(), oldOrder.getPlatformUpdatedAt());
continue;
}
List<OrderItemPO> oldItems = List.of();
if (oldOrder != null) {
oldItems = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemPO>()
.eq(OrderItemPO::getOrderId, oldOrder.getId()));
}
OrderStatContributionCalculator.OrderContribution oldContrib =
contributionCalculator.contribute(oldOrder, oldItems, stat);
OrderPO neu = upsertInternalOrder(channel, mappedAt);
// 以库中最新 update_time 为准(转换完成时刻),供 BI 与全量快照比较
OrderPO refreshed = orderMapper.selectById(neu.getId());
LocalDateTime internalUpdated = refreshed != null && refreshed.getUpdateTime() != null
? refreshed.getUpdateTime()
: (neu.getLastMappedTime() != null ? neu.getLastMappedTime() : mappedAt);
List<OrderItemPO> newItems = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemPO>()
.eq(OrderItemPO::getOrderId, neu.getId()));
OrderStatContributionCalculator.OrderContribution newContrib =
contributionCalculator.contribute(refreshed != null ? refreshed : neu, newItems, stat);
OffsetDateTime internalOrderUpdateTime = internalUpdated.atZone(ZONE).toOffsetDateTime();
emitIncDeltas(message, channel.getId(), neu.getId(), internalOrderUpdateTime, oldContrib, newContrib);
}
}
private OrderPO findInternalBySource(PddOrderPO channel) {
return orderMapper.selectOne(new LambdaQueryWrapper<OrderPO>()
.eq(OrderPO::getCompanyId, channel.getCompanyId())
.eq(OrderPO::getPlatformCode, PlatformCode.PDD.getCode())
.eq(OrderPO::getSourceOrderId, channel.getId())
.last("LIMIT 1"));
}
/** 渠道更新时间严格晚于内部已记录的平台更新时间,或内部尚未记录时,视为需要转换。 */
private static boolean isChannelNewer(PddOrderPO channel, OrderPO internal) {
if (internal.getPlatformUpdatedAt() == null) {
return true;
}
if (channel.getPddUpdatedAt() == null) {
return true;
}
return channel.getPddUpdatedAt().isAfter(internal.getPlatformUpdatedAt());
}
private void emitIncDeltas(OrderConvertMessage message, Long channelOrderId, Long orderId,
OffsetDateTime internalOrderUpdateTime,
OrderStatContributionCalculator.OrderContribution oldC,
OrderStatContributionCalculator.OrderContribution newC) {
Map<LocalDate, BiStatMetricDelta> shopByDate = new HashMap<>();
Map<LocalDate, Map<String, BiProductStatDelta>> prodByDate = new HashMap<>();
Map<LocalDate, Map<String, BiSpecStatDelta>> specByDate = new HashMap<>();
applyContrib(shopByDate, prodByDate, specByDate, oldC, true);
applyContrib(shopByDate, prodByDate, specByDate, newC, false);
for (LocalDate date : shopByDate.keySet()) {
BiStatMetricDelta shopDelta = shopByDate.getOrDefault(date, BiStatMetricDelta.zeros());
List<BiProductStatDelta> products = new ArrayList<>(
prodByDate.getOrDefault(date, Map.of()).values());
products.removeIf(p -> p.getMetrics() == null || p.getMetrics().isAllZero());
List<BiSpecStatDelta> specs = new ArrayList<>(
specByDate.getOrDefault(date, Map.of()).values());
specs.removeIf(s -> s.getMetrics() == null || s.getMetrics().isAllZero());
biCalcPublisher.publishIncDelta(
message.getCompanyId(), message.getShopId(), date, internalOrderUpdateTime,
orderId, channelOrderId, shopDelta, products, specs);
}
}
private void applyContrib(Map<LocalDate, BiStatMetricDelta> shopByDate,
Map<LocalDate, Map<String, BiProductStatDelta>> prodByDate,
Map<LocalDate, Map<String, BiSpecStatDelta>> specByDate,
OrderStatContributionCalculator.OrderContribution c,
boolean subtract) {
if (c == null || c.getStatDate() == null) {
return;
}
LocalDate d = c.getStatDate();
BiStatMetricDelta shop = c.getShop() != null ? c.getShop() : BiStatMetricDelta.zeros();
shopByDate.merge(d, subtract ? shop.negate() : shop, BiStatMetricDelta::plus);
Map<String, BiProductStatDelta> pm = prodByDate.computeIfAbsent(d, k -> new HashMap<>());
if (c.getProducts() != null) {
for (BiProductStatDelta p : c.getProducts()) {
String key = p.getProductId() + ":" + p.getCategoryId();
BiStatMetricDelta m = p.getMetrics() != null ? p.getMetrics() : BiStatMetricDelta.zeros();
BiStatMetricDelta delta = subtract ? m.negate() : m;
pm.merge(key, BiProductStatDelta.builder()
.productId(p.getProductId())
.categoryId(p.getCategoryId())
.metrics(delta)
.build(),
(a, b) -> BiProductStatDelta.builder()
.productId(a.getProductId())
.categoryId(a.getCategoryId())
.metrics(a.getMetrics().plus(b.getMetrics()))
.build());
}
}
Map<String, BiSpecStatDelta> sm = specByDate.computeIfAbsent(d, k -> new HashMap<>());
if (c.getSpecs() != null) {
for (BiSpecStatDelta s : c.getSpecs()) {
String key = String.valueOf(s.getProductSpecId());
BiStatMetricDelta m = s.getMetrics() != null ? s.getMetrics() : BiStatMetricDelta.zeros();
BiStatMetricDelta delta = subtract ? m.negate() : m;
sm.merge(key, BiSpecStatDelta.builder()
.productId(s.getProductId())
.productSpecId(s.getProductSpecId())
.metrics(delta)
.build(),
(a, b) -> BiSpecStatDelta.builder()
.productId(a.getProductId())
.productSpecId(a.getProductSpecId())
.metrics(a.getMetrics().plus(b.getMetrics()))
.build());
}
}
}
private List<PddOrderPO> loadChannelOrders(OrderConvertMessage message) {
if (message.getOrders() != null && !message.getOrders().isEmpty()) {
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 (message.getMode() == OrderConvertMode.FULL_DAY && message.getStatDate() != null) {
LocalDate day = LocalDate.parse(message.getStatDate());
LocalDateTime start = day.atStartOfDay();
LocalDateTime end = day.plusDays(1).atStartOfDay();
return pddOrderMapper.selectList(new LambdaQueryWrapper<PddOrderPO>()
.eq(PddOrderPO::getCompanyId, message.getCompanyId())
.eq(PddOrderPO::getShopId, message.getShopId())
.and(w -> w
.nested(n -> n.isNotNull(PddOrderPO::getConfirmTime)
.ge(PddOrderPO::getConfirmTime, start)
.lt(PddOrderPO::getConfirmTime, end))
.or(n -> n.isNull(PddOrderPO::getConfirmTime)
.ge(PddOrderPO::getCreatedTime, start)
.lt(PddOrderPO::getCreatedTime, end))));
}
return List.of();
}
private OrderPO upsertInternalOrder(PddOrderPO channel, LocalDateTime mappedAt) {
OrderPO existing = findInternalBySource(channel);
if (existing == null) {
// 兼容:早期仅按平台单号落库、尚未写 source_order_id 的行
existing = orderMapper.selectOne(new LambdaQueryWrapper<OrderPO>()
.eq(OrderPO::getCompanyId, channel.getCompanyId())
.eq(OrderPO::getShopId, channel.getShopId())
.eq(OrderPO::getPlatformOrderNo, channel.getOrderSn())
.last("LIMIT 1"));
}
OrderPO order = existing != null ? existing : new OrderPO();
order.setCompanyId(channel.getCompanyId());
order.setShopId(channel.getShopId());
order.setPlatformCode(PlatformCode.PDD.getCode());
OrderStatus status = PddOrderStatusMapper.map(channel.getOrderStatus(), channel.getRefundStatus());
order.setStatus(status.getCode());
order.setPlatformOrderNo(channel.getOrderSn());
order.setSource("sync");
order.setSourceOrderId(channel.getId());
order.setPayAmount(channel.getPayAmount());
order.setGoodsAmount(channel.getGoodsAmount());
order.setDiscountAmount(channel.getDiscountAmount());
order.setPostage(channel.getPostage());
order.setPlatformDiscount(channel.getPlatformDiscount());
order.setSellerDiscount(channel.getSellerDiscount());
order.setLogisticsId(channel.getLogisticsId() != null ? String.valueOf(channel.getLogisticsId()) : null);
order.setTrackingNumber(channel.getTrackingNumber());
order.setOrderTime(channel.getCreatedTime());
order.setPayTime(channel.getPayTime());
order.setConfirmTime(channel.getConfirmTime());
order.setShippingTime(channel.getShippingTime());
order.setReceiveTime(channel.getReceiveTime());
order.setProvince(channel.getProvince());
order.setCity(channel.getCity());
order.setTown(channel.getTown());
order.setReceiverNameMask(channel.getReceiverNameMask());
order.setReceiverPhoneMask(channel.getReceiverPhoneMask());
order.setReceiverAddressMask(channel.getReceiverAddressMask());
order.setBuyerMemo(channel.getBuyerMemo());
order.setRemark(channel.getRemark());
order.setConfirm(1);
order.setPlatformUpdatedAt(channel.getPddUpdatedAt());
order.setLastMappedTime(mappedAt);
if (existing == null) {
orderMapper.insert(order);
} else {
orderMapper.updateById(order);
orderItemMapper.delete(new LambdaQueryWrapper<OrderItemPO>()
.eq(OrderItemPO::getOrderId, order.getId()));
}
List<PddOrderItemPO> channelItems = pddOrderItemMapper.selectList(new LambdaQueryWrapper<PddOrderItemPO>()
.eq(PddOrderItemPO::getOrderId, channel.getId()));
int lineNo = 1;
for (PddOrderItemPO ci : channelItems) {
orderItemMapper.insert(mapItem(order, ci, lineNo++));
}
return order;
}
private OrderItemPO mapItem(OrderPO order, PddOrderItemPO ci, int lineNo) {
OrderItemPO item = new OrderItemPO();
item.setOrderId(order.getId());
item.setCompanyId(order.getCompanyId());
item.setShopId(order.getShopId());
item.setLineNo(lineNo);
item.setPlatformGoodsId(ci.getGoodsId());
item.setPlatformSkuId(ci.getSkuId());
item.setLinkProductName(ci.getGoodsName());
item.setLinkSkuName(ci.getGoodsSpec());
item.setGoodsImg(ci.getGoodsImg());
item.setQuantity(ci.getGoodsCount() != null && ci.getGoodsCount() > 0 ? ci.getGoodsCount() : 1);
item.setUnitPrice(ci.getGoodsPrice());
if (ci.getGoodsPrice() != null && item.getQuantity() != null) {
item.setLineAmount(ci.getGoodsPrice().multiply(BigDecimal.valueOf(item.getQuantity())));
}
Long productId = 0L;
Long skuId = 0L;
String skuCode = null;
if (StringUtils.hasText(ci.getOuterId())) {
ProductSkuPO sku = productSkuService.getByCompanyIdAndSkuCode(order.getCompanyId(), ci.getOuterId().trim());
if (sku != null) {
productId = sku.getProductId() != null ? sku.getProductId() : 0L;
skuId = sku.getId();
skuCode = sku.getSkuCode();
ProductSkuCostPO cost = productSkuCostService.getCurrentCost(sku.getId());
if (cost != null) {
item.setProductCost(cost.getProductCost());
item.setShippingCost(cost.getShippingCost());
item.setOtherCost(cost.getOtherCost());
}
}
}
item.setProductId(productId);
item.setProductSkuId(skuId);
item.setSkuCode(skuCode != null ? skuCode : ci.getOuterId());
if (item.getProductCost() == null) {
item.setProductCost(BigDecimal.ZERO);
}
if (item.getShippingCost() == null) {
item.setShippingCost(BigDecimal.ZERO);
}
if (item.getOtherCost() == null) {
item.setOtherCost(BigDecimal.ZERO);
}
return item;
}
}
@@ -0,0 +1,35 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.support;
import top.xyquan.ecomdmbbackend.modules.ec.order.status.model.enums.OrderStatus;
/**
* 拼多多订单/售后状态 → 内部 {@link OrderStatus}。
* <p>
* order_status: 1 待发货, 2 已发货待签收, 3 已签收<br>
* refund_status: 1 无售后或关闭, 2 售后处理中, 3 退款中, 4 退款成功
*/
public final class PddOrderStatusMapper {
private PddOrderStatusMapper() {
}
public static OrderStatus map(Integer orderStatus, Integer refundStatus) {
if (refundStatus != null) {
if (refundStatus == 4) {
return OrderStatus.REFUNDED;
}
if (refundStatus == 2 || refundStatus == 3) {
return OrderStatus.REFUNDING;
}
}
if (orderStatus == null) {
return OrderStatus.UNKNOWN;
}
return switch (orderStatus) {
case 1 -> OrderStatus.PENDING_SHIPMENT;
case 2 -> OrderStatus.SHIPPED;
case 3 -> OrderStatus.COMPLETED;
default -> OrderStatus.UNKNOWN;
};
}
}
@@ -0,0 +1,29 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.consumer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.messaging.PddSyncFullMessage;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service.PddOrderFullSyncTaskExecutor;
@Slf4j
@Component
@RequiredArgsConstructor
public class PddOrderSyncFullConsumer {
private final PddOrderFullSyncTaskExecutor fullSyncTaskExecutor;
@RabbitListener(queues = OrderMqConstants.QUEUE_ORDER_SYNC_PDD_FULL)
public void onMessage(PddSyncFullMessage message) {
if (message == null || message.getCompanyId() == null || message.getShopId() == null
|| message.getDateFrom() == null || message.getDateTo() == null) {
log.warn("全量同步消息非法: {}", message);
return;
}
log.info("收到全量同步消息 taskId={} shopId={} {}~{}",
message.getTaskId(), message.getShopId(), message.getDateFrom(), message.getDateTo());
fullSyncTaskExecutor.execute(message);
}
}
@@ -0,0 +1,27 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.consumer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.messaging.PddSyncIncMessage;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service.PddOrderSyncService;
@Slf4j
@Component
@RequiredArgsConstructor
public class PddOrderSyncIncConsumer {
private final PddOrderSyncService pddOrderSyncService;
@RabbitListener(queues = OrderMqConstants.QUEUE_ORDER_SYNC_PDD_INC)
public void onMessage(PddSyncIncMessage message) {
if (message == null || message.getCompanyId() == null || message.getShopId() == null) {
log.warn("增量同步消息非法: {}", message);
return;
}
log.info("收到增量同步消息 shopId={} messageId={}", message.getShopId(), message.getMessageId());
pddOrderSyncService.syncIncrementalInternal(message.getCompanyId(), message.getShopId());
}
}
@@ -8,56 +8,132 @@ import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.messaging.PddOrderSyncPublisher;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.PddOrderSyncShopContext;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.dto.PddOrderFullSyncTaskCreateDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.dto.PddOrderIncrementalToggleDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.dto.PddOrderRepairDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.dto.PddOrderSyncDayDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.vo.PddOrderFullSyncTaskVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.vo.PddOrderIncrementalStatusVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.vo.PddOrderSyncResultVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service.PddOrderFullSyncTaskService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service.PddOrderSyncContextResolver;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service.PddOrderSyncService;
import java.time.LocalDate;
import java.util.List;
/**
* 拼多多订单同步(手动触发)。落库仅 channel_pdd_*,不写内部 ec_order。
* 拼多多订单同步:执行类接口入队;补单仍同步执行。
*/
@Tag(name = "拼多多-订单同步", description = "按天回补 / 增量 / 补单")
@Tag(name = "拼多多-订单同步", description = "按天回补 / 增量 / 补单 / 全量任务 / 增量开关")
@RestController
@RequestMapping("/api/channel/pdd/order/sync")
public class PddOrderSyncController {
private final PddOrderSyncService pddOrderSyncService;
private final PddOrderFullSyncTaskService fullSyncTaskService;
private final PddOrderSyncPublisher syncPublisher;
private final PddOrderSyncContextResolver contextResolver;
public PddOrderSyncController(PddOrderSyncService pddOrderSyncService) {
public PddOrderSyncController(PddOrderSyncService pddOrderSyncService,
PddOrderFullSyncTaskService fullSyncTaskService,
PddOrderSyncPublisher syncPublisher,
PddOrderSyncContextResolver contextResolver) {
this.pddOrderSyncService = pddOrderSyncService;
this.fullSyncTaskService = fullSyncTaskService;
this.syncPublisher = syncPublisher;
this.contextResolver = contextResolver;
}
@Operation(summary = "按成交日同步一天", description = "调用 pdd.order.list.get,按 confirm_time 拉取指定自然日订单并 upsert")
@Operation(summary = "按成交日同步一天(入队)")
@PostMapping("/day")
@RequirePermission(value = "biz:pdd:order:sync", description = "拼多多订单同步", allowSuper = true)
public ApiResponse<PddOrderSyncResultVO> syncDay(@Valid @RequestBody PddOrderSyncDayDTO dto) {
return ApiResponse.success("同步完成", pddOrderSyncService.syncByConfirmDate(dto));
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(dto.getShopId());
syncPublisher.publishFullRange(ctx.getCompanyId(), ctx.getShopId(), dto.getConfirmDate(), dto.getConfirmDate());
return ApiResponse.success("已入队", PddOrderSyncResultVO.builder()
.mode("day")
.shopId(dto.getShopId())
.fetchedCount(0)
.upsertedCount(0)
.skippedCount(0)
.errors(List.of())
.build());
}
@Operation(summary = "按成交日范围回补", description = "多天回补,内部按天切窗")
@Operation(summary = "按成交日范围回补(入队)")
@PostMapping("/bootstrap")
@RequirePermission(value = "biz:pdd:order:sync", description = "拼多多订单同步", allowSuper = true)
public ApiResponse<PddOrderSyncResultVO> bootstrap(
@Parameter(description = "内部店铺 ID") @RequestParam Long shopId,
@Parameter(description = "开始日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
@Parameter(description = "结束日期") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
return ApiResponse.success("回补完成", pddOrderSyncService.bootstrapByConfirmRange(shopId, startDate, endDate));
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(shopId);
syncPublisher.publishFullRange(ctx.getCompanyId(), ctx.getShopId(), startDate, endDate);
return ApiResponse.success("已入队", PddOrderSyncResultVO.builder()
.mode("bootstrap")
.shopId(shopId)
.fetchedCount(0)
.upsertedCount(0)
.skippedCount(0)
.errors(List.of())
.build());
}
@Operation(summary = "增量同步", description = "调用 pdd.order.number.list.increment.get,按 updated_at 推进游标")
@Operation(summary = "增量同步(入队)")
@PostMapping("/incremental")
@RequirePermission(value = "biz:pdd:order:sync", description = "拼多多订单同步", allowSuper = true)
public ApiResponse<PddOrderSyncResultVO> incremental(
@Parameter(description = "内部店铺 ID") @RequestParam Long shopId) {
return ApiResponse.success("增量同步完成", pddOrderSyncService.syncIncremental(shopId));
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(shopId);
syncPublisher.publishInc(ctx.getCompanyId(), ctx.getShopId());
return ApiResponse.success("已入队", PddOrderSyncResultVO.builder()
.mode("incremental")
.shopId(shopId)
.fetchedCount(0)
.upsertedCount(0)
.skippedCount(0)
.errors(List.of())
.build());
}
@Operation(summary = "按订单号补拉", description = "调用 pdd.order.information.get")
@Operation(summary = "按订单号补拉", description = "同步执行;完成后投递 INC 转换")
@PostMapping("/repair")
@RequirePermission(value = "biz:pdd:order:sync", description = "拼多多订单同步", allowSuper = true)
public ApiResponse<PddOrderSyncResultVO> repair(@Valid @RequestBody PddOrderRepairDTO dto) {
return ApiResponse.success("补单完成", pddOrderSyncService.repair(dto));
}
@Operation(summary = "创建全量同步任务", description = "写任务表并入全量同步队列")
@PostMapping("/full-task")
@RequirePermission(value = "biz:pdd:order:sync", description = "拼多多订单同步", allowSuper = true)
public ApiResponse<PddOrderFullSyncTaskVO> createFullTask(
@Valid @RequestBody PddOrderFullSyncTaskCreateDTO dto) {
return ApiResponse.success("任务已入队", fullSyncTaskService.createTask(dto));
}
@Operation(summary = "查询全量同步任务")
@GetMapping("/full-task/{taskId}")
@RequirePermission(value = "biz:pdd:order:sync", description = "拼多多订单同步", allowSuper = true)
public ApiResponse<PddOrderFullSyncTaskVO> getFullTask(@PathVariable Long taskId) {
return ApiResponse.success(fullSyncTaskService.getTask(taskId));
}
@Operation(summary = "增量同步开关")
@PostMapping("/incremental/toggle")
@RequirePermission(value = "biz:pdd:order:sync", description = "拼多多订单同步", allowSuper = true)
public ApiResponse<PddOrderIncrementalStatusVO> toggleIncremental(
@Valid @RequestBody PddOrderIncrementalToggleDTO dto) {
return ApiResponse.success(fullSyncTaskService.toggleIncremental(dto));
}
@Operation(summary = "查询增量同步开关状态")
@GetMapping("/incremental/status")
@RequirePermission(value = "biz:pdd:order:sync", description = "拼多多订单同步", allowSuper = true)
public ApiResponse<PddOrderIncrementalStatusVO> incrementalStatus(
@Parameter(description = "内部店铺 ID") @RequestParam Long shopId) {
return ApiResponse.success(fullSyncTaskService.incrementalStatus(shopId));
}
}
@@ -0,0 +1,39 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.hook;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import top.xyquan.ecomdmbbackend.common.mq.ChannelOrderRef;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.messaging.PddOrderConvertPublisher;
import java.util.ArrayList;
import java.util.List;
/**
* 仅补单路径投递 INC 转换;日常增量已在 sync 按页投递。
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class PddOrderConvertAfterSyncListener implements PddOrderAfterSyncListener {
private final PddOrderConvertPublisher convertPublisher;
@Override
public void onOrdersUpserted(Long companyId, Long shopId, List<Long> pddOrderIds, String syncMode) {
if (pddOrderIds == null || pddOrderIds.isEmpty()) {
return;
}
if (!"repair".equals(syncMode)) {
return;
}
List<ChannelOrderRef> refs = new ArrayList<>();
for (Long id : pddOrderIds) {
ChannelOrderRef ref = PddOrderConvertPublisher.ref(id);
if (ref != null) {
refs.add(ref);
}
}
convertPublisher.publishInc(companyId, shopId, refs);
}
}
@@ -5,10 +5,8 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.mapper.PddOrderSyncCursorMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po.PddOrderSyncCursorPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service.PddOrderSyncService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.messaging.PddOrderSyncPublisher;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service.PddOrderFullSyncTaskService;
import top.xyquan.ecomdmbbackend.modules.ec.platform.model.enums.PlatformCode;
import top.xyquan.ecomdmbbackend.modules.ec.shop.mapper.ShopMapper;
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
@@ -18,7 +16,7 @@ import java.util.List;
import java.util.Set;
/**
* 定时增量同步已绑定外部店的拼多多店铺;跳过增量游标 status=2(出错暂停)。
* 定时将开启增量开关的店铺投入增量同步队列(与全量队列可并行)。
*/
@Slf4j
@Component
@@ -26,21 +24,22 @@ import java.util.Set;
public class PddOrderIncrementalSyncJob {
private final ShopMapper shopMapper;
private final PddOrderSyncCursorMapper cursorMapper;
private final PddOrderSyncService pddOrderSyncService;
private final PddOrderFullSyncTaskService fullSyncTaskService;
private final PddOrderSyncPublisher syncPublisher;
public PddOrderIncrementalSyncJob(ShopMapper shopMapper,
PddOrderSyncCursorMapper cursorMapper,
PddOrderSyncService pddOrderSyncService) {
PddOrderFullSyncTaskService fullSyncTaskService,
PddOrderSyncPublisher syncPublisher) {
this.shopMapper = shopMapper;
this.cursorMapper = cursorMapper;
this.pddOrderSyncService = pddOrderSyncService;
this.fullSyncTaskService = fullSyncTaskService;
this.syncPublisher = syncPublisher;
}
@Scheduled(cron = "${pdd.order-sync.incremental-cron:0 */5 * * * ?}")
public void run() {
List<ShopPO> shops = shopMapper.selectList(new LambdaQueryWrapper<ShopPO>()
.eq(ShopPO::getPlatformCode, PlatformCode.PDD.getCode())
.eq(ShopPO::getOrderIncSyncEnabled, 1)
.isNotNull(ShopPO::getExternalShopId)
.ne(ShopPO::getExternalShopId, ""));
Set<Long> done = new HashSet<>();
@@ -48,23 +47,15 @@ public class PddOrderIncrementalSyncJob {
if (!done.add(shop.getId())) {
continue;
}
if (isIncrementalPaused(shop.getId())) {
if (fullSyncTaskService.isIncrementalPaused(shop.getId())) {
log.debug("跳过出错暂停的增量店铺 shopId={}", shop.getId());
continue;
}
try {
pddOrderSyncService.syncIncrementalInternal(shop.getCompanyId(), shop.getId());
syncPublisher.publishInc(shop.getCompanyId(), shop.getId());
} catch (Exception e) {
log.warn("定时增量同步失败 shopId={}: {}", shop.getId(), e.getMessage());
log.warn("投递增量同步失败 shopId={}: {}", shop.getId(), e.getMessage());
}
}
}
private boolean isIncrementalPaused(Long shopId) {
PddOrderSyncCursorPO cursor = cursorMapper.selectOne(new LambdaQueryWrapper<PddOrderSyncCursorPO>()
.eq(PddOrderSyncCursorPO::getShopId, shopId)
.eq(PddOrderSyncCursorPO::getSyncType, PddOrderSyncCursorPO.TYPE_INCREMENTAL)
.last("LIMIT 1"));
return cursor != null && Integer.valueOf(2).equals(cursor.getStatus());
}
}
@@ -0,0 +1,9 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po.PddOrderFullSyncTaskPO;
@Mapper
public interface PddOrderFullSyncTaskMapper extends BaseMapper<PddOrderFullSyncTaskPO> {
}
@@ -1,11 +1,9 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po.PddOrderSyncCursorPO;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po.PddOrderIncSyncPO;
@Mapper
public interface PddOrderSyncCursorMapper extends BaseMapper<PddOrderSyncCursorPO> {
public interface PddOrderIncSyncMapper extends BaseMapper<PddOrderIncSyncPO> {
}
@@ -0,0 +1,68 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.messaging;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.util.UUID;
@Slf4j
@Component
@RequiredArgsConstructor
public class PddOrderSyncPublisher {
private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
private final RabbitTemplate rabbitTemplate;
public void publishFullTask(Long taskId, Long companyId, Long shopId,
LocalDate dateFrom, LocalDate dateTo) {
PddSyncFullMessage msg = PddSyncFullMessage.builder()
.messageId(UUID.randomUUID().toString())
.taskId(taskId)
.companyId(companyId)
.shopId(shopId)
.dateFrom(dateFrom)
.dateTo(dateTo)
.occurredAt(OffsetDateTime.now(ZONE))
.retryCount(0)
.build();
rabbitTemplate.convertAndSend(
OrderMqConstants.EXCHANGE, OrderMqConstants.RK_ORDER_SYNC_PDD_FULL, msg);
log.info("已投递全量同步任务消息 taskId={} shopId={} {}~{}",
taskId, shopId, dateFrom, dateTo);
}
public void publishFullRange(Long companyId, Long shopId, LocalDate dateFrom, LocalDate dateTo) {
PddSyncFullMessage msg = PddSyncFullMessage.builder()
.messageId(UUID.randomUUID().toString())
.companyId(companyId)
.shopId(shopId)
.dateFrom(dateFrom)
.dateTo(dateTo)
.occurredAt(OffsetDateTime.now(ZONE))
.retryCount(0)
.build();
rabbitTemplate.convertAndSend(
OrderMqConstants.EXCHANGE, OrderMqConstants.RK_ORDER_SYNC_PDD_FULL, msg);
log.info("已投递全量同步区间消息 shopId={} {}~{}", shopId, dateFrom, dateTo);
}
public void publishInc(Long companyId, Long shopId) {
PddSyncIncMessage msg = PddSyncIncMessage.builder()
.messageId(UUID.randomUUID().toString())
.companyId(companyId)
.shopId(shopId)
.occurredAt(OffsetDateTime.now(ZONE))
.retryCount(0)
.build();
rabbitTemplate.convertAndSend(
OrderMqConstants.EXCHANGE, OrderMqConstants.RK_ORDER_SYNC_PDD_INC, msg);
log.info("已投递增量同步消息 shopId={}", shopId);
}
}
@@ -0,0 +1,29 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.messaging;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
import java.time.OffsetDateTime;
/**
* 全量同步入队:有 taskId 则按任务表推进;否则按 dateFrom~dateTo 直接拉。
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PddSyncFullMessage {
private String messageId;
/** 可空:手动按日/区间且不落任务表时为空 */
private Long taskId;
private Long companyId;
private Long shopId;
private LocalDate dateFrom;
private LocalDate dateTo;
private OffsetDateTime occurredAt;
private Integer retryCount;
}
@@ -0,0 +1,21 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.messaging;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.OffsetDateTime;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PddSyncIncMessage {
private String messageId;
private Long companyId;
private Long shopId;
private OffsetDateTime occurredAt;
private Integer retryCount;
}
@@ -0,0 +1,19 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.dto;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import java.time.LocalDate;
@Data
public class PddOrderFullSyncTaskCreateDTO {
@NotNull
private Long shopId;
@NotNull
private LocalDate dateFrom;
@NotNull
private LocalDate dateTo;
}
@@ -0,0 +1,14 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.dto;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
@Data
public class PddOrderIncrementalToggleDTO {
@NotNull
private Long shopId;
@NotNull
private Boolean enabled;
}
@@ -0,0 +1,63 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Data
@TableName("channel_pdd_order_full_sync_task")
public class PddOrderFullSyncTaskPO {
public static final String STATUS_PENDING = "PENDING";
public static final String STATUS_RUNNING = "RUNNING";
public static final String STATUS_SUCCESS = "SUCCESS";
public static final String STATUS_FAILED = "FAILED";
public static final String STATUS_CANCELLED = "CANCELLED";
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("company_id")
private Long companyId;
@TableField("shop_id")
private Long shopId;
@TableField("platform_code")
private String platformCode;
@TableField("date_from")
private LocalDate dateFrom;
@TableField("date_to")
private LocalDate dateTo;
@TableField("current_date")
private LocalDate currentDate;
@TableField("total_days")
private Integer totalDays;
@TableField("done_days")
private Integer doneDays;
@TableField("failed_days")
private Integer failedDays;
@TableField("status")
private String status;
@TableField("last_error")
private String lastError;
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableField("finish_time")
private LocalDateTime finishTime;
}
@@ -1,16 +1,20 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po;
import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("channel_pdd_order_sync_cursor")
public class PddOrderSyncCursorPO {
@TableName("channel_pdd_order_inc_sync")
public class PddOrderIncSyncPO {
public static final String TYPE_BOOTSTRAP = "bootstrap";
public static final String TYPE_INCREMENTAL = "incremental";
/** 出错暂停:Job 跳过直至开关重新打开或人工恢复 */
public static final int STATUS_PAUSED = 2;
public static final int STATUS_OK = 1;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@@ -24,16 +28,12 @@ public class PddOrderSyncCursorPO {
@TableField("pdd_auth_id")
private Long pddAuthId;
@TableField("sync_type")
private String syncType;
@TableField("last_cursor_at")
private LocalDateTime lastCursorAt;
@TableField("overlap_seconds")
private Integer overlapSeconds;
/** 0停用 1正常 2出错暂停 */
@TableField("status")
private Integer status;
@@ -43,9 +43,9 @@ public class PddOrderSyncCursorPO {
@TableField("last_success_time")
private LocalDateTime lastSuccessTime;
@TableField(value = "create_time", fill = FieldFill.INSERT)
@TableField("create_time")
private LocalDateTime createTime;
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
@TableField("update_time")
private LocalDateTime updateTime;
}
@@ -0,0 +1,25 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.vo;
import lombok.Builder;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Data
@Builder
public class PddOrderFullSyncTaskVO {
private Long id;
private Long shopId;
private LocalDate dateFrom;
private LocalDate dateTo;
private LocalDate currentDate;
private Integer totalDays;
private Integer doneDays;
private Integer failedDays;
private String status;
private String lastError;
private LocalDateTime createTime;
private LocalDateTime finishTime;
}
@@ -0,0 +1,14 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.vo;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class PddOrderIncrementalStatusVO {
private Long shopId;
private Boolean enabled;
private Integer cursorStatus;
private String lastError;
}
@@ -0,0 +1,74 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.mapper.PddOrderFullSyncTaskMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.messaging.PddSyncFullMessage;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po.PddOrderFullSyncTaskPO;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* 消费全量同步队列:有 taskId 则回写任务进度,否则直接按区间同步。
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class PddOrderFullSyncTaskExecutor {
private final PddOrderFullSyncTaskMapper taskMapper;
private final PddOrderSyncService pddOrderSyncService;
public void execute(PddSyncFullMessage message) {
if (message.getTaskId() != null) {
executeTask(message.getTaskId());
return;
}
LocalDate day = message.getDateFrom();
while (!day.isAfter(message.getDateTo())) {
pddOrderSyncService.syncByConfirmDateForTask(
message.getCompanyId(), message.getShopId(), day, null);
day = day.plusDays(1);
}
}
public void executeTask(Long taskId) {
PddOrderFullSyncTaskPO task = taskMapper.selectById(taskId);
if (task == null) {
return;
}
task.setStatus(PddOrderFullSyncTaskPO.STATUS_RUNNING);
taskMapper.updateById(task);
LocalDate day = task.getDateFrom();
if (task.getCurrentDate() != null && task.getDoneDays() != null && task.getDoneDays() > 0) {
day = task.getCurrentDate().plusDays(1);
}
try {
while (!day.isAfter(task.getDateTo())) {
task.setCurrentDate(day);
taskMapper.updateById(task);
pddOrderSyncService.syncByConfirmDateForTask(
task.getCompanyId(), task.getShopId(), day, task.getId());
task.setDoneDays((task.getDoneDays() == null ? 0 : task.getDoneDays()) + 1);
taskMapper.updateById(task);
day = day.plusDays(1);
}
task.setStatus(PddOrderFullSyncTaskPO.STATUS_SUCCESS);
task.setFinishTime(LocalDateTime.now());
task.setLastError(null);
taskMapper.updateById(task);
} catch (Exception e) {
log.error("全量同步任务失败 taskId={}", taskId, e);
task.setFailedDays((task.getFailedDays() == null ? 0 : task.getFailedDays()) + 1);
task.setStatus(PddOrderFullSyncTaskPO.STATUS_FAILED);
task.setLastError(e.getMessage() != null && e.getMessage().length() > 500
? e.getMessage().substring(0, 500) : e.getMessage());
task.setFinishTime(LocalDateTime.now());
taskMapper.updateById(task);
throw e;
}
}
}
@@ -0,0 +1,164 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.config.PddOrderSyncProperties;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.mapper.PddOrderFullSyncTaskMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.mapper.PddOrderIncSyncMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.messaging.PddOrderSyncPublisher;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.PddOrderSyncShopContext;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.dto.PddOrderFullSyncTaskCreateDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.dto.PddOrderIncrementalToggleDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po.PddOrderFullSyncTaskPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po.PddOrderIncSyncPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.vo.PddOrderFullSyncTaskVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.vo.PddOrderIncrementalStatusVO;
import top.xyquan.ecomdmbbackend.modules.ec.platform.model.enums.PlatformCode;
import top.xyquan.ecomdmbbackend.modules.ec.shop.mapper.ShopMapper;
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
import java.time.temporal.ChronoUnit;
@Slf4j
@Service
@RequiredArgsConstructor
public class PddOrderFullSyncTaskService {
private final PddOrderFullSyncTaskMapper taskMapper;
private final PddOrderIncSyncMapper incSyncMapper;
private final ShopMapper shopMapper;
private final PddOrderSyncContextResolver contextResolver;
private final PddOrderSyncPublisher syncPublisher;
private final PddOrderSyncProperties syncProperties;
@Transactional(rollbackFor = Exception.class)
public PddOrderFullSyncTaskVO createTask(PddOrderFullSyncTaskCreateDTO dto) {
if (dto.getDateTo().isBefore(dto.getDateFrom())) {
throw new BusinessException("结束日期不能早于开始日期");
}
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(dto.getShopId());
Long running = taskMapper.selectCount(new LambdaQueryWrapper<PddOrderFullSyncTaskPO>()
.eq(PddOrderFullSyncTaskPO::getShopId, dto.getShopId())
.in(PddOrderFullSyncTaskPO::getStatus,
PddOrderFullSyncTaskPO.STATUS_PENDING, PddOrderFullSyncTaskPO.STATUS_RUNNING));
if (running != null && running > 0) {
throw new BusinessException("该店铺已有进行中的全量同步任务");
}
int totalDays = (int) ChronoUnit.DAYS.between(dto.getDateFrom(), dto.getDateTo()) + 1;
PddOrderFullSyncTaskPO task = new PddOrderFullSyncTaskPO();
task.setCompanyId(ctx.getCompanyId());
task.setShopId(ctx.getShopId());
task.setPlatformCode(PlatformCode.PDD.getCode());
task.setDateFrom(dto.getDateFrom());
task.setDateTo(dto.getDateTo());
task.setTotalDays(totalDays);
task.setDoneDays(0);
task.setFailedDays(0);
task.setStatus(PddOrderFullSyncTaskPO.STATUS_PENDING);
taskMapper.insert(task);
syncPublisher.publishFullTask(
task.getId(), task.getCompanyId(), task.getShopId(),
task.getDateFrom(), task.getDateTo());
return toVo(task);
}
public PddOrderFullSyncTaskVO getTask(Long taskId) {
PddOrderFullSyncTaskPO task = taskMapper.selectById(taskId);
if (task == null) {
throw new BusinessException("全量同步任务不存在");
}
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(task.getShopId());
if (!ctx.getCompanyId().equals(task.getCompanyId())) {
throw new BusinessException("无权查看该任务");
}
return toVo(task);
}
@Transactional(rollbackFor = Exception.class)
public PddOrderIncrementalStatusVO toggleIncremental(PddOrderIncrementalToggleDTO dto) {
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(dto.getShopId());
ShopPO shop = shopMapper.selectById(ctx.getShopId());
if (shop == null) {
throw new BusinessException("店铺不存在");
}
boolean enabled = Boolean.TRUE.equals(dto.getEnabled());
shop.setOrderIncSyncEnabled(enabled ? 1 : 0);
shopMapper.updateById(shop);
PddOrderIncSyncPO state = getOrCreateIncState(ctx);
if (enabled && Integer.valueOf(PddOrderIncSyncPO.STATUS_PAUSED).equals(state.getStatus())) {
state.setStatus(PddOrderIncSyncPO.STATUS_OK);
state.setLastError(null);
incSyncMapper.updateById(state);
}
return incrementalStatus(ctx.getShopId());
}
public PddOrderIncrementalStatusVO incrementalStatus(Long shopId) {
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(shopId);
ShopPO shop = shopMapper.selectById(ctx.getShopId());
PddOrderIncSyncPO state = findIncState(ctx.getShopId());
boolean enabled = shop != null && Integer.valueOf(1).equals(shop.getOrderIncSyncEnabled());
return PddOrderIncrementalStatusVO.builder()
.shopId(shopId)
.enabled(enabled)
.cursorStatus(state != null ? state.getStatus() : null)
.lastError(state != null ? state.getLastError() : null)
.build();
}
public boolean isIncrementalEnabled(Long shopId) {
ShopPO shop = shopMapper.selectById(shopId);
return shop != null && Integer.valueOf(1).equals(shop.getOrderIncSyncEnabled());
}
public boolean isIncrementalPaused(Long shopId) {
PddOrderIncSyncPO state = findIncState(shopId);
return state != null && Integer.valueOf(PddOrderIncSyncPO.STATUS_PAUSED).equals(state.getStatus());
}
private PddOrderIncSyncPO findIncState(Long shopId) {
return incSyncMapper.selectOne(new LambdaQueryWrapper<PddOrderIncSyncPO>()
.eq(PddOrderIncSyncPO::getShopId, shopId)
.last("LIMIT 1"));
}
private PddOrderIncSyncPO getOrCreateIncState(PddOrderSyncShopContext ctx) {
PddOrderIncSyncPO existing = findIncState(ctx.getShopId());
if (existing != null) {
return existing;
}
PddOrderIncSyncPO state = new PddOrderIncSyncPO();
state.setCompanyId(ctx.getCompanyId());
state.setShopId(ctx.getShopId());
state.setPddAuthId(ctx.getAuth().getId());
state.setOverlapSeconds(syncProperties.getOverlapSeconds());
state.setStatus(PddOrderIncSyncPO.STATUS_OK);
incSyncMapper.insert(state);
return state;
}
private static PddOrderFullSyncTaskVO toVo(PddOrderFullSyncTaskPO task) {
return PddOrderFullSyncTaskVO.builder()
.id(task.getId())
.shopId(task.getShopId())
.dateFrom(task.getDateFrom())
.dateTo(task.getDateTo())
.currentDate(task.getCurrentDate())
.totalDays(task.getTotalDays())
.doneDays(task.getDoneDays())
.failedDays(task.getFailedDays())
.status(task.getStatus())
.lastError(task.getLastError())
.createTime(task.getCreateTime())
.finishTime(task.getFinishTime())
.build();
}
}
@@ -6,13 +6,15 @@ import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.common.mq.ChannelOrderRef;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.messaging.PddOrderConvertPublisher;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.config.PddOrderSyncProperties;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.hook.PddOrderAfterSyncListener;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.mapper.PddOrderSyncCursorMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.mapper.PddOrderIncSyncMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.PddOrderSyncShopContext;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.dto.PddOrderRepairDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.dto.PddOrderSyncDayDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po.PddOrderSyncCursorPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po.PddOrderIncSyncPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.vo.PddOrderSyncResultVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.PddPopRateLimitedException;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.order.PddOrderPopApiClient;
@@ -30,82 +32,72 @@ import java.util.UUID;
/**
* 拼多多订单同步门面:day(按天回补)/ incremental / repair。
* 只写 channel_pdd_*;转内部订单通过 {@link PddOrderAfterSyncListener}。
* 全量进度看 full_sync_task;增量游标看 channel_pdd_order_inc_sync。
*/
@Slf4j
@Service
public class PddOrderSyncService {
private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
private static final String LOCK_PREFIX = "pdd:order:sync:lock:";
private static final String LOCK_FULL_PREFIX = "pdd:order:sync:full:lock:";
private static final String LOCK_INC_PREFIX = "pdd:order:sync:inc:lock:";
private final PddOrderSyncContextResolver contextResolver;
private final PddOrderPopApiClient apiClient;
private final PddOrderUpsertService upsertService;
private final PddOrderSyncCursorMapper cursorMapper;
private final PddOrderIncSyncMapper incSyncMapper;
private final PddOrderSyncProperties syncProperties;
private final StringRedisTemplate stringRedisTemplate;
private final ShopMapper shopMapper;
private final List<PddOrderAfterSyncListener> afterSyncListeners;
private final PddOrderConvertPublisher convertPublisher;
public PddOrderSyncService(PddOrderSyncContextResolver contextResolver,
PddOrderPopApiClient apiClient,
PddOrderUpsertService upsertService,
PddOrderSyncCursorMapper cursorMapper,
PddOrderIncSyncMapper incSyncMapper,
PddOrderSyncProperties syncProperties,
StringRedisTemplate stringRedisTemplate,
ShopMapper shopMapper,
List<PddOrderAfterSyncListener> afterSyncListeners) {
List<PddOrderAfterSyncListener> afterSyncListeners,
PddOrderConvertPublisher convertPublisher) {
this.contextResolver = contextResolver;
this.apiClient = apiClient;
this.upsertService = upsertService;
this.cursorMapper = cursorMapper;
this.incSyncMapper = incSyncMapper;
this.syncProperties = syncProperties;
this.stringRedisTemplate = stringRedisTemplate;
this.shopMapper = shopMapper;
this.afterSyncListeners = afterSyncListeners != null ? afterSyncListeners : List.of();
this.convertPublisher = convertPublisher;
}
/**
* 按成交日同步一天(list.get,窗口 ≤24h)。
*/
public PddOrderSyncResultVO syncByConfirmDate(PddOrderSyncDayDTO dto) {
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(dto.getShopId());
return withShopLock(ctx.getShopId(), () -> doSyncConfirmRange(ctx, dto.getConfirmDate(), dto.getConfirmDate(), "day"));
return withFullLock(ctx.getShopId(), () -> doSyncConfirmRange(ctx, dto.getConfirmDate(), dto.getConfirmDate(), "day", null));
}
/**
* 按成交日起止回补(多天切 24h 窗)。
*/
public PddOrderSyncResultVO bootstrapByConfirmRange(Long shopId, LocalDate startDate, LocalDate endDate) {
if (startDate == null || endDate == null || endDate.isBefore(startDate)) {
throw new BusinessException("回补日期范围无效");
}
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(shopId);
return withShopLock(ctx.getShopId(), () -> doSyncConfirmRange(ctx, startDate, endDate, "bootstrap"));
return withFullLock(ctx.getShopId(), () -> doSyncConfirmRange(ctx, startDate, endDate, "bootstrap", null));
}
/**
* 增量:按 updated_at 从游标拉到现在(≤30min 切窗)。
*/
public PddOrderSyncResultVO syncIncremental(Long shopId) {
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(shopId);
return withShopLock(ctx.getShopId(), () -> doIncremental(ctx));
return withIncLock(ctx.getShopId(), () -> doIncremental(ctx));
}
/**
* Job 用:按公司扫店(当前实现:对传入 shopId 做增量)。
*/
public PddOrderSyncResultVO syncIncrementalInternal(Long companyId, Long shopId) {
PddOrderSyncShopContext ctx = contextResolver.resolve(companyId, shopId);
return withShopLock(ctx.getShopId(), () -> doIncremental(ctx));
return withIncLock(ctx.getShopId(), () -> doIncremental(ctx));
}
/**
* 按 order_sn 补单。
*/
public PddOrderSyncResultVO repair(PddOrderRepairDTO dto) {
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(dto.getShopId());
return withShopLock(ctx.getShopId(), () -> {
return withIncLock(ctx.getShopId(), () -> {
List<Long> upsertedIds = new ArrayList<>();
List<String> errors = new ArrayList<>();
int fetched = 0;
@@ -132,7 +124,6 @@ public class PddOrderSyncService {
}
} catch (PddPopRateLimitedException e) {
errors.add(e.getMessage());
// 补单不推进、不改写 bootstrap/incremental 游标
break;
} catch (Exception e) {
log.warn("补单失败 orderSn={}: {}", orderSn, e.getMessage());
@@ -158,16 +149,23 @@ public class PddOrderSyncService {
.ne(ShopPO::getExternalShopId, ""));
}
public PddOrderSyncResultVO syncByConfirmDateForTask(Long companyId, Long shopId, LocalDate day, Long taskId) {
PddOrderSyncShopContext ctx = contextResolver.resolve(companyId, shopId);
return withFullLock(ctx.getShopId(), () -> doSyncConfirmRange(ctx, day, day, "day", taskId));
}
private PddOrderSyncResultVO doSyncConfirmRange(PddOrderSyncShopContext ctx,
LocalDate startDate,
LocalDate endDate,
String mode) {
String mode,
Long taskId) {
List<Long> upsertedIds = new ArrayList<>();
List<String> errors = new ArrayList<>();
int fetched = 0;
int upserted = 0;
try {
for (LocalDate day = startDate; !day.isAfter(endDate); day = day.plusDays(1)) {
List<ChannelOrderRef> dayRefs = new ArrayList<>();
LocalDateTime dayStart = day.atStartOfDay();
LocalDateTime dayEnd = day.plusDays(1).atStartOfDay().minusSeconds(1);
long startTs = dayStart.atZone(ZONE).toEpochSecond();
@@ -179,31 +177,33 @@ public class PddOrderSyncService {
ctx.getMallId(), ctx.getAccessToken(), startTs, endTs, page);
for (PddOrderPopApiClient.RawOrder raw : pageData.orders()) {
fetched++;
Long id = upsertService.upsert(ctx, raw.snapshot(), raw.raw(), false);
if (id != null) {
upsertedIds.add(id);
PddOrderUpsertService.UpsertResult ur =
upsertService.upsertWithMeta(ctx, raw.snapshot(), raw.raw(), false);
if (ur != null && ur.id() != null) {
ChannelOrderRef ref = PddOrderConvertPublisher.ref(ur.id());
if (ref != null) {
dayRefs.add(ref);
}
upsertedIds.add(ur.id());
upserted++;
}
}
hasNext = pageData.hasNext();
page++;
}
saveCursorSuccess(ctx, PddOrderSyncCursorPO.TYPE_BOOTSTRAP, dayEnd);
convertPublisher.publishFullDay(
ctx.getCompanyId(), ctx.getShopId(), day, dayRefs, taskId);
}
} catch (PddPopRateLimitedException e) {
errors.add(e.getMessage());
noteRateLimit(ctx, PddOrderSyncCursorPO.TYPE_BOOTSTRAP, e.getMessage());
} catch (BusinessException e) {
errors.add(e.getMessage());
markCursorError(ctx, PddOrderSyncCursorPO.TYPE_BOOTSTRAP, e.getMessage());
throw e;
} catch (Exception e) {
log.error("按成交日同步失败 shopId={}", ctx.getShopId(), e);
errors.add(e.getMessage());
markCursorError(ctx, PddOrderSyncCursorPO.TYPE_BOOTSTRAP, e.getMessage());
throw new BusinessException("同步失败: " + e.getMessage());
}
notifyListeners(ctx, upsertedIds, mode);
return PddOrderSyncResultVO.builder()
.mode(mode)
.shopId(ctx.getShopId())
@@ -221,9 +221,9 @@ public class PddOrderSyncService {
int upserted = 0;
int overlap = Math.max(syncProperties.getOverlapSeconds(), 0);
LocalDateTime now = LocalDateTime.now(ZONE);
PddOrderSyncCursorPO cursor = getOrCreateCursor(ctx, PddOrderSyncCursorPO.TYPE_INCREMENTAL);
LocalDateTime cursorAt = cursor.getLastCursorAt() != null
? cursor.getLastCursorAt()
PddOrderIncSyncPO state = getOrCreateIncState(ctx);
LocalDateTime cursorAt = state.getLastCursorAt() != null
? state.getLastCursorAt()
: now.minusMinutes(30);
LocalDateTime pullStart = cursorAt.minusSeconds(overlap);
if (pullStart.isAfter(now)) {
@@ -237,7 +237,6 @@ public class PddOrderSyncService {
if (windowEnd.isAfter(now)) {
windowEnd = now;
}
// 保证窗口不超过 30 分钟
if (Duration.between(windowStart, windowEnd).toSeconds() > 30 * 60) {
windowEnd = windowStart.plusMinutes(30).minusSeconds(1);
}
@@ -252,35 +251,43 @@ public class PddOrderSyncService {
while (hasNext) {
PddOrderPopApiClient.ListPage pageData = apiClient.fetchOrderListByUpdatedAt(
ctx.getMallId(), ctx.getAccessToken(), startTs, endTs, page);
List<ChannelOrderRef> pageRefs = new ArrayList<>();
for (PddOrderPopApiClient.RawOrder raw : pageData.orders()) {
fetched++;
Long id = upsertService.upsert(ctx, raw.snapshot(), raw.raw(), false);
if (id != null) {
upsertedIds.add(id);
PddOrderUpsertService.UpsertResult ur =
upsertService.upsertWithMeta(ctx, raw.snapshot(), raw.raw(), false);
if (ur != null && ur.id() != null) {
ChannelOrderRef ref = PddOrderConvertPublisher.ref(ur.id());
if (ref != null) {
pageRefs.add(ref);
}
upsertedIds.add(ur.id());
upserted++;
}
}
if (!pageRefs.isEmpty()) {
convertPublisher.publishInc(ctx.getCompanyId(), ctx.getShopId(), pageRefs);
}
hasNext = pageData.hasNext();
page++;
}
saveCursorSuccess(ctx, PddOrderSyncCursorPO.TYPE_INCREMENTAL, windowEnd);
saveIncSuccess(ctx, windowEnd);
windowStart = windowEnd;
}
} catch (PddPopRateLimitedException e) {
errors.add(e.getMessage());
noteRateLimit(ctx, PddOrderSyncCursorPO.TYPE_INCREMENTAL, e.getMessage());
noteIncRateLimit(ctx, e.getMessage());
} catch (BusinessException e) {
errors.add(e.getMessage());
markCursorError(ctx, PddOrderSyncCursorPO.TYPE_INCREMENTAL, e.getMessage());
markIncError(ctx, e.getMessage());
throw e;
} catch (Exception e) {
log.error("增量同步失败 shopId={}", ctx.getShopId(), e);
errors.add(e.getMessage());
markCursorError(ctx, PddOrderSyncCursorPO.TYPE_INCREMENTAL, e.getMessage());
markIncError(ctx, e.getMessage());
throw new BusinessException("增量同步失败: " + e.getMessage());
}
notifyListeners(ctx, upsertedIds, "incremental");
return PddOrderSyncResultVO.builder()
.mode("incremental")
.shopId(ctx.getShopId())
@@ -291,59 +298,55 @@ public class PddOrderSyncService {
.build();
}
private PddOrderSyncCursorPO getOrCreateCursor(PddOrderSyncShopContext ctx, String syncType) {
PddOrderSyncCursorPO existing = cursorMapper.selectOne(new LambdaQueryWrapper<PddOrderSyncCursorPO>()
.eq(PddOrderSyncCursorPO::getShopId, ctx.getShopId())
.eq(PddOrderSyncCursorPO::getSyncType, syncType)
private PddOrderIncSyncPO getOrCreateIncState(PddOrderSyncShopContext ctx) {
PddOrderIncSyncPO existing = incSyncMapper.selectOne(new LambdaQueryWrapper<PddOrderIncSyncPO>()
.eq(PddOrderIncSyncPO::getShopId, ctx.getShopId())
.last("LIMIT 1"));
if (existing != null) {
return existing;
}
PddOrderSyncCursorPO cursor = new PddOrderSyncCursorPO();
cursor.setCompanyId(ctx.getCompanyId());
cursor.setShopId(ctx.getShopId());
cursor.setPddAuthId(ctx.getAuth().getId());
cursor.setSyncType(syncType);
cursor.setOverlapSeconds(syncProperties.getOverlapSeconds());
cursor.setStatus(1);
cursorMapper.insert(cursor);
return cursor;
PddOrderIncSyncPO state = new PddOrderIncSyncPO();
state.setCompanyId(ctx.getCompanyId());
state.setShopId(ctx.getShopId());
state.setPddAuthId(ctx.getAuth().getId());
state.setOverlapSeconds(syncProperties.getOverlapSeconds());
state.setStatus(PddOrderIncSyncPO.STATUS_OK);
incSyncMapper.insert(state);
return state;
}
private void saveCursorSuccess(PddOrderSyncShopContext ctx, String syncType, LocalDateTime cursorAt) {
PddOrderSyncCursorPO cursor = getOrCreateCursor(ctx, syncType);
cursor.setLastCursorAt(cursorAt);
cursor.setStatus(1);
cursor.setLastError(null);
cursor.setLastSuccessTime(LocalDateTime.now(ZONE));
cursor.setPddAuthId(ctx.getAuth().getId());
cursor.setOverlapSeconds(syncProperties.getOverlapSeconds());
cursorMapper.updateById(cursor);
private void saveIncSuccess(PddOrderSyncShopContext ctx, LocalDateTime cursorAt) {
PddOrderIncSyncPO state = getOrCreateIncState(ctx);
state.setLastCursorAt(cursorAt);
state.setStatus(PddOrderIncSyncPO.STATUS_OK);
state.setLastError(null);
state.setLastSuccessTime(LocalDateTime.now(ZONE));
state.setPddAuthId(ctx.getAuth().getId());
state.setOverlapSeconds(syncProperties.getOverlapSeconds());
incSyncMapper.updateById(state);
}
/** 业务失败:游标 status=2,Job 将跳过直至人工恢复。 */
private void markCursorError(PddOrderSyncShopContext ctx, String syncType, String error) {
private void markIncError(PddOrderSyncShopContext ctx, String error) {
try {
PddOrderSyncCursorPO cursor = getOrCreateCursor(ctx, syncType);
cursor.setStatus(2);
cursor.setLastError(truncateError(error));
cursorMapper.updateById(cursor);
PddOrderIncSyncPO state = getOrCreateIncState(ctx);
state.setStatus(PddOrderIncSyncPO.STATUS_PAUSED);
state.setLastError(truncateError(error));
incSyncMapper.updateById(state);
} catch (Exception e) {
log.warn("写入同步游标错误失败: {}", e.getMessage());
log.warn("写入增量状态错误失败: {}", e.getMessage());
}
}
/** 限流:只记 last_error,保持可调度(不置 status=2),不推进游标。 */
private void noteRateLimit(PddOrderSyncShopContext ctx, String syncType, String error) {
private void noteIncRateLimit(PddOrderSyncShopContext ctx, String error) {
try {
PddOrderSyncCursorPO cursor = getOrCreateCursor(ctx, syncType);
if (cursor.getStatus() == null || cursor.getStatus() == 0) {
cursor.setStatus(1);
PddOrderIncSyncPO state = getOrCreateIncState(ctx);
if (state.getStatus() == null || state.getStatus() == 0) {
state.setStatus(PddOrderIncSyncPO.STATUS_OK);
}
cursor.setLastError(truncateError(error));
cursorMapper.updateById(cursor);
state.setLastError(truncateError(error));
incSyncMapper.updateById(state);
} catch (Exception e) {
log.warn("写入限流备注失败: {}", e.getMessage());
log.warn("写入增量限流备注失败: {}", e.getMessage());
}
}
@@ -367,13 +370,20 @@ public class PddOrderSyncService {
}
}
private <T> T withShopLock(Long shopId, SyncAction<T> action) {
private <T> T withFullLock(Long shopId, SyncAction<T> action) {
return withTypedLock(LOCK_FULL_PREFIX + shopId, "该店铺全量同步进行中,请稍后重试", action);
}
private <T> T withIncLock(Long shopId, SyncAction<T> action) {
return withTypedLock(LOCK_INC_PREFIX + shopId, "该店铺增量同步进行中,请稍后重试", action);
}
private <T> T withTypedLock(String key, String busyMessage, SyncAction<T> action) {
String token = UUID.randomUUID().toString();
String key = LOCK_PREFIX + shopId;
Boolean ok = stringRedisTemplate.opsForValue()
.setIfAbsent(key, token, Duration.ofSeconds(Math.max(syncProperties.getLockTtlSeconds(), 60)));
if (!Boolean.TRUE.equals(ok)) {
throw new BusinessException("该店铺正在同步中,请稍后重试");
throw new BusinessException(busyMessage);
}
try {
return action.run();
@@ -52,6 +52,13 @@ public class PddOrderUpsertService {
@Transactional(rollbackFor = Exception.class)
public Long upsert(PddOrderSyncShopContext ctx, PddOrderApiSnapshot snapshot, Object rawSdkObject, boolean force) {
UpsertResult r = upsertWithMeta(ctx, snapshot, rawSdkObject, force);
return r != null ? r.id() : null;
}
@Transactional(rollbackFor = Exception.class)
public UpsertResult upsertWithMeta(PddOrderSyncShopContext ctx, PddOrderApiSnapshot snapshot,
Object rawSdkObject, boolean force) {
if (snapshot == null || !StringUtils.hasText(snapshot.getOrderSn())) {
return null;
}
@@ -63,7 +70,7 @@ public class PddOrderUpsertService {
if (!force && existing != null && existing.getPddUpdatedAt() != null && remoteUpdated != null
&& !existing.getPddUpdatedAt().isBefore(remoteUpdated)) {
return existing.getId();
return new UpsertResult(existing.getId(), existing.getPddUpdatedAt());
}
PddOrderPO order = existing != null ? existing : new PddOrderPO();
@@ -111,7 +118,11 @@ public class PddOrderUpsertService {
}
replaceItems(order, snapshot);
return order.getId();
LocalDateTime updatedAt = order.getPddUpdatedAt() != null ? order.getPddUpdatedAt() : order.getLastSyncTime();
return new UpsertResult(order.getId(), updatedAt);
}
public record UpsertResult(Long id, LocalDateTime pddUpdatedAt) {
}
private void replaceItems(PddOrderPO order, PddOrderApiSnapshot snapshot) {
@@ -108,6 +108,10 @@ public class OrderPO {
@TableField("confirm")
private Integer confirm;
/** 平台侧订单更新时间(渠道镜像同步过来的 updated_at) */
@TableField("platform_updated_at")
private LocalDateTime platformUpdatedAt;
@TableField("last_mapped_time")
private LocalDateTime lastMappedTime;
@@ -50,6 +50,12 @@ public class ShopPO {
@TableField("external_shop_id")
private String externalShopId;
/**
* 订单增量同步开关:0关 1开
*/
@TableField("order_inc_sync_enabled")
private Integer orderIncSyncEnabled;
/**
* 创建时间
*/