feat: 新增拼读都类目管理

This commit is contained in:
2026-09-06 01:29:39 +08:00
parent dc864ea57c
commit 2b5bc02dc8
27 changed files with 1738 additions and 92 deletions
@@ -0,0 +1,45 @@
-- ========================================
-- 拼多多平台类目库设计
-- 数据来源:pdd.goods.cats.get(无需店铺 accessToken)
-- 设计原则:
-- 1. 平台级全库一份,无 company_id
-- 2. cat_id 即平台类目 ID,作为主键
-- 3. path_ids / path_names 便于搜索与展示面包屑
-- 4. is_leaf 由同步后「是否作为他人 parent」回写
-- 5. channel_pdd_cat_sync 单行控制面(id=1)记录全量同步状态
-- ========================================
DROP TABLE IF EXISTS `channel_pdd_cat`;
CREATE TABLE `channel_pdd_cat` (
`cat_id` bigint NOT NULL COMMENT '拼多多类目ID',
`parent_cat_id` bigint NOT NULL DEFAULT 0 COMMENT '父类目ID(0=顶级)',
`cat_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '类目名称',
`level` tinyint NOT NULL COMMENT '层级:1~4',
`is_leaf` tinyint NOT NULL DEFAULT 0 COMMENT '是否叶子:0否 1是',
`path_ids` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '祖先路径ID,如 1/23/456',
`path_names` varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '祖先路径名称',
`last_sync_time` datetime NOT NULL COMMENT '最近同步时间',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`cat_id`) USING BTREE,
INDEX `idx_channel_pdd_cat_parent` (`parent_cat_id` ASC) USING BTREE,
INDEX `idx_channel_pdd_cat_name` (`cat_name` ASC) USING BTREE,
INDEX `idx_channel_pdd_cat_leaf_name` (`is_leaf` ASC, `cat_name` ASC) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '拼多多-平台类目表' ROW_FORMAT = Dynamic;
DROP TABLE IF EXISTS `channel_pdd_cat_sync`;
CREATE TABLE `channel_pdd_cat_sync` (
`id` tinyint NOT NULL COMMENT '固定为 1',
`status` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'IDLE' COMMENT 'IDLE/RUNNING/SUCCESS/FAILED',
`started_at` datetime NULL DEFAULT NULL COMMENT '最近一次开始时间',
`finished_at` datetime NULL DEFAULT NULL COMMENT '最近一次结束时间',
`last_error` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '失败原因',
`synced_count` int NOT NULL DEFAULT 0 COMMENT '最近一次成功同步条数',
`message` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '状态说明',
`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
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '拼多多-平台类目同步控制面' ROW_FORMAT = Dynamic;
INSERT INTO `channel_pdd_cat_sync` (`id`, `status`, `synced_count`)
VALUES (1, 'IDLE', 0);
@@ -0,0 +1,34 @@
-- 拼多多平台类目表 + 同步控制面
CREATE TABLE IF NOT EXISTS `channel_pdd_cat` (
`cat_id` bigint NOT NULL COMMENT '拼多多类目ID',
`parent_cat_id` bigint NOT NULL DEFAULT 0 COMMENT '父类目ID(0=顶级)',
`cat_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '类目名称',
`level` tinyint NOT NULL COMMENT '层级:1~4',
`is_leaf` tinyint NOT NULL DEFAULT 0 COMMENT '是否叶子:0否 1是',
`path_ids` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '祖先路径ID,如 1/23/456',
`path_names` varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '祖先路径名称',
`last_sync_time` datetime NOT NULL COMMENT '最近同步时间',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`cat_id`) USING BTREE,
INDEX `idx_channel_pdd_cat_parent` (`parent_cat_id` ASC) USING BTREE,
INDEX `idx_channel_pdd_cat_name` (`cat_name` ASC) USING BTREE,
INDEX `idx_channel_pdd_cat_leaf_name` (`is_leaf` ASC, `cat_name` ASC) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '拼多多-平台类目表' ROW_FORMAT = Dynamic;
CREATE TABLE IF NOT EXISTS `channel_pdd_cat_sync` (
`id` tinyint NOT NULL COMMENT '固定为 1',
`status` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'IDLE' COMMENT 'IDLE/RUNNING/SUCCESS/FAILED',
`started_at` datetime NULL DEFAULT NULL COMMENT '最近一次开始时间',
`finished_at` datetime NULL DEFAULT NULL COMMENT '最近一次结束时间',
`last_error` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '失败原因',
`synced_count` int NOT NULL DEFAULT 0 COMMENT '最近一次成功同步条数',
`message` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '状态说明',
`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
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '拼多多-平台类目同步控制面' ROW_FORMAT = Dynamic;
INSERT INTO `channel_pdd_cat_sync` (`id`, `status`, `synced_count`)
SELECT 1, 'IDLE', 0
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `channel_pdd_cat_sync` WHERE `id` = 1);
@@ -0,0 +1,12 @@
-- 拼多多类目权限:channel:pdd:cat / read / sync
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 3670, (SELECT id FROM `sys_permission` WHERE `code` = 'channel:pdd' LIMIT 1), 'channel:pdd:cat', '类目', 'module', 1, '', 25
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3670 OR `code` = 'channel:pdd:cat');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 3671, (SELECT id FROM `sys_permission` WHERE `code` = 'channel:pdd:cat' LIMIT 1), 'channel:pdd:cat:read', '查看', 'api', 1, '', 1
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3671 OR `code` = 'channel:pdd:cat:read');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 3672, (SELECT id FROM `sys_permission` WHERE `code` = 'channel:pdd:cat' LIMIT 1), 'channel:pdd:cat:sync', '同步', 'api', 1, '', 2
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3672 OR `code` = 'channel:pdd:cat:sync');
@@ -0,0 +1,20 @@
-- 拼多多类目菜单:插在店铺(1)与订单之间,order=2;顺移订单/商品/广告费
UPDATE `sys_menu` SET `order` = 3 WHERE `id` = 12032 AND `name` = '拼多多订单';
UPDATE `sys_menu` SET `order` = 4 WHERE `id` = 12034 AND `name` = '拼多多商品';
UPDATE `sys_menu` SET `order` = 5 WHERE `id` = 14009 AND `name` = '拼多多商品广告费';
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 12035, (SELECT id FROM `sys_menu` WHERE `id` = 52 OR `name` = '拼多多' LIMIT 1), 0, '拼多多类目', 'PddCatManagement', '拼多多类目', '/pdd/cats', '/channel/pdd/cats/index', '', 'lucide:folder-tree', 'menu', 1, 1, 0, 2
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 12035 OR `name` = '拼多多类目' OR `route_name` = 'PddCatManagement');
-- 类目菜单绑定 cat 权限
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 'channel:pdd:cat:%'
WHERE m.name = '拼多多类目';
-- 商品发布弹窗需查本地类目:商品菜单额外绑定 cat:read
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 = 'channel:pdd:cat:read'
WHERE m.name = '拼多多商品';
@@ -0,0 +1,55 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.model.dto.PddCatChildrenQueryDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.model.dto.PddCatSearchQueryDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.model.vo.PddCatSyncStatusVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.model.vo.PddCatVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.service.PddCatService;
import java.util.List;
/**
* 拼多多平台类目 API(本地库查询 + 全量同步)。
*/
@RestController
@RequestMapping("/api/channel/pdd/cat")
public class PddCatController {
private final PddCatService pddCatService;
public PddCatController(PddCatService pddCatService) {
this.pddCatService = pddCatService;
}
@PostMapping("/sync")
@RequirePermission(value = "channel:pdd:cat:sync", description = "同步拼多多类目", allowSuper = true)
public ApiResponse<Void> triggerSync() {
pddCatService.triggerSync();
return ApiResponse.success("已开始同步");
}
@GetMapping("/sync/status")
@RequirePermission(value = "channel:pdd:cat:read", description = "查询拼多多类目同步状态", allowSuper = true)
public ApiResponse<PddCatSyncStatusVO> getSyncStatus() {
return ApiResponse.success("获取成功", pddCatService.getSyncStatus());
}
@PostMapping("/children")
@RequirePermission(value = "channel:pdd:cat:read", description = "查询拼多多子类目", allowSuper = true)
public ApiResponse<List<PddCatVO>> listChildren(@RequestBody(required = false) PddCatChildrenQueryDTO query) {
return ApiResponse.success("获取成功", pddCatService.listChildren(query));
}
@PostMapping("/search")
@RequirePermission(value = "channel:pdd:cat:read", description = "搜索拼多多类目", allowSuper = true)
public ApiResponse<List<PddCatVO>> search(@RequestBody PddCatSearchQueryDTO query) {
return ApiResponse.success("获取成功", pddCatService.search(query));
}
}
@@ -0,0 +1,29 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Update;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.model.po.PddCatPO;
/**
* 拼多多平台类目 Mapper。
*/
@Mapper
public interface PddCatMapper extends BaseMapper<PddCatPO> {
/** 全部暂标为叶子。 */
@Update("UPDATE channel_pdd_cat SET is_leaf = 1")
int markAllLeaf();
/** 将作为他人 parent 的节点标为非叶子。 */
@Update("""
UPDATE channel_pdd_cat c
INNER JOIN (
SELECT DISTINCT parent_cat_id AS pid
FROM channel_pdd_cat
WHERE parent_cat_id <> 0
) t ON c.cat_id = t.pid
SET c.is_leaf = 0
""")
int markNonLeafParents();
}
@@ -0,0 +1,12 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.model.po.PddCatSyncPO;
/**
* 平台类目同步控制面 Mapper。
*/
@Mapper
public interface PddCatSyncMapper extends BaseMapper<PddCatSyncPO> {
}
@@ -0,0 +1,13 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.model.dto;
import lombok.Data;
/**
* 查询子类目请求。
*/
@Data
public class PddCatChildrenQueryDTO {
/** 父类目 ID;空或 0 表示顶级 */
private Long parentCatId;
}
@@ -0,0 +1,19 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.model.dto;
import lombok.Data;
/**
* 类目关键字搜索请求。
*/
@Data
public class PddCatSearchQueryDTO {
/** 关键字(匹配 cat_name / path_names) */
private String keyword;
/** 是否仅叶子;默认 false */
private Boolean leafOnly;
/** 返回条数;默认 50,最大 100 */
private Integer limit;
}
@@ -0,0 +1,49 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.model.po;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 拼多多平台类目(全库一份,无公司维度)。
*/
@Data
@TableName("channel_pdd_cat")
public class PddCatPO {
@TableId(value = "cat_id", type = IdType.INPUT)
private Long catId;
@TableField("parent_cat_id")
private Long parentCatId;
@TableField("cat_name")
private String catName;
@TableField("level")
private Integer level;
/** 是否叶子:0否 1是 */
@TableField("is_leaf")
private Integer isLeaf;
@TableField("path_ids")
private String pathIds;
@TableField("path_names")
private String pathNames;
@TableField("last_sync_time")
private LocalDateTime lastSyncTime;
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
}
@@ -0,0 +1,46 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.model.po;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 平台类目全量同步控制面(单行 id=1)。
*/
@Data
@TableName("channel_pdd_cat_sync")
public class PddCatSyncPO {
@TableId(value = "id", type = IdType.INPUT)
private Integer id;
/** IDLE / RUNNING / SUCCESS / FAILED */
@TableField("status")
private String status;
@TableField("started_at")
private LocalDateTime startedAt;
@TableField("finished_at")
private LocalDateTime finishedAt;
@TableField("last_error")
private String lastError;
@TableField("synced_count")
private Integer syncedCount;
@TableField("message")
private String message;
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
}
@@ -0,0 +1,20 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.model.vo;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 平台类目同步状态 VO。
*/
@Data
public class PddCatSyncStatusVO {
/** IDLE / RUNNING / SUCCESS / FAILED */
private String status;
private LocalDateTime startedAt;
private LocalDateTime finishedAt;
private String lastError;
private Integer syncedCount;
private String message;
}
@@ -0,0 +1,18 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.model.vo;
import lombok.Data;
/**
* 平台类目节点 VO。
*/
@Data
public class PddCatVO {
private Long catId;
private Long parentCatId;
private String catName;
private Integer level;
private Boolean leaf;
private String pathIds;
private String pathNames;
}
@@ -0,0 +1,26 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.service;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.model.dto.PddCatChildrenQueryDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.model.dto.PddCatSearchQueryDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.model.vo.PddCatSyncStatusVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.model.vo.PddCatVO;
import java.util.List;
/**
* 拼多多平台类目:同步触发与本地查询。
*/
public interface PddCatService {
/** 触发全量异步同步;已 RUNNING 则抛业务异常。 */
void triggerSync();
/** 查询同步控制面状态。 */
PddCatSyncStatusVO getSyncStatus();
/** 按父节点查子类目。 */
List<PddCatVO> listChildren(PddCatChildrenQueryDTO query);
/** 关键字搜索类目。 */
List<PddCatVO> search(PddCatSearchQueryDTO query);
}
@@ -0,0 +1,162 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.common.time.BizClock;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.mapper.PddCatMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.mapper.PddCatSyncMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.model.dto.PddCatChildrenQueryDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.model.dto.PddCatSearchQueryDTO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.model.po.PddCatPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.model.po.PddCatSyncPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.model.vo.PddCatSyncStatusVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.model.vo.PddCatVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.service.PddCatService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.sync.PddCatSyncRunner;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
/**
* 拼多多平台类目服务实现。
*/
@Slf4j
@Service
public class PddCatServiceImpl implements PddCatService {
private static final int SYNC_ROW_ID = 1;
private static final int DEFAULT_SEARCH_LIMIT = 50;
private static final int MAX_SEARCH_LIMIT = 100;
private final PddCatMapper catMapper;
private final PddCatSyncMapper syncMapper;
private final PddCatSyncRunner syncRunner;
public PddCatServiceImpl(PddCatMapper catMapper,
PddCatSyncMapper syncMapper,
PddCatSyncRunner syncRunner) {
this.catMapper = catMapper;
this.syncMapper = syncMapper;
this.syncRunner = syncRunner;
}
@Override
public void triggerSync() {
ensureSyncRow();
LocalDateTime now = LocalDateTime.now(BizClock.ZONE);
// 乐观抢占:仅非 RUNNING 可切入,防止并发同步
int updated = syncMapper.update(null, new LambdaUpdateWrapper<PddCatSyncPO>()
.eq(PddCatSyncPO::getId, SYNC_ROW_ID)
.ne(PddCatSyncPO::getStatus, PddCatSyncRunner.STATUS_RUNNING)
.set(PddCatSyncPO::getStatus, PddCatSyncRunner.STATUS_RUNNING)
.set(PddCatSyncPO::getStartedAt, now)
.set(PddCatSyncPO::getFinishedAt, null)
.set(PddCatSyncPO::getLastError, null)
.set(PddCatSyncPO::getMessage, "同步中"));
if (updated == 0) {
throw new BusinessException("类目同步正在进行中");
}
try {
syncRunner.runAsync();
} catch (RuntimeException e) {
syncMapper.update(null, new LambdaUpdateWrapper<PddCatSyncPO>()
.eq(PddCatSyncPO::getId, SYNC_ROW_ID)
.set(PddCatSyncPO::getStatus, PddCatSyncRunner.STATUS_FAILED)
.set(PddCatSyncPO::getFinishedAt, LocalDateTime.now(BizClock.ZONE))
.set(PddCatSyncPO::getLastError, e.getMessage())
.set(PddCatSyncPO::getMessage, "提交异步任务失败"));
throw e;
}
}
@Override
public PddCatSyncStatusVO getSyncStatus() {
ensureSyncRow();
PddCatSyncPO po = syncMapper.selectById(SYNC_ROW_ID);
PddCatSyncStatusVO vo = new PddCatSyncStatusVO();
if (po == null) {
vo.setStatus(PddCatSyncRunner.STATUS_IDLE);
vo.setSyncedCount(0);
return vo;
}
vo.setStatus(po.getStatus());
vo.setStartedAt(po.getStartedAt());
vo.setFinishedAt(po.getFinishedAt());
vo.setLastError(po.getLastError());
vo.setSyncedCount(po.getSyncedCount());
vo.setMessage(po.getMessage());
// 同步中控制面可能尚未回写条数:用库内实时计数,避免前端一直显示 0
if (PddCatSyncRunner.STATUS_RUNNING.equals(po.getStatus())) {
long live = catMapper.selectCount(null);
vo.setSyncedCount((int) Math.min(live, Integer.MAX_VALUE));
if (!StringUtils.hasText(vo.getMessage()) || "同步中".equals(vo.getMessage())) {
vo.setMessage("同步中(触达限流时会自动等待,属正常)");
}
}
return vo;
}
@Override
public List<PddCatVO> listChildren(PddCatChildrenQueryDTO query) {
long parentId = query == null || query.getParentCatId() == null ? 0L : query.getParentCatId();
List<PddCatPO> list = catMapper.selectList(new LambdaQueryWrapper<PddCatPO>()
.eq(PddCatPO::getParentCatId, parentId)
.orderByAsc(PddCatPO::getCatId));
return list.stream().map(this::toVo).collect(Collectors.toList());
}
@Override
public List<PddCatVO> search(PddCatSearchQueryDTO query) {
if (query == null || !StringUtils.hasText(query.getKeyword())) {
throw new BusinessException("关键字不能为空");
}
String kw = query.getKeyword().trim();
int limit = query.getLimit() == null ? DEFAULT_SEARCH_LIMIT : query.getLimit();
if (limit < 1) {
limit = DEFAULT_SEARCH_LIMIT;
}
if (limit > MAX_SEARCH_LIMIT) {
limit = MAX_SEARCH_LIMIT;
}
boolean leafOnly = Boolean.TRUE.equals(query.getLeafOnly());
List<PddCatPO> list = catMapper.selectList(new LambdaQueryWrapper<PddCatPO>()
.and(w -> w.like(PddCatPO::getCatName, kw).or().like(PddCatPO::getPathNames, kw))
.eq(leafOnly, PddCatPO::getIsLeaf, 1)
.orderByDesc(PddCatPO::getIsLeaf)
.orderByAsc(PddCatPO::getCatName)
.last("LIMIT " + limit));
return list.stream().map(this::toVo).collect(Collectors.toList());
}
private void ensureSyncRow() {
if (syncMapper.selectById(SYNC_ROW_ID) != null) {
return;
}
PddCatSyncPO row = new PddCatSyncPO();
row.setId(SYNC_ROW_ID);
row.setStatus(PddCatSyncRunner.STATUS_IDLE);
row.setSyncedCount(0);
try {
syncMapper.insert(row);
} catch (Exception e) {
log.debug("类目同步控制面行已存在: {}", e.getMessage());
}
}
private PddCatVO toVo(PddCatPO po) {
PddCatVO vo = new PddCatVO();
vo.setCatId(po.getCatId());
vo.setParentCatId(po.getParentCatId());
vo.setCatName(po.getCatName());
vo.setLevel(po.getLevel());
vo.setLeaf(po.getIsLeaf() != null && po.getIsLeaf() == 1);
vo.setPathIds(po.getPathIds());
vo.setPathNames(po.getPathNames());
return vo;
}
}
@@ -0,0 +1,233 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.sync;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.common.time.BizClock;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.mapper.PddCatMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.mapper.PddCatSyncMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.model.po.PddCatPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.cat.model.po.PddCatSyncPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.goods.PddCatPopApiClient;
import java.time.LocalDateTime;
import java.util.ArrayDeque;
import java.util.HashSet;
import java.util.List;
import java.util.Queue;
import java.util.Set;
/**
* 平台类目全量同步执行器(BFS + 异步单飞)。
* <p>
* 拼多多类目最深 4 级:4 级节点直接视为叶子,不再对叶子发起 {@code cats.get},
* 避免数万次空请求在限流下拖成「假死」同步。
*/
@Slf4j
@Service
public class PddCatSyncRunner {
public static final String STATUS_IDLE = "IDLE";
public static final String STATUS_RUNNING = "RUNNING";
public static final String STATUS_SUCCESS = "SUCCESS";
public static final String STATUS_FAILED = "FAILED";
/** 平台类目最大层级(开放平台文档:1~4)。 */
private static final int MAX_CAT_LEVEL = 4;
private static final int SYNC_ROW_ID = 1;
/** 每处理若干父节点回写一次进度,便于前端感知限流等待。 */
private static final int PROGRESS_EVERY_PARENTS = 20;
private final PddCatPopApiClient catPopApiClient;
private final PddCatMapper catMapper;
private final PddCatSyncMapper syncMapper;
public PddCatSyncRunner(PddCatPopApiClient catPopApiClient,
PddCatMapper catMapper,
PddCatSyncMapper syncMapper) {
this.catPopApiClient = catPopApiClient;
this.catMapper = catMapper;
this.syncMapper = syncMapper;
}
/**
* 进程重启后:上一轮 @Async 已死,RUNNING 会永久卡住。
* 用库内数据刷新叶子标记并置为 FAILED,便于用户重新触发(走修复后的 BFS)。
*/
@EventListener(ApplicationReadyEvent.class)
public void recoverInterruptedSyncOnReady() {
PddCatSyncPO po = syncMapper.selectById(SYNC_ROW_ID);
if (po == null || !STATUS_RUNNING.equals(po.getStatus())) {
return;
}
long cnt = catMapper.selectCount(null);
try {
if (cnt > 0) {
catMapper.markAllLeaf();
catMapper.markNonLeafParents();
}
} catch (Exception e) {
log.warn("类目同步中断恢复:刷新叶子标记失败", e);
}
LocalDateTime now = LocalDateTime.now(BizClock.ZONE);
syncMapper.update(null, new LambdaUpdateWrapper<PddCatSyncPO>()
.eq(PddCatSyncPO::getId, SYNC_ROW_ID)
.eq(PddCatSyncPO::getStatus, STATUS_RUNNING)
.set(PddCatSyncPO::getStatus, STATUS_FAILED)
.set(PddCatSyncPO::getFinishedAt, now)
.set(PddCatSyncPO::getSyncedCount, (int) Math.min(cnt, Integer.MAX_VALUE))
.set(PddCatSyncPO::getLastError, "服务重启,同步中断")
.set(PddCatSyncPO::getMessage, "服务重启导致同步中断,已按库内 " + cnt + " 条刷新叶子标记,请重新同步"));
log.warn("拼多多类目同步控制面从 RUNNING 恢复为 FAILED,库内条数={}", cnt);
}
/** 异步执行全量同步;调用方须已将控制面置为 RUNNING。 */
@Async
public void runAsync() {
LocalDateTime syncTime = LocalDateTime.now(BizClock.ZONE);
int count = 0;
try {
count = bfsUpsertAll(syncTime);
catMapper.markAllLeaf();
catMapper.markNonLeafParents();
markSuccess(count, "同步完成,共 " + count + " 条");
log.info("拼多多类目全量同步完成 syncedCount={}", count);
} catch (Exception e) {
log.error("拼多多类目全量同步失败", e);
markFailed(truncate(e.getMessage(), 1000));
}
}
private int bfsUpsertAll(LocalDateTime syncTime) throws Exception {
int count = 0;
int parentsVisited = 0;
Queue<PathCtx> queue = new ArrayDeque<>();
Set<Long> visitedParents = new HashSet<>();
queue.add(new PathCtx(0L, "", ""));
while (!queue.isEmpty()) {
PathCtx ctx = queue.poll();
if (!visitedParents.add(ctx.parentCatId())) {
continue;
}
parentsVisited++;
List<PddCatPopApiClient.CatItem> children = catPopApiClient.listCats(ctx.parentCatId());
if (children == null || children.isEmpty()) {
markLeafIfPresent(ctx.parentCatId());
maybeReportProgress(count, parentsVisited, queue.size());
continue;
}
for (PddCatPopApiClient.CatItem item : children) {
if (item == null || item.catId() == null) {
continue;
}
String pathIds = ctx.pathIds().isEmpty()
? String.valueOf(item.catId())
: ctx.pathIds() + "/" + item.catId();
String pathNames = ctx.pathNames().isEmpty()
? nullToEmpty(item.catName())
: ctx.pathNames() + "/" + nullToEmpty(item.catName());
boolean leafByLevel = item.level() >= MAX_CAT_LEVEL;
upsert(item, pathIds, pathNames, syncTime, leafByLevel);
count++;
// 未达最深层级才继续下探;4 级不再 cats.get,省掉海量空请求
if (!leafByLevel) {
queue.add(new PathCtx(item.catId(), pathIds, pathNames));
}
}
maybeReportProgress(count, parentsVisited, queue.size());
}
return count;
}
private void maybeReportProgress(int count, int parentsVisited, int queueSize) {
if (parentsVisited % PROGRESS_EVERY_PARENTS != 0) {
return;
}
syncMapper.update(null, new LambdaUpdateWrapper<PddCatSyncPO>()
.eq(PddCatSyncPO::getId, SYNC_ROW_ID)
.eq(PddCatSyncPO::getStatus, STATUS_RUNNING)
.set(PddCatSyncPO::getSyncedCount, count)
.set(PddCatSyncPO::getMessage,
"同步中:已写入 " + count + " 条,已探父节点 " + parentsVisited
+ ",队列剩余 " + queueSize));
}
private void markLeafIfPresent(long catId) {
if (catId <= 0) {
return;
}
catMapper.update(null, new LambdaUpdateWrapper<PddCatPO>()
.eq(PddCatPO::getCatId, catId)
.set(PddCatPO::getIsLeaf, 1));
}
private void upsert(PddCatPopApiClient.CatItem item,
String pathIds,
String pathNames,
LocalDateTime syncTime,
boolean leafByLevel) {
PddCatPO existing = catMapper.selectById(item.catId());
int isLeaf = leafByLevel ? 1 : 0;
if (existing == null) {
PddCatPO po = new PddCatPO();
po.setCatId(item.catId());
po.setParentCatId(item.parentCatId() == null ? 0L : item.parentCatId());
po.setCatName(nullToEmpty(item.catName()));
po.setLevel(item.level());
po.setIsLeaf(isLeaf);
po.setPathIds(pathIds);
po.setPathNames(pathNames);
po.setLastSyncTime(syncTime);
catMapper.insert(po);
return;
}
existing.setParentCatId(item.parentCatId() == null ? 0L : item.parentCatId());
existing.setCatName(nullToEmpty(item.catName()));
existing.setLevel(item.level());
existing.setIsLeaf(isLeaf);
existing.setPathIds(pathIds);
existing.setPathNames(pathNames);
existing.setLastSyncTime(syncTime);
catMapper.updateById(existing);
}
private void markSuccess(int syncedCount, String message) {
LocalDateTime now = LocalDateTime.now(BizClock.ZONE);
syncMapper.update(null, new LambdaUpdateWrapper<PddCatSyncPO>()
.eq(PddCatSyncPO::getId, SYNC_ROW_ID)
.set(PddCatSyncPO::getStatus, STATUS_SUCCESS)
.set(PddCatSyncPO::getFinishedAt, now)
.set(PddCatSyncPO::getSyncedCount, syncedCount)
.set(PddCatSyncPO::getMessage, truncate(message, 500))
.set(PddCatSyncPO::getLastError, null));
}
private void markFailed(String error) {
LocalDateTime now = LocalDateTime.now(BizClock.ZONE);
syncMapper.update(null, new LambdaUpdateWrapper<PddCatSyncPO>()
.eq(PddCatSyncPO::getId, SYNC_ROW_ID)
.set(PddCatSyncPO::getStatus, STATUS_FAILED)
.set(PddCatSyncPO::getFinishedAt, now)
.set(PddCatSyncPO::getLastError, error)
.set(PddCatSyncPO::getMessage, "同步失败"));
}
private static String nullToEmpty(String s) {
return s == null ? "" : s;
}
private static String truncate(String s, int max) {
if (!StringUtils.hasText(s)) {
return s;
}
return s.length() <= max ? s : s.substring(0, max);
}
private record PathCtx(long parentCatId, String pathIds, String pathNames) {
}
}
@@ -19,6 +19,8 @@ public final class PddPopApiTypes {
public static final String GOODS_ADD = "pdd.goods.add";
public static final String GOODS_IMAGE_UPLOAD = "pdd.goods.image.upload";
public static final String GOODS_AUTHORIZATION_CATS = "pdd.goods.authorization.cats";
/** 平台全量类目树(无需 accessToken) */
public static final String GOODS_CATS_GET = "pdd.goods.cats.get";
public static final String GOODS_LOGISTICS_TEMPLATE_GET = "pdd.goods.logistics.template.get";
public static final String GOODS_CAT_TEMPLATE_GET = "pdd.goods.cat.template.get";
public static final String GOODS_SPEC_GET = "pdd.goods.spec.get";
@@ -84,6 +84,8 @@ public class PddPopProperties {
map.put(PddPopApiTypes.ORDER_INCREMENT_GET, ApiRule.of(6000, 60, 800, 10));
map.put(PddPopApiTypes.ORDER_INFORMATION_GET, ApiRule.of(6000, 60, 800, 10));
map.put(PddPopApiTypes.GOODS_INFORMATION_GET, ApiRule.of(5000, 60, 800, 10));
map.put(PddPopApiTypes.GOODS_AUTHORIZATION_CATS, ApiRule.of(6000, 60, 800, 10));
map.put(PddPopApiTypes.GOODS_CATS_GET, ApiRule.of(6000, 60, 800, 10));
map.put(PddPopApiTypes.MALL_INFO_GET, ApiRule.of(6000, 60, 800, 10));
return map;
}
@@ -0,0 +1,63 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.goods;
import com.pdd.pop.sdk.http.api.pop.request.PddGoodsCatsGetRequest;
import com.pdd.pop.sdk.http.api.pop.response.PddGoodsCatsGetResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.PddPopApiTypes;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.support.PddPopInvokeSupport;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* 平台类目 POP:{@value PddPopApiTypes#GOODS_CATS_GET}(无需 accessToken)。
*/
@Slf4j
@Component
public class PddCatPopApiClient {
private final PddPopInvokeSupport invokeSupport;
public PddCatPopApiClient(PddPopInvokeSupport invokeSupport) {
this.invokeSupport = invokeSupport;
}
/**
* 拉取指定父节点下的子类目;parentCatId 空或 0 为顶级。
*/
public List<CatItem> listCats(Long parentCatId) throws Exception {
return invokeSupport.invoke(PddPopApiTypes.GOODS_CATS_GET, null, client -> {
PddGoodsCatsGetRequest request = new PddGoodsCatsGetRequest();
request.setParentCatId(parentCatId == null ? 0L : parentCatId);
PddGoodsCatsGetResponse response = client.syncInvoke(request);
invokeSupport.assertNoError(response, PddPopApiTypes.GOODS_CATS_GET);
return mapCats(response);
});
}
private static List<CatItem> mapCats(PddGoodsCatsGetResponse response) {
if (response == null || response.getGoodsCatsGetResponse() == null
|| response.getGoodsCatsGetResponse().getGoodsCatsList() == null) {
return Collections.emptyList();
}
List<CatItem> result = new ArrayList<>();
for (PddGoodsCatsGetResponse.GoodsCatsGetResponseGoodsCatsListItem item
: response.getGoodsCatsGetResponse().getGoodsCatsList()) {
if (item == null || item.getCatId() == null) {
continue;
}
result.add(new CatItem(
item.getCatId(),
item.getParentCatId() == null ? 0L : item.getParentCatId(),
item.getCatName(),
item.getLevel() == null ? 0 : item.getLevel()));
}
return result;
}
/** POP 类目节点。 */
public record CatItem(Long catId, Long parentCatId, String catName, int level) {
}
}
@@ -35,21 +35,32 @@ public class PddPopRateLimiter {
* 阻塞获取调用许可;超时抛 {@link PddPopRateLimitedException}。
*
* @param apiType 如 pdd.order.list.get
* @param mallId 拼多多店铺 mall_id
* @param mallId 拼多多店铺 mall_id;平台级接口(无需店铺)可传 null,仅走 ISV 短窗桶
*/
public void acquire(String apiType, Long mallId) {
if (!popProperties.getRateLimit().isEnabled()) {
return;
}
if (mallId == null) {
throw new BusinessException("限流需要 mallId");
}
PddPopProperties.ApiRule rule = popProperties.resolveRule(apiType);
long deadline = System.currentTimeMillis() + popProperties.getRateLimit().getAcquireWaitMs();
String clientId = oauthProperties.getClientId() == null ? "unknown" : oauthProperties.getClientId();
String shopKey = shopKey(mallId, apiType, rule.getShopWindowSeconds());
String appKey = appKey(clientId, apiType, rule.getAppBurstWindowSeconds());
// 平台级 API:无店铺维度,仅占用 ISV 短窗
if (mallId == null) {
while (true) {
if (tryConsume(appKey, rule.getAppBurstLimit(), rule.getAppBurstWindowSeconds())) {
return;
}
if (System.currentTimeMillis() >= deadline) {
throw new PddPopRateLimitedException(
"拼多多接口调用过于频繁,请稍后重试(api=" + apiType + ", mallId=null)");
}
sleepAcquire();
}
}
String shopKey = shopKey(mallId, apiType, rule.getShopWindowSeconds());
while (true) {
if (tryAcquireBoth(shopKey, rule.getShopLimit(), rule.getShopWindowSeconds(),
appKey, rule.getAppBurstLimit(), rule.getAppBurstWindowSeconds())) {
@@ -59,12 +70,16 @@ public class PddPopRateLimiter {
throw new PddPopRateLimitedException(
"拼多多接口调用过于频繁,请稍后重试(api=" + apiType + ", mallId=" + mallId + ")");
}
try {
TimeUnit.MILLISECONDS.sleep(50);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new BusinessException("等待限流许可被中断");
}
sleepAcquire();
}
}
private static void sleepAcquire() {
try {
TimeUnit.MILLISECONDS.sleep(50);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new BusinessException("等待限流许可被中断");
}
}
@@ -56,6 +56,11 @@ pdd:
shop-window-seconds: 60
app-burst-limit: 800
app-burst-window-seconds: 10
pdd.goods.cats.get:
shop-limit: 6000
shop-window-seconds: 60
app-burst-limit: 800
app-burst-window-seconds: 10
pdd.goods.logistics.template.get:
shop-limit: 6000
shop-window-seconds: 60
@@ -523,6 +523,18 @@ INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status
SELECT 3665, (SELECT id FROM `sys_permission` WHERE `code` = 'channel:pdd:ad-fee' LIMIT 1), 'channel:pdd:ad-fee:import', '导入', 'api', 1, '', 5
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3665 OR `code` = 'channel:pdd:ad-fee:import');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 3670, (SELECT id FROM `sys_permission` WHERE `code` = 'channel:pdd' LIMIT 1), 'channel:pdd:cat', '类目', 'module', 1, '', 25
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3670 OR `code` = 'channel:pdd:cat');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 3671, (SELECT id FROM `sys_permission` WHERE `code` = 'channel:pdd:cat' LIMIT 1), 'channel:pdd:cat:read', '查看', 'api', 1, '', 1
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3671 OR `code` = 'channel:pdd:cat:read');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 3672, (SELECT id FROM `sys_permission` WHERE `code` = 'channel:pdd:cat' LIMIT 1), 'channel:pdd:cat:sync', '同步', 'api', 1, '', 2
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3672 OR `code` = 'channel:pdd:cat:sync');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 3710, (SELECT id FROM `sys_permission` WHERE `code` = 'bi' LIMIT 1), 'bi:workbench', '工作台', 'module', 1, '', 10
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3710 OR `code` = 'bi:workbench');
@@ -844,7 +856,7 @@ SELECT 10091, (SELECT id FROM `sys_menu` WHERE `id` = 1 OR `name` = '系统设
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 10091 OR `name` = '授权管理');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 12032, (SELECT id FROM `sys_menu` WHERE `id` = 52 OR `name` = '拼多多' LIMIT 1), 0, '拼多多订单', 'PddOrderManagement', '拼多多订单', '/channel/pdd/order', '/channel/pdd/order/index', '', 'lucide:shopping-bag', 'menu', 1, 1, 1, 2
SELECT 12032, (SELECT id FROM `sys_menu` WHERE `id` = 52 OR `name` = '拼多多' LIMIT 1), 0, '拼多多订单', 'PddOrderManagement', '拼多多订单', '/channel/pdd/order', '/channel/pdd/order/index', '', 'lucide:shopping-bag', 'menu', 1, 1, 1, 3
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 12032 OR `name` = '拼多多订单');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
@@ -852,15 +864,19 @@ SELECT 12033, (SELECT id FROM `sys_menu` WHERE `id` = 52 OR `name` = '拼多多'
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 12033 OR `name` = '拼多多店铺');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 12034, (SELECT id FROM `sys_menu` WHERE `id` = 52 OR `name` = '拼多多' LIMIT 1), 0, '拼多多商品', 'PddGoodsManagement', '拼多多商品', '/pdd/goods', '/channel/pdd/goods/index', '', 'lucide:package', 'menu', 1, 1, 0, 3
SELECT 12034, (SELECT id FROM `sys_menu` WHERE `id` = 52 OR `name` = '拼多多' LIMIT 1), 0, '拼多多商品', 'PddGoodsManagement', '拼多多商品', '/pdd/goods', '/channel/pdd/goods/index', '', 'lucide:package', 'menu', 1, 1, 0, 4
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 12034 OR `name` = '拼多多商品');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 12035, (SELECT id FROM `sys_menu` WHERE `id` = 52 OR `name` = '拼多多' LIMIT 1), 0, '拼多多类目', 'PddCatManagement', '拼多多类目', '/pdd/cats', '/channel/pdd/cats/index', '', 'lucide:folder-tree', 'menu', 1, 1, 0, 2
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 12035 OR `name` = '拼多多类目' OR `route_name` = 'PddCatManagement');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 14001, (SELECT id FROM `sys_menu` WHERE `id` = 49 OR `name` = 'OpenApi' LIMIT 1), 0, 'OpenApiKeyManagement', 'OpenApiKeyManagement', 'API Key 管理', '/open/api-key', '/open/api-key/index', '', 'lucide:key', 'menu', 1, 1, 0, 1
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14001 OR `name` = 'OpenApiKeyManagement');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 14009, (SELECT id FROM `sys_menu` WHERE `id` = 52 OR `name` = '拼多多' LIMIT 1), 0, '拼多多商品广告费', 'PddGoodsAdFeeManagement', '商品广告费', '/pdd/goods-ad-fee', '/channel/pdd/goods-ad-fee/index', '', 'lucide:megaphone', 'menu', 1, 1, 0, 4
SELECT 14009, (SELECT id FROM `sys_menu` WHERE `id` = 52 OR `name` = '拼多多' LIMIT 1), 0, '拼多多商品广告费', 'PddGoodsAdFeeManagement', '商品广告费', '/pdd/goods-ad-fee', '/channel/pdd/goods-ad-fee/index', '', 'lucide:megaphone', 'menu', 1, 1, 0, 5
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14009 OR `name` = '拼多多商品广告费');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
@@ -914,11 +930,13 @@ 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 'channel:pdd:shop:%' OR p.code LIKE 'channel:pdd:goods:%') 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 'channel:pdd:goods:%' WHERE m.name = '拼多多商品';
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON (p.code LIKE 'channel:pdd:goods:%' OR p.code = 'channel:pdd:cat:read') 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 'channel:pdd:cat:%' 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 'channel:pdd:ad-fee:%' 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 'ec:product:%' WHERE m.name = '商品列表';
@@ -0,0 +1,26 @@
/**
* 拼多多平台类目(本地落库)API
*/
import { requestClient } from '#/api/request';
import type { PddCatDTO, PddCatVO } from './types';
/** 触发全量同步 */
export async function syncPddCatsApi() {
return requestClient.post<void>('/channel/pdd/cat/sync');
}
/** 同步状态 */
export async function getPddCatSyncStatusApi() {
return requestClient.get<PddCatVO.SyncStatus>('/channel/pdd/cat/sync/status');
}
/** 子类目列表(懒加载树) */
export async function listPddCatChildrenApi(data: PddCatDTO.ChildrenQuery) {
return requestClient.post<PddCatVO.Cat[]>('/channel/pdd/cat/children', data);
}
/** 按名称/路径搜索(跨层级) */
export async function searchPddCatsApi(data: PddCatDTO.SearchQuery) {
return requestClient.post<PddCatVO.Cat[]>('/channel/pdd/cat/search', data);
}
@@ -0,0 +1,2 @@
export * from './apis';
export type * from './types';
@@ -0,0 +1,40 @@
/** 拼多多类目 DTO / VO */
export namespace PddCatDTO {
export interface ChildrenQuery {
/** 父类目;0 或省略为顶级 */
parentCatId?: number;
}
export interface SearchQuery {
keyword: string;
/** 默认 true:仅叶子(可发布) */
leafOnly?: boolean;
/** 默认 50,最大 100 */
limit?: number;
}
}
export namespace PddCatVO {
export interface Cat {
catId: number;
parentCatId?: number;
catName?: string;
level?: number;
leaf?: boolean;
/** 如 1/23/456 */
pathIds?: string;
/** 如 洗护/纸品/抽纸 */
pathNames?: string;
lastSyncTime?: string;
}
export interface SyncStatus {
status?: 'IDLE' | 'RUNNING' | 'SUCCESS' | 'FAILED' | string;
startedAt?: string | null;
finishedAt?: string | null;
lastError?: string | null;
syncedCount?: number | null;
message?: string | null;
}
}
@@ -0,0 +1,418 @@
<script lang="ts" setup>
import type { TreeProps } from 'ant-design-vue';
import type { PddCatVO } from '#/api/channel/pdd/cat';
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import {
Alert,
Button,
Input,
Modal,
Space,
Table,
Tag,
Tree,
message,
notification,
} from 'ant-design-vue';
import {
getPddCatSyncStatusApi,
listPddCatChildrenApi,
searchPddCatsApi,
syncPddCatsApi,
} from '#/api/channel/pdd/cat';
import { PermissionGate } from '#/components/permission';
defineOptions({ name: 'PddCatManagement' });
const RefreshIcon = createIconifyIcon('lucide:refresh-cw');
const SearchIcon = createIconifyIcon('lucide:search');
type TreeNode = {
key: number;
title: string;
isLeaf?: boolean;
children?: TreeNode[];
pathNames?: string;
level?: number;
};
const syncStatus = ref<null | PddCatVO.SyncStatus>(null);
const syncing = ref(false);
const treeLoading = ref(false);
const treeData = ref<TreeNode[]>([]);
const rootRows = ref<PddCatVO.Cat[]>([]);
const expandedKeys = ref<number[]>([]);
const searchKeyword = ref('');
const searchLoading = ref(false);
const searchRows = ref<PddCatVO.Cat[]>([]);
let pollTimer: null | ReturnType<typeof setInterval> = null;
const isRunning = computed(() => syncStatus.value?.status === 'RUNNING');
function mapTreeNode(c: PddCatVO.Cat): TreeNode {
// 同步未收尾时 is_leaf 可能尚未标记;先按非叶子懒加载,空子节点再标叶子
return {
key: c.catId,
title: `${c.catName || `类目${c.catId}`}(${c.catId})`,
isLeaf: !!c.leaf,
pathNames: c.pathNames,
level: c.level,
};
}
async function refreshSyncStatus() {
try {
const prev = syncStatus.value?.status;
syncStatus.value = await getPddCatSyncStatusApi();
if (syncStatus.value?.status === 'RUNNING') {
startPoll();
} else {
stopPoll();
if (prev === 'RUNNING' && syncStatus.value?.status === 'SUCCESS') {
await loadRoot();
const n = syncStatus.value.syncedCount ?? 0;
notification.success({
message: '拼多多类目同步完成',
description: `共入库 ${n} 条。发布商品现可使用本地跨层类目搜索;同步进行中或未成功时会自动降级为拼多多接口逐级选择。`,
duration: 10,
});
message.success(`类目同步完成,共 ${n} 条`);
}
}
} catch {
/* 忽略 */
}
}
function startPoll() {
if (pollTimer) return;
pollTimer = setInterval(() => {
void refreshSyncStatus();
}, 2000);
}
function stopPoll() {
if (pollTimer) {
clearInterval(pollTimer);
pollTimer = null;
}
}
async function handleSync() {
await refreshSyncStatus();
if (isRunning.value) {
message.warning('类目同步正在进行中');
return;
}
const hadSuccess = syncStatus.value?.status === 'SUCCESS';
const hasLocalData =
(syncStatus.value?.syncedCount ?? 0) > 0 || rootRows.value.length > 0;
// 已成功过或库内已有数据:全量重同步很慢,先确认
if (hadSuccess || hasLocalData) {
const countHint =
syncStatus.value?.syncedCount != null
? `当前约 ${syncStatus.value.syncedCount} 条`
: rootRows.value.length
? `当前一级类目 ${rootRows.value.length} 个`
: '本地已有类目数据';
Modal.confirm({
title: '确认重新全量同步类目?',
content: `${countHint}。全量同步通常需要较长时间(受拼多多限流影响可能更久)。同步进行中时,发布商品无法使用本地跨层类目搜索,将自动降级为拼多多接口逐级选择。是否仍要重新同步?`,
okText: '重新同步',
okType: 'primary',
cancelText: '取消',
centered: true,
onOk: () => doTriggerSync(),
});
return;
}
await doTriggerSync();
}
async function doTriggerSync() {
syncing.value = true;
try {
await syncPddCatsApi();
message.success(
'已开始同步拼多多类目;同步期间发布商品的类目搜索功能受限',
);
notification.info({
message: '类目同步进行中',
description:
'全量同步耗时较长。期间发布商品暂不可用本地跨层类目搜索,将自动降级为拼多多授权类目逐级加载。',
duration: 8,
});
await refreshSyncStatus();
startPoll();
} catch (e: any) {
message.error(e?.message || '触发同步失败');
} finally {
syncing.value = false;
}
}
async function loadRoot() {
treeLoading.value = true;
try {
const list = await listPddCatChildrenApi({ parentCatId: 0 });
rootRows.value = list;
treeData.value = list.map(mapTreeNode);
expandedKeys.value = [];
} catch (e: any) {
message.error(e?.message || '加载类目失败,请先同步');
rootRows.value = [];
treeData.value = [];
} finally {
treeLoading.value = false;
}
}
const onLoadData: TreeProps['loadData'] = (treeNode) => {
return new Promise<void>((resolve) => {
void (async () => {
const key = Number(treeNode.key);
if (treeNode.dataRef?.children) {
resolve();
return;
}
try {
const children = await listPddCatChildrenApi({ parentCatId: key });
const nodes = children.map(mapTreeNode);
if (treeNode.dataRef) {
// 无子节点则标为叶子,避免展开空白面板
treeNode.dataRef.isLeaf = nodes.length === 0;
treeNode.dataRef.children = nodes;
}
treeData.value = [...treeData.value];
} catch (e: any) {
message.error(e?.message || '加载子类目失败');
} finally {
resolve();
}
})();
});
};
async function handleSearch() {
const kw = searchKeyword.value.trim();
if (!kw) {
searchRows.value = [];
return;
}
searchLoading.value = true;
try {
searchRows.value = await searchPddCatsApi({
keyword: kw,
leafOnly: false,
limit: 80,
});
} catch (e: any) {
message.error(e?.message || '搜索失败');
searchRows.value = [];
} finally {
searchLoading.value = false;
}
}
const rootColumns = [
{ title: '类目ID', dataIndex: 'catId', width: 120 },
{ title: '名称', dataIndex: 'catName', width: 220 },
{ title: '层级', dataIndex: 'level', width: 72 },
{ title: '路径', dataIndex: 'pathNames', ellipsis: true },
];
const searchColumns = [
{ title: '类目ID', dataIndex: 'catId', width: 120 },
{ title: '名称', dataIndex: 'catName', width: 160 },
{ title: '层级', dataIndex: 'level', width: 72 },
{
title: '叶子',
dataIndex: 'leaf',
width: 72,
customRender: ({ text }: { text: boolean }) => (text ? '是' : '否'),
},
{ title: '完整路径', dataIndex: 'pathNames', ellipsis: true },
];
onMounted(async () => {
await refreshSyncStatus();
await loadRoot();
});
onUnmounted(() => stopPoll());
</script>
<template>
<Page
title="拼多多类目"
description="平台标准类目本地缓存;发布商品时可按名称跨层级搜索,无需每次请求拼多多"
>
<div class="space-y-4">
<Alert
type="info"
show-icon
message="类目为拼多多平台级全量树(pdd.goods.cats.get),与店铺授权可发范围无关。发布时仍以平台校验为准。"
/>
<Alert
v-if="isRunning"
type="warning"
show-icon
message="全量同步进行中:触达拼多多限流时会自动等待,进度可能间歇停顿,属正常现象。已入库数据可在本页浏览/搜索;发布商品暂不可用本地跨层搜索,将自动降级为拼多多授权类目接口。"
/>
<div
class="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-slate-200/80 bg-white p-4 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
>
<div class="min-w-0 text-sm text-slate-600 dark:text-slate-300">
<div class="flex flex-wrap items-center gap-2">
<span class="font-medium text-slate-800 dark:text-slate-100">
同步状态
</span>
<Tag v-if="isRunning" color="processing">同步中</Tag>
<Tag
v-else-if="syncStatus?.status === 'SUCCESS'"
color="success"
>
成功
</Tag>
<Tag
v-else-if="syncStatus?.status === 'FAILED'"
color="error"
>
失败
</Tag>
<Tag v-else color="default">未同步 / 空闲</Tag>
</div>
<p class="mb-0 mt-1 text-xs text-slate-500">
<template v-if="syncStatus?.syncedCount != null">
已入库 {{ syncStatus.syncedCount }} 条
</template>
<template v-if="rootRows.length">
· 一级类目 {{ rootRows.length }} 个
</template>
<template v-if="syncStatus?.startedAt && isRunning">
· 开始于 {{ syncStatus.startedAt }}
</template>
<template v-if="syncStatus?.finishedAt && !isRunning">
· 完成于 {{ syncStatus.finishedAt }}
</template>
<template v-if="syncStatus?.lastError">
· {{ syncStatus.lastError }}
</template>
<template v-if="syncStatus?.message">
· {{ syncStatus.message }}
</template>
</p>
</div>
<Space wrap>
<Button
@click="
() => {
void refreshSyncStatus();
void loadRoot();
}
"
>
<template #icon>
<component :is="RefreshIcon" class="size-4" />
</template>
刷新
</Button>
<PermissionGate code="channel:pdd:cat:sync">
<Button
type="primary"
:loading="syncing || isRunning"
:disabled="isRunning"
@click="handleSync"
>
同步类目
</Button>
</PermissionGate>
</Space>
</div>
<div
class="rounded-xl border border-slate-200/80 bg-white p-4 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
>
<h3 class="mb-3 text-sm font-semibold text-slate-800 dark:text-slate-100">
一级类目({{ rootRows.length }})
</h3>
<Table
size="small"
row-key="catId"
:loading="treeLoading"
:columns="rootColumns"
:data-source="rootRows"
:pagination="{ pageSize: 20, hideOnSinglePage: true }"
:locale="{ emptyText: isRunning ? '同步中,稍候刷新…' : '暂无数据,请先同步' }"
/>
</div>
<div
class="rounded-xl border border-slate-200/80 bg-white p-4 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
>
<h3 class="mb-3 text-sm font-semibold text-slate-800 dark:text-slate-100">
类目树浏览
</h3>
<div
v-if="treeData.length"
class="max-h-[420px] min-h-0 overflow-y-auto rounded-lg border border-slate-100 p-2 dark:border-slate-700"
>
<Tree
v-model:expanded-keys="expandedKeys"
:tree-data="treeData"
:load-data="onLoadData"
:show-line="{ showLeafIcon: false }"
/>
</div>
<p
v-else
class="mb-0 text-sm text-slate-500"
>
{{ treeLoading ? '加载中…' : isRunning ? '同步中,稍候刷新…' : '暂无类目数据' }}
</p>
</div>
<div
class="rounded-xl border border-slate-200/80 bg-white p-4 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
>
<h3 class="mb-3 text-sm font-semibold text-slate-800 dark:text-slate-100">
跨层级搜索
</h3>
<Space wrap class="mb-3">
<Input
v-model:value="searchKeyword"
class="!w-72"
allow-clear
placeholder="类目名称或路径关键词"
@press-enter="handleSearch"
/>
<Button type="primary" :loading="searchLoading" @click="handleSearch">
<template #icon>
<component :is="SearchIcon" class="size-4" />
</template>
搜索
</Button>
</Space>
<Table
size="small"
row-key="catId"
:loading="searchLoading"
:columns="searchColumns"
:data-source="searchRows"
:pagination="{ pageSize: 20, hideOnSinglePage: true }"
:locale="{ emptyText: '输入关键词后搜索' }"
/>
</div>
</div>
</Page>
</template>
@@ -13,6 +13,7 @@ import { useVbenModal } from '@vben/common-ui';
import { PlusOutlined, DeleteOutlined, MinusOutlined } from '@ant-design/icons-vue';
import {
Alert,
Button,
Card,
Cascader,
@@ -42,6 +43,11 @@ import {
listPddPublishParentSpecsApi,
publishPddGoodsApi,
} from '#/api/channel/pdd/goods';
import {
getPddCatSyncStatusApi,
listPddCatChildrenApi,
searchPddCatsApi,
} from '#/api/channel/pdd/cat';
import { getPddShopPageApi } from '#/api/channel/pdd/shop';
import { getProductPageApi } from '#/api/ec/product';
import { getProductSkuPageApi } from '#/api/ec/product/sku';
@@ -204,13 +210,82 @@ const saleProps = computed(() =>
(catTemplate.value?.properties ?? []).filter((p) => p.sale),
);
const rootCatOptions = ref<
{ label?: string; value: number; isLeaf?: boolean; loading?: boolean; children?: any[] }[]
>([]);
type CatCascaderNode = {
label?: string;
value: number;
isLeaf?: boolean;
loading?: boolean;
children?: CatCascaderNode[];
/** 搜索命中时带回完整 path,便于回填 */
pathIds?: string;
};
type DefaultOptionType = { label?: any; value?: any; children?: any[] };
const rootCatOptions = ref<CatCascaderNode[]>([]);
const catsLoading = ref(false);
/** 已按 parent 拉过的类目,避免重复请求 */
const loadedCatParents = ref<Set<number>>(new Set());
/** 本地库同步状态:仅 SUCCESS 走本地树 + 跨层搜索,其余降级拼多多授权类目接口 */
const catSyncStatus = ref<null | string>(null);
const localCatReady = computed(() => catSyncStatus.value === 'SUCCESS');
const catSourceDegraded = computed(() => !localCatReady.value);
/** Cascader 搜索框文案;本地就绪时用于跨层检索 */
const catCascaderSearch = ref('');
/** 本地跨层搜索命中(扁平叶子),非空时临时替换树选项 */
const catSearchHitOptions = ref<CatCascaderNode[]>([]);
const catSearchLoading = ref(false);
let catSearchTimer: undefined | ReturnType<typeof setTimeout>;
/** 选中后展示的完整路径文案 */
const selectedCatPathLabel = ref('');
/**
* 搜索选中的叶子:清空搜索结果后仍挂到 options 上,避免 Cascader 只显示裸 catId。
*/
const pinnedSelectedCat = ref<CatCascaderNode | null>(null);
const displayCatOptions = computed(() => {
if (localCatReady.value && catCascaderSearch.value.trim()) {
return catSearchHitOptions.value;
}
const roots = rootCatOptions.value;
const pinned = pinnedSelectedCat.value;
if (
pinned &&
form.catPath.length === 1 &&
form.catPath[0] === pinned.value &&
!roots.some((r) => r.value === pinned.value)
) {
return [pinned, ...roots];
}
return roots;
});
/** Cascader 输入框展示:优先完整路径文案,避免只剩数字 ID */
function catDisplayRender(info: {
labels: string[];
selectedOptions?: DefaultOptionType[];
}) {
if (selectedCatPathLabel.value) {
return selectedCatPathLabel.value;
}
const labels = (info.labels ?? []).filter(
(l) => l != null && String(l).trim() !== '',
);
if (labels.length) {
return labels.join(' / ');
}
return '';
}
const catDegradeHint = computed(() => {
if (catSyncStatus.value === 'RUNNING') {
return '平台类目同步进行中:暂不可用本地跨层搜索,已降级为拼多多授权类目逐级加载;搜索仅匹配已展开节点';
}
return '本地类目未就绪:已降级为拼多多授权类目逐级加载;搜索仅匹配已展开节点。同步成功后可跨层搜索';
});
const skuSelectOptions = computed(() =>
skuOptions.value.map((s) => ({
label: `${s.productName} / ${s.name}${s.skuCode ? ` (${s.skuCode})` : ''}`,
@@ -218,40 +293,71 @@ const skuSelectOptions = computed(() =>
})),
);
/** 仅在已加载的本地节点中按类目名过滤 */
const catShowSearch: CascaderProps['showSearch'] = {
filter: (inputValue, path) => {
const kw = String(inputValue ?? '')
.trim()
.toLowerCase();
if (!kw) return true;
return path.some((option) =>
String(option.label ?? '')
.toLowerCase()
.includes(kw),
);
},
};
async function refreshCatSyncStatus() {
try {
const s = await getPddCatSyncStatusApi();
catSyncStatus.value = s?.status ?? null;
} catch {
// 无权限或失败时降级拼多多接口
catSyncStatus.value = null;
}
}
/** 展开时按需加载子类目(每个 parent 只请求一次) */
function mapLocalCatNode(c: {
catId: number;
catName?: string;
leaf?: boolean;
}): CatCascaderNode {
return {
label: c.catName,
value: c.catId,
isLeaf: !!c.leaf,
};
}
function mapPopCatNode(c: PddGoodsPublishVO.Cat): CatCascaderNode {
return {
label: c.catName,
value: c.catId,
isLeaf: !!c.leaf,
};
}
async function fetchCatChildren(parentCatId: number): Promise<CatCascaderNode[]> {
if (localCatReady.value) {
const list = await listPddCatChildrenApi({ parentCatId });
return list.map(mapLocalCatNode);
}
if (!form.pddShopId) {
return [];
}
const list = await listPddPublishCatsApi({
pddShopId: form.pddShopId,
parentCatId,
});
return list.map(mapPopCatNode);
}
/** 展开时按需加载子类目(本地库或拼多多接口) */
const catLoadData: CascaderProps['loadData'] = async (selectedOptions) => {
// 跨层搜索结果为扁平叶子,不走懒加载
if (localCatReady.value && catCascaderSearch.value.trim()) {
return;
}
const target = selectedOptions[selectedOptions.length - 1];
if (!target || !form.pddShopId) return;
if (!target) return;
const parentId = Number(target.value);
if (loadedCatParents.value.has(parentId) || target.isLeaf) {
return;
}
target.loading = true;
try {
const children = await listPddPublishCatsApi({
pddShopId: form.pddShopId,
parentCatId: parentId,
});
target.children = children.map((c) => ({
label: c.catName,
value: c.catId,
isLeaf: !!c.leaf,
}));
const children = await fetchCatChildren(parentId);
target.children = children;
// 降级场景:接口未标 leaf 且无子时标叶子,避免空白展开
if (children.length === 0) {
target.isLeaf = true;
}
loadedCatParents.value.add(parentId);
} catch (e: any) {
message.error(e?.message || '加载类目失败');
@@ -260,6 +366,52 @@ const catLoadData: CascaderProps['loadData'] = async (selectedOptions) => {
}
};
/** Cascader 内置搜索:本地跨层时选项已是命中集;降级时仅过滤已加载节点 */
function catCascaderFilter(inputValue: string, path: DefaultOptionType[]) {
if (localCatReady.value && inputValue.trim()) {
return true;
}
const kw = inputValue.trim().toLowerCase();
if (!kw) return true;
return path.some((o) => String(o.label ?? '').toLowerCase().includes(kw));
}
function onCatCascaderSearch(keyword: string) {
catCascaderSearch.value = keyword ?? '';
if (catSearchTimer) clearTimeout(catSearchTimer);
if (!localCatReady.value) {
catSearchHitOptions.value = [];
return;
}
const kw = String(keyword ?? '').trim();
if (!kw) {
catSearchHitOptions.value = [];
catSearchLoading.value = false;
return;
}
catSearchTimer = setTimeout(async () => {
catSearchLoading.value = true;
try {
const list = await searchPddCatsApi({
keyword: kw,
leafOnly: true,
limit: 50,
});
catSearchHitOptions.value = list.map((c) => ({
label: c.pathNames || c.catName || `类目${c.catId}`,
value: c.catId,
isLeaf: true,
pathIds: c.pathIds,
}));
} catch (e: any) {
message.error(e?.message || '搜索类目失败');
catSearchHitOptions.value = [];
} finally {
catSearchLoading.value = false;
}
}, 280);
}
async function loadShops(keyword = '') {
try {
const data = await getPddShopPageApi({
@@ -279,30 +431,65 @@ async function loadShops(keyword = '') {
}
async function loadRootCats() {
if (!form.pddShopId) return;
// 同店已加载过根节点则不再请求
if (loadedCatParents.value.has(0) && rootCatOptions.value.length > 0) {
if (!form.pddShopId) {
rootCatOptions.value = [];
return;
}
catsLoading.value = true;
loadedCatParents.value = new Set();
rootCatOptions.value = [];
catSearchHitOptions.value = [];
catCascaderSearch.value = '';
pinnedSelectedCat.value = null;
try {
const list = await listPddPublishCatsApi({
pddShopId: form.pddShopId,
parentCatId: 0,
});
rootCatOptions.value = list.map((c) => ({
label: c.catName,
value: c.catId,
isLeaf: !!c.leaf,
}));
await refreshCatSyncStatus();
const list = await fetchCatChildren(0);
rootCatOptions.value = list;
loadedCatParents.value.add(0);
} catch (e: any) {
message.error(e?.message || '加载类目失败');
message.error(
e?.message ||
(localCatReady.value
? '加载本地类目失败'
: '加载拼多多授权类目失败'),
);
} finally {
catsLoading.value = false;
}
}
async function applyCatSelection(catId: number, pathIds?: string, pathLabel?: string) {
const path = pathIds
? pathIds
.split('/')
.map((x) => Number(x))
.filter((n) => Number.isFinite(n) && n > 0)
: [catId];
form.catPath = path;
form.catId = catId;
selectedCatPathLabel.value = pathLabel || '';
catTemplate.value = null;
parentSpecs.value = [];
form.goodsPropValues = {};
if (!form.pddShopId || !form.catId) return;
try {
const [tpl, specs] = await Promise.all([
getPddPublishCatTemplateApi({
pddShopId: form.pddShopId,
catId: form.catId,
}),
listPddPublishParentSpecsApi({
pddShopId: form.pddShopId,
catId: form.catId,
}),
]);
catTemplate.value = tpl;
parentSpecs.value = specs ?? [];
} catch (e: any) {
message.error(e?.message || '加载类目模板失败');
}
}
async function loadLogistics() {
if (!form.pddShopId) return;
try {
@@ -383,14 +570,18 @@ watch(
(id) => {
form.catPath = [];
form.catId = undefined;
selectedCatPathLabel.value = '';
form.costTemplateId = undefined;
costTemplateDetail.value = null;
catTemplate.value = null;
parentSpecs.value = [];
rootCatOptions.value = [];
logisticsOptions.value = [];
form.goodsPropValues = {};
catSearchHitOptions.value = [];
catCascaderSearch.value = '';
rootCatOptions.value = [];
loadedCatParents.value = new Set();
pinnedSelectedCat.value = null;
if (!id) return;
void loadRootCats();
void loadLogistics();
@@ -464,44 +655,85 @@ function removeSkuRow(key: number) {
}
async function onCatChange(path: number[]) {
form.catPath = path ?? [];
form.catId = path?.length ? path[path.length - 1] : undefined;
catTemplate.value = null;
parentSpecs.value = [];
form.goodsPropValues = {};
if (!form.pddShopId || !form.catId) return;
const leafOpt = findCascaderNode(rootCatOptions.value, path);
if (leafOpt && leafOpt.isLeaf === false) {
if (!path?.length) {
form.catPath = [];
form.catId = undefined;
selectedCatPathLabel.value = '';
pinnedSelectedCat.value = null;
catTemplate.value = null;
parentSpecs.value = [];
form.goodsPropValues = {};
return;
}
try {
const [tpl, specs] = await Promise.all([
getPddPublishCatTemplateApi({
pddShopId: form.pddShopId,
catId: form.catId,
}),
listPddPublishParentSpecsApi({
pddShopId: form.pddShopId,
catId: form.catId,
}),
]);
catTemplate.value = tpl;
parentSpecs.value = specs ?? [];
} catch (e: any) {
message.error(e?.message || '加载类目模板失败');
const searching =
localCatReady.value && !!catCascaderSearch.value.trim();
const options = searching
? catSearchHitOptions.value
: rootCatOptions.value;
const leafOpt = findCascaderNode(options, path);
if (leafOpt && leafOpt.isLeaf === false) {
form.catPath = path;
form.catId = undefined;
selectedCatPathLabel.value = '';
pinnedSelectedCat.value = null;
catTemplate.value = null;
parentSpecs.value = [];
return;
}
const catId = path[path.length - 1]!;
const hit =
catSearchHitOptions.value.find((o) => o.value === catId) ||
(pinnedSelectedCat.value?.value === catId
? pinnedSelectedCat.value
: undefined);
const pathLabel =
hit?.label != null
? String(hit.label)
: buildCascaderPathLabel(options, path) ||
(leafOpt?.label != null ? String(leafOpt.label) : undefined);
await applyCatSelection(
catId,
hit?.pathIds || path.join('/'),
pathLabel,
);
// 搜索命中为扁平选项:钉住展示节点,Cascader 值用单级 id
if (hit?.pathIds || searching) {
const label = pathLabel || `类目${catId}`;
pinnedSelectedCat.value = {
label,
value: catId,
isLeaf: true,
pathIds: hit?.pathIds,
};
form.catPath = [catId];
} else {
pinnedSelectedCat.value = null;
}
catCascaderSearch.value = '';
catSearchHitOptions.value = [];
}
function buildCascaderPathLabel(
options: CatCascaderNode[],
path: number[],
): string {
const parts: string[] = [];
let nodes = options;
for (const id of path) {
const found = nodes.find((n) => n.value === id);
if (!found) break;
if (found.label) parts.push(String(found.label));
nodes = found.children ?? [];
}
return parts.join(' / ');
}
function findCascaderNode(
options: { value: number; isLeaf?: boolean; children?: any[] }[],
options: CatCascaderNode[],
path: number[],
): { value: number; isLeaf?: boolean } | null {
): CatCascaderNode | null {
let nodes = options;
let found: { value: number; isLeaf?: boolean; children?: any[] } | null =
null;
let found: CatCascaderNode | null = null;
for (const id of path) {
found = nodes.find((n) => n.value === id) ?? null;
if (!found) return null;
@@ -873,6 +1105,7 @@ function resetAll() {
form.goodsDesc = '';
form.catPath = [];
form.catId = undefined;
selectedCatPathLabel.value = '';
form.costTemplateId = undefined;
costTemplateDetail.value = null;
form.marketPriceYuan = undefined;
@@ -887,14 +1120,19 @@ function resetAll() {
catTemplate.value = null;
parentSpecs.value = [];
rootCatOptions.value = [];
catSearchHitOptions.value = [];
catCascaderSearch.value = '';
logisticsOptions.value = [];
loadedCatParents.value = new Set();
pinnedSelectedCat.value = null;
catSyncStatus.value = null;
specIdCache.clear();
}
onBeforeUnmount(() => {
document.removeEventListener('pointerdown', onOverlayPointerDown, true);
clearLocalImages();
if (catSearchTimer) clearTimeout(catSearchTimer);
});
</script>
@@ -951,23 +1189,47 @@ onBeforeUnmount(() => {
/>
</Form.Item>
<Alert
v-if="form.pddShopId && catSourceDegraded"
class="mb-3"
type="warning"
show-icon
:message="catDegradeHint"
/>
<div class="grid grid-cols-2 gap-3">
<Form.Item label="叶子类目" required>
<Cascader
v-model:value="form.catPath"
v-model:search-value="catCascaderSearch"
class="w-full"
:options="rootCatOptions"
:options="displayCatOptions"
:load-data="catLoadData"
:show-search="catShowSearch"
:show-search="{
filter: catCascaderFilter,
limit: 50,
}"
:display-render="catDisplayRender"
change-on-select
:placeholder="
catsLoading
? '类目加载中…'
: '搜索已加载类目,或逐级展开选择'
!form.pddShopId
? '请先选择渠道店铺'
: catsLoading || catSearchLoading
? '类目加载中…'
: localCatReady
? '搜索类目名称或逐级展开选择'
: '逐级展开选择(搜索仅匹配已展开)'
"
:disabled="!form.pddShopId || catsLoading"
@search="onCatCascaderSearch"
@change="(v: any) => onCatChange(v || [])"
/>
<p
v-if="selectedCatPathLabel"
class="mb-0 mt-1 text-xs text-slate-500"
>
已选:{{ selectedCatPathLabel }}
</p>
</Form.Item>
<Form.Item label="运费模板" required>
<Select