feat: 新增拼多多店铺管理和商品管理

This commit is contained in:
2026-08-15 10:52:38 +08:00
parent 2dda6a2d30
commit 949c5dcf0c
28 changed files with 1546 additions and 50 deletions
@@ -15,8 +15,8 @@ DROP TABLE IF EXISTS `channel_pdd_goods`;
CREATE TABLE `channel_pdd_goods` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
`shop_id` bigint UNSIGNED NOT NULL COMMENT '店铺ID(ec_shop.id)',
`pdd_auth_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '拼多多授权ID(open_pdd_auth.id)',
`shop_id` bigint UNSIGNED NOT NULL COMMENT '渠道店铺ID(channel_pdd_shop.id)',
`mall_id` bigint UNSIGNED NOT NULL COMMENT '拼多多店铺ID(mall_id)',
`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)',
@@ -31,14 +31,13 @@ CREATE TABLE `channel_pdd_goods` (
`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,
UNIQUE INDEX `uk_channel_pdd_goods_company_goods`(`company_id` ASC, `goods_id` ASC) USING BTREE,
INDEX `idx_channel_pdd_goods_shop`(`shop_id` ASC) USING BTREE,
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_onsale`(`is_onsale` ASC) USING BTREE,
INDEX `idx_channel_pdd_goods_auth`(`pdd_auth_id` 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 `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_channel_pdd_goods_auth` FOREIGN KEY (`pdd_auth_id`) REFERENCES `open_pdd_auth` (`id`) ON DELETE SET NULL 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,52 @@
-- 拼多多商品权限 + 渠道店铺菜单(商品表已手工建库,此处不建表)
-- sys_permission.id / sys_menu.id 均为 AUTO_INCREMENT,插入不写死主键,避免与存量 id 冲突
-- 权限(唯一约束:uk_code_parent(code, parent_id))
INSERT INTO `sys_permission` (`parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT p.id, 'biz:pdd:goods:read', '拼多多商品查看', 'api', 1, '', 364
FROM `sys_permission` p
WHERE p.`code` = 'biz:pdd'
AND NOT EXISTS (SELECT 1 FROM `sys_permission` x WHERE x.`code` = 'biz:pdd:goods:read')
LIMIT 1;
INSERT INTO `sys_permission` (`parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT p.id, 'biz:pdd:goods:manage', '拼多多商品管理', 'api', 1, '同步/维护拼多多商品', 365
FROM `sys_permission` p
WHERE p.`code` = 'biz:pdd'
AND NOT EXISTS (SELECT 1 FROM `sys_permission` x WHERE x.`code` = 'biz:pdd:goods:manage')
LIMIT 1;
-- 菜单:拼多多店铺(渠道店列表 + 同步商品)
INSERT INTO `sys_menu` (`parent_id`, `super`, `name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT m.id, 0, '拼多多店铺', '店铺', '/pdd/shop', '/channel/pdd/shop/index', '', 'lucide:store', 'menu', 1, 1, 0, 0
FROM `sys_menu` m
WHERE m.`name` = '拼多多'
AND NOT EXISTS (SELECT 1 FROM `sys_menu` x WHERE x.`name` = '拼多多店铺')
LIMIT 1;
-- 修正拼多多订单组件路径(views 已迁到 channel/pdd)
UPDATE `sys_menu`
SET `component` = '/channel/pdd/order/index',
`path` = '/pdd/order'
WHERE `name` = '拼多多订单'
AND (`component` LIKE '%ecommerce/pdd%' OR `component` = '/ecommerce/pdd/order/index');
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
SELECT m.id, p.id
FROM `sys_menu` m
JOIN `sys_permission` p ON p.code IN ('biz:pdd:shop:read', 'biz:pdd:shop:manage', 'biz:pdd:goods:read', 'biz:pdd:goods:manage')
WHERE m.name = '拼多多店铺';
-- 菜单:拼多多商品
INSERT INTO `sys_menu` (`parent_id`, `super`, `name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT m.id, 0, '拼多多商品', '商品', '/pdd/goods', '/channel/pdd/goods/index', '', 'lucide:package', 'menu', 1, 1, 0, 2
FROM `sys_menu` m
WHERE m.`name` = '拼多多'
AND NOT EXISTS (SELECT 1 FROM `sys_menu` x WHERE x.`name` = '拼多多商品')
LIMIT 1;
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
SELECT m.id, p.id
FROM `sys_menu` m
JOIN `sys_permission` p ON p.code IN ('biz:pdd:goods:read', 'biz:pdd:goods:manage')
WHERE m.name = '拼多多商品';
@@ -0,0 +1,13 @@
-- 拼多多商品菜单(幂等)
INSERT INTO `sys_menu` (`parent_id`, `super`, `name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT m.id, 0, '拼多多商品', '商品', '/pdd/goods', '/channel/pdd/goods/index', '', 'lucide:package', 'menu', 1, 1, 0, 2
FROM `sys_menu` m
WHERE m.`name` = '拼多多'
AND NOT EXISTS (SELECT 1 FROM `sys_menu` x WHERE x.`name` = '拼多多商品')
LIMIT 1;
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
SELECT m.id, p.id
FROM `sys_menu` m
JOIN `sys_permission` p ON p.code IN ('biz:pdd:goods:read', 'biz:pdd:goods:manage')
WHERE m.name = '拼多多商品';
@@ -12,6 +12,7 @@ import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.CreatePddGoodsDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.PddGoodsFilterDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.UpdatePddGoodsDTO;
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;
@@ -67,4 +68,13 @@ public class PddGoodsController {
PddGoodsVO vo = pddGoodsService.getPddGoodsDetail(id);
return ApiResponse.success("获取成功", vo);
}
@Operation(summary = "同步商品", description = "按渠道店铺调用 pdd.goods.list.get,同步上架+下架商品及SKU到本地")
@PostMapping("/sync/{pddShopId}")
@RequirePermission(value = "biz:pdd:goods:manage", description = "同步拼多多商品", allowSuper = true)
public ApiResponse<PddGoodsSyncResultVO> syncGoodsByPddShop(
@Parameter(description = "渠道店铺ID(channel_pdd_shop.id)") @PathVariable Long pddShopId) {
PddGoodsSyncResultVO result = pddGoodsService.syncGoodsByPddShop(pddShopId);
return ApiResponse.success("同步完成", result);
}
}
@@ -12,12 +12,13 @@ import java.util.List;
@Schema(description = "创建拼多多商品DTO")
public class CreatePddGoodsDTO {
@Schema(description = "店铺ID(ec_shop.id)", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "店铺ID不能为空")
@Schema(description = "渠道店铺ID(channel_pdd_shop.id)", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "渠道店铺ID不能为空")
private Long shopId;
@Schema(description = "拼多多授权ID")
private Long pddAuthId;
@Schema(description = "拼多多店铺ID(mall_id)", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "mall_id不能为空")
private Long mallId;
@Schema(description = "拼多多商品ID", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "商品ID不能为空")
@@ -7,9 +7,12 @@ import lombok.Data;
@Schema(description = "拼多多商品过滤DTO")
public class PddGoodsFilterDTO {
@Schema(description = "店铺ID")
@Schema(description = "渠道店铺ID(channel_pdd_shop.id)")
private Long shopId;
@Schema(description = "拼多多店铺ID(mall_id)")
private Long mallId;
@Schema(description = "商品名称")
private String goodsName;
@@ -12,12 +12,13 @@ import java.util.List;
@Schema(description = "更新拼多多商品DTO")
public class UpdatePddGoodsDTO {
@Schema(description = "店铺ID(ec_shop.id)", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "店铺ID不能为空")
@Schema(description = "渠道店铺ID(channel_pdd_shop.id)", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "渠道店铺ID不能为空")
private Long shopId;
@Schema(description = "拼多多授权ID")
private Long pddAuthId;
@Schema(description = "拼多多店铺ID(mall_id)", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "mall_id不能为空")
private Long mallId;
@Schema(description = "拼多多商品ID", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "商品ID不能为空")
@@ -15,11 +15,13 @@ public class PddGoodsPO {
@TableField("company_id")
private Long companyId;
/** 渠道店铺ID(channel_pdd_shop.id) */
@TableField("shop_id")
private Long shopId;
@TableField("pdd_auth_id")
private Long pddAuthId;
/** 拼多多店铺 mall_id */
@TableField("mall_id")
private Long mallId;
@TableField("goods_id")
private String goodsId;
@@ -0,0 +1,36 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "拼多多商品同步结果")
public class PddGoodsSyncResultVO {
@Schema(description = "渠道店铺ID")
private Long pddShopId;
@Schema(description = "拼多多 mall_id")
private Long mallId;
@Schema(description = "本次拉取并落库的商品数(去重后)")
private Integer syncedCount;
@Schema(description = "新增数")
private Integer createdCount;
@Schema(description = "更新数")
private Integer updatedCount;
@Schema(description = "SKU 落库条数")
private Integer skuCount;
@Schema(description = "调用列表接口页次数")
private Integer pageCount;
}
@@ -16,11 +16,11 @@ public class PddGoodsVO {
@Schema(description = "公司ID")
private Long companyId;
@Schema(description = "店铺ID")
@Schema(description = "渠道店铺ID(channel_pdd_shop.id)")
private Long shopId;
@Schema(description = "拼多多授权ID")
private Long pddAuthId;
@Schema(description = "拼多多店铺ID(mall_id)")
private Long mallId;
@Schema(description = "拼多多商品ID")
private String goodsId;
@@ -7,6 +7,7 @@ import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.CreatePddGo
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.PddGoodsFilterDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.UpdatePddGoodsDTO;
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;
public interface PddGoodsService extends IService<PddGoodsPO> {
@@ -20,4 +21,11 @@ public interface PddGoodsService extends IService<PddGoodsPO> {
PageResultVO<PddGoodsVO> getPddGoodsPage(PageQueryDTO<PddGoodsFilterDTO> pageQueryDTO);
PddGoodsVO getPddGoodsDetail(Long id);
/**
* 按渠道店铺调用 pdd.goods.list.get 全量同步(上架+下架)到 channel_pdd_goods / sku。
*
* @param pddShopId channel_pdd_shop.id
*/
PddGoodsSyncResultVO syncGoodsByPddShop(Long pddShopId);
}
@@ -4,12 +4,16 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
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.auth.mapper.PddAuthMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.model.po.PddAuthPO;
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;
@@ -19,22 +23,45 @@ 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.po.PddGoodsSkuPO;
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.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.utils.CurrentUserContext;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Slf4j
@Service
public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO> implements PddGoodsService {
private static final int LIST_PAGE_SIZE = 100;
private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
private final PddGoodsSkuMapper pddGoodsSkuMapper;
private final PddShopMapper pddShopMapper;
private final PddAuthMapper pddAuthMapper;
private final PddGoodsPopApiClient goodsPopApiClient;
private final CurrentUserContext currentUserContext;
public PddGoodsServiceImpl(PddGoodsSkuMapper pddGoodsSkuMapper, CurrentUserContext currentUserContext) {
public PddGoodsServiceImpl(PddGoodsSkuMapper pddGoodsSkuMapper,
PddShopMapper pddShopMapper,
PddAuthMapper pddAuthMapper,
PddGoodsPopApiClient goodsPopApiClient,
CurrentUserContext currentUserContext) {
this.pddGoodsSkuMapper = pddGoodsSkuMapper;
this.pddShopMapper = pddShopMapper;
this.pddAuthMapper = pddAuthMapper;
this.goodsPopApiClient = goodsPopApiClient;
this.currentUserContext = currentUserContext;
}
@@ -44,7 +71,7 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
Long companyId = currentUserContext.getCurrentCompanyId();
LambdaQueryWrapper<PddGoodsPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(PddGoodsPO::getCompanyId, companyId)
wrapper.eq(PddGoodsPO::getShopId, createPddGoodsDTO.getShopId())
.eq(PddGoodsPO::getGoodsId, createPddGoodsDTO.getGoodsId());
if (this.count(wrapper) > 0) {
throw new BusinessException("该商品已存在");
@@ -71,12 +98,12 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
Long companyId = currentUserContext.getCurrentCompanyId();
PddGoodsPO existing = this.getById(id);
if (existing == null) {
if (existing == null || !companyId.equals(existing.getCompanyId())) {
throw new BusinessException("商品不存在");
}
LambdaQueryWrapper<PddGoodsPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(PddGoodsPO::getCompanyId, companyId)
wrapper.eq(PddGoodsPO::getShopId, updatePddGoodsDTO.getShopId())
.eq(PddGoodsPO::getGoodsId, updatePddGoodsDTO.getGoodsId())
.ne(PddGoodsPO::getId, id);
if (this.count(wrapper) > 0) {
@@ -100,14 +127,15 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
skus.forEach(pddGoodsSkuMapper::insert);
}
return convertToVO(goods);
return convertToVO(this.getById(id));
}
@Override
@Transactional
public void deletePddGoods(Long id) {
Long companyId = currentUserContext.getCurrentCompanyId();
PddGoodsPO existing = this.getById(id);
if (existing == null) {
if (existing == null || !companyId.equals(existing.getCompanyId())) {
throw new BusinessException("商品不存在");
}
@@ -130,6 +158,9 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
if (filter.getShopId() != null) {
wrapper.eq(PddGoodsPO::getShopId, filter.getShopId());
}
if (filter.getMallId() != null) {
wrapper.eq(PddGoodsPO::getMallId, filter.getMallId());
}
if (filter.getGoodsName() != null && !filter.getGoodsName().isEmpty()) {
wrapper.like(PddGoodsPO::getGoodsName, filter.getGoodsName());
}
@@ -143,13 +174,14 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
wrapper.eq(PddGoodsPO::getIsMoreSku, filter.getIsMoreSku());
}
wrapper.orderByDesc(PddGoodsPO::getCreateTime);
wrapper.orderByDesc(PddGoodsPO::getIsOnsale)
.orderByDesc(PddGoodsPO::getPddCreatedAt);
IPage<PddGoodsPO> page = new Page<>(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
IPage<PddGoodsPO> result = this.page(page, wrapper);
List<PddGoodsVO> voList = result.getRecords().stream()
.map(this::convertToVO)
.map(this::convertToBriefVO)
.collect(Collectors.toList());
return PageResultVO.create(voList, result.getTotal(),
@@ -158,13 +190,193 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
@Override
public PddGoodsVO getPddGoodsDetail(Long id) {
Long companyId = currentUserContext.getCurrentCompanyId();
PddGoodsPO goods = this.getById(id);
if (goods == null) {
if (goods == null || !companyId.equals(goods.getCompanyId())) {
throw new BusinessException("商品不存在");
}
return convertToVO(goods);
}
@Override
public PddGoodsSyncResultVO syncGoodsByPddShop(Long pddShopId) {
Long companyId = currentUserContext.getCurrentCompanyId();
if (pddShopId == null) {
throw new BusinessException("渠道店铺ID不能为空");
}
PddShopPO pddShop = pddShopMapper.selectById(pddShopId);
if (pddShop == null || !companyId.equals(pddShop.getCompanyId())) {
throw new BusinessException("拼多多渠道店铺不存在");
}
if (pddShop.getPddAuthId() == null) {
throw new BusinessException("该渠道店铺尚未绑定授权,请先完成授权");
}
PddAuthPO auth = pddAuthMapper.selectById(pddShop.getPddAuthId());
if (auth == null || auth.getStatus() == null || auth.getStatus() != 1
|| !StringUtils.hasText(auth.getAccessToken())) {
throw new BusinessException("拼多多授权无效或已失效,请重新授权");
}
Long mallId = pddShop.getMallId();
String accessToken = auth.getAccessToken();
LocalDateTime syncTime = LocalDateTime.now();
int pageCount = 0;
int created = 0;
int updated = 0;
int skuCount = 0;
Set<String> seenGoodsIds = new HashSet<>();
// 列表接口 is_onsale / outer_id / goods_name 三选一,需分别拉上架与下架
for (int isOnsale : List.of(1, 0)) {
int page = 1;
Integer total = null;
while (true) {
PddGoodsPopApiClient.GoodsListPage listPage;
try {
listPage = goodsPopApiClient.fetchGoodsList(
mallId, accessToken, page, LIST_PAGE_SIZE, isOnsale);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
log.error("同步拼多多商品失败 pddShopId={} mallId={} isOnsale={} page={}",
pddShopId, mallId, isOnsale, page, e);
throw new BusinessException("同步拼多多商品失败: " + e.getMessage());
}
pageCount++;
if (total == null) {
total = listPage.totalCount();
}
List<PddGoodsPopApiClient.GoodsListItem> items = listPage.goodsList();
if (items == null || items.isEmpty()) {
break;
}
for (PddGoodsPopApiClient.GoodsListItem item : items) {
if (item.goodsId() == null) {
continue;
}
String goodsId = String.valueOf(item.goodsId());
if (!seenGoodsIds.add(goodsId)) {
continue;
}
UpsertResult ur = upsertGoodsItem(companyId, pddShopId, mallId, item, syncTime);
if (ur.created()) {
created++;
} else {
updated++;
}
skuCount += ur.skuCount();
}
if (items.size() < LIST_PAGE_SIZE) {
break;
}
if (total != null && page * LIST_PAGE_SIZE >= total) {
break;
}
page++;
}
}
return PddGoodsSyncResultVO.builder()
.pddShopId(pddShopId)
.mallId(mallId)
.syncedCount(seenGoodsIds.size())
.createdCount(created)
.updatedCount(updated)
.skuCount(skuCount)
.pageCount(pageCount)
.build();
}
private UpsertResult upsertGoodsItem(Long companyId,
Long pddShopId,
Long mallId,
PddGoodsPopApiClient.GoodsListItem item,
LocalDateTime syncTime) {
String goodsId = String.valueOf(item.goodsId());
PddGoodsPO existing = this.getOne(new LambdaQueryWrapper<PddGoodsPO>()
.eq(PddGoodsPO::getShopId, pddShopId)
.eq(PddGoodsPO::getGoodsId, goodsId)
.last("LIMIT 1"));
boolean created = existing == null;
PddGoodsPO goods = existing != null ? existing : new PddGoodsPO();
goods.setCompanyId(companyId);
goods.setShopId(pddShopId);
goods.setMallId(mallId);
goods.setGoodsId(goodsId);
goods.setGoodsName(StringUtils.hasText(item.goodsName()) ? item.goodsName() : goodsId);
goods.setGoodsQuantity(toInt(item.goodsQuantity()));
goods.setGoodsReserveQuantity(toInt(item.goodsReserveQuantity()));
goods.setImageUrl(blankToNull(item.imageUrl()));
goods.setThumbUrl(blankToNull(item.thumbUrl()));
goods.setIsMoreSku(item.isMoreSku() != null ? item.isMoreSku() : 0);
goods.setIsOnsale(item.isOnsale() != null ? item.isOnsale() : 0);
goods.setPddCreatedAt(epochSecToLocalDateTime(item.createdAtEpochSec()));
goods.setRawResponse(item.rawJson());
goods.setLastSyncTime(syncTime);
if (created) {
this.save(goods);
} else {
this.updateById(goods);
pddGoodsSkuMapper.delete(new LambdaQueryWrapper<PddGoodsSkuPO>()
.eq(PddGoodsSkuPO::getGoodsRowId, goods.getId()));
}
int skuInserted = 0;
if (item.skuList() != null) {
for (PddGoodsPopApiClient.GoodsListSku sku : item.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.setSpecDetails(blankToNull(sku.specDetailsJson()));
po.setSkuQuantity(toInt(sku.skuQuantity()));
po.setReserveQuantity(toInt(sku.reserveQuantity()));
po.setIsSkuOnsale(sku.isSkuOnsale() != null ? sku.isSkuOnsale() : 0);
po.setOuterGoodsId(blankToNull(sku.outerGoodsId()));
po.setOuterId(blankToNull(sku.outerId()));
pddGoodsSkuMapper.insert(po);
skuInserted++;
}
}
return new UpsertResult(created, skuInserted);
}
private record UpsertResult(boolean created, int skuCount) {
}
private static Integer toInt(Long v) {
if (v == null) {
return 0;
}
if (v > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
if (v < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
return v.intValue();
}
private static String blankToNull(String s) {
return StringUtils.hasText(s) ? s.trim() : null;
}
private static LocalDateTime epochSecToLocalDateTime(Long epochSec) {
if (epochSec == null || epochSec <= 0) {
return null;
}
return LocalDateTime.ofInstant(Instant.ofEpochSecond(epochSec), ZONE);
}
private PddGoodsSkuPO convertToSkuPO(CreatePddGoodsSkuDTO dto, Long goodsRowId, Long companyId) {
PddGoodsSkuPO sku = new PddGoodsSkuPO();
BeanCopyUtils.copyProperties(dto, sku);
@@ -173,6 +385,13 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
return sku;
}
private PddGoodsVO convertToBriefVO(PddGoodsPO goods) {
PddGoodsVO vo = new PddGoodsVO();
BeanCopyUtils.copyProperties(goods, vo);
vo.setSkus(null);
return vo;
}
private PddGoodsVO convertToVO(PddGoodsPO goods) {
PddGoodsVO vo = new PddGoodsVO();
BeanCopyUtils.copyProperties(goods, vo);
@@ -15,6 +15,7 @@ public final class PddPopApiTypes {
// ---------- 商品 ----------
public static final String GOODS_INFORMATION_GET = "pdd.goods.information.get";
public static final String GOODS_LIST_GET = "pdd.goods.list.get";
// ---------- 店铺 ----------
public static final String MALL_INFO_GET = "pdd.mall.info.get";
@@ -1,8 +1,10 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.goods;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pdd.pop.sdk.http.api.pop.request.PddGoodsInformationGetRequest;
import com.pdd.pop.sdk.http.api.pop.request.PddGoodsListGetRequest;
import com.pdd.pop.sdk.http.api.pop.response.PddGoodsInformationGetResponse;
import lombok.RequiredArgsConstructor;
import com.pdd.pop.sdk.http.api.pop.response.PddGoodsListGetResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
@@ -14,14 +16,19 @@ import java.util.Collections;
import java.util.List;
/**
* 商品域 POP:{@value PddPopApiTypes#GOODS_INFORMATION_GET}。
* 商品域 POP:{@value PddPopApiTypes#GOODS_INFORMATION_GET}、{@value PddPopApiTypes#GOODS_LIST_GET}。
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class PddGoodsPopApiClient {
private final PddPopInvokeSupport invokeSupport;
private final ObjectMapper objectMapper;
public PddGoodsPopApiClient(PddPopInvokeSupport invokeSupport, ObjectMapper objectMapper) {
this.invokeSupport = invokeSupport;
this.objectMapper = objectMapper;
}
public GoodsDetail fetchGoodsInformation(Long mallId, String accessToken, Long goodsId) throws Exception {
if (goodsId == null) {
@@ -32,11 +39,78 @@ public class PddGoodsPopApiClient {
request.setGoodsId(goodsId);
PddGoodsInformationGetResponse response = client.syncInvoke(request, accessToken);
invokeSupport.assertNoError(response, PddPopApiTypes.GOODS_INFORMATION_GET);
return map(response);
return mapInformation(response);
});
}
private static GoodsDetail map(PddGoodsInformationGetResponse response) {
/**
* 商品列表分页。isOnsale:0 下架 / 1 上架;与 outer_id、goods_name 三选一,优先级 is_onsale 最高。
*/
public GoodsListPage fetchGoodsList(Long mallId,
String accessToken,
int page,
int pageSize,
Integer isOnsale) throws Exception {
return invokeSupport.invoke(PddPopApiTypes.GOODS_LIST_GET, mallId, client -> {
PddGoodsListGetRequest request = new PddGoodsListGetRequest();
request.setPage(Math.max(page, 1));
request.setPageSize(Math.min(Math.max(pageSize, 1), 100));
if (isOnsale != null) {
request.setIsOnsale(isOnsale);
}
PddGoodsListGetResponse response = client.syncInvoke(request, accessToken);
invokeSupport.assertNoError(response, PddPopApiTypes.GOODS_LIST_GET);
return mapList(response);
});
}
private GoodsListPage mapList(PddGoodsListGetResponse response) {
if (response == null || response.getGoodsListGetResponse() == null) {
return new GoodsListPage(0, List.of());
}
var body = response.getGoodsListGetResponse();
int total = body.getTotalCount() != null ? body.getTotalCount() : 0;
List<GoodsListItem> items = new ArrayList<>();
if (body.getGoodsList() != null) {
for (var g : body.getGoodsList()) {
if (g == null || g.getGoodsId() == null) {
continue;
}
List<GoodsListSku> skus = new ArrayList<>();
if (g.getSkuList() != null) {
for (var s : g.getSkuList()) {
if (s == null || s.getSkuId() == null) {
continue;
}
skus.add(new GoodsListSku(
s.getSkuId(),
s.getSpec(),
s.getSkuQuantity(),
s.getReserveQuantity(),
s.getIsSkuOnsale(),
s.getOuterGoodsId(),
s.getOuterId(),
toJsonQuietly(s.getSpecDetails())));
}
}
items.add(new GoodsListItem(
g.getGoodsId(),
g.getGoodsName(),
g.getGoodsQuantity(),
g.getGoodsReserveQuantity(),
g.getImageUrl(),
g.getThumbUrl(),
g.getIsMoreSku(),
g.getIsOnsale(),
g.getCreatedAt(),
Collections.unmodifiableList(skus),
toJsonQuietly(g)));
}
}
return new GoodsListPage(total, Collections.unmodifiableList(items));
}
private GoodsDetail mapInformation(PddGoodsInformationGetResponse response) {
if (response == null || response.getGoodsInfoGetResponse() == null
|| response.getGoodsInfoGetResponse().getGoodsInfo() == null) {
return null;
@@ -65,6 +139,46 @@ public class PddGoodsPopApiClient {
Collections.unmodifiableList(skus));
}
private String toJsonQuietly(Object value) {
if (value == null) {
return null;
}
try {
return objectMapper.writeValueAsString(value);
} catch (Exception e) {
log.warn("序列化拼多多商品字段失败: {}", e.getMessage());
return null;
}
}
public record GoodsListPage(int totalCount, List<GoodsListItem> goodsList) {
}
public record GoodsListItem(
Long goodsId,
String goodsName,
Long goodsQuantity,
Long goodsReserveQuantity,
String imageUrl,
String thumbUrl,
Integer isMoreSku,
Integer isOnsale,
Long createdAtEpochSec,
List<GoodsListSku> skuList,
String rawJson) {
}
public record GoodsListSku(
Long skuId,
String spec,
Long skuQuantity,
Long reserveQuantity,
Integer isSkuOnsale,
String outerGoodsId,
String outerId,
String specDetailsJson) {
}
public record GoodsDetail(
Long goodsId,
String goodsName,
@@ -143,7 +143,7 @@ public class PddShopServiceImpl extends ServiceImpl<PddShopMapper, PddShopPO> im
IPage<PddShopPO> page = new Page<>(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
IPage<PddShopPO> result = this.page(page, wrapper);
List<PddShopVO> voList = toBriefVoList(result.getRecords());
List<PddShopVO> voList = toVoList(result.getRecords(), true);
return PageResultVO.create(voList, result.getTotal(),
(int) pageQueryDTO.getPage(), (int) pageQueryDTO.getPageSize());
@@ -121,6 +121,14 @@ INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status
SELECT 3603, (SELECT id FROM `sys_permission` WHERE `code` = 'biz:pdd' LIMIT 1), 'biz:pdd:shop:manage', '拼多多店铺管理', 'api', 1, '', 363
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'biz:pdd:shop:manage');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 3610, (SELECT id FROM `sys_permission` WHERE `code` = 'biz:pdd' LIMIT 1), 'biz:pdd:goods:read', '拼多多商品查看', 'api', 1, '', 364
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'biz:pdd:goods:read');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 3611, (SELECT id FROM `sys_permission` WHERE `code` = 'biz:pdd' LIMIT 1), 'biz:pdd:goods:manage', '拼多多商品管理', 'api', 1, '同步/维护拼多多商品', 365
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'biz:pdd:goods:manage');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 4100, (SELECT id FROM `sys_permission` WHERE `code` = 'MODULE:data' LIMIT 1), 'data:import-group', '数据导入', 'module', 1, '', 400
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'data:import-group');
@@ -374,9 +382,17 @@ SELECT 12030, NULL, 0, '拼多多', '拼多多', '/pdd', '', '', 'arcticons:pind
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` = '拼多多');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 12032, (SELECT id FROM `sys_menu` WHERE `name` = '拼多多' LIMIT 1), 0, '拼多多订单', '订单', '/pdd/order', '/ecommerce/pdd/order/index', '', 'lucide:shopping-bag', 'menu', 1, 1, 0, 1
SELECT 12032, (SELECT id FROM `sys_menu` WHERE `name` = '拼多多' LIMIT 1), 0, '拼多多订单', '订单', '/pdd/order', '/channel/pdd/order/index', '', 'lucide:shopping-bag', 'menu', 1, 1, 0, 1
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` = '拼多多订单');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 12033, (SELECT id FROM `sys_menu` WHERE `name` = '拼多多' LIMIT 1), 0, '拼多多店铺', '店铺', '/pdd/shop', '/channel/pdd/shop/index', '', 'lucide:store', 'menu', 1, 1, 0, 0
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` = '拼多多店铺');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 12034, (SELECT id FROM `sys_menu` WHERE `name` = '拼多多' LIMIT 1), 0, '拼多多商品', '商品', '/pdd/goods', '/channel/pdd/goods/index', '', 'lucide:package', 'menu', 1, 1, 0, 2
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` = '拼多多商品');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 12031, NULL, 0, '淘宝', '淘宝', '', '', '', 'ri:taobao-fill', 'menu', 1, 1, 0, 0
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` = '淘宝');
@@ -516,6 +532,12 @@ SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'ecom
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code IN ('biz:pdd:order:read', 'biz:pdd:order:manage', 'biz:pdd:order:sync') WHERE m.name = '拼多多订单';
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code IN ('biz:pdd:shop:read', 'biz:pdd:shop:manage', 'biz:pdd:goods:read', 'biz:pdd:goods:manage') WHERE m.name = '拼多多店铺';
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code IN ('biz:pdd:goods:read', 'biz:pdd:goods:manage') WHERE m.name = '拼多多商品';
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'ecom:product:%' WHERE m.name = '商品管理';
@@ -0,0 +1,32 @@
import type { PageQueryDTO, PageResultVO } from '#/types/common';
import { requestClient } from '#/api/request';
import type { PddGoodsDTO, PddGoodsVO } from './types';
/** 分页查询拼多多渠道商品 */
export async function getPddGoodsPageApi(
params: PageQueryDTO<PddGoodsDTO.Filters>,
) {
return requestClient.post<PageResultVO<PddGoodsVO.Info>>(
'/channel/pdd/goods/list',
params,
);
}
/** 拼多多商品详情(含 SKU) */
export async function getPddGoodsDetailApi(id: number) {
return requestClient.get<PddGoodsVO.Info>(`/channel/pdd/goods/detail/${id}`);
}
/** 删除拼多多商品及 SKU */
export async function deletePddGoodsApi(id: number) {
return requestClient.delete<void>(`/channel/pdd/goods/delete/${id}`);
}
/** 按渠道店铺同步商品 */
export async function syncPddGoodsByShopApi(pddShopId: number) {
return requestClient.post<PddGoodsVO.SyncResult>(
`/channel/pdd/goods/sync/${pddShopId}`,
);
}
@@ -0,0 +1,2 @@
export * from './apis';
export * from './types';
@@ -0,0 +1,59 @@
export namespace PddGoodsDTO {
export interface Filters {
/** 渠道店铺ID(channel_pdd_shop.id) */
shopId?: number;
mallId?: number;
goodsName?: string;
goodsId?: string;
/** 0否 1是 */
isOnsale?: number;
/** 0否 1是 */
isMoreSku?: number;
}
}
export namespace PddGoodsVO {
export interface Sku {
id?: number;
goodsRowId?: number;
goodsId?: string;
skuId?: string;
spec?: string;
specDetails?: string;
skuQuantity?: number;
reserveQuantity?: number;
isSkuOnsale?: number;
outerGoodsId?: string;
outerId?: string;
}
export interface Info {
id: number;
companyId?: number;
shopId?: number;
mallId?: number;
goodsId?: string;
goodsName?: string;
goodsQuantity?: number;
goodsReserveQuantity?: number;
imageUrl?: string;
thumbUrl?: string;
isMoreSku?: number;
isOnsale?: number;
pddCreatedAt?: string;
lastSyncTime?: string;
createTime?: string;
updateTime?: string;
skus?: Sku[];
}
export interface SyncResult {
pddShopId: number;
mallId?: number;
syncedCount?: number;
createdCount?: number;
updatedCount?: number;
skuCount?: number;
pageCount?: number;
}
}
@@ -1,10 +1,20 @@
import type { PddShopInfo } from '#/api/ec/shop/types';
import type { PageQueryDTO, PageResultVO } from '#/types/common';
import { requestClient } from '#/api/request';
/**
* 拼多多渠道店铺详情(含授权信息,不含 token)
*/
import type { PddShopDTO, PddShopVO } from './types';
/** 分页查询拼多多渠道店铺 */
export async function getPddShopPageApi(
params: PageQueryDTO<PddShopDTO.Filters>,
) {
return requestClient.post<PageResultVO<PddShopVO.Info>>(
'/channel/pdd/shop/list',
params,
);
}
/** 拼多多渠道店铺详情(含授权信息,不含 token) */
export async function getPddShopDetailApi(id: number) {
return requestClient.get<PddShopInfo>(`/channel/pdd/shop/detail/${id}`);
return requestClient.get<PddShopVO.Info>(`/channel/pdd/shop/detail/${id}`);
}
@@ -1 +1,2 @@
export * from './apis';
export * from './types';
@@ -0,0 +1,39 @@
export namespace PddShopDTO {
export interface Filters {
mallName?: string;
merchantType?: number;
mallCharacter?: number;
pddAuthId?: number;
}
}
export namespace PddShopVO {
export interface AuthInfo {
id: number;
companyId?: number;
ownerId?: string;
expiresAt?: string;
refreshTokenExpiresAt?: string;
scope?: string;
/** 0失效 1正常 2已撤销 */
status?: number;
createTime?: string;
updateTime?: string;
}
export interface Info {
id: number;
companyId?: number;
pddAuthId?: null | number;
auth?: AuthInfo | null;
mallId?: number;
mallName?: string;
logo?: string;
mallDesc?: string;
merchantType?: number;
mallCharacter?: number;
lastSyncTime?: string;
createTime?: string;
updateTime?: string;
}
}
@@ -0,0 +1,150 @@
<script lang="ts" setup>
import type { PddGoodsVO } from '#/api/channel/pdd/goods';
import { ref } from 'vue';
import {
Descriptions,
DescriptionsItem,
Drawer,
Image,
Spin,
Table,
Tag,
message,
} from 'ant-design-vue';
import { getPddGoodsDetailApi } from '#/api/channel/pdd/goods';
defineOptions({ name: 'PddGoodsDetailDrawer' });
const openFlag = ref(false);
const loading = ref(false);
const shopName = ref('');
const detail = ref<null | PddGoodsVO.Info>(null);
const skuColumns = [
{
title: '外部SKU',
dataIndex: 'outerId',
key: 'outerId',
ellipsis: true,
width: 140,
},
{ title: '规格', dataIndex: 'spec', key: 'spec', ellipsis: true },
{ title: '库存', dataIndex: 'skuQuantity', key: 'skuQuantity', width: 80 },
{
title: '预扣',
dataIndex: 'reserveQuantity',
key: 'reserveQuantity',
width: 80,
},
{ title: '在架', key: 'isSkuOnsale', width: 80 },
{
title: '外部商品',
dataIndex: 'outerGoodsId',
key: 'outerGoodsId',
ellipsis: true,
width: 120,
},
];
async function open(id: number, shopLabel?: string) {
openFlag.value = true;
shopName.value = shopLabel || '';
loading.value = true;
detail.value = null;
try {
detail.value = await getPddGoodsDetailApi(id);
} catch (error) {
console.error(error);
message.error('加载商品详情失败');
openFlag.value = false;
} finally {
loading.value = false;
}
}
function close() {
openFlag.value = false;
}
defineExpose({ open, close });
</script>
<template>
<Drawer
v-model:open="openFlag"
:title="detail?.goodsName || '拼多多商品详情'"
width="720"
destroy-on-close
>
<Spin :spinning="loading">
<template v-if="detail">
<div class="mb-4 flex gap-4">
<Image
v-if="detail.thumbUrl || detail.imageUrl"
:src="detail.thumbUrl || detail.imageUrl"
:width="72"
:height="72"
/>
<div class="min-w-0 flex-1">
<div class="truncate text-base font-medium">
{{ detail.goodsName }}
</div>
<div class="mt-2 flex flex-wrap gap-2">
<Tag :color="detail.isOnsale === 1 ? 'success' : 'default'">
{{ detail.isOnsale === 1 ? '在架' : '下架' }}
</Tag>
<Tag :color="detail.isMoreSku === 1 ? 'blue' : 'default'">
{{ detail.isMoreSku === 1 ? '多SKU' : '单SKU' }}
</Tag>
</div>
</div>
</div>
<Descriptions bordered :column="2" size="small" class="mb-4">
<DescriptionsItem label="goods_id">
{{ detail.goodsId || '-' }}
</DescriptionsItem>
<DescriptionsItem label="mall_id">
{{ detail.mallId ?? '-' }}
</DescriptionsItem>
<DescriptionsItem label="渠道店铺" :span="2">
{{ shopName || `渠道店#${detail.shopId}` }}
</DescriptionsItem>
<DescriptionsItem label="总库存">
{{ detail.goodsQuantity ?? 0 }}
</DescriptionsItem>
<DescriptionsItem label="预扣库存">
{{ detail.goodsReserveQuantity ?? 0 }}
</DescriptionsItem>
<DescriptionsItem label="最近同步">
{{ detail.lastSyncTime || '-' }}
</DescriptionsItem>
<DescriptionsItem label="平台创建">
{{ detail.pddCreatedAt || '-' }}
</DescriptionsItem>
</Descriptions>
<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)"
:scroll="{ x: 700 }"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'isSkuOnsale'">
<Tag :color="record.isSkuOnsale === 1 ? 'success' : 'default'">
{{ record.isSkuOnsale === 1 ? '在架' : '下架' }}
</Tag>
</template>
</template>
</Table>
</template>
</Spin>
</Drawer>
</template>
@@ -0,0 +1,387 @@
<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { PddGoodsDTO, PddGoodsVO } from '#/api/channel/pdd/goods';
import type { PddShopVO } from '#/api/channel/pdd/shop';
import type { PageQueryDTO } from '#/types/common';
import { computed, onMounted, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { Button, Image, Popconfirm, Space, Tag, message } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deletePddGoodsApi,
getPddGoodsPageApi,
} from '#/api/channel/pdd/goods';
import { getPddShopPageApi } from '#/api/channel/pdd/shop';
import PddGoodsDetailDrawer from './components/PddGoodsDetailDrawer.vue';
import PddShopDetailModal from '#/views/channel/pdd/shop/components/PddShopDetailModal.vue';
defineOptions({ name: 'PddGoodsManagement' });
const loading = ref(false);
const detailDrawerRef = ref<InstanceType<typeof PddGoodsDetailDrawer>>();
const shopDetailModalRef = ref<InstanceType<typeof PddShopDetailModal>>();
const shopOptions = ref<{ label: string; value: number }[]>([]);
const shopNameById = ref<Record<number, string>>({});
const searchForm = ref({
shopId: undefined as number | undefined,
goodsName: '',
goodsId: '',
isOnsale: undefined as number | undefined,
});
const gridReloadRef = ref<null | (() => void)>(null);
async function loadShops() {
try {
const data = await getPddShopPageApi({
page: 1,
pageSize: 500,
filters: {},
});
const list = data.records ?? [];
shopOptions.value = list.map((s: PddShopVO.Info) => ({
label: s.mallName || `店铺#${s.id}`,
value: s.id,
}));
const map: Record<number, string> = {};
for (const s of list) {
map[s.id] = s.mallName || `店铺#${s.id}`;
}
shopNameById.value = map;
await gridApi.formApi?.updateSchema([
{
fieldName: 'shopId',
componentProps: { options: shopOptions.value },
},
]);
} catch {
message.error('获取渠道店铺失败');
}
}
const gridOptions: VxeGridProps<PddGoodsVO.Info> = {
columns: [
{ type: 'seq' as const, width: 56, title: '序号' },
{
title: '主图',
width: 80,
align: 'center' as const,
showOverflow: false,
slots: { default: 'thumb' },
},
{
title: '商品名称',
minWidth: 200,
showOverflow: 'tooltip' as const,
slots: { default: 'goodsName' },
},
{
title: '渠道店铺',
minWidth: 140,
showOverflow: 'tooltip' as const,
slots: { default: 'shop' },
},
{
title: '状态',
width: 90,
slots: { default: 'onsale' },
},
{
title: 'SKU',
width: 80,
slots: { default: 'moreSku' },
},
{
field: 'goodsQuantity',
title: '库存',
width: 80,
},
{
field: 'pddCreatedAt',
title: '拼多多创建时间',
minWidth: 160,
},
{
field: 'lastSyncTime',
title: '最近同步',
minWidth: 160,
},
{
field: 'updateTime',
title: '更新时间',
minWidth: 160,
},
{
title: '操作',
minWidth: 140,
fixed: 'right' as const,
showOverflow: false,
slots: { default: 'action' },
},
],
height: 'auto',
border: true,
stripe: true,
rowConfig: { isHover: true, height: 72 },
showOverflow: true,
size: 'small',
toolbarConfig: {
custom: true,
refresh: true,
zoom: true,
},
data: [],
pagerConfig: {
enabled: true,
pageSizes: [10, 20, 50, 100],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
proxyConfig: {
ajax: {
query: async ({ page }: any) => {
try {
loading.value = true;
const params: PageQueryDTO<PddGoodsDTO.Filters> = {
page: page.currentPage,
pageSize: page.pageSize,
filters: {
shopId: searchForm.value.shopId,
goodsName: searchForm.value.goodsName || undefined,
goodsId: searchForm.value.goodsId || undefined,
isOnsale: searchForm.value.isOnsale,
},
};
const data = await getPddGoodsPageApi(params);
return {
items: data.records ?? [],
total: data.total ?? 0,
};
} catch (error) {
console.error('获取拼多多商品失败:', error);
message.error('获取拼多多商品失败');
return { items: [], total: 0 };
} finally {
loading.value = false;
}
},
},
},
};
const formOptions = computed(() => ({
schema: [
{
component: 'Select',
componentProps: {
placeholder: '全部店铺',
options: shopOptions.value,
allowClear: true,
showSearch: true,
optionFilterProp: 'label',
onChange: (val: number | undefined) => {
searchForm.value.shopId = val;
gridReloadRef.value?.();
},
},
fieldName: 'shopId',
label: '渠道店铺',
},
{
component: 'Input',
componentProps: {
placeholder: '商品名称(模糊)',
allowClear: true,
onChange: (e: any) => {
searchForm.value.goodsName = e?.target?.value ?? '';
},
onPressEnter: () => gridReloadRef.value?.(),
},
fieldName: 'goodsName',
label: '商品名称',
},
{
component: 'Input',
componentProps: {
placeholder: '拼多多商品ID',
allowClear: true,
onChange: (e: any) => {
searchForm.value.goodsId = e?.target?.value ?? '';
},
onPressEnter: () => gridReloadRef.value?.(),
},
fieldName: 'goodsId',
label: 'goods_id',
},
{
component: 'Select',
componentProps: {
placeholder: '全部',
allowClear: true,
options: [
{ label: '在架', value: 1 },
{ label: '下架', value: 0 },
],
onChange: (val: number | undefined) => {
searchForm.value.isOnsale = val;
gridReloadRef.value?.();
},
},
fieldName: 'isOnsale',
label: '在架状态',
},
],
submitButtonOptions: { content: '搜索' },
resetButtonOptions: { content: '重置' },
handleSubmit: async () => {
gridReloadRef.value?.();
},
handleReset: async () => {
searchForm.value = {
shopId: undefined,
goodsName: '',
goodsId: '',
isOnsale: undefined,
};
gridReloadRef.value?.();
},
}));
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
formOptions: formOptions.value,
showSearchForm: true,
tableTitle: '拼多多渠道商品',
});
gridReloadRef.value = () => gridApi.reload();
function openDetail(row: PddGoodsVO.Info) {
const shopLabel = row.shopId
? shopNameById.value[row.shopId]
: undefined;
detailDrawerRef.value?.open(row.id, shopLabel);
}
function openShopDetail(row: PddGoodsVO.Info) {
if (!row.shopId) {
message.warning('该商品未关联渠道店铺');
return;
}
shopDetailModalRef.value?.open(row.shopId);
}
async function handleDelete(row: PddGoodsVO.Info) {
try {
await deletePddGoodsApi(row.id);
message.success('已删除');
gridApi.reload();
} catch (error: any) {
message.error(error?.message || '删除失败');
}
}
onMounted(async () => {
await loadShops();
});
</script>
<template>
<Page auto-content-height>
<Grid class="pdd-goods-grid">
<template #thumb="{ row }: { row: PddGoodsVO.Info }">
<Image
v-if="row.thumbUrl || row.imageUrl"
:src="row.thumbUrl || row.imageUrl"
:width="40"
:height="40"
class="goods-thumb"
/>
<span v-else class="text-slate-400">-</span>
</template>
<template #goodsName="{ row }: { row: PddGoodsVO.Info }">
<Button type="link" size="small" class="!px-0" @click="openDetail(row)">
{{ row.goodsName || '-' }}
</Button>
</template>
<template #shop="{ row }: { row: PddGoodsVO.Info }">
<Button
v-if="row.shopId"
type="link"
size="small"
class="!px-0"
@click="openShopDetail(row)"
>
{{ shopNameById[row.shopId] || `渠道店#${row.shopId}` }}
</Button>
<span v-else>-</span>
</template>
<template #onsale="{ row }: { row: PddGoodsVO.Info }">
<Tag :color="row.isOnsale === 1 ? 'success' : 'default'">
{{ row.isOnsale === 1 ? '在架' : '下架' }}
</Tag>
</template>
<template #moreSku="{ row }: { row: PddGoodsVO.Info }">
<Tag :color="row.isMoreSku === 1 ? 'blue' : 'default'">
{{ row.isMoreSku === 1 ? '多SKU' : '单SKU' }}
</Tag>
</template>
<template #action="{ row }: { row: PddGoodsVO.Info }">
<Space size="small" :wrap="false">
<Button type="link" size="small" @click="openDetail(row)">
详情
</Button>
<Popconfirm
title="确定删除该商品及全部 SKU 吗?"
@confirm="handleDelete(row)"
>
<Button type="link" size="small" danger>删除</Button>
</Popconfirm>
</Space>
</template>
</Grid>
<PddGoodsDetailDrawer ref="detailDrawerRef" />
<PddShopDetailModal ref="shopDetailModalRef" />
</Page>
</template>
<style scoped>
.goods-thumb {
border-radius: 6px;
object-fit: cover;
}
:deep(.pdd-goods-grid .vxe-body--column) {
vertical-align: middle;
}
</style>
@@ -1,5 +1,5 @@
<script lang="ts" setup>
import type { PddShopInfo } from '#/api/ec/shop/types';
import type { PddShopVO } from '#/api/channel/pdd/shop';
import { computed, ref } from 'vue';
@@ -9,6 +9,8 @@ import { Descriptions, Spin, Tag, message } from 'ant-design-vue';
import { getPddShopDetailApi } from '#/api/channel/pdd/shop';
defineOptions({ name: 'PddShopDetailModal' });
const MERCHANT_TYPE_MAP: Record<number, string> = {
1: '个人',
2: '企业',
@@ -32,7 +34,7 @@ const AUTH_STATUS_MAP: Record<number, { color: string; label: string }> = {
};
const loading = ref(false);
const pddShop = ref<null | PddShopInfo>(null);
const pddShop = ref<null | PddShopVO.Info>(null);
const internalShopName = ref('');
const [Modal, modalApi] = useVbenModal({
@@ -64,9 +66,13 @@ const authStatus = computed(() => {
return AUTH_STATUS_MAP[status] ?? { color: 'default', label: String(status) };
});
/**
* @param pddShopId channel_pdd_shop.id
* @param shopName 可选:内部店铺名等上下文标题旁注
*/
async function open(pddShopId: number, shopName?: string) {
if (!pddShopId) {
message.warning('暂无外部店铺详情,请先完成授权同步');
message.warning('暂无外部店铺详情');
return;
}
internalShopName.value = shopName || '';
@@ -88,7 +94,7 @@ defineExpose({ open });
</script>
<template>
<Modal title="拼多多外部店铺" content-class="px-5 py-4">
<Modal title="拼多多渠道店铺详情" content-class="px-5 py-4">
<Spin :spinning="loading">
<div v-if="pddShop" class="space-y-4">
<div class="flex items-center gap-3">
@@ -103,13 +109,13 @@ defineExpose({ open });
{{ pddShop.mallName || '-' }}
</div>
<div v-if="internalShopName" class="mt-1 text-xs text-slate-500">
内部店铺:{{ internalShopName }}
{{ internalShopName }}
</div>
</div>
</div>
<Descriptions :column="1" bordered size="small" title="店铺信息">
<Descriptions.Item label="平台店铺主键">
<Descriptions.Item label="渠道店铺ID">
{{ pddShop.id }}
</Descriptions.Item>
<Descriptions.Item label="mall_id">
@@ -0,0 +1,329 @@
<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { PddShopDTO, PddShopVO } from '#/api/channel/pdd/shop';
import type { PageQueryDTO } from '#/types/common';
import { computed, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { Button, Image, Space, Tag, message } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
getPddShopPageApi,
} from '#/api/channel/pdd/shop';
import { syncPddGoodsByShopApi } from '#/api/channel/pdd/goods';
import PddShopDetailModal from './components/PddShopDetailModal.vue';
defineOptions({ name: 'PddShopManagement' });
const MERCHANT_TYPE_MAP: Record<number, string> = {
1: '个人',
2: '企业',
3: '旗舰店',
4: '专卖店',
5: '专营店',
6: '普通店',
};
const AUTH_STATUS_MAP: Record<number, { color: string; text: string }> = {
0: { color: 'error', text: '失效' },
1: { color: 'success', text: '正常' },
2: { color: 'default', text: '已撤销' },
};
const loading = ref(false);
const syncingShopId = ref<null | number>(null);
const shopDetailModalRef = ref<InstanceType<typeof PddShopDetailModal>>();
const searchForm = ref({
mallName: '',
merchantType: undefined as number | undefined,
});
const gridReloadRef = ref<null | (() => void)>(null);
const gridOptions: VxeGridProps<PddShopVO.Info> = {
columns: [
{ type: 'seq' as const, width: 56, title: '序号' },
{
title: 'Logo',
width: 88,
align: 'center' as const,
showOverflow: false,
slots: { default: 'logo' },
},
{
title: '店铺名称',
minWidth: 160,
showOverflow: 'tooltip' as const,
slots: { default: 'mallName' },
},
{
field: 'mallId',
title: 'mall_id',
minWidth: 120,
},
{
title: '店铺类型',
width: 100,
slots: { default: 'merchantType' },
},
{
title: '授权',
minWidth: 140,
slots: { default: 'auth' },
},
{
field: 'lastSyncTime',
title: '店铺最近同步',
minWidth: 160,
},
{
field: 'createTime',
title: '创建时间',
minWidth: 160,
},
{
title: '操作',
minWidth: 200,
fixed: 'right' as const,
showOverflow: false,
slots: { default: 'action' },
},
],
height: 'auto',
border: true,
stripe: true,
rowConfig: { isHover: true, height: 72 },
showOverflow: true,
size: 'small',
toolbarConfig: {
custom: true,
refresh: true,
zoom: true,
},
data: [],
pagerConfig: {
enabled: true,
pageSizes: [10, 20, 50, 100],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
proxyConfig: {
ajax: {
query: async ({ page }: any) => {
try {
loading.value = true;
const params: PageQueryDTO<PddShopDTO.Filters> = {
page: page.currentPage,
pageSize: page.pageSize,
filters: {
mallName: searchForm.value.mallName || undefined,
merchantType: searchForm.value.merchantType,
},
};
const data = await getPddShopPageApi(params);
return {
items: data.records ?? [],
total: data.total ?? 0,
};
} catch (error) {
console.error('获取拼多多店铺失败:', error);
message.error('获取拼多多店铺失败');
return { items: [], total: 0 };
} finally {
loading.value = false;
}
},
},
},
};
const formOptions = computed(() => ({
schema: [
{
component: 'Input',
componentProps: {
placeholder: '店铺名称(模糊)',
allowClear: true,
onChange: (e: any) => {
searchForm.value.mallName = e?.target?.value ?? '';
},
onPressEnter: () => gridReloadRef.value?.(),
},
fieldName: 'mallName',
label: '店铺名称',
},
{
component: 'Select',
componentProps: {
placeholder: '全部类型',
allowClear: true,
options: Object.entries(MERCHANT_TYPE_MAP).map(([value, label]) => ({
label,
value: Number(value),
})),
onChange: (val: number | undefined) => {
searchForm.value.merchantType = val;
gridReloadRef.value?.();
},
},
fieldName: 'merchantType',
label: '店铺类型',
},
],
submitButtonOptions: { content: '搜索' },
resetButtonOptions: { content: '重置' },
handleSubmit: async () => {
gridReloadRef.value?.();
},
handleReset: async () => {
searchForm.value = { mallName: '', merchantType: undefined };
gridReloadRef.value?.();
},
}));
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
formOptions: formOptions.value,
showSearchForm: true,
tableTitle: '拼多多渠道店铺',
});
gridReloadRef.value = () => gridApi.reload();
function merchantTypeText(type?: null | number) {
if (type == null) return '-';
return MERCHANT_TYPE_MAP[type] ?? String(type);
}
function authTag(row: PddShopVO.Info) {
if (row.pddAuthId == null) {
return { color: 'default', text: '未授权' };
}
const status = row.auth?.status;
if (status == null) {
return { color: 'processing', text: '已绑定' };
}
return AUTH_STATUS_MAP[status] ?? { color: 'default', text: String(status) };
}
function openShopDetail(row: PddShopVO.Info) {
if (!row?.id) return;
shopDetailModalRef.value?.open(row.id);
}
async function handleSyncGoods(row: PddShopVO.Info) {
if (!row?.id) return;
if (row.pddAuthId == null) {
message.warning('该店铺尚未绑定授权,无法同步商品');
return;
}
if (syncingShopId.value != null) {
message.warning('已有同步任务进行中,请稍候');
return;
}
syncingShopId.value = row.id;
const hide = message.loading(`正在同步「${row.mallName || row.mallId}」商品…`, 0);
try {
const result = await syncPddGoodsByShopApi(row.id);
message.success(
`同步完成:共 ${result.syncedCount ?? 0} 个商品(新增 ${result.createdCount ?? 0} / 更新 ${result.updatedCount ?? 0}),SKU ${result.skuCount ?? 0}`,
);
gridApi.reload();
} catch (error: any) {
message.error(error?.message || '同步商品失败');
} finally {
hide();
syncingShopId.value = null;
}
}
</script>
<template>
<Page auto-content-height>
<Grid class="pdd-shop-grid">
<template #logo="{ row }: { row: PddShopVO.Info }">
<Image
v-if="row.logo"
:src="row.logo"
:width="40"
:height="40"
class="shop-logo"
/>
<span v-else class="text-slate-400">-</span>
</template>
<template #mallName="{ row }: { row: PddShopVO.Info }">
<Button type="link" size="small" class="!px-0" @click="openShopDetail(row)">
{{ row.mallName || '-' }}
</Button>
</template>
<template #merchantType="{ row }: { row: PddShopVO.Info }">
{{ merchantTypeText(row.merchantType) }}
</template>
<template #auth="{ row }: { row: PddShopVO.Info }">
<Tag :color="authTag(row).color">{{ authTag(row).text }}</Tag>
<div
v-if="row.auth?.ownerId"
class="mt-1 max-w-[140px] truncate text-xs text-slate-400"
:title="row.auth.ownerId"
>
{{ row.auth.ownerId }}
</div>
</template>
<template #action="{ row }: { row: PddShopVO.Info }">
<Space size="small" :wrap="false">
<Button type="link" size="small" @click="openShopDetail(row)">
详情
</Button>
<Button
type="link"
size="small"
:loading="syncingShopId === row.id"
:disabled="syncingShopId != null && syncingShopId !== row.id"
@click="handleSyncGoods(row)"
>
同步商品
</Button>
</Space>
</template>
</Grid>
<PddShopDetailModal ref="shopDetailModalRef" />
</Page>
</template>
<style scoped>
.shop-logo {
border-radius: 6px;
object-fit: cover;
}
:deep(.pdd-shop-grid .vxe-body--column) {
vertical-align: middle;
}
</style>
@@ -14,7 +14,7 @@ import {
getPlatformTagColor,
} from '#/utils/platform-display';
import PddShopDetailModal from '../list/components/PddShopDetailModal.vue';
import PddShopDetailModal from '#/views/channel/pdd/shop/components/PddShopDetailModal.vue';
defineOptions({ name: 'ShopDetails' });
@@ -24,8 +24,8 @@ import {
} from '#/utils/platform-display';
import PddOrderSyncDrawer from './components/PddOrderSyncDrawer.vue';
import PddShopDetailModal from './components/PddShopDetailModal.vue';
import ShopFormModal from './components/ShopFormModal.vue';
import PddShopDetailModal from '#/views/channel/pdd/shop/components/PddShopDetailModal.vue';
defineOptions({ name: 'ShopManagement' });