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,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 = '商品列表';