refactor: 重构拼多多渠道同步任务和数据只关联渠道店铺

This commit is contained in:
2026-08-21 11:12:19 +08:00
parent b4fae1acb5
commit 7e4b0d3e55
28 changed files with 478 additions and 197 deletions
@@ -7,7 +7,7 @@ import lombok.NoArgsConstructor;
/**
* 渠道订单引用:镜像表主键。
* 转换侧按 id 查渠道镜像;内部单用 platform_code + source_order_id 定位。
* 转换侧按 id 查渠道镜像;内部单按平台单号幂等键定位。
*/
@Data
@Builder
@@ -36,6 +36,9 @@ 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 top.xyquan.ecomdmbbackend.modules.ec.shop.mapper.ShopMapper;
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import java.math.BigDecimal;
import java.time.LocalDate;
@@ -70,6 +73,7 @@ public class PddOrderConvertService {
private final PlatformTransactionManager transactionManager;
private final OrderStatContributionCalculator contributionCalculator;
private final OrderStatusStatResolver orderStatusStatResolver;
private final ShopMapper shopMapper;
public void convert(OrderConvertMessage message) {
if (message.getMode() == OrderConvertMode.FULL_DAY) {
@@ -80,9 +84,10 @@ public class PddOrderConvertService {
// 必须等转换事务提交后再投递 BI / 自动建品,否则消费者可能读到未提交快照
ConvertBatchResult result = tt.execute(status -> convertFullDay(message));
if (result != null) {
Long internalShopId = requireInternalShopId(message.getCompanyId(), message.getShopId());
for (LocalDate d : result.biDates()) {
biCalcPublisher.publishFull(
message.getCompanyId(), message.getShopId(), d, message.getSyncBatchId());
message.getCompanyId(), internalShopId, d, message.getSyncBatchId());
}
publishAutoCreate(message.getCompanyId(), message.getShopId(), result.pendingGoodsIds());
}
@@ -113,7 +118,7 @@ public class PddOrderConvertService {
}
SkuBindContext bindCtx = preloadSkuBind(message.getCompanyId(), channelOrders);
for (PddOrderPO channel : channelOrders) {
OrderPO existing = findInternalBySource(channel);
OrderPO existing = findInternalOrder(channel);
if (existing != null && !isChannelNewer(channel, existing)) {
continue;
}
@@ -131,7 +136,7 @@ public class PddOrderConvertService {
/**
* 增量:消息带渠道镜像主键列表;按 id 查渠道单。
* 内部单用 platform_code + source_order_id 定位:无则新增;有则仅当渠道更新时间更新时覆盖,并产出 BI delta。
* 内部单按 uk(company, shop, platform_order_no) 定位;仅当渠道更新时间更新时覆盖并产出 BI delta。
* @return 未绑定需异步建品的 goodsId
*/
private Set<Long> convertInc(OrderConvertMessage message) {
@@ -159,7 +164,7 @@ public class PddOrderConvertService {
SkuBindContext bindCtx = preloadSkuBind(message.getCompanyId(), channels);
for (PddOrderPO channel : channels) {
OrderPO oldOrder = findInternalBySource(channel);
OrderPO oldOrder = findInternalOrder(channel);
if (oldOrder != null && !isChannelNewer(channel, oldOrder)) {
log.info("跳过 INC 转换(内部已是最新) channelOrderId={} platformUpdatedAt={}",
channel.getId(), oldOrder.getPlatformUpdatedAt());
@@ -191,11 +196,16 @@ public class PddOrderConvertService {
return bindCtx.pendingGoodsIds();
}
private OrderPO findInternalBySource(PddOrderPO channel) {
/** 定位内部单:uk(company_id, shop_id, platform_order_no)。 */
private OrderPO findInternalOrder(PddOrderPO channel) {
if (!StringUtils.hasText(channel.getOrderSn())) {
return null;
}
Long internalShopId = requireInternalShopId(channel.getCompanyId(), channel.getShopId());
return orderMapper.selectOne(new LambdaQueryWrapper<OrderPO>()
.eq(OrderPO::getCompanyId, channel.getCompanyId())
.eq(OrderPO::getPlatformCode, PlatformCode.PDD.getCode())
.eq(OrderPO::getSourceOrderId, channel.getId())
.eq(OrderPO::getShopId, internalShopId)
.eq(OrderPO::getPlatformOrderNo, channel.getOrderSn())
.last("LIMIT 1"));
}
@@ -230,7 +240,9 @@ public class PddOrderConvertService {
skuByDate.getOrDefault(date, Map.of()).values());
skus.removeIf(s -> s.getMetrics() == null || s.getMetrics().isAllZero());
biCalcPublisher.publishIncDelta(
message.getCompanyId(), message.getShopId(), date, internalOrderUpdateTime,
message.getCompanyId(),
requireInternalShopId(message.getCompanyId(), message.getShopId()),
date, internalOrderUpdateTime,
orderId, channelOrderId, shopDelta, products, skus);
}
}
@@ -324,25 +336,16 @@ public class PddOrderConvertService {
}
private OrderPO upsertInternalOrder(PddOrderPO channel, LocalDateTime mappedAt, SkuBindContext bindCtx) {
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"));
}
Long internalShopId = requireInternalShopId(channel.getCompanyId(), channel.getShopId());
OrderPO existing = findInternalOrder(channel);
OrderPO order = existing != null ? existing : new OrderPO();
order.setCompanyId(channel.getCompanyId());
order.setShopId(channel.getShopId());
order.setShopId(internalShopId);
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(nz(channel.getPayAmount()));
order.setGoodsAmount(channel.getGoodsAmount());
order.setDiscountAmount(channel.getDiscountAmount());
@@ -483,6 +486,21 @@ public class PddOrderConvertService {
return new SkuBindContext(itemsByOrderId, skuByCode, costs, new HashSet<>());
}
private Long requireInternalShopId(Long companyId, Long channelShopId) {
if (channelShopId == null) {
throw new BusinessException("渠道店铺 ID 不能为空");
}
ShopPO shop = shopMapper.selectOne(new LambdaQueryWrapper<ShopPO>()
.eq(ShopPO::getCompanyId, companyId)
.eq(ShopPO::getPlatformCode, PlatformCode.PDD.getCode())
.eq(ShopPO::getExternalShopId, channelShopId)
.last("LIMIT 1"));
if (shop == null) {
throw new BusinessException("未找到绑定该拼多多店的内部店铺,无法写入经营订单");
}
return shop.getId();
}
private record ConvertBatchResult(Set<LocalDate> biDates, Set<Long> pendingGoodsIds) {
}
@@ -63,7 +63,8 @@ public class PddProductAutoCreateService {
|| message.getShopId() == null || message.getGoodsId() == null) {
return;
}
PddOrderSyncShopContext ctx = contextResolver.resolve(message.getCompanyId(), message.getShopId());
PddOrderSyncShopContext ctx = contextResolver.resolveByChannelShopId(
message.getCompanyId(), message.getShopId());
if (ctx.getPddShop() == null || ctx.getPddShop().getId() == null) {
log.warn("自动建品:缺少渠道店铺,跳过 companyId={} goodsId={}",
message.getCompanyId(), message.getGoodsId());
@@ -14,8 +14,6 @@ public class CreatePddOrderDTO {
@NotNull(message = "店铺ID不能为空")
private Long shopId;
private Long pddAuthId;
@NotBlank(message = "拼多多订单号不能为空")
private String orderSn;
@@ -4,9 +4,11 @@ import lombok.Data;
import java.time.LocalDateTime;
/** 拼多多渠道订单列表筛选;shopId 为 channel_pdd_shop.id。 */
@Data
public class PddOrderFilterDTO {
/** 渠道店铺 ID(channel_pdd_shop.id) */
private Long shopId;
private String orderSn;
@@ -14,8 +14,6 @@ public class UpdatePddOrderDTO {
@NotNull(message = "店铺ID不能为空")
private Long shopId;
private Long pddAuthId;
@NotBlank(message = "拼多多订单号不能为空")
private String orderSn;
@@ -19,9 +19,6 @@ public class PddOrderPO {
@TableField("shop_id")
private Long shopId;
@TableField("pdd_auth_id")
private Long pddAuthId;
@TableField("order_sn")
private String orderSn;
@@ -6,6 +6,10 @@ import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
/**
* 拼多多渠道订单返回体。
* shopId 为 channel_pdd_shop.id;shopName 为展示用 mall_name。
*/
@Data
public class PddOrderVO {
@@ -13,9 +17,11 @@ public class PddOrderVO {
private Long companyId;
/** 渠道店铺 ID(channel_pdd_shop.id) */
private Long shopId;
private Long pddAuthId;
/** 渠道店铺名称(channel_pdd_shop.mall_name) */
private String shopName;
private String orderSn;
@@ -21,20 +21,32 @@ import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.model.po.PddOrderPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.model.vo.PddOrderItemVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.model.vo.PddOrderVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.service.PddOrderService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.shop.mapper.PddShopMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.shop.model.po.PddShopPO;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
/** 拼多多渠道订单 CRUD;列表/详情补全渠道店铺展示名。 */
@Service
public class PddOrderServiceImpl extends ServiceImpl<PddOrderMapper, PddOrderPO> implements PddOrderService {
private final PddOrderItemMapper pddOrderItemMapper;
private final PddShopMapper pddShopMapper;
private final CurrentUserContext currentUserContext;
public PddOrderServiceImpl(PddOrderItemMapper pddOrderItemMapper, CurrentUserContext currentUserContext) {
public PddOrderServiceImpl(PddOrderItemMapper pddOrderItemMapper,
PddShopMapper pddShopMapper,
CurrentUserContext currentUserContext) {
this.pddOrderItemMapper = pddOrderItemMapper;
this.pddShopMapper = pddShopMapper;
this.currentUserContext = currentUserContext;
}
@@ -62,7 +74,7 @@ public class PddOrderServiceImpl extends ServiceImpl<PddOrderMapper, PddOrderPO>
items.forEach(pddOrderItemMapper::insert);
}
return convertToVO(order);
return toVoWithShop(order);
}
@Override
@@ -100,7 +112,7 @@ public class PddOrderServiceImpl extends ServiceImpl<PddOrderMapper, PddOrderPO>
items.forEach(pddOrderItemMapper::insert);
}
return convertToVO(order);
return toVoWithShop(order);
}
@Override
@@ -169,6 +181,7 @@ public class PddOrderServiceImpl extends ServiceImpl<PddOrderMapper, PddOrderPO>
List<PddOrderVO> voList = result.getRecords().stream()
.map(this::convertToVO)
.collect(Collectors.toList());
fillShopNames(voList);
return PageResultVO.create(voList, result.getTotal(),
(int) pageQueryDTO.getPage(), (int) pageQueryDTO.getPageSize());
@@ -180,7 +193,43 @@ public class PddOrderServiceImpl extends ServiceImpl<PddOrderMapper, PddOrderPO>
if (order == null) {
throw new BusinessException("订单不存在");
}
return convertToVO(order);
return toVoWithShop(order);
}
private PddOrderVO toVoWithShop(PddOrderPO order) {
PddOrderVO vo = convertToVO(order);
fillShopNames(Collections.singletonList(vo));
return vo;
}
/** 按渠道店铺 ID 批量补全 shopName,避免列表 N+1。 */
private void fillShopNames(List<PddOrderVO> vos) {
if (vos == null || vos.isEmpty()) {
return;
}
Set<Long> shopIds = new HashSet<>();
for (PddOrderVO vo : vos) {
if (vo.getShopId() != null) {
shopIds.add(vo.getShopId());
}
}
if (shopIds.isEmpty()) {
return;
}
Map<Long, PddShopPO> shopMap = pddShopMapper.selectList(
new LambdaQueryWrapper<PddShopPO>().in(PddShopPO::getId, shopIds))
.stream()
.filter(Objects::nonNull)
.collect(Collectors.toMap(PddShopPO::getId, Function.identity(), (a, b) -> a));
for (PddOrderVO vo : vos) {
if (vo.getShopId() == null) {
continue;
}
PddShopPO shop = shopMap.get(vo.getShopId());
if (shop != null) {
vo.setShopName(shop.getMallName());
}
}
}
private PddOrderItemPO convertToItemPO(CreatePddOrderItemDTO dto, Long orderId, Long companyId, String orderSn) {
@@ -46,14 +46,14 @@ public class PddOrderIncrementalSyncJob {
if (!done.add(shop.getId())) {
continue;
}
if (fullSyncTaskService.isIncrementalPaused(shop.getId())) {
log.debug("跳过出错暂停的增量店铺 shopId={}", shop.getId());
if (fullSyncTaskService.isIncrementalPaused(shop.getExternalShopId())) {
log.debug("跳过出错暂停的增量店铺 channelShopId={}", shop.getExternalShopId());
continue;
}
try {
syncPublisher.publishInc(shop.getCompanyId(), shop.getId());
syncPublisher.publishInc(shop.getCompanyId(), shop.getExternalShopId());
} catch (Exception e) {
log.warn("投递增量同步失败 shopId={}: {}", shop.getId(), e.getMessage());
log.warn("投递增量同步失败 channelShopId={}: {}", shop.getExternalShopId(), e.getMessage());
}
}
}
@@ -8,6 +8,8 @@ import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
/**
* 一次同步所需的店铺/授权上下文。
* shopId = channel_pdd_shop.id(写入渠道表与本模块 MQ);
* internalShopId = ec_shop.id(增量开关、ec_order、BI)。
*/
@Data
@Builder
@@ -17,7 +19,10 @@ public class PddOrderSyncShopContext {
private PddShopPO pddShop;
private PddAuthPO auth;
private Long companyId;
/** 渠道店铺 ID(channel_pdd_shop.id) */
private Long shopId;
/** 内部店铺 ID(ec_shop.id) */
private Long internalShopId;
private Long mallId;
private String accessToken;
}
@@ -25,9 +25,6 @@ public class PddOrderIncSyncPO {
@TableField("shop_id")
private Long shopId;
@TableField("pdd_auth_id")
private Long pddAuthId;
@TableField("last_cursor_at")
private LocalDateTime lastCursorAt;
@@ -1,9 +1,12 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po.PddOrderFullSyncTaskPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.vo.PddOrderFullSyncTaskVO;
import top.xyquan.ecomdmbbackend.modules.ec.shop.mapper.ShopMapper;
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
import top.xyquan.ecomdmbbackend.modules.notify.sse.RealtimeSseEvents;
import top.xyquan.ecomdmbbackend.modules.notify.sse.RealtimeSseService;
@@ -17,6 +20,7 @@ import java.util.Map;
public class PddOrderFullSyncProgressPublisher {
private final RealtimeSseService realtimeSseService;
private final ShopMapper shopMapper;
public void publish(PddOrderFullSyncTaskPO task) {
if (task == null || task.getCompanyId() == null) {
@@ -37,10 +41,18 @@ public class PddOrderFullSyncProgressPublisher {
}
}
private static PddOrderFullSyncTaskVO toVo(PddOrderFullSyncTaskPO task) {
private PddOrderFullSyncTaskVO toVo(PddOrderFullSyncTaskPO task) {
Long apiShopId = task.getShopId();
ShopPO shop = shopMapper.selectOne(new LambdaQueryWrapper<ShopPO>()
.eq(ShopPO::getCompanyId, task.getCompanyId())
.eq(ShopPO::getExternalShopId, task.getShopId())
.last("LIMIT 1"));
if (shop != null) {
apiShopId = shop.getId();
}
return PddOrderFullSyncTaskVO.builder()
.id(task.getId())
.shopId(task.getShopId())
.shopId(apiShopId)
.dateFrom(task.getDateFrom())
.dateTo(task.getDateTo())
.currentDate(task.getCurrentDate())
@@ -81,7 +81,7 @@ public class PddOrderFullSyncTaskService {
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(dto.getShopId());
PddOrderFullSyncTaskPO active = taskMapper.selectOne(new LambdaQueryWrapper<PddOrderFullSyncTaskPO>()
.eq(PddOrderFullSyncTaskPO::getShopId, dto.getShopId())
.eq(PddOrderFullSyncTaskPO::getShopId, ctx.getShopId())
.in(PddOrderFullSyncTaskPO::getStatus,
PddOrderFullSyncTaskPO.STATUS_PENDING, PddOrderFullSyncTaskPO.STATUS_RUNNING)
.orderByDesc(PddOrderFullSyncTaskPO::getId)
@@ -107,7 +107,7 @@ public class PddOrderFullSyncTaskService {
Long taskId = task.getId();
scheduleAfterCommit(taskId);
progressPublisher.publish(task);
return toVo(task);
return toVo(task, ctx.getInternalShopId());
}
private void insertDayRows(PddOrderFullSyncTaskPO task) {
@@ -172,19 +172,21 @@ public class PddOrderFullSyncTaskService {
.eq(PddOrderFullSyncTaskPO::getShopId, ctx.getShopId())
.orderByDesc(PddOrderFullSyncTaskPO::getId)
.last("LIMIT " + lim));
return tasks.stream().map(PddOrderFullSyncTaskService::toVo).collect(Collectors.toList());
return tasks.stream()
.map(t -> toVo(t, ctx.getInternalShopId()))
.collect(Collectors.toList());
}
public PddOrderFullSyncTaskVO getTask(Long taskId) {
PddOrderFullSyncTaskPO task = requireOwnedTask(taskId);
return toVo(task);
return toVo(task, resolveApiShopId(task));
}
/** 进行中优先,否则该店最近一次全量任务。 */
public PddOrderFullSyncTaskVO latestTask(Long shopId) {
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(shopId);
PddOrderFullSyncTaskPO task = findLatestTask(ctx.getCompanyId(), ctx.getShopId());
return task == null ? null : toVo(task);
return task == null ? null : toVo(task, ctx.getInternalShopId());
}
@Transactional(rollbackFor = Exception.class)
@@ -203,7 +205,7 @@ public class PddOrderFullSyncTaskService {
task.setLastError(null);
taskMapper.updateById(task);
progressPublisher.publish(task);
return toVo(task);
return toVo(task, resolveApiShopId(task));
}
@Transactional(rollbackFor = Exception.class)
@@ -243,7 +245,7 @@ public class PddOrderFullSyncTaskService {
scheduleAfterCommit(task.getId());
progressPublisher.publish(task);
return toVo(task);
return toVo(task, resolveApiShopId(task));
}
public List<PddOrderSyncShopStatusVO> batchStatus(List<Long> shopIds) {
@@ -266,8 +268,13 @@ public class PddOrderFullSyncTaskService {
Map<Long, ShopPO> shopMap = shops.stream()
.collect(Collectors.toMap(ShopPO::getId, s -> s, (a, b) -> a));
Map<Long, PddOrderFullSyncTaskPO> latestByShop = loadLatestTasksByShop(companyId, owned);
Map<Long, PddOrderIncSyncPO> incByShop = loadIncStatesByShop(owned);
Map<Long, Long> ecToChannel = shops.stream()
.filter(s -> s.getExternalShopId() != null)
.collect(Collectors.toMap(ShopPO::getId, ShopPO::getExternalShopId, (a, b) -> a));
Set<Long> channelIds = new HashSet<>(ecToChannel.values());
Map<Long, PddOrderFullSyncTaskPO> latestByChannel = loadLatestTasksByShop(companyId, channelIds);
Map<Long, PddOrderIncSyncPO> incByChannel = loadIncStatesByShop(channelIds);
List<PddOrderSyncShopStatusVO> result = new ArrayList<>();
for (Long shopId : distinctIds) {
@@ -275,12 +282,13 @@ public class PddOrderFullSyncTaskService {
continue;
}
ShopPO shop = shopMap.get(shopId);
PddOrderFullSyncTaskPO full = latestByShop.get(shopId);
PddOrderIncSyncPO inc = incByShop.get(shopId);
Long channelId = ecToChannel.get(shopId);
PddOrderFullSyncTaskPO full = channelId == null ? null : latestByChannel.get(channelId);
PddOrderIncSyncPO inc = channelId == null ? null : incByChannel.get(channelId);
boolean enabled = shop != null && Integer.valueOf(1).equals(shop.getOrderIncSyncEnabled());
result.add(PddOrderSyncShopStatusVO.builder()
.shopId(shopId)
.fullTask(full == null ? null : toVo(full))
.fullTask(full == null ? null : toVo(full, shopId))
.incremental(toIncVo(shopId, enabled, inc))
.build());
}
@@ -290,7 +298,7 @@ public class PddOrderFullSyncTaskService {
@Transactional(rollbackFor = Exception.class)
public PddOrderIncrementalStatusVO toggleIncremental(PddOrderIncrementalToggleDTO dto) {
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(dto.getShopId());
ShopPO shop = shopMapper.selectById(ctx.getShopId());
ShopPO shop = shopMapper.selectById(ctx.getInternalShopId());
if (shop == null) {
throw new BusinessException("店铺不存在");
}
@@ -304,15 +312,15 @@ public class PddOrderFullSyncTaskService {
state.setLastError(null);
incSyncMapper.updateById(state);
}
return incrementalStatus(ctx.getShopId());
return incrementalStatus(ctx.getInternalShopId());
}
public PddOrderIncrementalStatusVO incrementalStatus(Long shopId) {
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(shopId);
ShopPO shop = shopMapper.selectById(ctx.getShopId());
ShopPO shop = shopMapper.selectById(ctx.getInternalShopId());
PddOrderIncSyncPO state = findIncState(ctx.getShopId());
boolean enabled = shop != null && Integer.valueOf(1).equals(shop.getOrderIncSyncEnabled());
return toIncVo(shopId, enabled, state);
return toIncVo(ctx.getInternalShopId(), enabled, state);
}
public boolean isIncrementalEnabled(Long shopId) {
@@ -320,8 +328,9 @@ public class PddOrderFullSyncTaskService {
return shop != null && Integer.valueOf(1).equals(shop.getOrderIncSyncEnabled());
}
public boolean isIncrementalPaused(Long shopId) {
PddOrderIncSyncPO state = findIncState(shopId);
/** @param channelShopId channel_pdd_shop.id */
public boolean isIncrementalPaused(Long channelShopId) {
PddOrderIncSyncPO state = findIncState(channelShopId);
return state != null && Integer.valueOf(PddOrderIncSyncPO.STATUS_PAUSED).equals(state.getStatus());
}
@@ -330,7 +339,7 @@ public class PddOrderFullSyncTaskService {
if (task == null) {
throw new BusinessException("全量同步任务不存在");
}
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(task.getShopId());
PddOrderSyncShopContext ctx = contextResolver.resolveByChannelShopId(task.getCompanyId(), task.getShopId());
if (!ctx.getCompanyId().equals(task.getCompanyId())) {
throw new BusinessException("无权操作该任务");
}
@@ -411,7 +420,6 @@ public class PddOrderFullSyncTaskService {
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);
@@ -448,10 +456,26 @@ public class PddOrderFullSyncTaskService {
return HEALTH_OK;
}
private Long resolveApiShopId(PddOrderFullSyncTaskPO task) {
if (task == null || task.getShopId() == null) {
return null;
}
ShopPO shop = shopMapper.selectOne(new LambdaQueryWrapper<ShopPO>()
.eq(ShopPO::getCompanyId, task.getCompanyId())
.eq(ShopPO::getExternalShopId, task.getShopId())
.last("LIMIT 1"));
return shop != null ? shop.getId() : task.getShopId();
}
private static PddOrderFullSyncTaskVO toVo(PddOrderFullSyncTaskPO task) {
return toVo(task, task.getShopId());
}
/** @param apiShopId 对前端暴露的店铺 ID(内部 ec_shop.id) */
private static PddOrderFullSyncTaskVO toVo(PddOrderFullSyncTaskPO task, Long apiShopId) {
return PddOrderFullSyncTaskVO.builder()
.id(task.getId())
.shopId(task.getShopId())
.shopId(apiShopId)
.dateFrom(task.getDateFrom())
.dateTo(task.getDateTo())
.currentDate(task.getCurrentDate())
@@ -29,13 +29,35 @@ public class PddOrderSyncAuthFailureHandler {
private final PddShopMapper pddShopMapper;
private final PddOrderIncSyncMapper incSyncMapper;
/**
* @param internalShopId 内部店 ec_shop.id(可空)
* @param channelShopId 渠道店 channel_pdd_shop.id(可空;与 internal 至少其一)
*/
@Transactional(rollbackFor = Exception.class)
public void handle(Long companyId, Long shopId, Long authId, String error) {
public void handle(Long companyId, Long internalShopId, Long channelShopId, Long authId, String error) {
String msg = truncate(error, 900);
log.warn("拼多多同步授权失效处置 companyId={} shopId={} authId={} err={}",
companyId, shopId, authId, msg);
log.warn("拼多多同步授权失效处置 companyId={} internalShopId={} channelShopId={} authId={} err={}",
companyId, internalShopId, channelShopId, authId, msg);
Long resolvedAuthId = authId != null ? authId : resolveAuthId(companyId, shopId);
Long resolvedInternal = internalShopId;
Long resolvedChannel = channelShopId;
if (resolvedInternal != null && resolvedChannel == null) {
ShopPO shop = shopMapper.selectById(resolvedInternal);
if (shop != null) {
resolvedChannel = shop.getExternalShopId();
}
}
if (resolvedChannel != null && resolvedInternal == null) {
ShopPO shop = shopMapper.selectOne(new LambdaQueryWrapper<ShopPO>()
.eq(companyId != null, ShopPO::getCompanyId, companyId)
.eq(ShopPO::getExternalShopId, resolvedChannel)
.last("LIMIT 1"));
if (shop != null) {
resolvedInternal = shop.getId();
}
}
Long resolvedAuthId = authId != null ? authId : resolveAuthId(companyId, resolvedChannel);
if (resolvedAuthId != null) {
pddAuthMapper.update(null, new LambdaUpdateWrapper<PddAuthPO>()
.eq(PddAuthPO::getId, resolvedAuthId)
@@ -43,27 +65,25 @@ public class PddOrderSyncAuthFailureHandler {
.set(PddAuthPO::getStatus, 0));
}
if (shopId != null) {
if (resolvedInternal != null) {
shopMapper.update(null, new LambdaUpdateWrapper<ShopPO>()
.eq(ShopPO::getId, shopId)
.eq(ShopPO::getId, resolvedInternal)
.eq(companyId != null, ShopPO::getCompanyId, companyId)
.set(ShopPO::getOrderIncSyncEnabled, 0));
}
if (resolvedChannel != null && companyId != null) {
PddOrderIncSyncPO state = incSyncMapper.selectOne(new LambdaQueryWrapper<PddOrderIncSyncPO>()
.eq(PddOrderIncSyncPO::getShopId, shopId)
.eq(PddOrderIncSyncPO::getShopId, resolvedChannel)
.last("LIMIT 1"));
if (state != null) {
state.setStatus(PddOrderIncSyncPO.STATUS_PAUSED);
state.setLastError(msg != null ? msg : "拼多多授权失效,请重新授权");
if (resolvedAuthId != null) {
state.setPddAuthId(resolvedAuthId);
}
incSyncMapper.updateById(state);
} else if (companyId != null) {
} else {
PddOrderIncSyncPO neu = new PddOrderIncSyncPO();
neu.setCompanyId(companyId);
neu.setShopId(shopId);
neu.setPddAuthId(resolvedAuthId);
neu.setShopId(resolvedChannel);
neu.setStatus(PddOrderIncSyncPO.STATUS_PAUSED);
neu.setLastError(msg != null ? msg : "拼多多授权失效,请重新授权");
incSyncMapper.insert(neu);
@@ -71,19 +91,13 @@ public class PddOrderSyncAuthFailureHandler {
}
}
private Long resolveAuthId(Long companyId, Long shopId) {
if (shopId == null) {
return null;
}
ShopPO shop = shopMapper.selectById(shopId);
if (shop == null || shop.getExternalShopId() == null) {
return null;
}
if (companyId != null && !companyId.equals(shop.getCompanyId())) {
private Long resolveAuthId(Long companyId, Long channelShopId) {
if (channelShopId == null) {
return null;
}
PddShopPO pddShop = pddShopMapper.selectOne(new LambdaQueryWrapper<PddShopPO>()
.eq(PddShopPO::getId, shop.getExternalShopId())
.eq(PddShopPO::getId, channelShopId)
.eq(companyId != null, PddShopPO::getCompanyId, companyId)
.last("LIMIT 1"));
return pddShop != null ? pddShop.getPddAuthId() : null;
}
@@ -14,6 +14,11 @@ import top.xyquan.ecomdmbbackend.modules.ec.shop.mapper.ShopMapper;
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
/**
* 解析同步上下文。
* API 入参:内部店 {@code ec_shop.id};
* MQ / 渠道表:渠道店 {@code channel_pdd_shop.id}。
*/
@Service
public class PddOrderSyncContextResolver {
@@ -32,16 +37,17 @@ public class PddOrderSyncContextResolver {
this.authTokenService = authTokenService;
}
public PddOrderSyncShopContext resolveForCurrentCompany(Long shopId) {
Long companyId = currentUserContext.getCurrentCompanyId();
return resolve(companyId, shopId);
/** 当前公司 + 内部店铺 ID(API) */
public PddOrderSyncShopContext resolveForCurrentCompany(Long internalShopId) {
return resolveByInternalShopId(currentUserContext.getCurrentCompanyId(), internalShopId);
}
public PddOrderSyncShopContext resolve(Long companyId, Long shopId) {
if (shopId == null) {
/** 按内部店铺 ID 解析(ec_shop.id) */
public PddOrderSyncShopContext resolveByInternalShopId(Long companyId, Long internalShopId) {
if (internalShopId == null) {
throw new BusinessException("店铺 ID 不能为空");
}
ShopPO shop = shopMapper.selectById(shopId);
ShopPO shop = shopMapper.selectById(internalShopId);
if (shop == null || !companyId.equals(shop.getCompanyId())) {
throw new BusinessException("内部店铺不存在或不属于当前公司");
}
@@ -51,15 +57,33 @@ public class PddOrderSyncContextResolver {
if (shop.getExternalShopId() == null) {
throw new PddAuthFailureException("店铺尚未绑定拼多多外部店,请先完成授权");
}
return buildContext(companyId, shop, shop.getExternalShopId());
}
/** 按渠道店铺 ID 解析(channel_pdd_shop.id;MQ / 任务表) */
public PddOrderSyncShopContext resolveByChannelShopId(Long companyId, Long channelShopId) {
if (channelShopId == null) {
throw new BusinessException("渠道店铺 ID 不能为空");
}
ShopPO shop = shopMapper.selectOne(new LambdaQueryWrapper<ShopPO>()
.eq(ShopPO::getCompanyId, companyId)
.eq(ShopPO::getPlatformCode, PlatformCode.PDD.getCode())
.eq(ShopPO::getExternalShopId, channelShopId)
.last("LIMIT 1"));
if (shop == null) {
throw new BusinessException("未找到绑定该拼多多店的内部店铺");
}
return buildContext(companyId, shop, channelShopId);
}
private PddOrderSyncShopContext buildContext(Long companyId, ShopPO shop, Long channelShopId) {
PddShopPO pddShop = pddShopMapper.selectOne(new LambdaQueryWrapper<PddShopPO>()
.eq(PddShopPO::getId, shop.getExternalShopId())
.eq(PddShopPO::getId, channelShopId)
.eq(PddShopPO::getCompanyId, companyId)
.last("LIMIT 1"));
if (pddShop == null || pddShop.getPddAuthId() == null) {
throw new PddAuthFailureException("未找到拼多多店铺授权绑定,请重新授权");
}
// access 将过期则自动 refresh;真正失效看 refresh_token
PddAuthPO auth = authTokenService.ensureUsableById(pddShop.getPddAuthId());
return PddOrderSyncShopContext.builder()
@@ -67,7 +91,8 @@ public class PddOrderSyncContextResolver {
.pddShop(pddShop)
.auth(auth)
.companyId(companyId)
.shopId(shopId)
.shopId(pddShop.getId())
.internalShopId(shop.getId())
.mallId(pddShop.getMallId())
.accessToken(auth.getAccessToken())
.build();
@@ -107,7 +107,7 @@ public class PddOrderSyncService {
}
return PddOrderSyncResultVO.builder()
.mode("bootstrap")
.shopId(ctx.getShopId())
.shopId(ctx.getInternalShopId())
.fetchedCount(fetched)
.upsertedCount(upserted)
.skippedCount(Math.max(fetched - upserted, 0))
@@ -120,18 +120,19 @@ public class PddOrderSyncService {
try {
ctx = contextResolver.resolveForCurrentCompany(shopId);
} catch (PddAuthFailureException e) {
onAuthFailure(null, shopId, null, e);
onAuthFailureInternal(null, shopId, null, e);
throw e;
}
return withIncLock(ctx.getShopId(), () -> doIncremental(ctx));
}
public PddOrderSyncResultVO syncIncrementalInternal(Long companyId, Long shopId) {
/** MQ 消费:shopId = channel_pdd_shop.id */
public PddOrderSyncResultVO syncIncrementalInternal(Long companyId, Long channelShopId) {
PddOrderSyncShopContext ctx;
try {
ctx = contextResolver.resolve(companyId, shopId);
ctx = contextResolver.resolveByChannelShopId(companyId, channelShopId);
} catch (PddAuthFailureException e) {
onAuthFailure(companyId, shopId, null, e);
onAuthFailureChannel(companyId, channelShopId, null, e);
throw e;
}
return withIncLock(ctx.getShopId(), () -> doIncremental(ctx));
@@ -175,7 +176,7 @@ public class PddOrderSyncService {
notifyListeners(ctx, upsertedIds, "repair");
return PddOrderSyncResultVO.builder()
.mode("repair")
.shopId(ctx.getShopId())
.shopId(ctx.getInternalShopId())
.fetchedCount(fetched)
.upsertedCount(upserted)
.skippedCount(skipped)
@@ -190,12 +191,13 @@ public class PddOrderSyncService {
.isNotNull(ShopPO::getExternalShopId));
}
public PddOrderSyncResultVO syncByConfirmDateForTask(Long companyId, Long shopId, LocalDate day, Long taskId) {
/** MQ / 全量任务:shopId = channel_pdd_shop.id */
public PddOrderSyncResultVO syncByConfirmDateForTask(Long companyId, Long channelShopId, LocalDate day, Long taskId) {
PddOrderSyncShopContext ctx;
try {
ctx = contextResolver.resolve(companyId, shopId);
ctx = contextResolver.resolveByChannelShopId(companyId, channelShopId);
} catch (PddAuthFailureException e) {
onAuthFailure(companyId, shopId, null, e);
onAuthFailureChannel(companyId, channelShopId, null, e);
throw e;
}
return withFullDayLock(ctx.getShopId(), day,
@@ -272,7 +274,7 @@ public class PddOrderSyncService {
}
return PddOrderSyncResultVO.builder()
.mode(mode)
.shopId(ctx.getShopId())
.shopId(ctx.getInternalShopId())
.fetchedCount(fetched)
.upsertedCount(upserted)
.skippedCount(Math.max(fetched - upserted, 0))
@@ -377,7 +379,7 @@ public class PddOrderSyncService {
return PddOrderSyncResultVO.builder()
.mode("incremental")
.shopId(ctx.getShopId())
.shopId(ctx.getInternalShopId())
.fetchedCount(fetched)
.upsertedCount(upserted)
.skippedCount(Math.max(fetched - upserted, 0))
@@ -395,7 +397,6 @@ public class PddOrderSyncService {
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);
@@ -408,7 +409,6 @@ public class PddOrderSyncService {
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);
}
@@ -426,14 +426,27 @@ public class PddOrderSyncService {
private void onAuthFailure(PddOrderSyncShopContext ctx, PddAuthFailureException e) {
Long authId = ctx.getAuth() != null ? ctx.getAuth().getId() : null;
onAuthFailure(ctx.getCompanyId(), ctx.getShopId(), authId, e);
try {
authFailureHandler.handle(
ctx.getCompanyId(), ctx.getInternalShopId(), ctx.getShopId(), authId, e.getMessage());
} catch (Exception ex) {
log.warn("授权失效处置失败 channelShopId={}: {}", ctx.getShopId(), ex.getMessage());
}
}
private void onAuthFailure(Long companyId, Long shopId, Long authId, PddAuthFailureException e) {
private void onAuthFailureInternal(Long companyId, Long internalShopId, Long authId, PddAuthFailureException e) {
try {
authFailureHandler.handle(companyId, shopId, authId, e.getMessage());
authFailureHandler.handle(companyId, internalShopId, null, authId, e.getMessage());
} catch (Exception ex) {
log.warn("授权失效处置失败 shopId={}: {}", shopId, ex.getMessage());
log.warn("授权失效处置失败 internalShopId={}: {}", internalShopId, ex.getMessage());
}
}
private void onAuthFailureChannel(Long companyId, Long channelShopId, Long authId, PddAuthFailureException e) {
try {
authFailureHandler.handle(companyId, null, channelShopId, authId, e.getMessage());
} catch (Exception ex) {
log.warn("授权失效处置失败 channelShopId={}: {}", channelShopId, ex.getMessage());
}
}
@@ -77,7 +77,6 @@ public class PddOrderUpsertService {
PddOrderPO order = existing != null ? existing : new PddOrderPO();
order.setCompanyId(ctx.getCompanyId());
order.setShopId(ctx.getShopId());
order.setPddAuthId(ctx.getAuth().getId());
order.setOrderSn(snapshot.getOrderSn());
order.setOrderStatus(snapshot.getOrderStatus() != null ? snapshot.getOrderStatus() : 0);
order.setRefundStatus(snapshot.getRefundStatus());
@@ -36,9 +36,6 @@ public class OrderPO {
@TableField("source")
private String source;
@TableField("source_order_id")
private Long sourceOrderId;
@TableField("pay_amount")
private BigDecimal payAmount;