diff --git a/ecom-dmb-backend/sql/design/channel/channel_pdd_good_design.sql b/ecom-dmb-backend/sql/design/channel/channel_pdd_good_design.sql index c1174d57..1fd74390 100644 --- a/ecom-dmb-backend/sql/design/channel/channel_pdd_good_design.sql +++ b/ecom-dmb-backend/sql/design/channel/channel_pdd_good_design.sql @@ -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, diff --git a/ecom-dmb-backend/sql/migration/V20260831__channel_pdd_goods_product_id.sql b/ecom-dmb-backend/sql/migration/V20260831__channel_pdd_goods_product_id.sql new file mode 100644 index 00000000..97f4b10f --- /dev/null +++ b/ecom-dmb-backend/sql/migration/V20260831__channel_pdd_goods_product_id.sql @@ -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; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/model/dto/CreatePddGoodsDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/model/dto/CreatePddGoodsDTO.java index 417c920b..b081d736 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/model/dto/CreatePddGoodsDTO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/model/dto/CreatePddGoodsDTO.java @@ -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; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/model/dto/PddGoodsFilterDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/model/dto/PddGoodsFilterDTO.java index caf79019..5846ee4b 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/model/dto/PddGoodsFilterDTO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/model/dto/PddGoodsFilterDTO.java @@ -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; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/model/dto/UpdatePddGoodsDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/model/dto/UpdatePddGoodsDTO.java index b4402dd2..55a3c289 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/model/dto/UpdatePddGoodsDTO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/model/dto/UpdatePddGoodsDTO.java @@ -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; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/model/po/PddGoodsPO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/model/po/PddGoodsPO.java index bf22cd8a..80f37950 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/model/po/PddGoodsPO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/model/po/PddGoodsPO.java @@ -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; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/model/vo/PddGoodsSyncResultVO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/model/vo/PddGoodsSyncResultVO.java index c7992b2a..e15722dc 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/model/vo/PddGoodsSyncResultVO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/model/vo/PddGoodsSyncResultVO.java @@ -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; } diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/model/vo/PddGoodsVO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/model/vo/PddGoodsVO.java index 3f6ab787..dc819e34 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/model/vo/PddGoodsVO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/model/vo/PddGoodsVO.java @@ -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; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/service/PddGoodsService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/service/PddGoodsService.java index 9b1a8351..5dd061f6 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/service/PddGoodsService.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/service/PddGoodsService.java @@ -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 { @@ -28,4 +29,12 @@ public interface PddGoodsService extends IService { * @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); } diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/service/impl/PddGoodsServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/service/impl/PddGoodsServiceImpl.java index 9f8edea3..c2a0017b 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/service/impl/PddGoodsServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/goods/service/impl/PddGoodsServiceImpl.java @@ -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 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 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 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 deleteWrapper = new LambdaQueryWrapper<>(); @@ -161,6 +192,9 @@ public class PddGoodsServiceImpl extends ServiceImpl 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 IPage page = new Page<>(pageQueryDTO.getPage(), pageQueryDTO.getPageSize()); IPage result = this.page(page, wrapper); + Map productNames = loadProductNames(result.getRecords()); List 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 int created = 0; int updated = 0; int skuCount = 0; + int skipped = 0; + int autoCreated = 0; Set seenGoodsIds = new HashSet<>(); // 列表接口 is_onsale / outer_id / goods_name 三选一,需分别拉上架与下架 @@ -256,7 +293,15 @@ public class PddGoodsServiceImpl extends ServiceImpl 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 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() + .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() + .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 .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 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 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() + .eq(ProductSkuPO::getCompanyId, companyId) + .eq(ProductSkuPO::getSkuCode, outerId.trim()) + .last("LIMIT 1")); + return sku != null ? sku.getProductId() : null; + } + + private static String firstOuterIdFromApiSkus(List 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 loadProductNames(List goodsList) { + if (goodsList == null || goodsList.isEmpty()) { + return Map.of(); + } + List ids = goodsList.stream() + .map(PddGoodsPO::getProductId) + .filter(Objects::nonNull) + .distinct() + .collect(Collectors.toList()); + if (ids.isEmpty()) { + return Map.of(); + } + Map 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 return sku; } - private PddGoodsVO convertToBriefVO(PddGoodsPO goods) { + private PddGoodsVO convertToBriefVO(PddGoodsPO goods, Map 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 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 wrapper = new LambdaQueryWrapper<>(); wrapper.eq(PddGoodsSkuPO::getGoodsRowId, goods.getId()); diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/order/convert/service/PddProductAutoCreateService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/order/convert/service/PddProductAutoCreateService.java index 2b2219a2..aa05ba3e 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/order/convert/service/PddProductAutoCreateService.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/channel/pdd/order/convert/service/PddProductAutoCreateService.java @@ -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(); } /** diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/channel/pdd/goods/types/index.ts b/ecom-dmb-frontend/apps/web-antd/src/api/channel/pdd/goods/types/index.ts index a582b3ae..ef2cda3b 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/api/channel/pdd/goods/types/index.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/api/channel/pdd/goods/types/index.ts @@ -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; } } diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/channel/pdd/goods/components/PddGoodsDetailDrawer.vue b/ecom-dmb-frontend/apps/web-antd/src/views/channel/pdd/goods/components/PddGoodsDetailDrawer.vue index 421d6c1e..e09002c8 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/views/channel/pdd/goods/components/PddGoodsDetailDrawer.vue +++ b/ecom-dmb-frontend/apps/web-antd/src/views/channel/pdd/goods/components/PddGoodsDetailDrawer.vue @@ -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 }); @@ -113,6 +126,18 @@ defineExpose({ open, close }); {{ shopName || `渠道店#${detail.shopId}` }} + + + - + {{ detail.goodsQuantity ?? 0 }} diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/channel/pdd/goods/index.vue b/ecom-dmb-frontend/apps/web-antd/src/views/channel/pdd/goods/index.vue index 64510fbc..6946a059 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/views/channel/pdd/goods/index.vue +++ b/ecom-dmb-frontend/apps/web-antd/src/views/channel/pdd/goods/index.vue @@ -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>(); const shopDetailModalRef = ref>(); +const productDetailDrawerRef = ref>(); const shopOptions = ref<{ label: string; value: number }[]>([]); const shopNameById = ref>({}); @@ -88,6 +90,12 @@ const gridOptions: VxeGridProps = { 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 () => { + + - + + diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/channel/pdd/shop/index.vue b/ecom-dmb-frontend/apps/web-antd/src/views/channel/pdd/shop/index.vue index a6182c7e..e8a29156 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/views/channel/pdd/shop/index.vue +++ b/ecom-dmb-frontend/apps/web-antd/src/views/channel/pdd/shop/index.vue @@ -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) { diff --git a/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/list/components/ProductDetailDrawer.vue b/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/list/components/ProductDetailDrawer.vue new file mode 100644 index 00000000..86c63d73 --- /dev/null +++ b/ecom-dmb-frontend/apps/web-antd/src/views/ec/product/list/components/ProductDetailDrawer.vue @@ -0,0 +1,230 @@ + + +