refactor: 把内部店和渠道店的绑定关联放到渠道侧去

This commit is contained in:
2026-08-21 11:50:50 +08:00
parent 7e4b0d3e55
commit e030ca6e0a
23 changed files with 344 additions and 148 deletions
@@ -2,15 +2,16 @@
-- 拼多多店铺对接数据库设计
-- 数据来源:pdd.mall.info.get → mall_info_get_response
-- 设计原则:
-- 1. 与 ec_shop(内部店铺)分离,本表只存拼多多平台店铺镜像
-- 2. 不主动 FK 关联 ec_shop;绑定由 ec_shop.platform_code + external_shop_id(= channel_pdd_shop.id)维护
-- 3. 授权后写入本表,再把本表主键写入 ec_shop.external_shop_id
-- 1. 与 ec_shop(内部经营店)分离,本表只存拼多多平台店铺镜像 + 授权
-- 2. 绑定方向:ec_shop_id → ec_shop.id(渠道依赖核心;一对一 UNIQUE)
-- 3. 授权成功后写入/改绑本表 ec_shop_id;列表「是否已授权」由应用层按 ec_shop_id 反查组装
-- ========================================
DROP TABLE IF EXISTS `channel_pdd_shop`;
CREATE TABLE `channel_pdd_shop` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
`ec_shop_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '绑定的内部经营店(ec_shop.id);未绑定可空',
`pdd_auth_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '拼多多授权ID(channel_pdd_auth.id)',
`mall_id` bigint UNSIGNED NOT NULL COMMENT '拼多多店铺ID(mall_id)',
`mall_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '店铺名称(mall_name)',
@@ -24,6 +25,8 @@ CREATE TABLE `channel_pdd_shop` (
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uk_channel_pdd_shop_company_mall`(`company_id` ASC, `mall_id` ASC) USING BTREE,
UNIQUE INDEX `uk_channel_pdd_shop_auth`(`pdd_auth_id` ASC) USING BTREE COMMENT '一个授权对应一个拼多多店铺',
UNIQUE INDEX `uk_channel_pdd_shop_ec_shop`(`ec_shop_id` ASC) USING BTREE COMMENT '一个内部店最多绑一个拼多多渠道店(NULL 可重复)',
CONSTRAINT `fk_channel_pdd_shop_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_channel_pdd_shop_ec_shop` FOREIGN KEY (`ec_shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_channel_pdd_shop_auth` FOREIGN KEY (`pdd_auth_id`) REFERENCES `channel_pdd_auth` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '拼多多-店铺信息表' ROW_FORMAT = Dynamic;
@@ -14,14 +14,12 @@ CREATE TABLE `ec_shop` (
`logo_image_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT 'logo图片ID',
`logo_url` varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT 'logo外链URL(渠道授权等;查询时有 logo_image_id 则覆盖)',
`platform_code` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '平台代码(软约定枚举,无平台表)',
`external_shop_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '外部/平台店铺表主键ID(如 channel_pdd_shop.id;与 platform_code 组合关联)',
`order_inc_sync_enabled` tinyint NOT NULL DEFAULT 0 COMMENT '订单增量同步开关:0关 1开(产品配置,与渠道运行态分离)',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人ID',
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人ID',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uk_ec_shop_company_platform_external`(`company_id` ASC, `platform_code` ASC, `external_shop_id` ASC) USING BTREE COMMENT '同一公司同一平台下平台店铺主键唯一(NULL 可重复,手工店)',
INDEX `idx_company_id`(`company_id` ASC) USING BTREE,
INDEX `idx_platform_code`(`platform_code` ASC) USING BTREE,
INDEX `idx_ec_shop_order_inc_sync`(`platform_code` ASC, `order_inc_sync_enabled` ASC) USING BTREE COMMENT '增量同步 Job 扫描',
@@ -0,0 +1,147 @@
-- 店铺绑定迁到渠道侧:channel_pdd_shop.ec_shop_id → ec_shop.id;去掉 ec_shop.external_shop_id
DROP PROCEDURE IF EXISTS `tmp_add_col_if_missing`;
DROP PROCEDURE IF EXISTS `tmp_drop_idx_if_exists`;
DROP PROCEDURE IF EXISTS `tmp_drop_col_if_exists`;
DROP PROCEDURE IF EXISTS `tmp_add_uk_if_missing`;
DROP PROCEDURE IF EXISTS `tmp_add_fk_if_missing`;
DELIMITER $$
CREATE PROCEDURE `tmp_add_col_if_missing`(
IN p_table VARCHAR(64),
IN p_column VARCHAR(64),
IN p_ddl TEXT
)
BEGIN
IF NOT EXISTS (
SELECT 1 FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = p_table
AND COLUMN_NAME = p_column
) THEN
SET @sql = CONCAT('ALTER TABLE `', p_table, '` ', p_ddl);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END$$
CREATE PROCEDURE `tmp_drop_idx_if_exists`(
IN p_table VARCHAR(64),
IN p_index VARCHAR(64)
)
BEGIN
IF EXISTS (
SELECT 1 FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = p_table
AND INDEX_NAME = p_index
) THEN
SET @sql = CONCAT('ALTER TABLE `', p_table, '` DROP INDEX `', p_index, '`');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END$$
CREATE PROCEDURE `tmp_drop_col_if_exists`(
IN p_table VARCHAR(64),
IN p_column VARCHAR(64)
)
BEGIN
IF EXISTS (
SELECT 1 FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = p_table
AND COLUMN_NAME = p_column
) THEN
SET @sql = CONCAT('ALTER TABLE `', p_table, '` DROP COLUMN `', p_column, '`');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END$$
CREATE PROCEDURE `tmp_add_uk_if_missing`(
IN p_table VARCHAR(64),
IN p_index VARCHAR(64),
IN p_cols VARCHAR(255)
)
BEGIN
IF NOT EXISTS (
SELECT 1 FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = p_table
AND INDEX_NAME = p_index
) THEN
SET @sql = CONCAT('ALTER TABLE `', p_table, '` ADD UNIQUE INDEX `', p_index, '`(', p_cols, ')');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END$$
CREATE PROCEDURE `tmp_add_fk_if_missing`(
IN p_table VARCHAR(64),
IN p_fk VARCHAR(64),
IN p_ddl TEXT
)
BEGIN
IF NOT EXISTS (
SELECT 1 FROM information_schema.TABLE_CONSTRAINTS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = p_table
AND CONSTRAINT_NAME = p_fk
AND CONSTRAINT_TYPE = 'FOREIGN KEY'
) THEN
SET @sql = CONCAT('ALTER TABLE `', p_table, '` ', p_ddl);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END$$
DELIMITER ;
CALL `tmp_add_col_if_missing`(
'channel_pdd_shop',
'ec_shop_id',
'ADD COLUMN `ec_shop_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT ''绑定的内部经营店(ec_shop.id)'' AFTER `company_id`'
);
-- 从旧 external_shop_id 回填(列仍存在时;动态 SQL 避免列已删时报错)
SET @has_ext := (
SELECT COUNT(1) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'ec_shop'
AND COLUMN_NAME = 'external_shop_id'
);
SET @sql := IF(@has_ext > 0,
'UPDATE `channel_pdd_shop` cps
INNER JOIN `ec_shop` es
ON es.`external_shop_id` = cps.`id`
AND es.`company_id` = cps.`company_id`
AND es.`platform_code` = ''pdd''
SET cps.`ec_shop_id` = es.`id`
WHERE cps.`ec_shop_id` IS NULL',
'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
CALL `tmp_add_uk_if_missing`('channel_pdd_shop', 'uk_channel_pdd_shop_ec_shop', '`ec_shop_id`');
CALL `tmp_add_fk_if_missing`(
'channel_pdd_shop',
'fk_channel_pdd_shop_ec_shop',
'ADD CONSTRAINT `fk_channel_pdd_shop_ec_shop` FOREIGN KEY (`ec_shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE SET NULL ON UPDATE CASCADE'
);
CALL `tmp_drop_idx_if_exists`('ec_shop', 'uk_ec_shop_company_platform_external');
CALL `tmp_drop_col_if_exists`('ec_shop', 'external_shop_id');
DROP PROCEDURE IF EXISTS `tmp_add_col_if_missing`;
DROP PROCEDURE IF EXISTS `tmp_drop_idx_if_exists`;
DROP PROCEDURE IF EXISTS `tmp_drop_col_if_exists`;
DROP PROCEDURE IF EXISTS `tmp_add_uk_if_missing`;
DROP PROCEDURE IF EXISTS `tmp_add_fk_if_missing`;
@@ -13,11 +13,10 @@ import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.mapper.PddGoodsAdFeeD
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.po.PddGoodsAdFeeDailyPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.mapper.PddGoodsMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.po.PddGoodsPO;
import top.xyquan.ecomdmbbackend.modules.ec.platform.model.enums.PlatformCode;
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.modules.ec.shop.adfee.mapper.AdFeeMapper;
import top.xyquan.ecomdmbbackend.modules.ec.shop.adfee.model.po.AdFeePO;
import top.xyquan.ecomdmbbackend.modules.ec.shop.mapper.ShopMapper;
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
import java.math.BigDecimal;
import java.util.List;
@@ -36,20 +35,20 @@ public class PddGoodsAdFeeConvertService {
private final PddGoodsAdFeeDailyMapper channelAdFeeMapper;
private final PddGoodsAdFeeImportItemMapper importItemMapper;
private final PddGoodsMapper pddGoodsMapper;
private final ShopMapper shopMapper;
private final PddShopMapper pddShopMapper;
private final AdFeeMapper adFeeMapper;
private final TransactionTemplate transactionTemplate;
public PddGoodsAdFeeConvertService(PddGoodsAdFeeDailyMapper channelAdFeeMapper,
PddGoodsAdFeeImportItemMapper importItemMapper,
PddGoodsMapper pddGoodsMapper,
ShopMapper shopMapper,
PddShopMapper pddShopMapper,
AdFeeMapper adFeeMapper,
PlatformTransactionManager transactionManager) {
this.channelAdFeeMapper = channelAdFeeMapper;
this.importItemMapper = importItemMapper;
this.pddGoodsMapper = pddGoodsMapper;
this.shopMapper = shopMapper;
this.pddShopMapper = pddShopMapper;
this.adFeeMapper = adFeeMapper;
this.transactionTemplate = new TransactionTemplate(transactionManager);
}
@@ -120,12 +119,11 @@ public class PddGoodsAdFeeConvertService {
}
private Long resolveInternalShopId(Long companyId, Long channelShopId) {
ShopPO shop = shopMapper.selectOne(new LambdaQueryWrapper<ShopPO>()
.eq(ShopPO::getCompanyId, companyId)
.eq(ShopPO::getExternalShopId, channelShopId)
.eq(ShopPO::getPlatformCode, PlatformCode.PDD.getCode())
PddShopPO pddShop = pddShopMapper.selectOne(new LambdaQueryWrapper<PddShopPO>()
.eq(PddShopPO::getId, channelShopId)
.eq(PddShopPO::getCompanyId, companyId)
.last("LIMIT 1"));
return shop != null ? shop.getId() : null;
return pddShop != null ? pddShop.getEcShopId() : null;
}
private void upsertInternalAdFee(PddGoodsAdFeeDailyPO channelFee,
@@ -306,7 +306,7 @@ public class PddAuthServiceImpl implements PddAuthService {
}
/**
* 将 channel_pdd_shop 主键写入指定内部店铺的 external_shop_id;若已被其他内部店占用则先解绑再改绑。
* 将指定内部店写入 channel_pdd_shop.ec_shop_id;若该渠道店或内部店已被其他绑定占用则先解绑再改绑。
*/
private void bindInternalShop(Long companyId,
Long userId,
@@ -322,31 +322,40 @@ public class PddAuthServiceImpl implements PddAuthService {
throw new BusinessException("内部店铺不是拼多多平台,无法绑定");
}
// 同一公司+平台下外部店主键唯一:若已被其他内部店占用则解绑
ShopPO occupied = shopMapper.selectOne(new LambdaQueryWrapper<ShopPO>()
.eq(ShopPO::getCompanyId, companyId)
.eq(ShopPO::getPlatformCode, shop.getPlatformCode())
.eq(ShopPO::getExternalShopId, channelPddShopId)
.ne(ShopPO::getId, shopId)
.last("LIMIT 1"));
if (occupied != null) {
shopMapper.update(null, new LambdaUpdateWrapper<ShopPO>()
.eq(ShopPO::getId, occupied.getId())
.set(ShopPO::getExternalShopId, null)
.set(ShopPO::getUpdateBy, userId));
log.info("拼多多平台店铺 {} 从内部店 {} 解绑,改绑至 {}", channelPddShopId, occupied.getId(), shopId);
PddShopPO channelShop = pddShopMapper.selectById(channelPddShopId);
if (channelShop == null || !companyId.equals(channelShop.getCompanyId())) {
throw new BusinessException("拼多多渠道店铺不存在");
}
shop.setExternalShopId(channelPddShopId);
// 同一内部店若已绑其他渠道店,先解绑
PddShopPO boundElsewhere = pddShopMapper.selectOne(new LambdaQueryWrapper<PddShopPO>()
.eq(PddShopPO::getCompanyId, companyId)
.eq(PddShopPO::getEcShopId, shopId)
.ne(PddShopPO::getId, channelPddShopId)
.last("LIMIT 1"));
if (boundElsewhere != null) {
pddShopMapper.update(null, new LambdaUpdateWrapper<PddShopPO>()
.eq(PddShopPO::getId, boundElsewhere.getId())
.set(PddShopPO::getEcShopId, null));
log.info("内部店 {} 从拼多多渠道店 {} 解绑,改绑至 {}", shopId, boundElsewhere.getId(), channelPddShopId);
}
// 该渠道店若已绑其他内部店,改绑即可(UNIQUE(ec_shop_id))
if (channelShop.getEcShopId() != null && !shopId.equals(channelShop.getEcShopId())) {
log.info("拼多多渠道店 {} 从内部店 {} 改绑至 {}", channelPddShopId, channelShop.getEcShopId(), shopId);
}
channelShop.setEcShopId(shopId);
pddShopMapper.updateById(channelShop);
// 无系统内部 logo 时,用授权店铺 logo 填充外链(与商品渠道图口径一致)
if (shop.getLogoImageId() == null
&& !StringUtils.hasText(shop.getLogoUrl())
&& mallInfo != null
&& StringUtils.hasText(mallInfo.getLogo())) {
shop.setLogoUrl(mallInfo.getLogo().trim());
shop.setUpdateBy(userId);
shopMapper.updateById(shop);
}
shop.setUpdateBy(userId);
shopMapper.updateById(shop);
}
/**
@@ -24,6 +24,8 @@ import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.mapper.PddOrderItemMa
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.channel.pdd.shop.mapper.PddShopMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.shop.model.po.PddShopPO;
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;
@@ -36,8 +38,6 @@ 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;
@@ -73,7 +73,7 @@ public class PddOrderConvertService {
private final PlatformTransactionManager transactionManager;
private final OrderStatContributionCalculator contributionCalculator;
private final OrderStatusStatResolver orderStatusStatResolver;
private final ShopMapper shopMapper;
private final PddShopMapper pddShopMapper;
public void convert(OrderConvertMessage message) {
if (message.getMode() == OrderConvertMode.FULL_DAY) {
@@ -490,15 +490,14 @@ public class PddOrderConvertService {
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)
PddShopPO pddShop = pddShopMapper.selectOne(new LambdaQueryWrapper<PddShopPO>()
.eq(PddShopPO::getId, channelShopId)
.eq(PddShopPO::getCompanyId, companyId)
.last("LIMIT 1"));
if (shop == null) {
if (pddShop == null || pddShop.getEcShopId() == null) {
throw new BusinessException("未找到绑定该拼多多店的内部店铺,无法写入经营订单");
}
return shop.getId();
return pddShop.getEcShopId();
}
private record ConvertBatchResult(Set<LocalDate> biDates, Set<Long> pendingGoodsIds) {
@@ -7,16 +7,21 @@ import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
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.channel.pdd.shop.mapper.PddShopMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.shop.model.po.PddShopPO;
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.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* 定时将开启增量开关的店铺投入增量同步队列(与全量队列可并行)。
* 定时将开启增量开关且已绑定渠道店的店铺投入增量同步队列。
*/
@Slf4j
@Component
@@ -24,13 +29,16 @@ import java.util.Set;
public class PddOrderIncrementalSyncJob {
private final ShopMapper shopMapper;
private final PddShopMapper pddShopMapper;
private final PddOrderFullSyncTaskService fullSyncTaskService;
private final PddOrderSyncPublisher syncPublisher;
public PddOrderIncrementalSyncJob(ShopMapper shopMapper,
PddShopMapper pddShopMapper,
PddOrderFullSyncTaskService fullSyncTaskService,
PddOrderSyncPublisher syncPublisher) {
this.shopMapper = shopMapper;
this.pddShopMapper = pddShopMapper;
this.fullSyncTaskService = fullSyncTaskService;
this.syncPublisher = syncPublisher;
}
@@ -39,21 +47,33 @@ public class PddOrderIncrementalSyncJob {
public void run() {
List<ShopPO> shops = shopMapper.selectList(new LambdaQueryWrapper<ShopPO>()
.eq(ShopPO::getPlatformCode, PlatformCode.PDD.getCode())
.eq(ShopPO::getOrderIncSyncEnabled, 1)
.isNotNull(ShopPO::getExternalShopId));
.eq(ShopPO::getOrderIncSyncEnabled, 1));
if (shops.isEmpty()) {
return;
}
Map<Long, ShopPO> shopById = shops.stream()
.filter(s -> s.getId() != null)
.collect(Collectors.toMap(ShopPO::getId, Function.identity(), (a, b) -> a));
List<PddShopPO> bound = pddShopMapper.selectList(new LambdaQueryWrapper<PddShopPO>()
.in(PddShopPO::getEcShopId, shopById.keySet())
.isNotNull(PddShopPO::getEcShopId));
Set<Long> done = new HashSet<>();
for (ShopPO shop : shops) {
if (!done.add(shop.getId())) {
for (PddShopPO pddShop : bound) {
if (pddShop.getId() == null || !done.add(pddShop.getId())) {
continue;
}
if (fullSyncTaskService.isIncrementalPaused(shop.getExternalShopId())) {
log.debug("跳过出错暂停的增量店铺 channelShopId={}", shop.getExternalShopId());
ShopPO shop = shopById.get(pddShop.getEcShopId());
if (shop == null) {
continue;
}
if (fullSyncTaskService.isIncrementalPaused(pddShop.getId())) {
log.debug("跳过出错暂停的增量店铺 channelShopId={}", pddShop.getId());
continue;
}
try {
syncPublisher.publishInc(shop.getCompanyId(), shop.getExternalShopId());
syncPublisher.publishInc(shop.getCompanyId(), pddShop.getId());
} catch (Exception e) {
log.warn("投递增量同步失败 channelShopId={}: {}", shop.getExternalShopId(), e.getMessage());
log.warn("投递增量同步失败 channelShopId={}: {}", pddShop.getId(), e.getMessage());
}
}
}
@@ -5,8 +5,8 @@ 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.channel.pdd.shop.mapper.PddShopMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.shop.model.po.PddShopPO;
import top.xyquan.ecomdmbbackend.modules.notify.sse.RealtimeSseEvents;
import top.xyquan.ecomdmbbackend.modules.notify.sse.RealtimeSseService;
@@ -20,7 +20,7 @@ import java.util.Map;
public class PddOrderFullSyncProgressPublisher {
private final RealtimeSseService realtimeSseService;
private final ShopMapper shopMapper;
private final PddShopMapper pddShopMapper;
public void publish(PddOrderFullSyncTaskPO task) {
if (task == null || task.getCompanyId() == null) {
@@ -43,12 +43,12 @@ public class PddOrderFullSyncProgressPublisher {
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())
PddShopPO pddShop = pddShopMapper.selectOne(new LambdaQueryWrapper<PddShopPO>()
.eq(PddShopPO::getId, task.getShopId())
.eq(PddShopPO::getCompanyId, task.getCompanyId())
.last("LIMIT 1"));
if (shop != null) {
apiShopId = shop.getId();
if (pddShop != null && pddShop.getEcShopId() != null) {
apiShopId = pddShop.getEcShopId();
}
return PddOrderFullSyncTaskVO.builder()
.id(task.getId())
@@ -22,6 +22,8 @@ import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.PddOrderSyncShopStatusVO;
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.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;
@@ -55,6 +57,7 @@ public class PddOrderFullSyncTaskService {
private final PddOrderFullSyncTaskDayMapper dayMapper;
private final PddOrderIncSyncMapper incSyncMapper;
private final ShopMapper shopMapper;
private final PddShopMapper pddShopMapper;
private final PddOrderSyncContextResolver contextResolver;
private final PddOrderFullSyncDayScheduler dayScheduler;
private final PddOrderSyncProperties syncProperties;
@@ -268,9 +271,13 @@ public class PddOrderFullSyncTaskService {
Map<Long, ShopPO> shopMap = shops.stream()
.collect(Collectors.toMap(ShopPO::getId, s -> s, (a, b) -> a));
Map<Long, Long> ecToChannel = shops.stream()
.filter(s -> s.getExternalShopId() != null)
.collect(Collectors.toMap(ShopPO::getId, ShopPO::getExternalShopId, (a, b) -> a));
Map<Long, Long> ecToChannel = pddShopMapper.selectList(new LambdaQueryWrapper<PddShopPO>()
.eq(PddShopPO::getCompanyId, companyId)
.in(PddShopPO::getEcShopId, owned)
.isNotNull(PddShopPO::getEcShopId))
.stream()
.filter(p -> p.getEcShopId() != null && p.getId() != null)
.collect(Collectors.toMap(PddShopPO::getEcShopId, PddShopPO::getId, (a, b) -> a));
Set<Long> channelIds = new HashSet<>(ecToChannel.values());
Map<Long, PddOrderFullSyncTaskPO> latestByChannel = loadLatestTasksByShop(companyId, channelIds);
@@ -460,11 +467,11 @@ public class PddOrderFullSyncTaskService {
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())
PddShopPO pddShop = pddShopMapper.selectOne(new LambdaQueryWrapper<PddShopPO>()
.eq(PddShopPO::getId, task.getShopId())
.eq(PddShopPO::getCompanyId, task.getCompanyId())
.last("LIMIT 1"));
return shop != null ? shop.getId() : task.getShopId();
return pddShop != null && pddShop.getEcShopId() != null ? pddShop.getEcShopId() : task.getShopId();
}
private static PddOrderFullSyncTaskVO toVo(PddOrderFullSyncTaskPO task) {
@@ -42,18 +42,21 @@ public class PddOrderSyncAuthFailureHandler {
Long resolvedInternal = internalShopId;
Long resolvedChannel = channelShopId;
if (resolvedInternal != null && resolvedChannel == null) {
ShopPO shop = shopMapper.selectById(resolvedInternal);
if (shop != null) {
resolvedChannel = shop.getExternalShopId();
PddShopPO pddShop = pddShopMapper.selectOne(new LambdaQueryWrapper<PddShopPO>()
.eq(companyId != null, PddShopPO::getCompanyId, companyId)
.eq(PddShopPO::getEcShopId, resolvedInternal)
.last("LIMIT 1"));
if (pddShop != null) {
resolvedChannel = pddShop.getId();
}
}
if (resolvedChannel != null && resolvedInternal == null) {
ShopPO shop = shopMapper.selectOne(new LambdaQueryWrapper<ShopPO>()
.eq(companyId != null, ShopPO::getCompanyId, companyId)
.eq(ShopPO::getExternalShopId, resolvedChannel)
PddShopPO pddShop = pddShopMapper.selectOne(new LambdaQueryWrapper<PddShopPO>()
.eq(PddShopPO::getId, resolvedChannel)
.eq(companyId != null, PddShopPO::getCompanyId, companyId)
.last("LIMIT 1"));
if (shop != null) {
resolvedInternal = shop.getId();
if (pddShop != null) {
resolvedInternal = pddShop.getEcShopId();
}
}
@@ -18,6 +18,7 @@ import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
* 解析同步上下文。
* API 入参:内部店 {@code ec_shop.id};
* MQ / 渠道表:渠道店 {@code channel_pdd_shop.id}。
* 绑定关系在 {@code channel_pdd_shop.ec_shop_id}。
*/
@Service
public class PddOrderSyncContextResolver {
@@ -54,10 +55,14 @@ public class PddOrderSyncContextResolver {
if (!PlatformCode.PDD.getCode().equals(shop.getPlatformCode())) {
throw new BusinessException("仅支持拼多多平台店铺同步订单");
}
if (shop.getExternalShopId() == null) {
PddShopPO pddShop = pddShopMapper.selectOne(new LambdaQueryWrapper<PddShopPO>()
.eq(PddShopPO::getCompanyId, companyId)
.eq(PddShopPO::getEcShopId, internalShopId)
.last("LIMIT 1"));
if (pddShop == null) {
throw new PddAuthFailureException("店铺尚未绑定拼多多外部店,请先完成授权");
}
return buildContext(companyId, shop, shop.getExternalShopId());
return buildContext(companyId, shop, pddShop);
}
/** 按渠道店铺 ID 解析(channel_pdd_shop.id;MQ / 任务表) */
@@ -65,23 +70,25 @@ public class PddOrderSyncContextResolver {
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, channelShopId)
.eq(PddShopPO::getCompanyId, companyId)
.last("LIMIT 1"));
if (pddShop == null || pddShop.getPddAuthId() == null) {
if (pddShop == null) {
throw new BusinessException("拼多多渠道店铺不存在");
}
if (pddShop.getEcShopId() == null) {
throw new BusinessException("未找到绑定该拼多多店的内部店铺");
}
ShopPO shop = shopMapper.selectById(pddShop.getEcShopId());
if (shop == null || !companyId.equals(shop.getCompanyId())) {
throw new BusinessException("未找到绑定该拼多多店的内部店铺");
}
return buildContext(companyId, shop, pddShop);
}
private PddOrderSyncShopContext buildContext(Long companyId, ShopPO shop, PddShopPO pddShop) {
if (pddShop.getPddAuthId() == null) {
throw new PddAuthFailureException("未找到拼多多店铺授权绑定,请重新授权");
}
PddAuthPO auth = authTokenService.ensureUsableById(pddShop.getPddAuthId());
@@ -21,6 +21,8 @@ import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.vo.PddOrde
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.PddAuthFailureException;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.PddPopRateLimitedException;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.order.PddOrderPopApiClient;
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.modules.ec.shop.mapper.ShopMapper;
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
@@ -30,6 +32,7 @@ import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
/**
@@ -53,6 +56,7 @@ public class PddOrderSyncService {
private final PddOrderSyncProperties syncProperties;
private final StringRedisTemplate stringRedisTemplate;
private final ShopMapper shopMapper;
private final PddShopMapper pddShopMapper;
private final List<PddOrderAfterSyncListener> afterSyncListeners;
private final PddOrderConvertPublisher convertPublisher;
private final PddOrderSyncAuthFailureHandler authFailureHandler;
@@ -65,6 +69,7 @@ public class PddOrderSyncService {
PddOrderSyncProperties syncProperties,
StringRedisTemplate stringRedisTemplate,
ShopMapper shopMapper,
PddShopMapper pddShopMapper,
List<PddOrderAfterSyncListener> afterSyncListeners,
PddOrderConvertPublisher convertPublisher,
PddOrderSyncAuthFailureHandler authFailureHandler) {
@@ -76,6 +81,7 @@ public class PddOrderSyncService {
this.syncProperties = syncProperties;
this.stringRedisTemplate = stringRedisTemplate;
this.shopMapper = shopMapper;
this.pddShopMapper = pddShopMapper;
this.afterSyncListeners = afterSyncListeners != null ? afterSyncListeners : List.of();
this.convertPublisher = convertPublisher;
this.authFailureHandler = authFailureHandler;
@@ -186,9 +192,20 @@ public class PddOrderSyncService {
}
public List<ShopPO> listBoundPddShops(Long companyId) {
List<PddShopPO> bound = pddShopMapper.selectList(new LambdaQueryWrapper<PddShopPO>()
.eq(PddShopPO::getCompanyId, companyId)
.isNotNull(PddShopPO::getEcShopId));
if (bound.isEmpty()) {
return List.of();
}
List<Long> ecIds = bound.stream()
.map(PddShopPO::getEcShopId)
.filter(Objects::nonNull)
.distinct()
.toList();
return shopMapper.selectList(new LambdaQueryWrapper<ShopPO>()
.eq(ShopPO::getCompanyId, companyId)
.isNotNull(ShopPO::getExternalShopId));
.in(ShopPO::getId, ecIds));
}
/** MQ / 全量任务:shopId = channel_pdd_shop.id */
@@ -19,6 +19,10 @@ public class PddShopPO {
@TableField("company_id")
private Long companyId;
/** 绑定的内部经营店(ec_shop.id) */
@TableField("ec_shop_id")
private Long ecShopId;
@TableField("pdd_auth_id")
private Long pddAuthId;
@@ -12,6 +12,9 @@ public class PddShopVO {
private Long companyId;
/** 绑定的内部经营店 ID */
private Long ecShopId;
private Long pddAuthId;
private PddAuthVO auth;
@@ -210,6 +210,7 @@ public class PddShopServiceImpl extends ServiceImpl<PddShopMapper, PddShopPO> im
PddShopVO vo = new PddShopVO();
vo.setId(shop.getId());
vo.setCompanyId(shop.getCompanyId());
vo.setEcShopId(shop.getEcShopId());
vo.setMallId(shop.getMallId());
vo.setMallName(shop.getMallName());
vo.setLogo(shop.getLogo());
@@ -24,9 +24,4 @@ public class CreateShopDTO {
* 平台代码
*/
private String platformCode;
/**
* 外部/平台店铺表主键 ID(如 channel_pdd_shop.id)
*/
private Long externalShopId;
}
@@ -24,9 +24,4 @@ public class UpdateShopDTO {
* 平台代码
*/
private String platformCode;
/**
* 外部/平台店铺表主键 ID(如 channel_pdd_shop.id)
*/
private Long externalShopId;
}
@@ -50,12 +50,6 @@ public class ShopPO {
@TableField("platform_code")
private String platformCode;
/**
* 外部/平台店铺表主键 ID(如 channel_pdd_shop.id;与 platform_code 组合关联)
*/
@TableField("external_shop_id")
private Long externalShopId;
/**
* 订单增量同步开关:0关 1开
*/
@@ -37,12 +37,7 @@ public class ShopVO {
private String platformCode;
/**
* 外部/平台店铺表主键 ID(如 channel_pdd_shop.id)
*/
private Long externalShopId;
/**
* 关联的拼多多外部店铺(仅 platform=pdd 且已绑定 externalShopId 时有值)
* 关联的拼多多渠道店铺(已授权绑定时由应用层组装)
*/
private PddShopVO pddShop;
@@ -40,6 +40,7 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
@@ -264,15 +265,15 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
if (shopVO == null || shop == null) {
return;
}
if (PLATFORM_CODE_PDD.equals(shop.getPlatformCode())
&& shop.getExternalShopId() != null) {
PddShopPO pddShop = pddShopMapper.selectOne(new LambdaQueryWrapper<PddShopPO>()
.eq(PddShopPO::getId, shop.getExternalShopId())
.eq(PddShopPO::getCompanyId, shop.getCompanyId())
.last("LIMIT 1"));
if (pddShop != null) {
shopVO.setPddShop(pddShopService.toBriefVo(pddShop));
}
if (!PLATFORM_CODE_PDD.equals(shop.getPlatformCode())) {
return;
}
PddShopPO pddShop = pddShopMapper.selectOne(new LambdaQueryWrapper<PddShopPO>()
.eq(PddShopPO::getCompanyId, shop.getCompanyId())
.eq(PddShopPO::getEcShopId, shop.getId())
.last("LIMIT 1"));
if (pddShop != null) {
shopVO.setPddShop(pddShopService.toBriefVo(pddShop));
}
}
@@ -295,7 +296,7 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
}
/**
* 批量填充已绑定的外部店铺 VO(当前支持拼多多)
* 批量填充已绑定的拼多多渠道店铺 VO(按 channel_pdd_shop.ec_shop_id 反查)
*/
private void fillExternalShops(List<ShopVO> voList,
List<ShopPO> shops,
@@ -308,33 +309,35 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
.filter(v -> v.getId() != null)
.collect(Collectors.toMap(ShopVO::getId, Function.identity(), (a, b) -> a));
Map<Long, Long> shopIdToExternalId = new HashMap<>();
for (ShopPO shop : shops) {
if (shop.getExternalShopId() == null) {
continue;
}
if (!PLATFORM_CODE_PDD.equals(shop.getPlatformCode())) {
continue;
}
shopIdToExternalId.put(shop.getId(), shop.getExternalShopId());
}
if (shopIdToExternalId.isEmpty()) {
List<Long> pddShopIds = shops.stream()
.filter(s -> PLATFORM_CODE_PDD.equals(s.getPlatformCode()))
.map(ShopPO::getId)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
if (pddShopIds.isEmpty()) {
return;
}
List<PddShopPO> pddShops = pddShopMapper.selectList(new LambdaQueryWrapper<PddShopPO>()
.eq(PddShopPO::getCompanyId, companyId)
.in(PddShopPO::getId, shopIdToExternalId.values()));
Map<Long, PddShopVO> pddById = pddShopService.toBriefVoList(pddShops).stream()
.collect(Collectors.toMap(PddShopVO::getId, Function.identity(), (a, b) -> a));
.in(PddShopPO::getEcShopId, pddShopIds));
// 用 PO 建索引,避免 brief VO 漏字段导致挂不上
Map<Long, PddShopVO> pddByEcShopId = new HashMap<>();
for (PddShopPO po : pddShops) {
if (po.getEcShopId() == null) {
continue;
}
pddByEcShopId.put(po.getEcShopId(), pddShopService.toBriefVo(po));
}
shopIdToExternalId.forEach((shopId, externalId) -> {
for (Long shopId : pddShopIds) {
ShopVO vo = voById.get(shopId);
PddShopVO pddShop = pddById.get(externalId);
PddShopVO pddShop = pddByEcShopId.get(shopId);
if (vo != null && pddShop != null) {
vo.setPddShop(pddShop);
}
});
}
}
/**
@@ -71,8 +71,6 @@ export namespace ShopVO {
platformCode?: string;
/** 平台名称(后端回填) */
platformName?: string;
/** 外部/平台店铺表主键 ID(如 channel_pdd_shop.id) */
externalShopId?: null | number;
/** 关联的拼多多外部店铺(已授权绑定时返回) */
pddShop?: null | PddShopInfo;
/** 创建时间 */
@@ -48,7 +48,7 @@ async function loadDetail() {
}
function openPddShopDetail() {
const pddShopId = shop.value?.pddShop?.id ?? shop.value?.externalShopId;
const pddShopId = shop.value?.pddShop?.id;
if (!pddShopId) {
message.warning('暂无平台店铺信息');
return;
@@ -91,8 +91,8 @@ watch(shopId, loadDetail);
<Descriptions :column="2" bordered size="small" title="基础信息">
<Descriptions.Item label="店铺ID">{{ shop.id }}</Descriptions.Item>
<Descriptions.Item label="平台店铺主键">
{{ shop.externalShopId ?? '-' }}
<Descriptions.Item label="渠道店铺ID">
{{ shop.pddShop?.id ?? '-' }}
</Descriptions.Item>
<Descriptions.Item label="创建时间">
{{ shop.createTime || '-' }}
@@ -335,7 +335,7 @@ function isPddShop(row: ShopVO.Info) {
}
function hasExternalShop(row: ShopVO.Info) {
return Boolean(row.pddShop || row.externalShopId);
return Boolean(row.pddShop);
}
function handleAdd() {
@@ -362,7 +362,7 @@ function handleModalSuccess() {
}
function handleViewExternalShop(record: ShopVO.Info) {
const pddShopId = record.pddShop?.id ?? record.externalShopId;
const pddShopId = record.pddShop?.id;
if (!pddShopId) {
message.warning('暂无外部店铺详情,请先完成授权同步');
return;
@@ -475,10 +475,10 @@ onUnmounted(() => {
{{ row.pddShop.mallName }}
</span>
<span
v-else-if="row.externalShopId"
v-else-if="row.pddShop?.id"
class="text-center text-xs text-slate-500"
>
平台店#{{ row.externalShopId }}
渠道店#{{ row.pddShop.id }}
</span>
</div>
<span v-else class="text-slate-400">-</span>