feat(catalog): 新增分类推荐榜快照接口
backend-ci / test (push) Failing after 4m45s

This commit is contained in:
Zhou Weidong committed 2026-11-02 14:45:43 +08:00
1 parent afd8d00752
commit 8a5a381b44
23 files changed
+793 -16

No files matched your search

@@ -18,10 +18,16 @@ public class DramaClassification {
private Long id;
/** 中文名称。 */
private String name;
/** 稳定语义码,不随展示名称变化。 */
private String code;
private String nameEn;
private String nameId;
/** 已选语言的名称。 */
private String nameLocales;
/** 客户端布局:GRID / RANKING。 */
private String layoutType;
/** 内容或顺序版本。 */
private Long revision;
private Integer sort;
private Integer status;
private LocalDateTime createdAt;
@@ -18,5 +18,7 @@ public class DramaClassificationDrama {
private Long id;
private Long classificationId;
private Long dramaId;
/** 分类内展示位置,从 1 开始。 */
private Integer position;
private LocalDateTime createdAt;
}
@@ -27,7 +27,6 @@ import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 运营分类服务。分类是独立于「短剧类型(drama_category)」的一套概念,
@@ -37,9 +36,15 @@ import java.util.stream.Collectors;
@RequiredArgsConstructor
public class DramaClassificationService {
public static final String LAYOUT_GRID = "GRID";
public static final String LAYOUT_RANKING = "RANKING";
private static final long INITIAL_REVISION = 1L;
private static final String DEFAULT_CODE_PREFIX = "CLASSIFICATION_";
private final DramaClassificationMapper classificationMapper;
private final DramaClassificationDramaMapper classificationDramaMapper;
private final DramaMapper dramaMapper;
private final DramaRankingService rankingService;
public List<DramaClassificationRespVO> list() {
Map<Long, Integer> counts = countDramas();
@@ -49,12 +54,15 @@ public class DramaClassificationService {
.stream().map(item -> {
DramaClassificationRespVO vo = new DramaClassificationRespVO();
vo.setId(item.getId());
vo.setCode(codeOf(item));
Map<String, String> locales = ContentLocaleTexts.read(
item.getNameLocales(), item.getName(), item.getNameEn(), item.getNameId());
vo.setName(locales.get(ContentLocaleTexts.ZH));
vo.setNameEn(ContentLocaleTexts.value(locales, ContentLocaleTexts.EN));
vo.setNameId(ContentLocaleTexts.value(locales, ContentLocaleTexts.ID));
vo.setLocales(locales);
vo.setLayoutType(layoutOf(item));
vo.setRevision(revisionOf(item));
vo.setSort(item.getSort());
vo.setStatus(item.getStatus());
vo.setUpdatedAt(item.getUpdatedAt());
@@ -68,12 +76,18 @@ public class DramaClassificationService {
ensureNameAvailable(locales.get(ContentLocaleTexts.ZH), null);
DramaClassification entity = new DramaClassification();
writeNames(entity, locales);
writeClassificationSettings(entity, req);
Long count = classificationMapper.selectCount(null);
entity.setSort(req.getSort() == null
? (count == null ? 0 : count.intValue()) + 1
: req.getSort());
entity.setStatus(req.getStatus() == null ? 1 : req.getStatus());
entity.setRevision(INITIAL_REVISION);
classificationMapper.insert(entity);
if (!StringUtils.hasText(entity.getCode())) {
entity.setCode(DEFAULT_CODE_PREFIX + entity.getId());
classificationMapper.updateById(entity);
}
return entity.getId();
}
@@ -82,6 +96,7 @@ public class DramaClassificationService {
Map<String, String> locales = namesOf(req);
ensureNameAvailable(locales.get(ContentLocaleTexts.ZH), id);
writeNames(entity, locales);
writeClassificationSettings(entity, req);
if (req.getSort() != null) {
entity.setSort(req.getSort());
}
@@ -114,7 +129,7 @@ public class DramaClassificationService {
/** 批量关联短剧;已关联的自动跳过。 */
@Transactional(rollbackFor = Exception.class)
public int bindDramas(Long id, List<Long> dramaIds) {
getExisting(id);
ensureGridMutation(getExisting(id));
if (dramaIds == null || dramaIds.isEmpty()) {
return 0;
}
@@ -133,6 +148,7 @@ public class DramaClassificationService {
DramaClassificationDrama relation = new DramaClassificationDrama();
relation.setClassificationId(id);
relation.setDramaId(dramaId);
relation.setPosition(rankingService.nextPosition(id));
classificationDramaMapper.insert(relation);
added++;
}
@@ -141,15 +157,24 @@ public class DramaClassificationService {
/** 移出分类;短剧本身不受影响。 */
public void unbindDrama(Long id, Long dramaId) {
getExisting(id);
ensureGridMutation(getExisting(id));
classificationDramaMapper.delete(Wrappers.<DramaClassificationDrama>lambdaQuery()
.eq(DramaClassificationDrama::getClassificationId, id)
.eq(DramaClassificationDrama::getDramaId, dramaId));
}
/** 原子替换推荐榜内容与顺序,成功后递增版本。 */
@Transactional(rollbackFor = Exception.class)
public void saveRankingItems(Long id, List<Long> dramaIds) {
rankingService.saveItems(id, dramaIds);
}
private PageResult<DramaBriefVO> pageDramas(Long id, String keyword,
int pageIndex, int pageSize, boolean bound) {
getExisting(id);
DramaClassification classification = getExisting(id);
if (bound && LAYOUT_RANKING.equals(layoutOf(classification))) {
return rankingService.page(id, keyword, pageIndex, pageSize);
}
Page<Drama> page = new Page<>(Math.max(1, pageIndex), Math.max(1, Math.min(pageSize, 100)));
LambdaQueryWrapper<Drama> wrapper = Wrappers.<Drama>lambdaQuery()
.like(StringUtils.hasText(keyword), Drama::getTitle, keyword)
@@ -228,8 +253,12 @@ public class DramaClassificationService {
return entity;
}
/** C 端:分类下关联的全部 dramaId(按关联创建时间 desc)。 */
/** C 端:普通分类保留历史倒序,推荐榜严格按 position 升序。 */
public List<Long> listDramaIdsByClassification(Long classificationId) {
DramaClassification classification = getExisting(classificationId);
if (LAYOUT_RANKING.equals(layoutOf(classification))) {
return rankingService.orderedDramaIds(classificationId);
}
return classificationDramaMapper.selectList(
Wrappers.<DramaClassificationDrama>lambdaQuery()
.eq(DramaClassificationDrama::getClassificationId, classificationId)
@@ -237,10 +266,14 @@ public class DramaClassificationService {
.orderByDesc(DramaClassificationDrama::getId))
.stream()
.map(DramaClassificationDrama::getDramaId)
.collect(Collectors.toList());
.toList();
}
private DramaBriefVO toBrief(Drama drama) {
return toBrief(drama, null);
}
private DramaBriefVO toBrief(Drama drama, Integer position) {
DramaBriefVO vo = new DramaBriefVO();
vo.setId(drama.getId());
vo.setTitle(drama.getTitle());
@@ -248,7 +281,54 @@ public class DramaClassificationService {
vo.setStatus(drama.getStatus());
vo.setTotalEpisodes(drama.getTotalEpisodes());
vo.setSort(drama.getSort());
vo.setPosition(position);
vo.setUpdatedAt(drama.getUpdatedAt());
return vo;
}
private void writeClassificationSettings(DramaClassification entity,
DramaClassificationSaveReqVO req) {
if (StringUtils.hasText(req.getCode())) {
String code = req.getCode().trim();
ensureCodeAvailable(code, entity.getId());
entity.setCode(code);
}
if (StringUtils.hasText(req.getLayoutType())) {
entity.setLayoutType(req.getLayoutType());
} else if (!StringUtils.hasText(entity.getLayoutType())) {
entity.setLayoutType(LAYOUT_GRID);
}
}
private void ensureCodeAvailable(String code, Long excludeId) {
Long count = classificationMapper.selectCount(Wrappers.<DramaClassification>lambdaQuery()
.eq(DramaClassification::getCode, code)
.ne(excludeId != null, DramaClassification::getId, excludeId));
if (count != null && count > 0) {
throw new ServiceException(ErrorCode.DATA_EXISTS, "分类编码已存在");
}
}
private String codeOf(DramaClassification classification) {
return StringUtils.hasText(classification.getCode())
? classification.getCode()
: DEFAULT_CODE_PREFIX + classification.getId();
}
private String layoutOf(DramaClassification classification) {
return StringUtils.hasText(classification.getLayoutType())
? classification.getLayoutType()
: LAYOUT_GRID;
}
private long revisionOf(DramaClassification classification) {
return classification.getRevision() == null ? INITIAL_REVISION : classification.getRevision();
}
private void ensureGridMutation(DramaClassification classification) {
if (LAYOUT_RANKING.equals(layoutOf(classification))) {
throw new ServiceException(ErrorCode.OPERATION_NOT_ALLOWED,
"推荐榜请使用完整排序接口维护内容");
}
}
}
@@ -0,0 +1,161 @@
// Author: fruit.com.cn
package com.fruitshorts.content.service;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fruitshorts.common.exception.ErrorCode;
import com.fruitshorts.common.exception.ServiceException;
import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.content.dal.entity.Drama;
import com.fruitshorts.content.dal.entity.DramaClassification;
import com.fruitshorts.content.dal.entity.DramaClassificationDrama;
import com.fruitshorts.content.dal.mapper.DramaClassificationDramaMapper;
import com.fruitshorts.content.dal.mapper.DramaClassificationMapper;
import com.fruitshorts.content.dal.mapper.DramaMapper;
import com.fruitshorts.content.vo.DramaBriefVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
/** 推荐榜内容、顺序和版本服务。 */
@Service
@RequiredArgsConstructor
public class DramaRankingService {
private static final int MAX_RANKING_ITEMS = 50;
private static final long INITIAL_REVISION = 1L;
private final DramaClassificationMapper classificationMapper;
private final DramaClassificationDramaMapper relationMapper;
private final DramaMapper dramaMapper;
/** 原子替换推荐榜内容与顺序,成功后递增版本。 */
@Transactional(rollbackFor = Exception.class)
public void saveItems(Long classificationId, List<Long> dramaIds) {
DramaClassification classification = getRanking(classificationId);
List<Long> orderedIds = orderedIds(dramaIds);
ensureDramasExist(orderedIds);
relationMapper.delete(Wrappers.<DramaClassificationDrama>lambdaQuery()
.eq(DramaClassificationDrama::getClassificationId, classificationId));
for (int index = 0; index < orderedIds.size(); index++) {
relationMapper.insert(relation(classificationId, orderedIds.get(index), index + 1));
}
long revision = classification.getRevision() == null
? INITIAL_REVISION
: classification.getRevision();
classification.setRevision(revision + 1);
classificationMapper.updateById(classification);
}
/** 推荐榜后台分页,严格按持久化位置返回。 */
public PageResult<DramaBriefVO> page(Long classificationId, String keyword,
int pageIndex, int pageSize) {
List<DramaClassificationDrama> relations = orderedRelations(classificationId);
if (relations.isEmpty()) {
return PageResult.empty();
}
List<Long> ids = relations.stream().map(DramaClassificationDrama::getDramaId).toList();
Map<Long, Drama> dramas = dramaMapper.selectBatchIds(ids).stream()
.collect(Collectors.toMap(Drama::getId, Function.identity()));
List<DramaBriefVO> all = relations.stream()
.filter(item -> dramas.containsKey(item.getDramaId()))
.map(item -> toBrief(dramas.get(item.getDramaId()), item.getPosition()))
.filter(item -> !StringUtils.hasText(keyword) || item.getTitle().contains(keyword))
.toList();
return pageOf(all, pageIndex, pageSize);
}
/** 分类内全部短剧 id,严格按 position 升序。 */
public List<Long> orderedDramaIds(Long classificationId) {
return orderedRelations(classificationId).stream()
.map(DramaClassificationDrama::getDramaId)
.toList();
}
/** 新增关联时使用的末尾位置。 */
public int nextPosition(Long classificationId) {
return orderedRelations(classificationId).stream()
.map(DramaClassificationDrama::getPosition)
.filter(Objects::nonNull)
.max(Integer::compareTo)
.orElse(0) + 1;
}
private DramaClassification getRanking(Long id) {
DramaClassification classification = id == null ? null : classificationMapper.selectById(id);
if (classification == null) {
throw new ServiceException(ErrorCode.DATA_NOT_FOUND, "分类不存在");
}
if (!DramaClassificationService.LAYOUT_RANKING.equals(classification.getLayoutType())) {
throw new ServiceException(ErrorCode.OPERATION_NOT_ALLOWED, "只有推荐榜分类可以保存榜单顺序");
}
return classification;
}
private List<Long> orderedIds(List<Long> dramaIds) {
LinkedHashSet<Long> unique = new LinkedHashSet<>();
if (dramaIds != null) {
dramaIds.stream().filter(Objects::nonNull).forEach(unique::add);
}
if (unique.size() > MAX_RANKING_ITEMS) {
throw new ServiceException(ErrorCode.BAD_REQUEST, "推荐榜最多 50 部短剧");
}
return List.copyOf(unique);
}
private void ensureDramasExist(List<Long> dramaIds) {
if (dramaIds.isEmpty()) {
return;
}
if (dramaMapper.selectBatchIds(dramaIds).size() != dramaIds.size()) {
throw new ServiceException(ErrorCode.DATA_NOT_FOUND, "榜单中包含不存在的短剧");
}
}
private List<DramaClassificationDrama> orderedRelations(Long classificationId) {
return relationMapper.selectList(Wrappers.<DramaClassificationDrama>lambdaQuery()
.eq(DramaClassificationDrama::getClassificationId, classificationId)
.orderByAsc(DramaClassificationDrama::getPosition)
.orderByDesc(DramaClassificationDrama::getId));
}
private DramaClassificationDrama relation(Long classificationId, Long dramaId, int position) {
DramaClassificationDrama relation = new DramaClassificationDrama();
relation.setClassificationId(classificationId);
relation.setDramaId(dramaId);
relation.setPosition(position);
return relation;
}
private DramaBriefVO toBrief(Drama drama, Integer position) {
DramaBriefVO vo = new DramaBriefVO();
vo.setId(drama.getId());
vo.setTitle(drama.getTitle());
vo.setCover(drama.getCoverUrl());
vo.setStatus(drama.getStatus());
vo.setTotalEpisodes(drama.getTotalEpisodes());
vo.setSort(drama.getSort());
vo.setPosition(position);
vo.setUpdatedAt(drama.getUpdatedAt());
return vo;
}
private PageResult<DramaBriefVO> pageOf(List<DramaBriefVO> items, int pageIndex, int pageSize) {
int safeIndex = Math.max(1, pageIndex);
int safeSize = Math.max(1, Math.min(pageSize, 100));
int fromIndex = (safeIndex - 1) * safeSize;
if (fromIndex >= items.size()) {
return new PageResult<>(items.size(), List.of());
}
int toIndex = Math.min(fromIndex + safeSize, items.size());
return new PageResult<>(items.size(), items.subList(fromIndex, toIndex));
}
}
@@ -16,5 +16,7 @@ public class DramaBriefVO {
private String status;
private Integer totalEpisodes;
private Integer sort;
/** 分类内展示位置。 */
private Integer position;
private LocalDateTime updatedAt;
}
@@ -12,9 +12,12 @@ public class DramaClassificationRespVO {
private Long id;
private String name;
private String code;
private String nameEn;
private String nameId;
private java.util.Map<String, String> locales;
private String layoutType;
private Long revision;
private Integer sort;
private Integer status;
private Integer dramaCount;
@@ -3,6 +3,7 @@
package com.fruitshorts.content.vo;
import jakarta.validation.constraints.Size;
import jakarta.validation.constraints.Pattern;
import lombok.Data;
/** 分类新增/编辑请求体。 */
@@ -17,6 +18,13 @@ public class DramaClassificationSaveReqVO {
/** 勾选的语言名称,key 为 zh / en / id。 */
private java.util.Map<String, String> locales;
@Size(max = 64, message = "分类编码最多 64 个字符")
@Pattern(regexp = "^[A-Z0-9_]*$", message = "分类编码只能包含大写字母、数字和下划线")
private String code;
@Pattern(regexp = "^(GRID|RANKING)$", message = "展示类型只支持 GRID 或 RANKING")
private String layoutType;
private Integer sort;
private Integer status;
}
@@ -0,0 +1,18 @@
// Author: fruit.com.cn
package com.fruitshorts.content.vo;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Data;
import java.util.List;
/** 推荐榜完整有序短剧列表。 */
@Data
public class DramaRankingItemsReqVO {
@NotNull(message = "请提交推荐榜短剧列表")
@Size(max = 50, message = "推荐榜最多 50 部短剧")
private List<Long> dramaIds;
}
@@ -0,0 +1,82 @@
// Author: fruit.com.cn
package com.fruitshorts.content.service;
import com.fruitshorts.common.exception.ServiceException;
import com.fruitshorts.content.dal.entity.DramaClassification;
import com.fruitshorts.content.dal.entity.DramaClassificationDrama;
import com.fruitshorts.content.dal.mapper.DramaClassificationDramaMapper;
import com.fruitshorts.content.dal.mapper.DramaClassificationMapper;
import com.fruitshorts.content.dal.mapper.DramaMapper;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/** 运营分类布局隔离测试。 */
class DramaClassificationServiceTest {
@Test
void should_keep_legacy_relation_order_when_classification_is_grid() {
Fixture fixture = fixture(DramaClassificationService.LAYOUT_GRID);
given(fixture.relationMapper().selectList(any())).willReturn(List.of(
relation(21L), relation(13L)));
List<Long> ids = fixture.service().listDramaIdsByClassification(7L);
assertThat(ids).containsExactly(21L, 13L);
verify(fixture.rankingService(), never()).orderedDramaIds(any());
}
@Test
void should_use_position_order_when_classification_is_ranking() {
Fixture fixture = fixture(DramaClassificationService.LAYOUT_RANKING);
given(fixture.rankingService().orderedDramaIds(7L)).willReturn(List.of(13L, 21L));
List<Long> ids = fixture.service().listDramaIdsByClassification(7L);
assertThat(ids).containsExactly(13L, 21L);
verify(fixture.relationMapper(), never()).selectList(any());
}
@Test
void should_reject_legacy_bind_when_classification_is_ranking() {
Fixture fixture = fixture(DramaClassificationService.LAYOUT_RANKING);
assertThatThrownBy(() -> fixture.service().bindDramas(7L, List.of(13L)))
.isInstanceOf(ServiceException.class)
.hasMessageContaining("推荐榜请使用完整排序接口");
}
private Fixture fixture(String layoutType) {
DramaClassificationMapper classificationMapper = mock(DramaClassificationMapper.class);
DramaClassificationDramaMapper relationMapper = mock(DramaClassificationDramaMapper.class);
DramaMapper dramaMapper = mock(DramaMapper.class);
DramaRankingService rankingService = mock(DramaRankingService.class);
DramaClassification classification = new DramaClassification();
classification.setId(7L);
classification.setLayoutType(layoutType);
given(classificationMapper.selectById(7L)).willReturn(classification);
DramaClassificationService service = new DramaClassificationService(
classificationMapper, relationMapper, dramaMapper, rankingService);
return new Fixture(service, relationMapper, rankingService);
}
private DramaClassificationDrama relation(Long dramaId) {
DramaClassificationDrama relation = new DramaClassificationDrama();
relation.setDramaId(dramaId);
return relation;
}
private record Fixture(DramaClassificationService service,
DramaClassificationDramaMapper relationMapper,
DramaRankingService rankingService) {
}
}
@@ -0,0 +1,60 @@
// Author: fruit.com.cn
package com.fruitshorts.content.service;
import com.fruitshorts.content.dal.entity.Drama;
import com.fruitshorts.content.dal.entity.DramaClassification;
import com.fruitshorts.content.dal.entity.DramaClassificationDrama;
import com.fruitshorts.content.dal.mapper.DramaClassificationDramaMapper;
import com.fruitshorts.content.dal.mapper.DramaClassificationMapper;
import com.fruitshorts.content.dal.mapper.DramaMapper;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/** 推荐榜内容保存与版本测试。 */
class DramaRankingServiceTest {
@Test
void should_replace_items_in_request_order_and_increment_revision() {
DramaClassificationMapper classificationMapper = mock(DramaClassificationMapper.class);
DramaClassificationDramaMapper relationMapper = mock(DramaClassificationDramaMapper.class);
DramaMapper dramaMapper = mock(DramaMapper.class);
DramaRankingService service = new DramaRankingService(
classificationMapper, relationMapper, dramaMapper);
DramaClassification classification = new DramaClassification();
classification.setId(7L);
classification.setLayoutType(DramaClassificationService.LAYOUT_RANKING);
classification.setRevision(4L);
given(classificationMapper.selectById(7L)).willReturn(classification);
given(dramaMapper.selectBatchIds(List.of(22L, 11L)))
.willReturn(List.of(drama(11L), drama(22L)));
service.saveItems(7L, List.of(22L, 11L, 22L));
ArgumentCaptor<DramaClassificationDrama> captor =
ArgumentCaptor.forClass(DramaClassificationDrama.class);
verify(relationMapper, times(2)).insert(captor.capture());
assertThat(captor.getAllValues()).extracting(DramaClassificationDrama::getDramaId)
.containsExactly(22L, 11L);
assertThat(captor.getAllValues()).extracting(DramaClassificationDrama::getPosition)
.containsExactly(1, 2);
assertThat(classification.getRevision()).isEqualTo(5L);
verify(classificationMapper).updateById(classification);
verify(relationMapper).delete(any());
}
private Drama drama(Long id) {
Drama drama = new Drama();
drama.setId(id);
return drama;
}
}