refactor: 去掉拼多多商品内部 product_id 并按 SKU 分摊广告费

This commit is contained in:
2026-09-04 22:18:41 +08:00
parent ea9d792096
commit 558dfc4a28
19 changed files with 450 additions and 353 deletions
@@ -4,7 +4,8 @@
-- 设计原则:
-- 1. 与 ec_product / ec_product_sku(内部成本分析商品)分离,存平台同步数据
-- 2. SPU 主表 + SKU 明细表,spec_details 存入 SKU 行 JSON
-- 3. 主表 product_id 必填:取 SKU 明细首条 outer_id 匹配 ec_product_sku.sku_code 后关联商品
-- 3. 主表不定内部商品:一拼多多商品可含多个内部商品的 SKU;
-- 内部关联仅经 SKU.outer_id → ec_product_sku.sku_code(广告费按 SKU 等分后汇总)
-- ========================================
-- ========================================
@@ -17,7 +18,6 @@ CREATE TABLE `channel_pdd_goods` (
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
`shop_id` bigint UNSIGNED NOT NULL COMMENT '渠道店铺ID(channel_pdd_shop.id)',
`mall_id` bigint UNSIGNED NOT NULL COMMENT '拼多多店铺ID(mall_id)',
`product_id` bigint UNSIGNED NOT NULL COMMENT '内部商品ID(ec_product.id;由首条 SKU.outer_id → sku_code 解析)',
`goods_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '拼多多商品ID(goods_id)',
`goods_name` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '商品名称(goods_name)',
`goods_quantity` int NOT NULL DEFAULT 0 COMMENT '商品总库存(goods_quantity)',
@@ -35,12 +35,10 @@ CREATE TABLE `channel_pdd_goods` (
UNIQUE INDEX `uk_channel_pdd_goods_shop_goods`(`shop_id` ASC, `goods_id` ASC) USING BTREE,
INDEX `idx_channel_pdd_goods_company_mall`(`company_id` ASC, `mall_id` ASC) USING BTREE,
INDEX `idx_channel_pdd_goods_mall_goods`(`mall_id` ASC, `goods_id` ASC) USING BTREE,
INDEX `idx_channel_pdd_goods_product`(`product_id` ASC) USING BTREE,
INDEX `idx_channel_pdd_goods_onsale`(`is_onsale` ASC) USING BTREE,
INDEX `idx_channel_pdd_goods_sync`(`last_sync_time` ASC) USING BTREE,
CONSTRAINT `fk_channel_pdd_goods_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_channel_pdd_goods_shop` FOREIGN KEY (`shop_id`) REFERENCES `channel_pdd_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_channel_pdd_goods_product` FOREIGN KEY (`product_id`) REFERENCES `ec_product` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
CONSTRAINT `fk_channel_pdd_goods_shop` FOREIGN KEY (`shop_id`) REFERENCES `channel_pdd_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '拼多多-商品主表(SPU)' ROW_FORMAT = Dynamic;
-- ========================================
@@ -0,0 +1,9 @@
-- 拼多多商品主表去掉内部商品绑定:一 SPU 可含多个内部商品的 SKU
ALTER TABLE `channel_pdd_goods`
DROP FOREIGN KEY `fk_channel_pdd_goods_product`;
ALTER TABLE `channel_pdd_goods`
DROP INDEX `idx_channel_pdd_goods_product`;
ALTER TABLE `channel_pdd_goods`
DROP COLUMN `product_id`;
@@ -13,17 +13,25 @@ import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.mapper.Pdd
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.importtask.model.po.PddGoodsAdFeeImportItemPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.mapper.PddGoodsAdFeeDailyMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.po.PddGoodsAdFeeDailyPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.ensure.PddGoodsEnsureService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.mapper.PddGoodsMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.mapper.PddGoodsSkuMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.po.PddGoodsPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.po.PddGoodsSkuPO;
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.product.sku.mapper.ProductSkuMapper;
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.model.po.ProductSkuPO;
import top.xyquan.ecomdmbbackend.modules.ec.shop.adfee.mapper.AdFeeMapper;
import top.xyquan.ecomdmbbackend.modules.ec.shop.adfee.model.po.AdFeePO;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
@@ -33,38 +41,48 @@ import java.util.Set;
/**
* 渠道日表 → 内部 ec_product_ad_fee。
* <p>
* 内部表按 productId+feeDate 唯一;多个渠道 goods 可绑同一内部商品,
* 故转换时按「内部商品 × 日」对渠道日表金额求和后再 upsert,禁止逐条覆盖。
* 转换时:缺渠道商品则同步一次;按 outer_id 匹配内部 SKU,缺失则自动建品;
* 再按可匹配 SKU 等分日费用,汇总 upsert。全部匹配失败则跳过。
*/
@Slf4j
@Service
public class PddGoodsAdFeeConvertService {
private static final String CAMPAIGN_NAME = "拼多多商品推广";
private static final int MONEY_SCALE = 2;
private final PddGoodsAdFeeDailyMapper channelAdFeeMapper;
private final PddGoodsAdFeeImportItemMapper importItemMapper;
private final PddGoodsMapper pddGoodsMapper;
private final PddGoodsSkuMapper pddGoodsSkuMapper;
private final ProductSkuMapper productSkuMapper;
private final PddShopMapper pddShopMapper;
private final AdFeeMapper adFeeMapper;
private final PddGoodsEnsureService goodsEnsureService;
private final TransactionTemplate transactionTemplate;
public PddGoodsAdFeeConvertService(PddGoodsAdFeeDailyMapper channelAdFeeMapper,
PddGoodsAdFeeImportItemMapper importItemMapper,
PddGoodsMapper pddGoodsMapper,
PddGoodsSkuMapper pddGoodsSkuMapper,
ProductSkuMapper productSkuMapper,
PddShopMapper pddShopMapper,
AdFeeMapper adFeeMapper,
PddGoodsEnsureService goodsEnsureService,
PlatformTransactionManager transactionManager) {
this.channelAdFeeMapper = channelAdFeeMapper;
this.importItemMapper = importItemMapper;
this.pddGoodsMapper = pddGoodsMapper;
this.pddGoodsSkuMapper = pddGoodsSkuMapper;
this.productSkuMapper = productSkuMapper;
this.pddShopMapper = pddShopMapper;
this.adFeeMapper = adFeeMapper;
this.goodsEnsureService = goodsEnsureService;
this.transactionTemplate = new TransactionTemplate(transactionManager);
}
/**
* 转换任务中全部成功明细:先收集涉及的 (productId, feeDate),再按内部商品汇总渠道日表金额写入。
* 转换任务中全部成功明细:建品/匹配后按 SKU 等分,汇总到 (productId, feeDate) 再 upsert。
*/
public PddAdFeeConvertBatchResult convertByTaskId(Long taskId) {
if (taskId == null) {
@@ -76,30 +94,28 @@ public class PddGoodsAdFeeConvertService {
.eq(PddGoodsAdFeeImportItemPO::getStatus, PddGoodsAdFeeImportItemPO.STATUS_SUCCESS)
.isNotNull(PddGoodsAdFeeImportItemPO::getGoodsRowId));
// productId|feeDate → 任一成功明细对应的公司 / 渠道店(用于解析内部店)
Set<String> productDateKeys = new LinkedHashSet<>();
Map<String, ConvertTarget> targets = new HashMap<>();
int skipped = 0;
Set<String> dailyKeys = new LinkedHashSet<>();
List<DailyRef> dailyRefs = new ArrayList<>();
for (PddGoodsAdFeeImportItemPO item : items) {
PddGoodsPO goods = pddGoodsMapper.selectById(item.getGoodsRowId());
if (goods == null || goods.getProductId() == null || item.getFeeDate() == null) {
skipped++;
if (item.getFeeDate() == null || item.getGoodsRowId() == null) {
continue;
}
String key = productDateKey(goods.getProductId(), item.getFeeDate());
if (productDateKeys.add(key)) {
targets.put(key, new ConvertTarget(
String key = item.getGoodsRowId() + "|" + item.getFeeDate();
if (dailyKeys.add(key)) {
dailyRefs.add(new DailyRef(
item.getCompanyId(),
goods.getProductId(),
item.getGoodsRowId(),
item.getFeeDate(),
goods.getShopId()));
item.getGoodsId()));
}
}
AllocationResult allocation = allocateDailies(dailyRefs);
int skipped = allocation.skippedDailyCount();
int success = 0;
int failed = 0;
for (ConvertTarget target : targets.values()) {
for (ConvertTarget target : allocation.targets().values()) {
PddAdFeeConvertOutcome outcome = transactionTemplate.execute(
status -> convertProductDate(target));
if (outcome == PddAdFeeConvertOutcome.CONVERTED) {
@@ -117,6 +133,9 @@ public class PddGoodsAdFeeConvertService {
.build();
}
/**
* 单条渠道日行触发:先建品匹配,再重算同日相关内部商品份额后 upsert。
*/
@Transactional(rollbackFor = Exception.class)
public void convertByChannelAdFeeId(Long channelAdFeeId) {
if (channelAdFeeId == null) {
@@ -127,25 +146,225 @@ public class PddGoodsAdFeeConvertService {
log.warn("渠道广告费不存在,跳过转换 id={}", channelAdFeeId);
return;
}
if (channelFee.getGoodsRowId() == null || channelFee.getFeeDate() == null) {
if (channelFee.getGoodsRowId() == null || channelFee.getFeeDate() == null
|| channelFee.getCompanyId() == null) {
return;
}
PddGoodsPO goods = pddGoodsMapper.selectById(channelFee.getGoodsRowId());
if (goods == null || goods.getProductId() == null) {
log.warn("渠道商品未绑定内部商品,跳过转换 dailyId={} goodsRowId={}",
PddGoodsPO triggerGoods = prepareChannelGoods(
channelFee.getCompanyId(), channelFee.getGoodsRowId(), null);
if (triggerGoods == null) {
log.warn("渠道商品不存在且无法同步,跳过转换 dailyId={} goodsRowId={}",
channelFee.getId(), channelFee.getGoodsRowId());
return;
}
convertProductDate(new ConvertTarget(
channelFee.getCompanyId(),
goods.getProductId(),
channelFee.getFeeDate(),
goods.getShopId()));
goodsEnsureService.ensureInternalProductsForChannelGoods(
channelFee.getCompanyId(), triggerGoods);
List<Long> touchedProductIds = resolveMatchedProductIds(
channelFee.getCompanyId(), triggerGoods.getId());
if (touchedProductIds.isEmpty()) {
log.warn("渠道商品 SKU 均未匹配内部商品,跳过转换 dailyId={} goodsRowId={}",
channelFee.getId(), channelFee.getGoodsRowId());
return;
}
List<PddGoodsAdFeeDailyPO> sameDay = channelAdFeeMapper.selectList(
new LambdaQueryWrapper<PddGoodsAdFeeDailyPO>()
.eq(PddGoodsAdFeeDailyPO::getCompanyId, channelFee.getCompanyId())
.eq(PddGoodsAdFeeDailyPO::getFeeDate, channelFee.getFeeDate()));
List<DailyRef> refs = new ArrayList<>();
for (PddGoodsAdFeeDailyPO d : sameDay) {
if (d.getGoodsRowId() != null) {
refs.add(new DailyRef(d.getCompanyId(), d.getGoodsRowId(), d.getFeeDate(), null));
}
}
AllocationResult allocation = allocateDailies(refs);
Set<Long> touchSet = new HashSet<>(touchedProductIds);
for (ConvertTarget target : allocation.targets().values()) {
if (!Objects.equals(target.feeDate(), channelFee.getFeeDate())) {
continue;
}
if (!touchSet.contains(target.productId())) {
continue;
}
convertProductDate(target);
}
}
/**
* 将「内部商品 × 自然日」下全部已绑定渠道日表金额求和,写入 ec_product_ad_fee。
* 对若干渠道日行:先确保渠道商品与内部 SKU,再等分汇总。
*/
private AllocationResult allocateDailies(List<DailyRef> refs) {
Map<String, ConvertTarget> targets = new LinkedHashMap<>();
int skippedDaily = 0;
Map<Long, PddGoodsPO> goodsCache = new HashMap<>();
Map<Long, List<PddGoodsSkuPO>> skuCache = new HashMap<>();
Map<String, Long> outerToProductCache = new HashMap<>();
Set<Long> preparedGoodsIds = new HashSet<>();
for (DailyRef ref : refs) {
if (ref.companyId() == null || ref.goodsRowId() == null || ref.feeDate() == null) {
skippedDaily++;
continue;
}
PddGoodsAdFeeDailyPO daily = channelAdFeeMapper.selectOne(
new LambdaQueryWrapper<PddGoodsAdFeeDailyPO>()
.eq(PddGoodsAdFeeDailyPO::getCompanyId, ref.companyId())
.eq(PddGoodsAdFeeDailyPO::getGoodsRowId, ref.goodsRowId())
.eq(PddGoodsAdFeeDailyPO::getFeeDate, ref.feeDate())
.last("LIMIT 1"));
if (daily == null || daily.getFeeAmount() == null
|| daily.getFeeAmount().compareTo(BigDecimal.ZERO) <= 0) {
skippedDaily++;
continue;
}
PddGoodsPO goods = goodsCache.computeIfAbsent(ref.goodsRowId(), id ->
prepareChannelGoods(ref.companyId(), id, ref.goodsId()));
if (goods == null) {
log.warn("渠道商品不存在且同步失败,跳过 goodsRowId={} feeDate={}",
ref.goodsRowId(), ref.feeDate());
skippedDaily++;
continue;
}
// 行上 goodsRowId 可能在同步后仍指向旧 id;以准备后的主键为准
Long goodsRowId = goods.getId();
if (preparedGoodsIds.add(goodsRowId)) {
goodsEnsureService.ensureInternalProductsForChannelGoods(ref.companyId(), goods);
// 建品后清缓存,按最新内部 SKU 匹配
skuCache.remove(goodsRowId);
outerToProductCache.clear();
}
List<PddGoodsSkuPO> skus = skuCache.computeIfAbsent(goodsRowId, id ->
pddGoodsSkuMapper.selectList(new LambdaQueryWrapper<PddGoodsSkuPO>()
.eq(PddGoodsSkuPO::getGoodsRowId, id)));
List<Long> matchedProductIds = matchProductsInOrder(
ref.companyId(), skus, outerToProductCache);
if (matchedProductIds.isEmpty()) {
log.warn("渠道广告费 SKU 均未匹配内部商品,跳过 goodsRowId={} feeDate={}",
goodsRowId, ref.feeDate());
skippedDaily++;
continue;
}
List<BigDecimal> shares = splitEvenly(daily.getFeeAmount(), matchedProductIds.size());
for (int i = 0; i < matchedProductIds.size(); i++) {
Long productId = matchedProductIds.get(i);
BigDecimal share = shares.get(i);
String key = productDateKey(productId, ref.feeDate());
ConvertTarget existing = targets.get(key);
if (existing == null) {
targets.put(key, new ConvertTarget(
ref.companyId(),
productId,
ref.feeDate(),
goods.getShopId(),
share));
} else {
targets.put(key, new ConvertTarget(
existing.companyId(),
existing.productId(),
existing.feeDate(),
existing.channelShopId(),
existing.amount().add(share)));
}
}
}
return new AllocationResult(targets, skippedDaily);
}
/**
* 按 goods_row_id 取渠道商品;缺失时用 goodsId + 日表关联店尝试同步一次。
*/
private PddGoodsPO prepareChannelGoods(Long companyId, Long goodsRowId, String goodsIdHint) {
PddGoodsPO goods = pddGoodsMapper.selectById(goodsRowId);
if (goods != null) {
// SKU 为空时再拉一次详情刷新
Long skuCount = pddGoodsSkuMapper.selectCount(new LambdaQueryWrapper<PddGoodsSkuPO>()
.eq(PddGoodsSkuPO::getGoodsRowId, goods.getId()));
if (skuCount != null && skuCount > 0) {
return goods;
}
if (goods.getShopId() != null && StringUtils.hasText(goods.getGoodsId())) {
try {
return goodsEnsureService.ensureChannelGoods(
companyId, goods.getShopId(), goods.getGoodsId());
} catch (Exception e) {
log.warn("渠道商品无 SKU,刷新同步失败 goodsRowId={}: {}",
goodsRowId, e.getMessage());
return goods;
}
}
return goods;
}
// 日表仍挂着已删的 goods_row_id:用导入明细上的 goodsId 尝试同步
if (!StringUtils.hasText(goodsIdHint)) {
return null;
}
// 无 shopId 时无法定位渠道店,放弃
log.warn("渠道商品行已不存在 goodsRowId={},无法仅凭 goodsId={} 同步(缺店铺)",
goodsRowId, goodsIdHint);
return null;
}
private List<Long> matchProductsInOrder(Long companyId,
List<PddGoodsSkuPO> skus,
Map<String, Long> outerToProductCache) {
List<Long> matched = new ArrayList<>();
if (skus == null || skus.isEmpty()) {
return matched;
}
for (PddGoodsSkuPO sku : skus) {
if (sku == null || !StringUtils.hasText(sku.getOuterId())) {
continue;
}
String outer = sku.getOuterId().trim();
String cacheKey = companyId + "|" + outer;
Long productId;
if (outerToProductCache.containsKey(cacheKey)) {
productId = outerToProductCache.get(cacheKey);
} else {
ProductSkuPO internal = productSkuMapper.selectOne(new LambdaQueryWrapper<ProductSkuPO>()
.eq(ProductSkuPO::getCompanyId, companyId)
.eq(ProductSkuPO::getSkuCode, outer)
.last("LIMIT 1"));
productId = internal != null ? internal.getProductId() : null;
outerToProductCache.put(cacheKey, productId);
}
if (productId != null) {
matched.add(productId);
}
}
return matched;
}
private List<Long> resolveMatchedProductIds(Long companyId, Long goodsRowId) {
List<PddGoodsSkuPO> skus = pddGoodsSkuMapper.selectList(new LambdaQueryWrapper<PddGoodsSkuPO>()
.eq(PddGoodsSkuPO::getGoodsRowId, goodsRowId));
List<Long> ordered = matchProductsInOrder(companyId, skus, new HashMap<>());
return new ArrayList<>(new LinkedHashSet<>(ordered));
}
private static List<BigDecimal> splitEvenly(BigDecimal total, int n) {
List<BigDecimal> shares = new ArrayList<>(n);
if (n <= 0) {
return shares;
}
BigDecimal share = total.divide(BigDecimal.valueOf(n), MONEY_SCALE, RoundingMode.HALF_UP);
BigDecimal allocated = BigDecimal.ZERO;
for (int i = 0; i < n - 1; i++) {
shares.add(share);
allocated = allocated.add(share);
}
shares.add(total.subtract(allocated));
return shares;
}
private PddAdFeeConvertOutcome convertProductDate(ConvertTarget target) {
try {
Long internalShopId = resolveInternalShopId(target.companyId(), target.channelShopId());
@@ -154,12 +373,9 @@ public class PddGoodsAdFeeConvertService {
target.productId(), target.feeDate(), target.channelShopId());
return PddAdFeeConvertOutcome.SKIPPED;
}
BigDecimal total = sumChannelFeesForProductDate(
target.companyId(), target.productId(), target.feeDate());
if (total.compareTo(BigDecimal.ZERO) <= 0) {
if (target.amount() == null || target.amount().compareTo(BigDecimal.ZERO) <= 0) {
log.warn("内部商品当日渠道广告费合计无效,跳过 productId={} feeDate={} total={}",
target.productId(), target.feeDate(), total);
target.productId(), target.feeDate(), target.amount());
return PddAdFeeConvertOutcome.SKIPPED;
}
@@ -168,7 +384,7 @@ public class PddGoodsAdFeeConvertService {
internalShopId,
target.productId(),
target.feeDate(),
total);
target.amount());
return changed ? PddAdFeeConvertOutcome.CONVERTED : PddAdFeeConvertOutcome.SKIPPED;
} catch (Exception e) {
log.error("转换内部广告费失败 productId={} feeDate={}",
@@ -177,39 +393,6 @@ public class PddGoodsAdFeeConvertService {
}
}
/**
* 汇总:所有 product_id 指向该内部商品、且 fee_date 相同的渠道日表金额。
*/
private BigDecimal sumChannelFeesForProductDate(Long companyId, Long productId, LocalDate feeDate) {
List<PddGoodsPO> goodsList = pddGoodsMapper.selectList(new LambdaQueryWrapper<PddGoodsPO>()
.eq(PddGoodsPO::getCompanyId, companyId)
.eq(PddGoodsPO::getProductId, productId));
if (goodsList.isEmpty()) {
return BigDecimal.ZERO;
}
Set<Long> goodsRowIds = new HashSet<>();
for (PddGoodsPO g : goodsList) {
if (g.getId() != null) {
goodsRowIds.add(g.getId());
}
}
if (goodsRowIds.isEmpty()) {
return BigDecimal.ZERO;
}
List<PddGoodsAdFeeDailyPO> dailies = channelAdFeeMapper.selectList(
new LambdaQueryWrapper<PddGoodsAdFeeDailyPO>()
.eq(PddGoodsAdFeeDailyPO::getCompanyId, companyId)
.eq(PddGoodsAdFeeDailyPO::getFeeDate, feeDate)
.in(PddGoodsAdFeeDailyPO::getGoodsRowId, goodsRowIds));
BigDecimal sum = BigDecimal.ZERO;
for (PddGoodsAdFeeDailyPO d : dailies) {
if (d.getFeeAmount() != null && d.getFeeAmount().compareTo(BigDecimal.ZERO) > 0) {
sum = sum.add(d.getFeeAmount());
}
}
return sum;
}
private Long resolveInternalShopId(Long companyId, Long channelShopId) {
PddShopPO pddShop = pddShopMapper.selectOne(new LambdaQueryWrapper<PddShopPO>()
.eq(PddShopPO::getId, channelShopId)
@@ -218,7 +401,6 @@ public class PddGoodsAdFeeConvertService {
return pddShop != null ? pddShop.getEcShopId() : null;
}
/** @return true 表示写入或更新 */
private boolean upsertInternalAdFee(Long companyId,
Long internalShopId,
Long productId,
@@ -237,7 +419,7 @@ public class PddGoodsAdFeeConvertService {
po.setCampaignName(CAMPAIGN_NAME);
po.setFeeAmount(feeAmount);
po.setFeeDate(feeDate);
po.setRemark("channel_pdd_goods_ad_fee_daily 汇总 product_id=" + productId);
po.setRemark("channel_pdd_goods_ad_fee_daily 按SKU分摊汇总 product_id=" + productId);
adFeeMapper.insert(po);
log.info("已转换新增内部广告费 productId={} feeDate={} amount={}",
productId, feeDate, feeAmount);
@@ -258,7 +440,7 @@ public class PddGoodsAdFeeConvertService {
if (!StringUtils.hasText(existing.getCampaignName())) {
existing.setCampaignName(CAMPAIGN_NAME);
}
existing.setRemark("channel_pdd_goods_ad_fee_daily 汇总 product_id=" + productId);
existing.setRemark("channel_pdd_goods_ad_fee_daily 按SKU分摊汇总 product_id=" + productId);
adFeeMapper.updateById(existing);
log.info("已转换更新内部广告费 id={} productId={} feeDate={} amount={}",
existing.getId(), productId, feeDate, feeAmount);
@@ -269,10 +451,17 @@ public class PddGoodsAdFeeConvertService {
return productId + "|" + feeDate;
}
private record DailyRef(Long companyId, Long goodsRowId, LocalDate feeDate, String goodsId) {
}
private record ConvertTarget(
Long companyId,
Long productId,
LocalDate feeDate,
Long channelShopId) {
Long channelShopId,
BigDecimal amount) {
}
private record AllocationResult(Map<String, ConvertTarget> targets, int skippedDailyCount) {
}
}
@@ -32,7 +32,7 @@ import java.util.Map;
import java.util.Set;
/**
* 导入任务 worker:已绑定商品直接写日表;缺失的拉 POP 再写;授权失效不影响已有商品。
* 导入任务 worker:只写渠道日表;缺渠道商品时同步落库(不建内部品);授权失效不影响已有商品。
*/
@Slf4j
@Service
@@ -120,7 +120,8 @@ public class PddGoodsAdFeeImportProcessor {
continue;
}
try {
PddGoodsPO goods = goodsEnsureService.ensureBound(
// 导入仅同步渠道商品镜像,内部建品留给转换阶段
PddGoodsPO goods = goodsEnsureService.ensureChannelGoods(
task.getCompanyId(), task.getChannelShopId(), goodsId);
resolved.put(goodsId, GoodsResolve.ok(goods));
} catch (PddPopRateLimitedException e) {
@@ -321,16 +322,13 @@ public class PddGoodsAdFeeImportProcessor {
task.getId(), status, success, fail, task.getAuthExpired());
}
/** 渠道商品已落库即可(不再要求主表绑定内部商品)。 */
private PddGoodsPO findBound(Long companyId, Long channelShopId, String goodsId) {
PddGoodsPO goods = pddGoodsMapper.selectOne(new LambdaQueryWrapper<PddGoodsPO>()
return pddGoodsMapper.selectOne(new LambdaQueryWrapper<PddGoodsPO>()
.eq(PddGoodsPO::getCompanyId, companyId)
.eq(PddGoodsPO::getShopId, channelShopId)
.eq(PddGoodsPO::getGoodsId, goodsId)
.last("LIMIT 1"));
if (goods == null || goods.getProductId() == null) {
return null;
}
return goods;
}
private static String mapFailCode(BusinessException e) {
@@ -341,7 +339,7 @@ public class PddGoodsAdFeeImportProcessor {
if (msg.contains("拉取") || msg.contains("详情为空")) {
return PddGoodsAdFeeImportItemPO.FAIL_GOODS_FETCH;
}
if (msg.contains("无法关联") || msg.contains("落库失败") || msg.contains("自动创建")) {
if (msg.contains("落库失败")) {
return PddGoodsAdFeeImportItemPO.FAIL_BIND;
}
return PddGoodsAdFeeImportItemPO.FAIL_OTHER;
@@ -158,7 +158,7 @@ public class PddGoodsAdFeeServiceImpl implements PddGoodsAdFeeService {
private PddGoodsPO ensureGoods(Long companyId, Long channelShopId, String goodsId) {
try {
return goodsEnsureService.ensureBound(companyId, channelShopId, goodsId);
return goodsEnsureService.ensureChannelGoods(companyId, channelShopId, goodsId);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
@@ -3,15 +3,29 @@ package top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.ensure;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.po.PddGoodsPO;
/**
* 确保渠道商品已入库并绑定内部商品。已存在则直接返回,缺失时拉 POP 详情再建绑。
* 渠道商品确保:渠道镜像落库与内部建品分阶段。
* <p>
* 推广费导入只调 {@link #ensureChannelGoods};转换/订单再调内部建品。
*/
public interface PddGoodsEnsureService {
/**
* 按渠道店 + goods_id 返回已绑定内部品的渠道商品。
* 仅确保渠道 goods + sku 已落库;缺失时拉 POP 详情写入。
* <p>
* 绑定:扫 SKU 的 outer_id → 内部 sku_code,取首个命中的 product_id,
* 再把内部缺失的 SKU 补到该商品下;一个都没命中则自动建新品。
* 不创建、不补齐内部商品/SKU。
*
* @param channelShopId channel_pdd_shop.id
*/
PddGoodsPO ensureChannelGoods(Long companyId, Long channelShopId, String goodsId) throws Exception;
/**
* 按已落库渠道商品的 outer_id 匹配内部 SKU;有缺失则拉详情自动建品/补 SKU。
* 失败只打日志,不抛(调用方仍可按当前匹配结果分摊)。
*/
void ensureInternalProductsForChannelGoods(Long companyId, PddGoodsPO channelGoods);
/**
* 渠道落库 + 尽力内部建品(订单自动建品、商品同步等)。
*
* @param channelShopId channel_pdd_shop.id
*/
@@ -10,7 +10,9 @@ import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.model.po.PddAuthPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.service.PddAuthTokenService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.mapper.PddGoodsMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.mapper.PddGoodsSkuMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.po.PddGoodsPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.po.PddGoodsSkuPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.service.PddGoodsService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.convert.service.PddProductAutoCreateService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.PddAuthFailureException;
@@ -24,13 +26,14 @@ import java.util.List;
import java.util.Objects;
/**
* 渠道商品确保入库:查库 → 拉详情 → 首个 outer_id 定品 → 缺 SKU 补齐 → 否则自动建品。
* 渠道镜像落库与内部建品:导入只落渠道;转换/订单再补内部 SKU。
*/
@Slf4j
@Service
public class PddGoodsEnsureServiceImpl implements PddGoodsEnsureService {
private final PddGoodsMapper pddGoodsMapper;
private final PddGoodsSkuMapper pddGoodsSkuMapper;
private final PddShopMapper pddShopMapper;
private final PddAuthTokenService authTokenService;
private final PddGoodsPopApiClient goodsPopApiClient;
@@ -39,6 +42,7 @@ public class PddGoodsEnsureServiceImpl implements PddGoodsEnsureService {
private final PddGoodsService pddGoodsService;
public PddGoodsEnsureServiceImpl(PddGoodsMapper pddGoodsMapper,
PddGoodsSkuMapper pddGoodsSkuMapper,
PddShopMapper pddShopMapper,
PddAuthTokenService authTokenService,
PddGoodsPopApiClient goodsPopApiClient,
@@ -46,6 +50,7 @@ public class PddGoodsEnsureServiceImpl implements PddGoodsEnsureService {
PddProductAutoCreateService productAutoCreateService,
@Lazy PddGoodsService pddGoodsService) {
this.pddGoodsMapper = pddGoodsMapper;
this.pddGoodsSkuMapper = pddGoodsSkuMapper;
this.pddShopMapper = pddShopMapper;
this.authTokenService = authTokenService;
this.goodsPopApiClient = goodsPopApiClient;
@@ -56,16 +61,112 @@ public class PddGoodsEnsureServiceImpl implements PddGoodsEnsureService {
@Override
@Transactional(rollbackFor = Exception.class)
public PddGoodsPO ensureBound(Long companyId, Long channelShopId, String goodsId) throws Exception {
public PddGoodsPO ensureChannelGoods(Long companyId, Long channelShopId, String goodsId)
throws Exception {
if (companyId == null || channelShopId == null || !StringUtils.hasText(goodsId)) {
throw new BusinessException("渠道商品定位参数不完整");
}
String gid = goodsId.trim();
PddGoodsPO existing = find(companyId, channelShopId, gid);
if (existing != null && existing.getProductId() != null) {
return existing;
if (existing != null) {
Long skuCount = pddGoodsSkuMapper.selectCount(new LambdaQueryWrapper<PddGoodsSkuPO>()
.eq(PddGoodsSkuPO::getGoodsRowId, existing.getId()));
if (skuCount != null && skuCount > 0) {
return existing;
}
// 已有主表但无 SKU:再拉一次详情补齐
log.info("渠道商品无 SKU,重新同步 channelShopId={} goodsId={}", channelShopId, gid);
}
PddShopPO pddShop = requireShop(companyId, channelShopId);
PddGoodsPopApiClient.GoodsDetail detail = fetchDetail(pddShop, gid);
pddGoodsService.upsertFromGoodsDetail(
companyId, channelShopId, pddShop.getMallId(), detail);
PddGoodsPO saved = find(companyId, channelShopId, gid);
if (saved == null) {
throw new BusinessException("渠道商品落库失败 goods_id=" + gid);
}
log.info("已确保渠道商品入库 channelShopId={} goodsId={}", channelShopId, gid);
return saved;
}
@Override
public void ensureInternalProductsForChannelGoods(Long companyId, PddGoodsPO channelGoods) {
if (companyId == null || channelGoods == null || channelGoods.getId() == null) {
return;
}
try {
List<PddGoodsSkuPO> skus = pddGoodsSkuMapper.selectList(new LambdaQueryWrapper<PddGoodsSkuPO>()
.eq(PddGoodsSkuPO::getGoodsRowId, channelGoods.getId()));
MatchState match = classifyMatch(companyId, skus);
if (!match.hasOuterId()) {
log.warn("渠道商品无 outer_id,跳过内部建品 goodsRowId={} goodsId={}",
channelGoods.getId(), channelGoods.getGoodsId());
return;
}
if (!match.hasUnmatched()) {
return;
}
// 有缺失:拉详情后补 SKU 或整品创建
if (channelGoods.getShopId() == null || !StringUtils.hasText(channelGoods.getGoodsId())) {
log.warn("渠道商品缺少 shop/goodsId,无法拉详情建品 goodsRowId={}", channelGoods.getId());
return;
}
PddShopPO pddShop = requireShop(companyId, channelGoods.getShopId());
PddGoodsPopApiClient.GoodsDetail detail = fetchDetail(pddShop, channelGoods.getGoodsId());
if (match.firstMatchedProductId() != null) {
productAutoCreateService.ensureMissingSkus(
companyId, match.firstMatchedProductId(), detail);
} else {
Long created = productAutoCreateService.ensureInternalProduct(companyId, detail);
if (created == null) {
log.warn("转换/建品:无法自动创建内部商品 goodsId={}", channelGoods.getGoodsId());
}
}
} catch (Exception e) {
log.warn("按渠道商品自动建内部品失败 goodsRowId={} goodsId={}: {}",
channelGoods.getId(), channelGoods.getGoodsId(), e.getMessage());
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public PddGoodsPO ensureBound(Long companyId, Long channelShopId, String goodsId) throws Exception {
PddGoodsPO goods = ensureChannelGoods(companyId, channelShopId, goodsId);
ensureInternalProductsForChannelGoods(companyId, goods);
return goods;
}
private MatchState classifyMatch(Long companyId, List<PddGoodsSkuPO> skus) {
boolean hasOuter = false;
boolean hasUnmatched = false;
Long firstMatchedProductId = null;
if (skus == null) {
return new MatchState(false, false, null);
}
for (PddGoodsSkuPO sku : skus) {
if (sku == null || !StringUtils.hasText(sku.getOuterId())) {
continue;
}
hasOuter = true;
ProductSkuPO internal = productSkuMapper.selectOne(new LambdaQueryWrapper<ProductSkuPO>()
.eq(ProductSkuPO::getCompanyId, companyId)
.eq(ProductSkuPO::getSkuCode, sku.getOuterId().trim())
.last("LIMIT 1"));
if (internal != null && internal.getProductId() != null) {
if (firstMatchedProductId == null) {
firstMatchedProductId = internal.getProductId();
}
} else {
hasUnmatched = true;
}
}
return new MatchState(hasOuter, hasUnmatched, firstMatchedProductId);
}
private PddShopPO requireShop(Long companyId, Long channelShopId) {
PddShopPO pddShop = pddShopMapper.selectById(channelShopId);
if (pddShop == null || !Objects.equals(pddShop.getCompanyId(), companyId)) {
throw new BusinessException("渠道店铺不存在 channelShopId=" + channelShopId);
@@ -73,41 +174,24 @@ public class PddGoodsEnsureServiceImpl implements PddGoodsEnsureService {
if (pddShop.getPddAuthId() == null) {
throw new PddAuthFailureException("渠道店铺未授权,无法拉取商品");
}
return pddShop;
}
private PddGoodsPopApiClient.GoodsDetail fetchDetail(PddShopPO pddShop, String gid)
throws Exception {
long goodsIdLong;
try {
goodsIdLong = Long.parseLong(gid);
} catch (NumberFormatException e) {
throw new BusinessException("非法 goods_id=" + gid);
}
PddAuthPO auth = authTokenService.ensureUsableById(pddShop.getPddAuthId());
PddGoodsPopApiClient.GoodsDetail detail = goodsPopApiClient.fetchGoodsInformation(
pddShop.getMallId(), auth.getAccessToken(), goodsIdLong);
if (detail == null || detail.goodsId() == null) {
throw new BusinessException("拉取拼多多商品详情为空 goods_id=" + gid);
}
Long productId = resolveProductIdByOuterIds(companyId, detail.skuList());
if (productId != null) {
// 已有内部品:只补缺失 SKU,不挪动已挂在其他商品下的 SKU
productAutoCreateService.ensureMissingSkus(companyId, productId, detail);
} else {
productId = productAutoCreateService.ensureInternalProduct(companyId, detail);
}
if (productId == null) {
throw new BusinessException("无法关联或自动创建内部商品 goods_id=" + gid);
}
pddGoodsService.upsertFromGoodsDetail(
companyId, channelShopId, pddShop.getMallId(), productId, detail);
PddGoodsPO saved = find(companyId, channelShopId, gid);
if (saved == null || saved.getProductId() == null) {
throw new BusinessException("渠道商品落库失败 goods_id=" + gid);
}
log.info("已确保渠道商品绑定 channelShopId={} goodsId={} productId={}",
channelShopId, gid, saved.getProductId());
return saved;
return detail;
}
private PddGoodsPO find(Long companyId, Long channelShopId, String goodsId) {
@@ -118,26 +202,6 @@ public class PddGoodsEnsureServiceImpl implements PddGoodsEnsureService {
.last("LIMIT 1"));
}
/**
* 按 outer_id → 内部 sku_code 扫描,取第一个命中的 product_id。
* 多个 SKU 落在不同内部商品时仍取首个,不改动其余内部商品。
*/
private Long resolveProductIdByOuterIds(Long companyId, List<PddGoodsPopApiClient.SkuDetail> skus) {
if (skus == null || skus.isEmpty()) {
return null;
}
for (PddGoodsPopApiClient.SkuDetail sku : skus) {
if (sku == null || !StringUtils.hasText(sku.outerId())) {
continue;
}
ProductSkuPO internal = productSkuMapper.selectOne(new LambdaQueryWrapper<ProductSkuPO>()
.eq(ProductSkuPO::getCompanyId, companyId)
.eq(ProductSkuPO::getSkuCode, sku.outerId().trim())
.last("LIMIT 1"));
if (internal != null && internal.getProductId() != null) {
return internal.getProductId();
}
}
return null;
private record MatchState(boolean hasOuterId, boolean hasUnmatched, Long firstMatchedProductId) {
}
}
@@ -16,8 +16,6 @@ public class CreatePddGoodsDTO {
@NotNull(message = "mall_id不能为空")
private Long mallId;
private Long productId;
@NotBlank(message = "商品ID不能为空")
private String goodsId;
@@ -9,8 +9,6 @@ public class PddGoodsFilterDTO {
private Long mallId;
private Long productId;
private String goodsName;
private String goodsId;
@@ -16,8 +16,6 @@ public class UpdatePddGoodsDTO {
@NotNull(message = "mall_id不能为空")
private Long mallId;
private Long productId;
@NotBlank(message = "商品ID不能为空")
private String goodsId;
@@ -23,10 +23,6 @@ public class PddGoodsPO {
@TableField("mall_id")
private Long mallId;
/** 内部商品ID(ec_product.id) */
@TableField("product_id")
private Long productId;
@TableField("goods_id")
private String goodsId;
@@ -16,10 +16,6 @@ public class PddGoodsVO {
private Long mallId;
private Long productId;
private String productName;
private String goodsId;
private String goodsName;
@@ -31,10 +31,10 @@ public interface PddGoodsService extends IService<PddGoodsPO> {
PddGoodsSyncResultVO syncGoodsByPddShop(Long pddShopId);
/**
* 按商品详情 upsert 渠道商品及 SKU,并绑定内部商品(product_id 必填)。
* 按商品详情 upsert 渠道商品及 SKU(不定内部商品)。
*
* @param pddShopId channel_pdd_shop.id
*/
void upsertFromGoodsDetail(Long companyId, Long pddShopId, Long mallId,
Long productId, PddGoodsPopApiClient.GoodsDetail detail);
PddGoodsPopApiClient.GoodsDetail detail);
}
@@ -341,7 +341,7 @@ public class PddGoodsPublishServiceImpl implements PddGoodsPublishService {
// 主商品下补缺失 SKU(外商品已有 sku_code 会跳过,不挪绑)
productAutoCreateService.ensureMissingSkus(companyId, primary.getId(), detailInfo);
pddGoodsService.upsertFromGoodsDetail(
companyId, ctx.shop().getId(), ctx.mallId(), primary.getId(), detailInfo);
companyId, ctx.shop().getId(), ctx.mallId(), detailInfo);
PddGoodsPO local = pddGoodsMapper.selectOne(new LambdaQueryWrapper<PddGoodsPO>()
.eq(PddGoodsPO::getCompanyId, companyId)
@@ -15,6 +15,7 @@ import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.common.utils.BeanCopyUtils;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.model.po.PddAuthPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.service.PddAuthTokenService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.ensure.PddGoodsEnsureService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.mapper.PddGoodsMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.mapper.PddGoodsSkuMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.CreatePddGoodsDTO;
@@ -26,14 +27,11 @@ import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.po.PddGoodsSkuP
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.PddGoodsSkuVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.PddGoodsSyncResultVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.PddGoodsVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.ensure.PddGoodsEnsureService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.service.PddGoodsService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.goods.PddGoodsPopApiClient;
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.product.mapper.ProductMapper;
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.mapper.ProductSkuMapper;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.model.po.ProductSkuPO;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
@@ -41,14 +39,14 @@ import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
/**
* 拼多多渠道商品 CRUD 与列表同步;主表不定内部商品。
*/
@Slf4j
@Service
public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO> implements PddGoodsService {
@@ -61,7 +59,6 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
private final PddAuthTokenService authTokenService;
private final PddGoodsPopApiClient goodsPopApiClient;
private final ProductSkuMapper productSkuMapper;
private final ProductMapper productMapper;
private final PddGoodsEnsureService goodsEnsureService;
private final CurrentUserContext currentUserContext;
@@ -70,7 +67,6 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
PddAuthTokenService authTokenService,
PddGoodsPopApiClient goodsPopApiClient,
ProductSkuMapper productSkuMapper,
ProductMapper productMapper,
@Lazy PddGoodsEnsureService goodsEnsureService,
CurrentUserContext currentUserContext) {
this.pddGoodsSkuMapper = pddGoodsSkuMapper;
@@ -78,7 +74,6 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
this.authTokenService = authTokenService;
this.goodsPopApiClient = goodsPopApiClient;
this.productSkuMapper = productSkuMapper;
this.productMapper = productMapper;
this.goodsEnsureService = goodsEnsureService;
this.currentUserContext = currentUserContext;
}
@@ -95,14 +90,9 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
throw new BusinessException("该商品已存在");
}
Long productId = resolveProductIdForManual(
companyId, createPddGoodsDTO.getProductId(), createPddGoodsDTO.getSkus());
requireOwnedProduct(companyId, productId);
PddGoodsPO goods = new PddGoodsPO();
BeanCopyUtils.copyProperties(createPddGoodsDTO, goods);
goods.setCompanyId(companyId);
goods.setProductId(productId);
this.save(goods);
if (createPddGoodsDTO.getSkus() != null && !createPddGoodsDTO.getSkus().isEmpty()) {
@@ -133,18 +123,10 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
throw new BusinessException("该商品已存在");
}
Long productId = resolveProductIdForManual(
companyId, updatePddGoodsDTO.getProductId(), updatePddGoodsDTO.getSkus());
if (productId == null) {
productId = existing.getProductId();
}
requireOwnedProduct(companyId, productId);
PddGoodsPO goods = new PddGoodsPO();
BeanCopyUtils.copyProperties(updatePddGoodsDTO, goods);
goods.setId(id);
goods.setCompanyId(companyId);
goods.setProductId(productId);
this.updateById(goods);
LambdaQueryWrapper<PddGoodsSkuPO> deleteWrapper = new LambdaQueryWrapper<>();
@@ -192,9 +174,6 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
if (filter.getMallId() != null) {
wrapper.eq(PddGoodsPO::getMallId, filter.getMallId());
}
if (filter.getProductId() != null) {
wrapper.eq(PddGoodsPO::getProductId, filter.getProductId());
}
if (filter.getGoodsName() != null && !filter.getGoodsName().isEmpty()) {
wrapper.like(PddGoodsPO::getGoodsName, filter.getGoodsName());
}
@@ -214,9 +193,8 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
IPage<PddGoodsPO> page = new Page<>(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
IPage<PddGoodsPO> result = this.page(page, wrapper);
Map<Long, String> productNames = loadProductNames(result.getRecords());
List<PddGoodsVO> voList = result.getRecords().stream()
.map(g -> convertToBriefVO(g, productNames))
.map(this::convertToBriefVO)
.collect(Collectors.toList());
return PageResultVO.create(voList, result.getTotal(),
@@ -294,7 +272,7 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
continue;
}
UpsertResult ur = upsertGoodsItem(
companyId, pddShopId, mallId, accessToken, item, syncTime);
companyId, pddShopId, mallId, item, syncTime);
if (ur.skipped()) {
skipped++;
continue;
@@ -335,12 +313,11 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
@Override
@Transactional(rollbackFor = Exception.class)
public void upsertFromGoodsDetail(Long companyId, Long pddShopId, Long mallId,
Long productId, PddGoodsPopApiClient.GoodsDetail detail) {
if (companyId == null || pddShopId == null || productId == null
PddGoodsPopApiClient.GoodsDetail detail) {
if (companyId == null || pddShopId == null
|| detail == null || detail.goodsId() == null) {
throw new BusinessException("渠道商品落库参数不完整");
}
requireOwnedProduct(companyId, productId);
String goodsId = String.valueOf(detail.goodsId());
PddGoodsPO existing = this.getOne(new LambdaQueryWrapper<PddGoodsPO>()
@@ -354,7 +331,6 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
goods.setCompanyId(companyId);
goods.setShopId(pddShopId);
goods.setMallId(mallId);
goods.setProductId(productId);
goods.setGoodsId(goodsId);
goods.setGoodsName(StringUtils.hasText(detail.goodsName()) ? detail.goodsName().trim() : goodsId);
if (goods.getGoodsQuantity() == null) {
@@ -410,7 +386,6 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
private UpsertResult upsertGoodsItem(Long companyId,
Long pddShopId,
Long mallId,
String accessToken,
PddGoodsPopApiClient.GoodsListItem item,
LocalDateTime syncTime) {
String goodsId = String.valueOf(item.goodsId());
@@ -419,33 +394,11 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
.eq(PddGoodsPO::getGoodsId, goodsId)
.last("LIMIT 1"));
boolean autoCreatedInternal = false;
Long productId = resolveProductIdFromOuterIds(companyId, firstOuterIdFromApiSkus(item.skuList()));
if (productId == null && existing != null) {
productId = existing.getProductId();
}
if (productId == null) {
try {
PddGoodsPO bound = goodsEnsureService.ensureBound(companyId, pddShopId, goodsId);
productId = bound != null ? bound.getProductId() : null;
autoCreatedInternal = productId != null;
} catch (Exception e) {
log.warn("同步时确保渠道商品失败 shopId={} goodsId={}: {}",
pddShopId, goodsId, e.getMessage());
}
}
if (productId == null) {
log.warn("跳过拼多多商品:无法匹配或创建内部商品 shopId={} goodsId={} firstOuterId={}",
pddShopId, goodsId, firstOuterIdFromApiSkus(item.skuList()));
return new UpsertResult(false, 0, true, false);
}
boolean created = existing == null;
PddGoodsPO goods = existing != null ? existing : new PddGoodsPO();
goods.setCompanyId(companyId);
goods.setShopId(pddShopId);
goods.setMallId(mallId);
goods.setProductId(productId);
goods.setGoodsId(goodsId);
goods.setGoodsName(StringUtils.hasText(item.goodsName()) ? item.goodsName() : goodsId);
goods.setGoodsQuantity(toInt(item.goodsQuantity()));
@@ -488,82 +441,39 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
skuInserted++;
}
}
// 尽力而为:无 outer 匹配时尝试自动建品/补 SKU,不阻塞渠道镜像
boolean autoCreatedInternal = false;
if (!hasMatchedInternalSku(companyId, item.skuList())) {
try {
goodsEnsureService.ensureBound(companyId, pddShopId, goodsId);
autoCreatedInternal = true;
} catch (Exception e) {
log.warn("同步时尽力确保内部商品失败 shopId={} goodsId={}: {}",
pddShopId, goodsId, e.getMessage());
}
}
return new UpsertResult(created, skuInserted, false, autoCreatedInternal);
}
private Long resolveProductIdForManual(Long companyId, Long explicitProductId,
List<CreatePddGoodsSkuDTO> skus) {
if (explicitProductId != null) {
return explicitProductId;
}
String firstOuterId = null;
if (skus != null) {
for (CreatePddGoodsSkuDTO sku : skus) {
if (sku != null && StringUtils.hasText(sku.getOuterId())) {
firstOuterId = sku.getOuterId().trim();
break;
}
}
}
Long productId = resolveProductIdFromOuterIds(companyId, firstOuterId);
if (productId == null) {
throw new BusinessException("无法关联内部商品:请传入 productId,或保证首条 SKU 的 outerId 能匹配内部 sku_code");
}
return productId;
}
private Long resolveProductIdFromOuterIds(Long companyId, String outerId) {
if (!StringUtils.hasText(outerId) || companyId == null) {
return null;
}
ProductSkuPO sku = productSkuMapper.selectOne(new LambdaQueryWrapper<ProductSkuPO>()
.eq(ProductSkuPO::getCompanyId, companyId)
.eq(ProductSkuPO::getSkuCode, outerId.trim())
.last("LIMIT 1"));
return sku != null ? sku.getProductId() : null;
}
private static String firstOuterIdFromApiSkus(List<PddGoodsPopApiClient.GoodsListSku> skus) {
if (skus == null) {
return null;
private boolean hasMatchedInternalSku(Long companyId,
List<PddGoodsPopApiClient.GoodsListSku> skus) {
if (skus == null || companyId == null) {
return false;
}
for (PddGoodsPopApiClient.GoodsListSku sku : skus) {
if (sku != null && StringUtils.hasText(sku.outerId())) {
return sku.outerId().trim();
if (sku == null || !StringUtils.hasText(sku.outerId())) {
continue;
}
Long count = productSkuMapper.selectCount(new LambdaQueryWrapper<ProductSkuPO>()
.eq(ProductSkuPO::getCompanyId, companyId)
.eq(ProductSkuPO::getSkuCode, sku.outerId().trim()));
if (count != null && count > 0) {
return true;
}
}
return null;
}
private void requireOwnedProduct(Long companyId, Long productId) {
if (productId == null) {
throw new BusinessException("内部商品ID不能为空");
}
ProductPO product = productMapper.selectById(productId);
if (product == null || !Objects.equals(product.getCompanyId(), companyId)) {
throw new BusinessException("内部商品不存在或无权访问");
}
}
private Map<Long, String> loadProductNames(List<PddGoodsPO> goodsList) {
if (goodsList == null || goodsList.isEmpty()) {
return Map.of();
}
List<Long> ids = goodsList.stream()
.map(PddGoodsPO::getProductId)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
if (ids.isEmpty()) {
return Map.of();
}
Map<Long, String> map = new HashMap<>();
for (ProductPO p : productMapper.selectByIds(ids)) {
if (p != null && p.getId() != null) {
map.put(p.getId(), p.getName());
}
}
return map;
return false;
}
private record UpsertResult(boolean created, int skuCount, boolean skipped, boolean autoCreatedInternal) {
@@ -601,12 +511,9 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
return sku;
}
private PddGoodsVO convertToBriefVO(PddGoodsPO goods, Map<Long, String> productNames) {
private PddGoodsVO convertToBriefVO(PddGoodsPO goods) {
PddGoodsVO vo = new PddGoodsVO();
BeanCopyUtils.copyProperties(goods, vo);
if (goods.getProductId() != null) {
vo.setProductName(productNames.get(goods.getProductId()));
}
vo.setSkus(null);
return vo;
}
@@ -614,12 +521,6 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
private PddGoodsVO convertToVO(PddGoodsPO goods) {
PddGoodsVO vo = new PddGoodsVO();
BeanCopyUtils.copyProperties(goods, vo);
if (goods.getProductId() != null) {
ProductPO product = productMapper.selectById(goods.getProductId());
if (product != null) {
vo.setProductName(product.getName());
}
}
LambdaQueryWrapper<PddGoodsSkuPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(PddGoodsSkuPO::getGoodsRowId, goods.getId());
@@ -24,7 +24,7 @@ import top.xyquan.ecomdmbbackend.modules.ec.product.sku.service.ProductSkuServic
/**
* 按平台 goodsId 拉详情,自动创建内部商品 + 全部 SKU(已存在则跳过),
* 并 upsert 渠道商品 channel_pdd_goods(绑定 product_id)。
* 并 upsert 渠道商品 channel_pdd_goods(不定主表 product_id,内部关联经 SKU outer_id)。
* 类目:PDD 一级/叶子 → 内部一级/二级;按公司内叶子类目名复用,不重复创建。
*/
@Slf4j
@@ -5,8 +5,6 @@ export namespace PddGoodsDTO {
/** 渠道店铺ID(channel_pdd_shop.id) */
shopId?: number;
mallId?: number;
/** 内部商品ID */
productId?: number;
goodsName?: string;
goodsId?: string;
/** 0否 1是 */
@@ -36,8 +34,6 @@ export namespace PddGoodsVO {
companyId?: number;
shopId?: number;
mallId?: number;
productId?: number;
productName?: string;
goodsId?: string;
goodsName?: string;
goodsQuantity?: number;
@@ -4,7 +4,6 @@ import type { PddGoodsVO } from '#/api/channel/pdd/goods';
import { ref } from 'vue';
import {
Button,
Descriptions,
DescriptionsItem,
Drawer,
@@ -19,10 +18,6 @@ import { getPddGoodsDetailApi } from '#/api/channel/pdd/goods';
defineOptions({ name: 'PddGoodsDetailDrawer' });
const emit = defineEmits<{
openInternalProduct: [row: PddGoodsVO.Info];
}>();
const openFlag = ref(false);
const loading = ref(false);
const shopName = ref('');
@@ -74,14 +69,6 @@ function close() {
openFlag.value = false;
}
function openInternalProduct() {
if (!detail.value?.productId) {
message.warning('未关联内部商品');
return;
}
emit('openInternalProduct', detail.value);
}
defineExpose({ open, close });
</script>
@@ -126,18 +113,6 @@ defineExpose({ open, close });
<DescriptionsItem label="渠道店铺" :span="2">
{{ shopName || `渠道店#${detail.shopId}` }}
</DescriptionsItem>
<DescriptionsItem label="内部商品" :span="2">
<Button
v-if="detail.productId"
type="link"
size="small"
class="!px-0"
@click="openInternalProduct"
>
{{ detail.productName || `商品#${detail.productId}` }}
</Button>
<span v-else>-</span>
</DescriptionsItem>
<DescriptionsItem label="总库存">
{{ detail.goodsQuantity ?? 0 }}
</DescriptionsItem>
@@ -147,7 +122,7 @@ defineExpose({ open, close });
<DescriptionsItem label="最近同步">
{{ detail.lastSyncTime || '-' }}
</DescriptionsItem>
<DescriptionsItem label="平台创建">
<DescriptionsItem label="拼多多创建">
{{ detail.pddCreatedAt || '-' }}
</DescriptionsItem>
</Descriptions>
@@ -155,10 +130,10 @@ defineExpose({ open, close });
<div class="mb-2 text-sm font-medium">SKU 明细</div>
<Table
size="small"
:pagination="false"
:columns="skuColumns"
:data-source="detail.skus || []"
:row-key="(r: PddGoodsVO.Sku) => String(r.id ?? r.skuId)"
:pagination="false"
row-key="skuId"
:scroll="{ x: 700 }"
>
<template #bodyCell="{ column, record }">
@@ -17,7 +17,6 @@ import { getPddShopPageApi } from '#/api/channel/pdd/shop';
import { PermissionGate } from '#/components/permission';
import PddShopColPage from '#/views/channel/pdd/components/PddShopColPage.vue';
import PddShopDetailModal from '#/views/channel/pdd/shop/components/PddShopDetailModal.vue';
import ProductDetailDrawer from '#/views/ec/product/list/components/ProductDetailDrawer.vue';
import PddGoodsDetailDrawer from './components/PddGoodsDetailDrawer.vue';
import PddGoodsPublishModal from './components/PddGoodsPublishModal.vue';
@@ -27,7 +26,6 @@ defineOptions({ name: 'PddGoodsManagement' });
const loading = ref(false);
const detailDrawerRef = ref<InstanceType<typeof PddGoodsDetailDrawer>>();
const shopDetailModalRef = ref<InstanceType<typeof PddShopDetailModal>>();
const productDetailDrawerRef = ref<InstanceType<typeof ProductDetailDrawer>>();
const publishOpen = ref(false);
const publishHasDraft = ref(false);
/** 左侧选中的拼多多渠道店铺 ID */
@@ -93,12 +91,6 @@ const gridOptions: VxeGridProps<PddGoodsVO.Info> = {
showOverflow: 'tooltip' as const,
slots: { default: 'shop' },
},
{
title: '内部商品',
minWidth: 140,
showOverflow: 'tooltip' as const,
slots: { default: 'productName' },
},
{
title: '状态',
width: 90,
@@ -296,14 +288,6 @@ function openShopDetail(row: PddGoodsVO.Info) {
shopDetailModalRef.value?.open(row.shopId);
}
async function openInternalProduct(row: PddGoodsVO.Info) {
if (!row.productId) {
message.warning('未关联内部商品');
return;
}
await productDetailDrawerRef.value?.openById(row.productId, row.productName);
}
async function handleDelete(row: PddGoodsVO.Info) {
try {
await deletePddGoodsApi(row.id);
@@ -363,19 +347,6 @@ onMounted(async () => {
</Button>
</template>
<template #productName="{ row }: { row: PddGoodsVO.Info }">
<Button
v-if="row.productId"
type="link"
size="small"
class="!px-0"
@click="openInternalProduct(row)"
>
{{ row.productName || `商品#${row.productId}` }}
</Button>
<span v-else class="text-slate-400">-</span>
</template>
<template #shop="{ row }: { row: PddGoodsVO.Info }">
<Button
v-if="row.shopId"
@@ -420,12 +391,8 @@ onMounted(async () => {
</div>
</Card>
<PddGoodsDetailDrawer
ref="detailDrawerRef"
@open-internal-product="openInternalProduct"
/>
<PddGoodsDetailDrawer ref="detailDrawerRef" />
<PddShopDetailModal ref="shopDetailModalRef" />
<ProductDetailDrawer ref="productDetailDrawerRef" />
<PddGoodsPublishModal
v-model:open="publishOpen"
v-model:has-draft="publishHasDraft"