feat: 新增拼多多商品关联内部商品

This commit is contained in:
2026-08-17 11:10:43 +08:00
parent d91b7cd168
commit fa5c4929c9
16 changed files with 665 additions and 25 deletions
@@ -2,9 +2,9 @@
-- 拼多多商品对接数据库设计
-- 数据来源:pdd.goods.list.get → goods_list_get_response.goods_list
-- 设计原则:
-- 1. 与 ec_product / ec_product_spec(内部成本分析商品)分离,存平台同步数据
-- 1. 与 ec_product / ec_product_sku(内部成本分析商品)分离,存平台同步数据
-- 2. SPU 主表 + SKU 明细表,spec_details 存入 SKU 行 JSON
-- 3. 后续可通过 outer_id / outer_goods_id 映射到 ec_product_spec
-- 3. 主表 product_id 必填:取 SKU 明细首条 outer_id 匹配 ec_product_sku.sku_code 后关联商品
-- ========================================
-- ========================================
@@ -17,6 +17,7 @@ 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)',
@@ -34,10 +35,12 @@ 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_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
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '拼多多-商品主表(SPU)' ROW_FORMAT = Dynamic;
-- ========================================
@@ -55,7 +58,7 @@ CREATE TABLE `channel_pdd_goods_sku` (
`reserve_quantity` int NOT NULL DEFAULT 0 COMMENT 'SKU预扣库存(reserve_quantity)',
`is_sku_onsale` tinyint NOT NULL DEFAULT 0 COMMENT 'SKU是否在架 0否 1是(is_sku_onsale)',
`outer_goods_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '商家外部商品编码(outer_goods_id)',
`outer_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '商家外部SKU编码(outer_id),可映射 ec_product_spec.spec_code',
`outer_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '商家外部SKU编码(outer_id),映射 ec_product_sku.sku_code',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
@@ -0,0 +1,31 @@
-- channel_pdd_goods 增加内部商品外键 product_id(非空)
-- 回填规则:取每个 SPU 明细中 id 最小的一条 SKU,用 outer_id 匹配同公司 ec_product_sku.sku_code → product_id
-- 无法匹配的渠道商品删除后再加 NOT NULL(同步时可在补齐内部 SKU 后重新拉取)
ALTER TABLE `channel_pdd_goods`
ADD COLUMN `product_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '内部商品ID(ec_product.id)' AFTER `mall_id`;
UPDATE `channel_pdd_goods` g
INNER JOIN (
SELECT s.`goods_row_id`, s.`outer_id`
FROM `channel_pdd_goods_sku` s
INNER JOIN (
SELECT `goods_row_id`, MIN(`id`) AS `first_sku_id`
FROM `channel_pdd_goods_sku`
WHERE `outer_id` IS NOT NULL AND TRIM(`outer_id`) <> ''
GROUP BY `goods_row_id`
) f ON f.`first_sku_id` = s.`id`
) first_sku ON first_sku.`goods_row_id` = g.`id`
INNER JOIN `ec_product_sku` ps
ON ps.`company_id` = g.`company_id`
AND ps.`sku_code` = first_sku.`outer_id`
SET g.`product_id` = ps.`product_id`;
-- SKU 表 ON DELETE CASCADE,删主表即可
DELETE FROM `channel_pdd_goods`
WHERE `product_id` IS NULL;
ALTER TABLE `channel_pdd_goods`
MODIFY COLUMN `product_id` bigint UNSIGNED NOT NULL COMMENT '内部商品ID(ec_product.id;由首条 SKU.outer_id → sku_code 解析)',
ADD INDEX `idx_channel_pdd_goods_product`(`product_id` ASC) USING BTREE,
ADD CONSTRAINT `fk_channel_pdd_goods_product` FOREIGN KEY (`product_id`) REFERENCES `ec_product` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
@@ -20,6 +20,9 @@ public class CreatePddGoodsDTO {
@NotNull(message = "mall_id不能为空")
private Long mallId;
@Schema(description = "内部商品ID(ec_product.id);不传则按首条 SKU.outer_id 解析", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private Long productId;
@Schema(description = "拼多多商品ID", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "商品ID不能为空")
private String goodsId;
@@ -13,6 +13,9 @@ public class PddGoodsFilterDTO {
@Schema(description = "拼多多店铺ID(mall_id)")
private Long mallId;
@Schema(description = "内部商品ID(ec_product.id)")
private Long productId;
@Schema(description = "商品名称")
private String goodsName;
@@ -20,6 +20,9 @@ public class UpdatePddGoodsDTO {
@NotNull(message = "mall_id不能为空")
private Long mallId;
@Schema(description = "内部商品ID(ec_product.id);不传则按首条 SKU.outer_id 解析", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private Long productId;
@Schema(description = "拼多多商品ID", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "商品ID不能为空")
private String goodsId;
@@ -23,6 +23,10 @@ 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;
@@ -31,6 +31,12 @@ public class PddGoodsSyncResultVO {
@Schema(description = "SKU 落库条数")
private Integer skuCount;
@Schema(description = "因无法匹配内部商品而跳过的数")
private Integer skippedCount;
@Schema(description = "同步时自动创建内部商品的数量")
private Integer autoCreatedProductCount;
@Schema(description = "调用列表接口页次数")
private Integer pageCount;
}
@@ -22,6 +22,12 @@ public class PddGoodsVO {
@Schema(description = "拼多多店铺ID(mall_id)")
private Long mallId;
@Schema(description = "内部商品ID(ec_product.id)")
private Long productId;
@Schema(description = "内部商品名称")
private String productName;
@Schema(description = "拼多多商品ID")
private String goodsId;
@@ -9,6 +9,7 @@ import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.UpdatePddGo
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.po.PddGoodsPO;
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.pop.goods.PddGoodsPopApiClient;
public interface PddGoodsService extends IService<PddGoodsPO> {
@@ -28,4 +29,12 @@ public interface PddGoodsService extends IService<PddGoodsPO> {
* @param pddShopId channel_pdd_shop.id
*/
PddGoodsSyncResultVO syncGoodsByPddShop(Long pddShopId);
/**
* 按商品详情 upsert 渠道商品及 SKU,并绑定内部商品(product_id 必填)。
*
* @param pddShopId channel_pdd_shop.id
*/
void upsertFromGoodsDetail(Long companyId, Long pddShopId, Long mallId,
Long productId, PddGoodsPopApiClient.GoodsDetail detail);
}
@@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
@@ -26,17 +27,25 @@ import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.PddGoodsSkuV
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.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.product.mapper.ProductMapper;
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductSkuMapper;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductSkuPO;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
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;
@@ -51,17 +60,26 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
private final PddShopMapper pddShopMapper;
private final PddAuthTokenService authTokenService;
private final PddGoodsPopApiClient goodsPopApiClient;
private final ProductSkuMapper productSkuMapper;
private final ProductMapper productMapper;
private final PddProductAutoCreateService productAutoCreateService;
private final CurrentUserContext currentUserContext;
public PddGoodsServiceImpl(PddGoodsSkuMapper pddGoodsSkuMapper,
PddShopMapper pddShopMapper,
PddAuthTokenService authTokenService,
PddGoodsPopApiClient goodsPopApiClient,
ProductSkuMapper productSkuMapper,
ProductMapper productMapper,
@Lazy PddProductAutoCreateService productAutoCreateService,
CurrentUserContext currentUserContext) {
this.pddGoodsSkuMapper = pddGoodsSkuMapper;
this.pddShopMapper = pddShopMapper;
this.authTokenService = authTokenService;
this.goodsPopApiClient = goodsPopApiClient;
this.productSkuMapper = productSkuMapper;
this.productMapper = productMapper;
this.productAutoCreateService = productAutoCreateService;
this.currentUserContext = currentUserContext;
}
@@ -77,9 +95,14 @@ 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()) {
@@ -110,10 +133,18 @@ 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<>();
@@ -161,6 +192,9 @@ 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());
}
@@ -180,8 +214,9 @@ 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(this::convertToBriefVO)
.map(g -> convertToBriefVO(g, productNames))
.collect(Collectors.toList());
return PageResultVO.create(voList, result.getTotal(),
@@ -222,6 +257,8 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
int created = 0;
int updated = 0;
int skuCount = 0;
int skipped = 0;
int autoCreated = 0;
Set<String> seenGoodsIds = new HashSet<>();
// 列表接口 is_onsale / outer_id / goods_name 三选一,需分别拉上架与下架
@@ -256,7 +293,15 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
if (!seenGoodsIds.add(goodsId)) {
continue;
}
UpsertResult ur = upsertGoodsItem(companyId, pddShopId, mallId, item, syncTime);
UpsertResult ur = upsertGoodsItem(
companyId, pddShopId, mallId, accessToken, item, syncTime);
if (ur.skipped()) {
skipped++;
continue;
}
if (ur.autoCreatedInternal()) {
autoCreated++;
}
if (ur.created()) {
created++;
} else {
@@ -277,17 +322,95 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
return PddGoodsSyncResultVO.builder()
.pddShopId(pddShopId)
.mallId(mallId)
.syncedCount(seenGoodsIds.size())
.syncedCount(created + updated)
.createdCount(created)
.updatedCount(updated)
.skuCount(skuCount)
.skippedCount(skipped)
.autoCreatedProductCount(autoCreated)
.pageCount(pageCount)
.build();
}
@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
|| detail == null || detail.goodsId() == null) {
throw new BusinessException("渠道商品落库参数不完整");
}
requireOwnedProduct(companyId, productId);
String goodsId = String.valueOf(detail.goodsId());
PddGoodsPO existing = this.getOne(new LambdaQueryWrapper<PddGoodsPO>()
.eq(PddGoodsPO::getShopId, pddShopId)
.eq(PddGoodsPO::getGoodsId, goodsId)
.last("LIMIT 1"));
LocalDateTime syncTime = LocalDateTime.now();
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(detail.goodsName()) ? detail.goodsName().trim() : goodsId);
if (goods.getGoodsQuantity() == null) {
goods.setGoodsQuantity(0);
}
if (goods.getGoodsReserveQuantity() == null) {
goods.setGoodsReserveQuantity(0);
}
String imageUrl = blankToNull(detail.resolveImageUrl());
if (imageUrl != null) {
goods.setImageUrl(imageUrl);
if (!StringUtils.hasText(goods.getThumbUrl())) {
goods.setThumbUrl(imageUrl);
}
}
int skuSize = detail.skuList() != null ? detail.skuList().size() : 0;
goods.setIsMoreSku(skuSize > 1 ? 1 : 0);
if (goods.getIsOnsale() == null) {
goods.setIsOnsale(0);
}
goods.setLastSyncTime(syncTime);
if (created) {
this.save(goods);
} else {
this.updateById(goods);
pddGoodsSkuMapper.delete(new LambdaQueryWrapper<PddGoodsSkuPO>()
.eq(PddGoodsSkuPO::getGoodsRowId, goods.getId()));
}
if (detail.skuList() == null) {
return;
}
for (PddGoodsPopApiClient.SkuDetail sku : detail.skuList()) {
if (sku == null || sku.skuId() == null) {
continue;
}
PddGoodsSkuPO po = new PddGoodsSkuPO();
po.setGoodsRowId(goods.getId());
po.setCompanyId(companyId);
po.setGoodsId(goodsId);
po.setSkuId(String.valueOf(sku.skuId()));
po.setSpec(blankToNull(sku.spec()));
po.setSkuQuantity(0);
po.setReserveQuantity(0);
po.setIsSkuOnsale(0);
po.setOuterGoodsId(blankToNull(sku.outerGoodsId()));
po.setOuterId(blankToNull(sku.outerId()));
pddGoodsSkuMapper.insert(po);
}
}
private UpsertResult upsertGoodsItem(Long companyId,
Long pddShopId,
Long mallId,
String accessToken,
PddGoodsPopApiClient.GoodsListItem item,
LocalDateTime syncTime) {
String goodsId = String.valueOf(item.goodsId());
@@ -296,11 +419,33 @@ 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 {
productId = productAutoCreateService.ensureInternalProductByFetching(
companyId, mallId, accessToken, item.goodsId());
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()));
@@ -343,10 +488,85 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
skuInserted++;
}
}
return new UpsertResult(created, skuInserted);
return new UpsertResult(created, skuInserted, false, autoCreatedInternal);
}
private record UpsertResult(boolean created, int skuCount) {
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;
}
for (PddGoodsPopApiClient.GoodsListSku sku : skus) {
if (sku != null && StringUtils.hasText(sku.outerId())) {
return sku.outerId().trim();
}
}
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.selectBatchIds(ids)) {
if (p != null && p.getId() != null) {
map.put(p.getId(), p.getName());
}
}
return map;
}
private record UpsertResult(boolean created, int skuCount, boolean skipped, boolean autoCreatedInternal) {
}
private static Integer toInt(Long v) {
@@ -381,9 +601,12 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
return sku;
}
private PddGoodsVO convertToBriefVO(PddGoodsPO goods) {
private PddGoodsVO convertToBriefVO(PddGoodsPO goods, Map<Long, String> productNames) {
PddGoodsVO vo = new PddGoodsVO();
BeanCopyUtils.copyProperties(goods, vo);
if (goods.getProductId() != null) {
vo.setProductName(productNames.get(goods.getProductId()));
}
vo.setSkus(null);
return vo;
}
@@ -391,6 +614,12 @@ 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());
@@ -12,6 +12,7 @@ import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.mapper.PddOrderItemMa
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.model.po.PddOrderItemPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.PddOrderSyncShopContext;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service.PddOrderSyncContextResolver;
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.ec.category.model.po.CategoryPO;
import top.xyquan.ecomdmbbackend.modules.ec.category.service.CategoryService;
@@ -21,7 +22,8 @@ import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductService;
import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductSkuService;
/**
* 按平台 goodsId 拉详情,自动创建内部商品 + 全部 SKU(已存在则跳过),并回绑 orphan 明细。
* 按平台 goodsId 拉详情,自动创建内部商品 + 全部 SKU(已存在则跳过),
* 并 upsert 渠道商品 channel_pdd_goods(绑定 product_id)。
* 类目:PDD 一级/叶子 → 内部一级/二级;按公司内叶子类目名复用,不重复创建。
*/
@Slf4j
@@ -31,6 +33,7 @@ public class PddProductAutoCreateService {
private final PddOrderSyncContextResolver contextResolver;
private final PddGoodsPopApiClient goodsPopApiClient;
private final PddGoodsService pddGoodsService;
private final PddOrderItemMapper pddOrderItemMapper;
private final CategoryService categoryService;
private final ProductService productService;
@@ -45,31 +48,70 @@ public class PddProductAutoCreateService {
PddOrderSyncShopContext ctx = contextResolver.resolve(message.getCompanyId(), message.getShopId());
PddGoodsPopApiClient.GoodsDetail detail = goodsPopApiClient.fetchGoodsInformation(
ctx.getMallId(), ctx.getAccessToken(), message.getGoodsId());
if (detail == null || detail.goodsId() == null) {
log.warn("自动建品:商品详情为空 companyId={} goodsId={}",
Long productId = ensureInternalProduct(message.getCompanyId(), detail);
if (productId == null) {
return;
}
if (ctx.getPddShop() == null || ctx.getPddShop().getId() == null) {
log.warn("自动建品:缺少渠道店铺,跳过 channel_pdd_goods 落库 companyId={} goodsId={}",
message.getCompanyId(), message.getGoodsId());
return;
}
pddGoodsService.upsertFromGoodsDetail(
message.getCompanyId(),
ctx.getPddShop().getId(),
ctx.getMallId(),
productId,
detail);
log.info("自动建品已绑定渠道商品 companyId={} pddShopId={} goodsId={} productId={}",
message.getCompanyId(), ctx.getPddShop().getId(), message.getGoodsId(), productId);
}
/**
* 拉取商品详情并确保内部商品/SKU,返回 productId;失败返回 null。
* 不写 channel_pdd_goods(供列表同步等调用方自行落库)。
*/
@Transactional(rollbackFor = Exception.class)
public Long ensureInternalProductByFetching(Long companyId, Long mallId, String accessToken, Long goodsId)
throws Exception {
if (companyId == null || goodsId == null) {
return null;
}
PddGoodsPopApiClient.GoodsDetail detail = goodsPopApiClient.fetchGoodsInformation(
mallId, accessToken, goodsId);
return ensureInternalProduct(companyId, detail);
}
/**
* 根据已拉取的详情确保内部商品与 SKU,返回 productId;失败返回 null。
*/
@Transactional(rollbackFor = Exception.class)
public Long ensureInternalProduct(Long companyId, PddGoodsPopApiClient.GoodsDetail detail) {
if (companyId == null || detail == null || detail.goodsId() == null) {
log.warn("自动建品:商品详情为空 companyId={}", companyId);
return null;
}
String productCode = detail.resolveProductCode();
if (!StringUtils.hasText(productCode)) {
log.warn("自动建品:无法解析商品编码 goodsId={}", detail.goodsId());
return;
return null;
}
String productName = StringUtils.hasText(detail.goodsName())
? detail.goodsName().trim()
: productCode;
String imageUrl = resolveProductImageUrl(detail, message.getCompanyId(), message.getGoodsId());
Long categoryId = ensureCategoryId(message.getCompanyId(), detail.goodsCategory(), detail.lastCategory());
ProductPO product = ensureProduct(message.getCompanyId(), productCode, productName, imageUrl, categoryId);
String imageUrl = resolveProductImageUrl(detail, companyId, detail.goodsId());
Long categoryId = ensureCategoryId(companyId, detail.goodsCategory(), detail.lastCategory());
ProductPO product = ensureProduct(companyId, productCode, productName, imageUrl, categoryId);
if (product == null || product.getId() == null) {
return;
return null;
}
if (detail.skuList() == null || detail.skuList().isEmpty()) {
log.info("自动建品:商品无 SKU 列表 goodsId={}", detail.goodsId());
return;
log.info("自动建品:商品无 SKU 列表 goodsId={} productId={}", detail.goodsId(), product.getId());
return product.getId();
}
int created = 0;
@@ -83,20 +125,21 @@ public class PddProductAutoCreateService {
skipped++;
continue;
}
ProductSkuPO existing = productSkuService.getByCompanyIdAndSkuCode(message.getCompanyId(), skuCode);
ProductSkuPO existing = productSkuService.getByCompanyIdAndSkuCode(companyId, skuCode);
if (existing != null) {
skipped++;
continue;
}
if (createSku(message.getCompanyId(), product.getId(), skuCode, skuDetail, imageUrl)) {
if (createSku(companyId, product.getId(), skuCode, skuDetail, imageUrl)) {
created++;
} else {
skipped++;
}
}
log.info("自动建品完成 companyId={} goodsId={} productId={} categoryId={} createdSku={} skipped={} hasImage={}",
message.getCompanyId(), detail.goodsId(), product.getId(), categoryId, created, skipped,
companyId, detail.goodsId(), product.getId(), categoryId, created, skipped,
StringUtils.hasText(imageUrl));
return product.getId();
}
/**
@@ -3,6 +3,8 @@ export namespace PddGoodsDTO {
/** 渠道店铺ID(channel_pdd_shop.id) */
shopId?: number;
mallId?: number;
/** 内部商品ID */
productId?: number;
goodsName?: string;
goodsId?: string;
/** 0否 1是 */
@@ -32,6 +34,8 @@ export namespace PddGoodsVO {
companyId?: number;
shopId?: number;
mallId?: number;
productId?: number;
productName?: string;
goodsId?: string;
goodsName?: string;
goodsQuantity?: number;
@@ -54,6 +58,8 @@ export namespace PddGoodsVO {
createdCount?: number;
updatedCount?: number;
skuCount?: number;
skippedCount?: number;
autoCreatedProductCount?: number;
pageCount?: number;
}
}
@@ -4,6 +4,7 @@ import type { PddGoodsVO } from '#/api/channel/pdd/goods';
import { ref } from 'vue';
import {
Button,
Descriptions,
DescriptionsItem,
Drawer,
@@ -18,6 +19,10 @@ 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('');
@@ -69,6 +74,14 @@ function close() {
openFlag.value = false;
}
function openInternalProduct() {
if (!detail.value?.productId) {
message.warning('未关联内部商品');
return;
}
emit('openInternalProduct', detail.value);
}
defineExpose({ open, close });
</script>
@@ -113,6 +126,18 @@ 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>
@@ -19,12 +19,14 @@ import { getPddShopPageApi } from '#/api/channel/pdd/shop';
import PddGoodsDetailDrawer from './components/PddGoodsDetailDrawer.vue';
import PddShopDetailModal from '#/views/channel/pdd/shop/components/PddShopDetailModal.vue';
import ProductDetailDrawer from '#/views/ec/product/list/components/ProductDetailDrawer.vue';
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 shopOptions = ref<{ label: string; value: number }[]>([]);
const shopNameById = ref<Record<number, string>>({});
@@ -88,6 +90,12 @@ 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,
@@ -295,6 +303,14 @@ 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);
@@ -330,6 +346,19 @@ 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"
@@ -370,8 +399,12 @@ onMounted(async () => {
</template>
</Grid>
<PddGoodsDetailDrawer ref="detailDrawerRef" />
<PddGoodsDetailDrawer
ref="detailDrawerRef"
@open-internal-product="openInternalProduct"
/>
<PddShopDetailModal ref="shopDetailModalRef" />
<ProductDetailDrawer ref="productDetailDrawerRef" />
</Page>
</template>
@@ -248,7 +248,13 @@ async function handleSyncGoods(row: PddShopVO.Info) {
try {
const result = await syncPddGoodsByShopApi(row.id);
message.success(
`同步完成:共 ${result.syncedCount ?? 0} 个商品(新增 ${result.createdCount ?? 0} / 更新 ${result.updatedCount ?? 0}),SKU ${result.skuCount ?? 0}`,
`同步完成:共 ${result.syncedCount ?? 0} 个商品(新增 ${result.createdCount ?? 0} / 更新 ${result.updatedCount ?? 0}),SKU ${result.skuCount ?? 0}${
result.autoCreatedProductCount
? `,自动建内部商品 ${result.autoCreatedProductCount}`
: ''
}${
result.skippedCount ? `,跳过 ${result.skippedCount}` : ''
}`,
);
gridApi.reload();
} catch (error: any) {
@@ -0,0 +1,230 @@
<script lang="ts" setup>
import type { ProductVO } from '#/api/ec/product/types';
import { computed, h, ref } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import {
Descriptions,
DescriptionsItem,
Drawer,
Image,
Spin,
Table,
message,
} from 'ant-design-vue';
import { getProductSkuPageApi } from '#/api/ec/product/sku';
defineOptions({ name: 'ProductDetailDrawer' });
const ImageIcon = createIconifyIcon('lucide:image');
const openFlag = ref(false);
const loading = ref(false);
const product = ref<ProductVO.Info | null>(null);
const formatCost = (val?: number) => `¥${(val ?? 0).toFixed(2)}`;
const skuDataSource = computed(() => product.value?.skus ?? []);
const skuColumns = [
{
title: '图片',
dataIndex: 'imageUrl',
key: 'imageUrl',
width: 72,
align: 'center' as const,
customRender: ({ record }: { record: ProductVO.SkuInfo }) => {
if (record.imageUrl) {
return h(Image, {
src: record.imageUrl,
width: 40,
height: 40,
class: 'object-cover',
preview: true,
});
}
return h(ImageIcon, {
class: 'mx-auto h-5 w-5 text-slate-300 dark:text-[hsl(240deg_5%_45%)]',
});
},
},
{
title: 'SKU 编码',
dataIndex: 'skuCode',
key: 'skuCode',
width: 140,
customRender: ({ text }: { text?: string }) => text || '-',
},
{
title: 'SKU 名称',
dataIndex: 'name',
key: 'name',
ellipsis: true,
},
{
title: '商品成本',
dataIndex: 'productCost',
key: 'productCost',
width: 110,
customRender: ({ record }: { record: ProductVO.SkuInfo }) =>
formatCost(record.productCost),
},
{
title: '运费成本',
dataIndex: 'shippingCost',
key: 'shippingCost',
width: 100,
customRender: ({ record }: { record: ProductVO.SkuInfo }) =>
formatCost(record.shippingCost),
},
{
title: '其他成本',
dataIndex: 'otherCost',
key: 'otherCost',
width: 100,
customRender: ({ record }: { record: ProductVO.SkuInfo }) =>
formatCost(record.otherCost),
},
{
title: '成本生效日',
dataIndex: 'costEffectiveFrom',
key: 'costEffectiveFrom',
width: 120,
customRender: ({ text }: { text?: string }) => text || '-',
},
{
title: '备注',
dataIndex: 'remark',
key: 'remark',
ellipsis: true,
customRender: ({ text }: { text?: string }) => text || '-',
},
];
/** 直接传入已组装好的商品详情 */
function open(record: ProductVO.Info) {
product.value = record;
openFlag.value = true;
}
/**
* 按内部商品 ID 加载只读详情。
* @param productId 内部商品 ID
* @param fallbackName 列表侧已知名称(可选)
*/
async function openById(productId: number, fallbackName?: string) {
if (!productId) {
message.warning('未关联内部商品');
return;
}
openFlag.value = true;
loading.value = true;
product.value = null;
try {
const data = await getProductSkuPageApi({
page: 1,
pageSize: 500,
filters: { productId },
});
const skus = (data.records ?? []) as ProductVO.SkuInfo[];
const first = skus[0];
product.value = {
id: productId,
companyId: first?.companyId ?? 0,
name: fallbackName || first?.productName || `商品#${productId}`,
mainImage: first?.imageUrl,
createTime: first?.createTime ?? '',
updateTime: first?.updateTime ?? '',
skus,
};
} catch (error: any) {
console.error(error);
message.error(error?.message || '加载内部商品详情失败');
openFlag.value = false;
} finally {
loading.value = false;
}
}
function close() {
openFlag.value = false;
}
defineExpose({ open, openById, close });
</script>
<template>
<Drawer
v-model:open="openFlag"
:title="product?.name ? `内部商品 - ${product.name}` : '内部商品详情'"
width="720"
destroy-on-close
>
<Spin :spinning="loading">
<div v-if="product" class="space-y-5">
<div
class="flex flex-col gap-4 rounded-xl border border-slate-200 bg-slate-50/80 p-4 sm:flex-row sm:items-start dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_14%)]"
>
<div
class="flex h-[96px] w-[96px] shrink-0 items-center justify-center overflow-hidden rounded-lg border border-slate-200 bg-white dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
>
<Image
v-if="product.mainImage"
:src="product.mainImage"
:width="96"
:height="96"
class="object-cover"
:preview="true"
/>
<ImageIcon
v-else
class="h-8 w-8 text-slate-300 dark:text-[hsl(240deg_5%_45%)]"
/>
</div>
<div class="min-w-0 flex-1">
<div
class="mb-3 text-base font-semibold text-slate-900 dark:text-[hsl(0deg_0%_95%)]"
>
{{ product.name }}
</div>
<Descriptions :column="1" size="small" :colon="false">
<DescriptionsItem label="商品编码">
{{ product.productCode || '-' }}
</DescriptionsItem>
<DescriptionsItem label="商品类目">
{{ product.categoryName || '-' }}
</DescriptionsItem>
<DescriptionsItem label="SKU 数量">
{{ product.skus?.length ?? 0 }}
</DescriptionsItem>
<DescriptionsItem label="创建时间">
{{ product.createTime || '-' }}
</DescriptionsItem>
</Descriptions>
</div>
</div>
<div>
<div
class="mb-3 text-sm font-medium text-slate-900 dark:text-[hsl(0deg_0%_95%)]"
>
SKU 明细
</div>
<Table
:columns="skuColumns"
:data-source="skuDataSource"
:pagination="false"
row-key="id"
size="small"
bordered
:scroll="{ x: 700 }"
/>
</div>
</div>
</Spin>
</Drawer>
</template>