新增拼多多广告费转换层

This commit is contained in:
2026-08-17 11:24:16 +08:00
parent fa5c4929c9
commit 8a41072e6e
24 changed files with 330 additions and 415 deletions
@@ -65,7 +65,9 @@ public class PddGoodsAdFeeController {
return ApiResponse.success("获取成功", pddGoodsAdFeeService.getPage(pageQueryDTO));
}
@Operation(summary = "批量导入/覆盖", description = "按 goods_id+日期 upsert,店铺从商品表反查")
@Operation(summary = "批量导入/覆盖",
description = "按 channelShopId+goods_id+日期 upsert;金额无变化跳过更新;"
+ "新增/变更后异步转换为内部广告费(缺渠道商品时自动拉取并绑定内部商品)")
@PostMapping("/batch-import")
@RequirePermission(value = "biz:pdd:ad-fee:manage", description = "批量导入拼多多商品广告费", allowSuper = true)
public ApiResponse<BatchImportPddGoodsAdFeeResultVO> batchImport(
@@ -0,0 +1,46 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.convert.messaging;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.convert.service.PddGoodsAdFeeConvertService;
import java.util.List;
/**
* 渠道广告费 → 内部广告费 异步投递入口(事务提交后调用)。
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class PddGoodsAdFeeConvertAsyncInvoker {
private final PddGoodsAdFeeConvertService convertService;
@Async
public void convertAsync(Long channelAdFeeId) {
if (channelAdFeeId == null) {
return;
}
try {
convertService.convertByChannelAdFeeId(channelAdFeeId);
} catch (Exception e) {
log.error("异步转换拼多多广告费失败 channelAdFeeId={}", channelAdFeeId, e);
}
}
@Async
public void convertBatchAsync(List<Long> channelAdFeeIds) {
if (channelAdFeeIds == null || channelAdFeeIds.isEmpty()) {
return;
}
for (Long id : channelAdFeeIds) {
try {
convertService.convertByChannelAdFeeId(id);
} catch (Exception e) {
log.error("异步转换拼多多广告费失败 channelAdFeeId={}", id, e);
}
}
}
}
@@ -0,0 +1,185 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.convert.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
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.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.model.po.PddGoodsPO;
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.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.adfee.mapper.AdFeeMapper;
import top.xyquan.ecomdmbbackend.modules.ec.adfee.model.po.AdFeePO;
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.math.BigDecimal;
import java.util.Objects;
/**
* 拼多多渠道商品广告费 → 内部 ec_ad_fee 转换。
* <p>
* goods_id → channel_pdd_goods → product_id;渠道商品缺失时拉详情自动建品并落库绑定。
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class PddGoodsAdFeeConvertService {
private static final String CAMPAIGN_NAME = "拼多多商品推广";
private final PddGoodsAdFeeDailyMapper channelAdFeeMapper;
private final PddGoodsMapper pddGoodsMapper;
private final PddShopMapper pddShopMapper;
private final PddAuthTokenService authTokenService;
private final PddGoodsPopApiClient goodsPopApiClient;
private final PddProductAutoCreateService productAutoCreateService;
private final PddGoodsService pddGoodsService;
private final ShopMapper shopMapper;
private final AdFeeMapper adFeeMapper;
@Transactional(rollbackFor = Exception.class)
public void convertByChannelAdFeeId(Long channelAdFeeId) throws Exception {
if (channelAdFeeId == null) {
return;
}
PddGoodsAdFeeDailyPO channelFee = channelAdFeeMapper.selectById(channelAdFeeId);
if (channelFee == null) {
log.warn("渠道广告费不存在,跳过转换 id={}", channelAdFeeId);
return;
}
if (channelFee.getFeeAmount() == null
|| channelFee.getFeeAmount().compareTo(BigDecimal.ZERO) <= 0) {
log.warn("渠道广告费金额无效,跳过转换 id={} amount={}",
channelAdFeeId, channelFee.getFeeAmount());
return;
}
Long productId = resolveProductId(
channelFee.getCompanyId(),
channelFee.getChannelShopId(),
channelFee.getGoodsId());
if (productId == null) {
throw new BusinessException("无法解析内部商品 productId,goods_id=" + channelFee.getGoodsId());
}
Long internalShopId = resolveInternalShopId(
channelFee.getCompanyId(), channelFee.getChannelShopId());
if (internalShopId == null) {
throw new BusinessException("未找到绑定该渠道店的内部店铺 channelShopId="
+ channelFee.getChannelShopId());
}
upsertInternalAdFee(channelFee, productId, internalShopId);
}
/**
* 查找渠道商品绑定的内部商品;不存在则拉详情自动建品并 upsert channel_pdd_goods。
*/
private Long resolveProductId(Long companyId, Long channelShopId, String goodsId) throws Exception {
if (companyId == null || channelShopId == null || !StringUtils.hasText(goodsId)) {
return null;
}
String gid = goodsId.trim();
PddGoodsPO goods = pddGoodsMapper.selectOne(new LambdaQueryWrapper<PddGoodsPO>()
.eq(PddGoodsPO::getCompanyId, companyId)
.eq(PddGoodsPO::getShopId, channelShopId)
.eq(PddGoodsPO::getGoodsId, gid)
.last("LIMIT 1"));
if (goods != null && goods.getProductId() != null) {
return goods.getProductId();
}
PddShopPO pddShop = pddShopMapper.selectById(channelShopId);
if (pddShop == null || !Objects.equals(pddShop.getCompanyId(), companyId)) {
throw new BusinessException("渠道店铺不存在 channelShopId=" + channelShopId);
}
if (pddShop.getPddAuthId() == null) {
throw new BusinessException("渠道店铺未授权,无法拉取商品 channelShopId=" + channelShopId);
}
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);
Long productId = productAutoCreateService.ensureInternalProduct(companyId, detail);
if (productId == null) {
log.warn("自动建内部商品失败 companyId={} goodsId={}", companyId, gid);
return null;
}
pddGoodsService.upsertFromGoodsDetail(
companyId, channelShopId, pddShop.getMallId(), productId, detail);
log.info("广告费转换:已自动拉取并绑定渠道商品 channelShopId={} goodsId={} productId={}",
channelShopId, gid, productId);
return productId;
}
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())
.last("LIMIT 1"));
return shop != null ? shop.getId() : null;
}
private void upsertInternalAdFee(PddGoodsAdFeeDailyPO channelFee,
Long productId,
Long internalShopId) {
AdFeePO existing = adFeeMapper.selectOne(new LambdaQueryWrapper<AdFeePO>()
.eq(AdFeePO::getProductId, productId)
.eq(AdFeePO::getFeeDate, channelFee.getFeeDate())
.last("LIMIT 1"));
if (existing == null) {
AdFeePO po = new AdFeePO();
po.setCompanyId(channelFee.getCompanyId());
po.setShopId(internalShopId);
po.setProductId(productId);
po.setCampaignName(CAMPAIGN_NAME);
po.setFeeAmount(channelFee.getFeeAmount());
po.setFeeDate(channelFee.getFeeDate());
po.setRemark("channel_pdd_goods_ad_fee_daily#" + channelFee.getId()
+ " goods_id=" + channelFee.getGoodsId());
adFeeMapper.insert(po);
log.info("已转换新增内部广告费 productId={} feeDate={} amount={} channelId={}",
productId, channelFee.getFeeDate(), channelFee.getFeeAmount(), channelFee.getId());
return;
}
boolean amountChanged = existing.getFeeAmount() == null
|| existing.getFeeAmount().compareTo(channelFee.getFeeAmount()) != 0;
boolean shopChanged = !Objects.equals(existing.getShopId(), internalShopId);
if (!amountChanged && !shopChanged) {
log.debug("内部广告费无变化,跳过更新 productId={} feeDate={}",
productId, channelFee.getFeeDate());
return;
}
existing.setShopId(internalShopId);
existing.setFeeAmount(channelFee.getFeeAmount());
if (!StringUtils.hasText(existing.getCampaignName())) {
existing.setCampaignName(CAMPAIGN_NAME);
}
adFeeMapper.updateById(existing);
log.info("已转换更新内部广告费 id={} productId={} feeDate={} amount={}",
existing.getId(), productId, channelFee.getFeeDate(), channelFee.getFeeAmount());
}
}
@@ -0,0 +1,55 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.convert.support;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.convert.messaging.PddGoodsAdFeeConvertAsyncInvoker;
import java.util.ArrayList;
import java.util.List;
/**
* 事务提交后再异步触发渠道广告费转换,避免读到未提交数据。
*/
@Component
@RequiredArgsConstructor
public class PddGoodsAdFeeConvertScheduler {
private final PddGoodsAdFeeConvertAsyncInvoker asyncInvoker;
public void scheduleAfterCommit(Long channelAdFeeId) {
if (channelAdFeeId == null) {
return;
}
Runnable task = () -> asyncInvoker.convertAsync(channelAdFeeId);
if (!TransactionSynchronizationManager.isSynchronizationActive()) {
task.run();
return;
}
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCommit() {
task.run();
}
});
}
public void scheduleBatchAfterCommit(List<Long> channelAdFeeIds) {
if (channelAdFeeIds == null || channelAdFeeIds.isEmpty()) {
return;
}
List<Long> ids = new ArrayList<>(channelAdFeeIds);
Runnable task = () -> asyncInvoker.convertBatchAsync(ids);
if (!TransactionSynchronizationManager.isSynchronizationActive()) {
task.run();
return;
}
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCommit() {
task.run();
}
});
}
}
@@ -22,7 +22,8 @@ public interface PddGoodsAdFeeService {
PageResultVO<PddGoodsAdFeeVO> getPage(PageQueryDTO<PddGoodsAdFeeFilterDTO> pageQueryDTO);
/**
* 按 channelShopId + goods_id + fee_date + fee_amount 批量写入(存在则覆盖金额)。
* 按 channelShopId + goods_id + fee_date 批量写入;
* 金额有变化才更新;新增/变更后异步转换为内部广告费(缺渠道商品时自动拉取绑定)。
*/
BatchImportPddGoodsAdFeeResultVO batchImport(BatchImportPddGoodsAdFeeDTO dto);
}
@@ -11,6 +11,7 @@ import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.common.utils.BeanCopyUtils;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.convert.support.PddGoodsAdFeeConvertScheduler;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.mapper.PddGoodsAdFeeDailyMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.dto.BatchImportPddGoodsAdFeeDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.adfee.model.dto.BatchImportPddGoodsAdFeeItemDTO;
@@ -46,6 +47,7 @@ public class PddGoodsAdFeeServiceImpl implements PddGoodsAdFeeService {
private final PddShopMapper pddShopMapper;
private final PddGoodsMapper pddGoodsMapper;
private final CurrentUserContext currentUserContext;
private final PddGoodsAdFeeConvertScheduler convertScheduler;
@Override
@Transactional(rollbackFor = Exception.class)
@@ -65,6 +67,7 @@ public class PddGoodsAdFeeServiceImpl implements PddGoodsAdFeeService {
po.setFeeAmount(dto.getFeeAmount());
po.setLastSyncTime(LocalDateTime.now());
adFeeMapper.insert(po);
convertScheduler.scheduleAfterCommit(po.getId());
return toVo(po);
}
@@ -78,13 +81,25 @@ public class PddGoodsAdFeeServiceImpl implements PddGoodsAdFeeService {
assertUnique(shop.getId(), dto.getGoodsId(), dto.getFeeDate(), id);
assertFeeAmount(dto.getFeeAmount());
String goodsId = dto.getGoodsId().trim();
boolean changed = !Objects.equals(existing.getChannelShopId(), shop.getId())
|| !Objects.equals(existing.getGoodsId(), goodsId)
|| !Objects.equals(existing.getFeeDate(), dto.getFeeDate())
|| existing.getFeeAmount() == null
|| existing.getFeeAmount().compareTo(dto.getFeeAmount()) != 0;
if (!changed) {
return toVo(existing);
}
existing.setChannelShopId(shop.getId());
existing.setMallId(shop.getMallId());
existing.setGoodsId(dto.getGoodsId().trim());
existing.setGoodsId(goodsId);
existing.setFeeDate(dto.getFeeDate());
existing.setFeeAmount(dto.getFeeAmount());
existing.setLastSyncTime(LocalDateTime.now());
adFeeMapper.updateById(existing);
convertScheduler.scheduleAfterCommit(existing.getId());
return toVo(existing);
}
@@ -143,14 +158,18 @@ public class PddGoodsAdFeeServiceImpl implements PddGoodsAdFeeService {
result.setSuccessIds(new ArrayList<>());
result.setFailureRecords(new ArrayList<>());
List<Long> changedIds = new ArrayList<>();
int success = 0;
for (int i = 0; i < items.size(); i++) {
BatchImportPddGoodsAdFeeItemDTO item = items.get(i);
int rowNumber = i + 1;
try {
Long id = upsertByChannelShopAndGoods(companyId, item);
result.getSuccessIds().add(id);
UpsertOutcome outcome = upsertByChannelShopAndGoods(companyId, item);
result.getSuccessIds().add(outcome.id());
success++;
if (outcome.changed()) {
changedIds.add(outcome.id());
}
} catch (Exception e) {
BatchImportPddGoodsAdFeeResultVO.ImportFailureRecord failure =
new BatchImportPddGoodsAdFeeResultVO.ImportFailureRecord();
@@ -163,10 +182,15 @@ public class PddGoodsAdFeeServiceImpl implements PddGoodsAdFeeService {
}
result.setSuccessCount(success);
result.setFailureCount(items.size() - success);
convertScheduler.scheduleBatchAfterCommit(changedIds);
return result;
}
private Long upsertByChannelShopAndGoods(Long companyId, BatchImportPddGoodsAdFeeItemDTO item) {
/**
* 按 channelShopId + goods_id + fee_date upsert;金额无变化则不写库。
* 不强制渠道商品已存在(转换层会自动拉取并绑定)。
*/
private UpsertOutcome upsertByChannelShopAndGoods(Long companyId, BatchImportPddGoodsAdFeeItemDTO item) {
if (item.getChannelShopId() == null) {
throw new BusinessException("渠道店铺ID不能为空");
}
@@ -182,7 +206,6 @@ public class PddGoodsAdFeeServiceImpl implements PddGoodsAdFeeService {
PddShopPO shop = requireOwnedShop(item.getChannelShopId(), companyId);
String goodsId = item.getGoodsId().trim();
assertGoodsInShop(companyId, shop.getId(), goodsId);
PddGoodsAdFeeDailyPO existing = adFeeMapper.selectOne(new LambdaQueryWrapper<PddGoodsAdFeeDailyPO>()
.eq(PddGoodsAdFeeDailyPO::getChannelShopId, shop.getId())
@@ -192,11 +215,15 @@ public class PddGoodsAdFeeServiceImpl implements PddGoodsAdFeeService {
LocalDateTime now = LocalDateTime.now();
if (existing != null) {
if (existing.getFeeAmount() != null
&& existing.getFeeAmount().compareTo(item.getFeeAmount()) == 0) {
return new UpsertOutcome(existing.getId(), false);
}
existing.setFeeAmount(item.getFeeAmount());
existing.setMallId(shop.getMallId());
existing.setLastSyncTime(now);
adFeeMapper.updateById(existing);
return existing.getId();
return new UpsertOutcome(existing.getId(), true);
}
PddGoodsAdFeeDailyPO po = new PddGoodsAdFeeDailyPO();
@@ -208,7 +235,7 @@ public class PddGoodsAdFeeServiceImpl implements PddGoodsAdFeeService {
po.setFeeAmount(item.getFeeAmount());
po.setLastSyncTime(now);
adFeeMapper.insert(po);
return po.getId();
return new UpsertOutcome(po.getId(), true);
}
private PddShopPO requireOwnedShop(Long channelShopId, Long companyId) {
@@ -302,4 +329,7 @@ public class PddGoodsAdFeeServiceImpl implements PddGoodsAdFeeService {
BeanCopyUtils.copyProperties(po, vo);
return vo;
}
private record UpsertOutcome(Long id, boolean changed) {
}
}
@@ -26,7 +26,8 @@ public class OpenPddGoodsAdFeeController {
@PostMapping("/batch-import")
@RequireOpenScope(value = OpenApiScopeConstants.PDD_GOODS_AD_FEE_IMPORT, description = "批量导入拼多多商品广告费")
@Operation(summary = "批量导入拼多多商品广告费",
description = "每条需 channelShopId、feeDate、goodsId、feeAmount(须大于0);同店同商品同日覆盖金额")
description = "每条需 channelShopId、feeDate、goodsId、feeAmount(须大于0);"
+ "同店同商品同日金额无变化则跳过更新;新增/变更后异步转为内部广告费")
public ApiResponse<BatchImportPddGoodsAdFeeResultVO> batchImport(
@Valid @RequestBody BatchImportPddGoodsAdFeeDTO dto) {
return ApiResponse.success("批量导入完成", pddGoodsAdFeeService.batchImport(dto));