From 8a5a381b44ddbff6a80cc295e99628d5e3e7151a Mon Sep 17 00:00:00 2001 From: Zhou Weidong <502333560@qq.com> Date: Mon, 2 Nov 2026 14:45:43 +0800 Subject: [PATCH] =?UTF-8?q?feat(catalog):=20=E6=96=B0=E5=A2=9E=E5=88=86?= =?UTF-8?q?=E7=B1=BB=E6=8E=A8=E8=8D=90=E6=A6=9C=E5=BF=AB=E7=85=A7=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/api-phase1.md | 44 ++++- .../DramaClassificationController.java | 11 ++ .../app/controller/AppCatalogController.java | 9 + .../app/service/AppCatalogService.java | 5 + .../app/service/AppRankingService.java | 79 +++++++++ .../com/fruitshorts/app/vo/AppCategoryVO.java | 5 + .../fruitshorts/app/vo/AppRankingEntryVO.java | 15 ++ .../com/fruitshorts/app/vo/AppRankingVO.java | 22 +++ .../AppCatalogControllerContractTest.java | 37 +++- .../AppCommentCountAnonymousSecurityTest.java | 4 +- .../app/service/AppRankingServiceTest.java | 75 ++++++++ .../dal/entity/DramaClassification.java | 6 + .../dal/entity/DramaClassificationDrama.java | 2 + .../service/DramaClassificationService.java | 92 +++++++++- .../content/service/DramaRankingService.java | 161 ++++++++++++++++++ .../fruitshorts/content/vo/DramaBriefVO.java | 2 + .../content/vo/DramaClassificationRespVO.java | 3 + .../vo/DramaClassificationSaveReqVO.java | 8 + .../content/vo/DramaRankingItemsReqVO.java | 18 ++ .../DramaClassificationServiceTest.java | 82 +++++++++ .../service/DramaRankingServiceTest.java | 60 +++++++ sql/patch-2026-11-02-recommend-ranking.sql | 50 ++++++ sql/schema-phase1.sql | 19 ++- 23 files changed, 793 insertions(+), 16 deletions(-) create mode 100644 fruitshorts-app-api/src/main/java/com/fruitshorts/app/service/AppRankingService.java create mode 100644 fruitshorts-app-api/src/main/java/com/fruitshorts/app/vo/AppRankingEntryVO.java create mode 100644 fruitshorts-app-api/src/main/java/com/fruitshorts/app/vo/AppRankingVO.java create mode 100644 fruitshorts-app-api/src/test/java/com/fruitshorts/app/service/AppRankingServiceTest.java create mode 100644 fruitshorts-module-content/src/main/java/com/fruitshorts/content/service/DramaRankingService.java create mode 100644 fruitshorts-module-content/src/main/java/com/fruitshorts/content/vo/DramaRankingItemsReqVO.java create mode 100644 fruitshorts-module-content/src/test/java/com/fruitshorts/content/service/DramaClassificationServiceTest.java create mode 100644 fruitshorts-module-content/src/test/java/com/fruitshorts/content/service/DramaRankingServiceTest.java create mode 100644 sql/patch-2026-11-02-recommend-ranking.sql diff --git a/docs/api-phase1.md b/docs/api-phase1.md index 73715b3..c262443 100644 --- a/docs/api-phase1.md +++ b/docs/api-phase1.md @@ -170,8 +170,9 @@ app.register.max-per-device-per-day | GET | `/app/home/feed` | 首页:轮播 + 分区,卡片带 `preview` 可播预览集与 `language` 语种 | | GET | `/app/discover/feed` | 发现页分区 | | GET | `/app/feed?types=ANIME,LIVE&categoryId=7&cursor=&size=20` | 推荐流;支持内容类型与分类叠加过滤,游标翻页 | -| GET | `/app/categories` | 已启用首页分类。`name` 为中文,`locales` 为 `{zh,en,id}` | +| GET | `/app/categories` | 已启用首页分类。名称在 `locales`;另带 `code`、`layoutType`(`GRID` / `RANKING`)、`revision` | | GET | `/app/categories/{id}/dramas?pageIndex=&pageSize=` | 分类下已上线短剧,分页。`pageIndex` 默认 1,`pageSize` 默认 20、最大 50 | +| GET | `/app/categories/{id}/ranking` | 推荐榜快照;只接受 `layoutType=RANKING` 的已启用分类,按后台位置返回连续排名 | | GET | `/app/drama-categories` | 已启用类型。`locales` 为 `{zh,en,id}` | | GET | `/app/tags` | 已启用标签。`locales` 为 `{zh,en,id}` | | POST | `/app/dramas/page` | 全部短剧分页。请求体 `pageIndex`(默认 1)、`pageSize`(默认 20、最大 50)、`categoryIds`、`classificationIds`、`tagIds`。id 用 JSON 数组,不放查询串。同一组多选为或,组与组之间为且 | @@ -222,6 +223,28 @@ app.register.max-per-device-per-day > 只返回 `status = 1` 的剧单,排序与后台剧单排序一致,卡片顺序与后台关联顺序一致。 > 剧单列表越界页返回空 `list`,`total` 仍是全部剧单数。详情越界页同样返回空 `list`。 +#### 推荐榜(`GET /app/categories/{id}/ranking`) + +- 分类列表中的 `layoutType=RANKING` 表示客户端必须使用榜单布局,禁止按分类名称判断。 +- 榜单内容与顺序以 `drama_classification_drama.position asc` 为准;客户端不得按播放量重新排序。 +- 已下架、未发布或不存在的短剧会被过滤,剩余项目的 `rank` 从 1 连续补齐。 +- 最多返回 50 部;`revision` 在后台保存内容或顺序后递增,供缓存与曝光埋点使用。 +- 响应 `list` 项结构为 `{rank, drama}`,其中 `drama` 沿用 `AppDramaCardVO`。 + +```json +{ + "id": "2112807182243336193", + "code": "RECOMMEND_RANKING", + "locales": {"zh": "推荐榜", "en": "Top Picks", "id": "Pilihan Teratas"}, + "revision": "8", + "generatedAt": "2026-11-02T10:00:00", + "total": 1, + "list": [ + {"rank": 1, "drama": {"id": "2112807182243336194", "titleLocales": {"zh": "短剧 A"}}} + ] +} +``` + #### 推荐类型流(`GET /app/feed`) - `types` 可选,逗号分隔,支持 `ANIME`、`LIVE` 或多选 `ANIME,LIVE`;不传或空值返回全部已上线内容。 @@ -1269,6 +1292,7 @@ commentSummary,createdAt`。游客的 userId 为空、anonymous 为 true;评 | GET | `/admin/drama-classifications/{id}/dramas/candidates` | `drama:list` | 尚未关联到该分类的短剧(分页,供多选) | | POST | `/admin/drama-classifications/{id}/dramas` | `drama:update` | 批量关联短剧,返回实际新增数量 | | DELETE | `/admin/drama-classifications/{id}/dramas/{dramaId}` | `drama:update` | 从分类移出短剧(幂等) | +| PUT | `/admin/drama-classifications/{id}/ranking-items` | `drama:update` | 原子保存推荐榜完整顺序,最多 50 部;空数组表示清空 | **列表响应** @@ -1280,6 +1304,9 @@ commentSummary,createdAt`。游客的 userId 为空、anonymous 为 true;评 { "id": "2112807182243336193", "name": "本周必看", + "code": "CLASSIFICATION_2112807182243336193", + "layoutType": "GRID", + "revision": "1", "sort": 1, "status": 1, "dramaCount": 12, @@ -1295,12 +1322,20 @@ commentSummary,createdAt`。游客的 userId 为空、anonymous 为 true;评 **新建 / 编辑请求体** ```json -{ "name": "本周必看", "sort": 1, "status": 1 } +{ + "name": "推荐榜", + "code": "RECOMMEND_RANKING", + "layoutType": "RANKING", + "sort": 1, + "status": 1 +} ``` | 字段 | 必填 | 说明 | | --- | --- | --- | | `name` | 是 | 去首尾空格后保存,全局唯一;`@NotBlank` 提示「请填写分类名称」 | +| `code` | 否 | 稳定语义码,只允许大写字母、数字、下划线;不传时生成 `CLASSIFICATION_{id}` | +| `layoutType` | 否 | `GRID` 普通分类 / `RANKING` 推荐榜;默认 `GRID` | | `sort` | 否 | 新建不传时取 `现有条数 + 1`;编辑不传(null)时保持原值 | | `status` | 否 | `1` 启用 / `0` 停用;新建默认 `1`,编辑不传保持原值 | @@ -1314,6 +1349,11 @@ POST /admin/drama-classifications/2112807182243336193/dramas 返回 `data` 为实际新增条数(整数)。已关联的、以及不存在的 `dramaId` 会被静默跳过,不报错; 全部跳过时返回 `0`。`dramaIds` 为空数组 → `400 请选择短剧`。 +推荐榜应使用 `PUT /{id}/ranking-items` 一次提交完整有序 `dramaIds`。接口会去重、校验短剧存在, +按数组顺序写入 `position=1..N` 并递增分类 `revision`;`dramaIds` 必须显式传数组,空数组表示清空。 +普通分类调用该接口返回 `200003`;推荐榜调用旧的 `POST /{id}/dramas` 或 +`DELETE /{id}/dramas/{dramaId}` 同样返回 `200003`,防止绕过版本与排序更新。 + **短剧列表项(`GET /{id}/dramas` 与 `/dramas/candidates` 共用)** ```json diff --git a/fruitshorts-admin-api/src/main/java/com/fruitshorts/admin/controller/DramaClassificationController.java b/fruitshorts-admin-api/src/main/java/com/fruitshorts/admin/controller/DramaClassificationController.java index d9e8661..776a00a 100644 --- a/fruitshorts-admin-api/src/main/java/com/fruitshorts/admin/controller/DramaClassificationController.java +++ b/fruitshorts-admin-api/src/main/java/com/fruitshorts/admin/controller/DramaClassificationController.java @@ -9,6 +9,7 @@ import com.fruitshorts.content.vo.DramaBriefVO; import com.fruitshorts.content.vo.DramaClassificationRespVO; import com.fruitshorts.content.vo.DramaClassificationSaveReqVO; import com.fruitshorts.content.vo.DramaIdsReqVO; +import com.fruitshorts.content.vo.DramaRankingItemsReqVO; import com.fruitshorts.framework.log.OperationLog; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; @@ -104,6 +105,16 @@ public class DramaClassificationController { return Result.ok(classificationService.bindDramas(id, req.getDramaIds())); } + @Operation(summary = "保存推荐榜完整内容与顺序") + @PutMapping("/{id}/ranking-items") + @PreAuthorize("@ss.hasPermission('drama:update')") + @OperationLog(module = "内容管理", action = "保存推荐榜顺序") + public Result saveRankingItems(@PathVariable Long id, + @Valid @RequestBody DramaRankingItemsReqVO req) { + classificationService.saveRankingItems(id, req.getDramaIds()); + return Result.ok(); + } + @Operation(summary = "移除分类下的短剧") @DeleteMapping("/{id}/dramas/{dramaId}") @PreAuthorize("@ss.hasPermission('drama:update')") diff --git a/fruitshorts-app-api/src/main/java/com/fruitshorts/app/controller/AppCatalogController.java b/fruitshorts-app-api/src/main/java/com/fruitshorts/app/controller/AppCatalogController.java index ce23d55..8a46c77 100644 --- a/fruitshorts-app-api/src/main/java/com/fruitshorts/app/controller/AppCatalogController.java +++ b/fruitshorts-app-api/src/main/java/com/fruitshorts/app/controller/AppCatalogController.java @@ -3,11 +3,13 @@ package com.fruitshorts.app.controller; import com.fruitshorts.app.service.AppCatalogService; +import com.fruitshorts.app.service.AppRankingService; import com.fruitshorts.app.vo.AppCategoryVO; import com.fruitshorts.app.vo.AppDramaPageReqVO; import com.fruitshorts.app.vo.AppFeedVO; import com.fruitshorts.app.vo.AppDramaCardVO; import com.fruitshorts.app.vo.AppPlaylistDetailVO; +import com.fruitshorts.app.vo.AppRankingVO; import com.fruitshorts.common.pojo.CursorResult; import com.fruitshorts.common.pojo.PageResult; import com.fruitshorts.common.pojo.Result; @@ -37,6 +39,7 @@ public class AppCatalogController { private static final int DRAMA_PAGE_SIZE = 20; private final AppCatalogService appCatalogService; + private final AppRankingService appRankingService; @Operation(summary = "首页聚合:轮播 + 分区,一次请求渲染整页") @GetMapping("/home/feed") @@ -75,6 +78,12 @@ public class AppCatalogController { return Result.ok(appCatalogService.categoryDramas(id, pageIndex, pageSize)); } + @Operation(summary = "推荐榜:按后台配置顺序返回榜单快照") + @GetMapping("/categories/{id}/ranking") + public Result categoryRanking(@PathVariable Long id) { + return Result.ok(appRankingService.ranking(id)); + } + @Operation(summary = "已启用类型") @GetMapping("/drama-categories") public Result> dramaCategories() { diff --git a/fruitshorts-app-api/src/main/java/com/fruitshorts/app/service/AppCatalogService.java b/fruitshorts-app-api/src/main/java/com/fruitshorts/app/service/AppCatalogService.java index c40ea93..29e7956 100644 --- a/fruitshorts-app-api/src/main/java/com/fruitshorts/app/service/AppCatalogService.java +++ b/fruitshorts-app-api/src/main/java/com/fruitshorts/app/service/AppCatalogService.java @@ -92,6 +92,11 @@ public class AppCatalogService { c.getNameLocales(), c.getName(), c.getNameEn(), c.getNameId()); AppCategoryVO vo = new AppCategoryVO(c.getId(), ContentLocaleTexts.value(locales, ContentLocaleTexts.ZH)); vo.setLocales(locales); + vo.setCode(c.getCode()); + vo.setLayoutType(c.getLayoutType() == null + ? DramaClassificationService.LAYOUT_GRID + : c.getLayoutType()); + vo.setRevision(c.getRevision() == null ? 1L : c.getRevision()); return vo; }) .toList(); diff --git a/fruitshorts-app-api/src/main/java/com/fruitshorts/app/service/AppRankingService.java b/fruitshorts-app-api/src/main/java/com/fruitshorts/app/service/AppRankingService.java new file mode 100644 index 0000000..fcd11e8 --- /dev/null +++ b/fruitshorts-app-api/src/main/java/com/fruitshorts/app/service/AppRankingService.java @@ -0,0 +1,79 @@ +// Author: fruit.com.cn + +package com.fruitshorts.app.service; + +import com.fruitshorts.app.vo.AppDramaCardVO; +import com.fruitshorts.app.vo.AppRankingEntryVO; +import com.fruitshorts.app.vo.AppRankingVO; +import com.fruitshorts.common.exception.ErrorCode; +import com.fruitshorts.common.exception.ServiceException; +import com.fruitshorts.content.dal.entity.Drama; +import com.fruitshorts.content.service.ContentLocaleTexts; +import com.fruitshorts.content.service.DramaClassificationService; +import com.fruitshorts.content.service.DramaService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** C 端推荐榜快照组装。 */ +@Service +@RequiredArgsConstructor +public class AppRankingService { + + private static final int MAX_RANKING_ITEMS = 50; + + private final DramaClassificationService classificationService; + private final DramaService dramaService; + private final AppCatalogService catalogService; + + /** 过滤未上线短剧后保持后台位置,排名连续补齐。 */ + public AppRankingVO ranking(Long classificationId) { + var classification = classificationService.getEnabledById(classificationId); + if (!DramaClassificationService.LAYOUT_RANKING.equals(classification.getLayoutType())) { + throw new ServiceException(ErrorCode.OPERATION_NOT_ALLOWED, "该分类不是推荐榜"); + } + List ids = classificationService.listDramaIdsByClassification(classificationId); + List ordered = orderedPublished(ids).stream().limit(MAX_RANKING_ITEMS).toList(); + List cards = catalogService.toCards(ordered); + List entries = entries(cards); + Map locales = ContentLocaleTexts.read( + classification.getNameLocales(), classification.getName(), + classification.getNameEn(), classification.getNameId()); + AppRankingVO ranking = new AppRankingVO(); + ranking.setId(classification.getId()); + ranking.setCode(classification.getCode()); + ranking.setLocales(locales); + ranking.setRevision(classification.getRevision() == null ? 1L : classification.getRevision()); + ranking.setGeneratedAt(classification.getUpdatedAt()); + ranking.setTotal(entries.size()); + ranking.setList(entries); + return ranking; + } + + private List entries(List cards) { + List entries = new ArrayList<>(); + for (int index = 0; index < cards.size(); index++) { + entries.add(new AppRankingEntryVO(index + 1, cards.get(index))); + } + return entries; + } + + private List orderedPublished(List ids) { + if (ids.isEmpty()) { + return List.of(); + } + Map positions = new HashMap<>(); + for (int index = 0; index < ids.size(); index++) { + positions.put(ids.get(index), index); + } + return dramaService.listPublishedByIds(ids).stream() + .sorted((left, right) -> Integer.compare( + positions.getOrDefault(left.getId(), Integer.MAX_VALUE), + positions.getOrDefault(right.getId(), Integer.MAX_VALUE))) + .toList(); + } +} diff --git a/fruitshorts-app-api/src/main/java/com/fruitshorts/app/vo/AppCategoryVO.java b/fruitshorts-app-api/src/main/java/com/fruitshorts/app/vo/AppCategoryVO.java index d27d99c..135b443 100644 --- a/fruitshorts-app-api/src/main/java/com/fruitshorts/app/vo/AppCategoryVO.java +++ b/fruitshorts-app-api/src/main/java/com/fruitshorts/app/vo/AppCategoryVO.java @@ -11,10 +11,15 @@ import java.util.Map; public class AppCategoryVO { private Long id; + private String code; + private String layoutType; + private Long revision; private Map locales; public AppCategoryVO(Long id, String name) { this.id = id; + this.layoutType = "GRID"; + this.revision = 1L; this.locales = name == null || name.isBlank() ? Map.of() : Map.of("zh", name); } } diff --git a/fruitshorts-app-api/src/main/java/com/fruitshorts/app/vo/AppRankingEntryVO.java b/fruitshorts-app-api/src/main/java/com/fruitshorts/app/vo/AppRankingEntryVO.java new file mode 100644 index 0000000..230be2b --- /dev/null +++ b/fruitshorts-app-api/src/main/java/com/fruitshorts/app/vo/AppRankingEntryVO.java @@ -0,0 +1,15 @@ +// Author: fruit.com.cn + +package com.fruitshorts.app.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; + +/** 推荐榜单项,排名由服务端确定。 */ +@Data +@AllArgsConstructor +public class AppRankingEntryVO { + + private Integer rank; + private AppDramaCardVO drama; +} diff --git a/fruitshorts-app-api/src/main/java/com/fruitshorts/app/vo/AppRankingVO.java b/fruitshorts-app-api/src/main/java/com/fruitshorts/app/vo/AppRankingVO.java new file mode 100644 index 0000000..89cc9fe --- /dev/null +++ b/fruitshorts-app-api/src/main/java/com/fruitshorts/app/vo/AppRankingVO.java @@ -0,0 +1,22 @@ +// Author: fruit.com.cn + +package com.fruitshorts.app.vo; + +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; + +/** 推荐榜快照。 */ +@Data +public class AppRankingVO { + + private Long id; + private String code; + private Map locales; + private Long revision; + private LocalDateTime generatedAt; + private Integer total; + private List list; +} diff --git a/fruitshorts-app-api/src/test/java/com/fruitshorts/app/controller/AppCatalogControllerContractTest.java b/fruitshorts-app-api/src/test/java/com/fruitshorts/app/controller/AppCatalogControllerContractTest.java index 7b52c49..ed6e0c5 100644 --- a/fruitshorts-app-api/src/test/java/com/fruitshorts/app/controller/AppCatalogControllerContractTest.java +++ b/fruitshorts-app-api/src/test/java/com/fruitshorts/app/controller/AppCatalogControllerContractTest.java @@ -3,6 +3,7 @@ package com.fruitshorts.app.controller; import com.fruitshorts.app.service.AppCatalogService; import com.fruitshorts.app.service.AppEpisodeStatsService; +import com.fruitshorts.app.service.AppRankingService; import com.fruitshorts.app.support.ControllerContractSupport; import com.fruitshorts.app.vo.AppBannerVO; import com.fruitshorts.app.vo.AppCategoryVO; @@ -10,6 +11,8 @@ import com.fruitshorts.app.vo.AppDramaCardVO; import com.fruitshorts.app.vo.AppDramaDetailVO; import com.fruitshorts.app.vo.AppFeedVO; import com.fruitshorts.app.vo.AppSectionVO; +import com.fruitshorts.app.vo.AppRankingEntryVO; +import com.fruitshorts.app.vo.AppRankingVO; import com.fruitshorts.common.pojo.CursorResult; import com.fruitshorts.content.service.EpisodeService; import com.fruitshorts.common.exception.ErrorCode; @@ -41,13 +44,16 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. class AppCatalogControllerContractTest { private AppCatalogService catalogService; + private AppRankingService rankingService; private MockMvc catalogMvc; private MockMvc dramaMvc; @BeforeEach void setUp() { catalogService = mock(AppCatalogService.class); - catalogMvc = ControllerContractSupport.mockMvcOf(new AppCatalogController(catalogService)); + rankingService = mock(AppRankingService.class); + catalogMvc = ControllerContractSupport.mockMvcOf( + new AppCatalogController(catalogService, rankingService)); dramaMvc = ControllerContractSupport.mockMvcOf( new AppDramaController(catalogService, mock(PlaybackService.class), mock(EpisodeService.class), mock(CommentService.class), @@ -122,15 +128,44 @@ class AppCatalogControllerContractTest { @Test void should_return_category_list_when_categories_are_requested() throws Exception { AppCategoryVO category = new AppCategoryVO(3L, "都市"); + category.setCode("RECOMMEND_RANKING"); + category.setLayoutType("RANKING"); + category.setRevision(7L); given(catalogService.categories()).willReturn(List.of(category)); catalogMvc.perform(get("/app/categories")) .andExpect(status().isOk()) .andExpect(jsonPath("$.code").value(0)) .andExpect(jsonPath("$.data[0].id").value(3)) + .andExpect(jsonPath("$.data[0].code").value("RECOMMEND_RANKING")) + .andExpect(jsonPath("$.data[0].layoutType").value("RANKING")) + .andExpect(jsonPath("$.data[0].revision").value("7")) .andExpect(jsonPath("$.data[0].locales.zh").value("都市")); } + @Test + void should_return_server_rank_when_ranking_is_requested() throws Exception { + AppDramaCardVO card = new AppDramaCardVO(); + card.setId(12L); + card.setTitleLocales(Map.of("zh", "榜首短剧")); + AppRankingVO ranking = new AppRankingVO(); + ranking.setId(3L); + ranking.setCode("RECOMMEND_RANKING"); + ranking.setRevision(8L); + ranking.setTotal(1); + ranking.setList(List.of(new AppRankingEntryVO(1, card))); + given(rankingService.ranking(3L)).willReturn(ranking); + + catalogMvc.perform(get("/app/categories/3/ranking")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.code").value(0)) + .andExpect(jsonPath("$.data.revision").value("8")) + .andExpect(jsonPath("$.data.list[0].rank").value(1)) + .andExpect(jsonPath("$.data.list[0].drama.id").value("12")); + + verify(rankingService).ranking(3L); + } + @Test void should_bind_path_variable_when_drama_detail_is_requested() throws Exception { AppDramaDetailVO detail = new AppDramaDetailVO(); diff --git a/fruitshorts-app-api/src/test/java/com/fruitshorts/app/controller/AppCommentCountAnonymousSecurityTest.java b/fruitshorts-app-api/src/test/java/com/fruitshorts/app/controller/AppCommentCountAnonymousSecurityTest.java index c715b1f..e8ade30 100644 --- a/fruitshorts-app-api/src/test/java/com/fruitshorts/app/controller/AppCommentCountAnonymousSecurityTest.java +++ b/fruitshorts-app-api/src/test/java/com/fruitshorts/app/controller/AppCommentCountAnonymousSecurityTest.java @@ -328,7 +328,9 @@ class AppCommentCountAnonymousSecurityTest { @Bean AppCatalogController appCatalogController(AppCatalogService appCatalogService) { - return new AppCatalogController(appCatalogService); + return new AppCatalogController( + appCatalogService, + mock(com.fruitshorts.app.service.AppRankingService.class)); } @Bean diff --git a/fruitshorts-app-api/src/test/java/com/fruitshorts/app/service/AppRankingServiceTest.java b/fruitshorts-app-api/src/test/java/com/fruitshorts/app/service/AppRankingServiceTest.java new file mode 100644 index 0000000..1fc0875 --- /dev/null +++ b/fruitshorts-app-api/src/test/java/com/fruitshorts/app/service/AppRankingServiceTest.java @@ -0,0 +1,75 @@ +// Author: fruit.com.cn + +package com.fruitshorts.app.service; + +import com.fruitshorts.app.vo.AppDramaCardVO; +import com.fruitshorts.app.vo.AppRankingVO; +import com.fruitshorts.content.dal.entity.Drama; +import com.fruitshorts.content.dal.entity.DramaClassification; +import com.fruitshorts.content.service.DramaClassificationService; +import com.fruitshorts.content.service.DramaService; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + +/** 推荐榜快照顺序与排名测试。 */ +class AppRankingServiceTest { + + @Test + void should_preserve_server_order_and_compact_rank_when_offline_items_are_filtered() { + DramaClassificationService classificationService = mock(DramaClassificationService.class); + DramaService dramaService = mock(DramaService.class); + AppCatalogService catalogService = mock(AppCatalogService.class); + AppRankingService service = new AppRankingService( + classificationService, dramaService, catalogService); + DramaClassification classification = rankingClassification(); + Drama second = drama(22L); + Drama first = drama(11L); + given(classificationService.getEnabledById(3L)).willReturn(classification); + given(classificationService.listDramaIdsByClassification(3L)) + .willReturn(List.of(11L, 99L, 22L)); + given(dramaService.listPublishedByIds(List.of(11L, 99L, 22L))) + .willReturn(List.of(second, first)); + AppDramaCardVO firstCard = card(11L); + AppDramaCardVO secondCard = card(22L); + given(catalogService.toCards(List.of(first, second))) + .willReturn(List.of(firstCard, secondCard)); + + AppRankingVO result = service.ranking(3L); + + assertThat(result.getRevision()).isEqualTo(7L); + assertThat(result.getList()).extracting(item -> item.getDrama().getId()) + .containsExactly(11L, 22L); + assertThat(result.getList()).extracting(item -> item.getRank()) + .containsExactly(1, 2); + } + + private DramaClassification rankingClassification() { + DramaClassification classification = new DramaClassification(); + classification.setId(3L); + classification.setCode("RECOMMEND_RANKING"); + classification.setName("推荐榜"); + classification.setNameLocales("{\"zh\":\"推荐榜\"}"); + classification.setLayoutType(DramaClassificationService.LAYOUT_RANKING); + classification.setRevision(7L); + return classification; + } + + private Drama drama(Long id) { + Drama drama = new Drama(); + drama.setId(id); + return drama; + } + + private AppDramaCardVO card(Long id) { + AppDramaCardVO card = new AppDramaCardVO(); + card.setId(id); + card.setTitleLocales(Map.of("zh", "短剧" + id)); + return card; + } +} diff --git a/fruitshorts-module-content/src/main/java/com/fruitshorts/content/dal/entity/DramaClassification.java b/fruitshorts-module-content/src/main/java/com/fruitshorts/content/dal/entity/DramaClassification.java index fd4fb2a..a22b79a 100644 --- a/fruitshorts-module-content/src/main/java/com/fruitshorts/content/dal/entity/DramaClassification.java +++ b/fruitshorts-module-content/src/main/java/com/fruitshorts/content/dal/entity/DramaClassification.java @@ -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; diff --git a/fruitshorts-module-content/src/main/java/com/fruitshorts/content/dal/entity/DramaClassificationDrama.java b/fruitshorts-module-content/src/main/java/com/fruitshorts/content/dal/entity/DramaClassificationDrama.java index cf0b0dc..e3ba2e6 100644 --- a/fruitshorts-module-content/src/main/java/com/fruitshorts/content/dal/entity/DramaClassificationDrama.java +++ b/fruitshorts-module-content/src/main/java/com/fruitshorts/content/dal/entity/DramaClassificationDrama.java @@ -18,5 +18,7 @@ public class DramaClassificationDrama { private Long id; private Long classificationId; private Long dramaId; + /** 分类内展示位置,从 1 开始。 */ + private Integer position; private LocalDateTime createdAt; } diff --git a/fruitshorts-module-content/src/main/java/com/fruitshorts/content/service/DramaClassificationService.java b/fruitshorts-module-content/src/main/java/com/fruitshorts/content/service/DramaClassificationService.java index 7708671..7138553 100644 --- a/fruitshorts-module-content/src/main/java/com/fruitshorts/content/service/DramaClassificationService.java +++ b/fruitshorts-module-content/src/main/java/com/fruitshorts/content/service/DramaClassificationService.java @@ -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 list() { Map 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 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 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 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.lambdaQuery() .eq(DramaClassificationDrama::getClassificationId, id) .eq(DramaClassificationDrama::getDramaId, dramaId)); } + /** 原子替换推荐榜内容与顺序,成功后递增版本。 */ + @Transactional(rollbackFor = Exception.class) + public void saveRankingItems(Long id, List dramaIds) { + rankingService.saveItems(id, dramaIds); + } + private PageResult 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 page = new Page<>(Math.max(1, pageIndex), Math.max(1, Math.min(pageSize, 100))); LambdaQueryWrapper wrapper = Wrappers.lambdaQuery() .like(StringUtils.hasText(keyword), Drama::getTitle, keyword) @@ -228,8 +253,12 @@ public class DramaClassificationService { return entity; } - /** C 端:分类下关联的全部 dramaId(按关联创建时间 desc)。 */ + /** C 端:普通分类保留历史倒序,推荐榜严格按 position 升序。 */ public List listDramaIdsByClassification(Long classificationId) { + DramaClassification classification = getExisting(classificationId); + if (LAYOUT_RANKING.equals(layoutOf(classification))) { + return rankingService.orderedDramaIds(classificationId); + } return classificationDramaMapper.selectList( Wrappers.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.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, + "推荐榜请使用完整排序接口维护内容"); + } + } } diff --git a/fruitshorts-module-content/src/main/java/com/fruitshorts/content/service/DramaRankingService.java b/fruitshorts-module-content/src/main/java/com/fruitshorts/content/service/DramaRankingService.java new file mode 100644 index 0000000..2ef5618 --- /dev/null +++ b/fruitshorts-module-content/src/main/java/com/fruitshorts/content/service/DramaRankingService.java @@ -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 dramaIds) { + DramaClassification classification = getRanking(classificationId); + List orderedIds = orderedIds(dramaIds); + ensureDramasExist(orderedIds); + relationMapper.delete(Wrappers.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 page(Long classificationId, String keyword, + int pageIndex, int pageSize) { + List relations = orderedRelations(classificationId); + if (relations.isEmpty()) { + return PageResult.empty(); + } + List ids = relations.stream().map(DramaClassificationDrama::getDramaId).toList(); + Map dramas = dramaMapper.selectBatchIds(ids).stream() + .collect(Collectors.toMap(Drama::getId, Function.identity())); + List 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 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 orderedIds(List dramaIds) { + LinkedHashSet 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 dramaIds) { + if (dramaIds.isEmpty()) { + return; + } + if (dramaMapper.selectBatchIds(dramaIds).size() != dramaIds.size()) { + throw new ServiceException(ErrorCode.DATA_NOT_FOUND, "榜单中包含不存在的短剧"); + } + } + + private List orderedRelations(Long classificationId) { + return relationMapper.selectList(Wrappers.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 pageOf(List 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)); + } +} diff --git a/fruitshorts-module-content/src/main/java/com/fruitshorts/content/vo/DramaBriefVO.java b/fruitshorts-module-content/src/main/java/com/fruitshorts/content/vo/DramaBriefVO.java index d9c6edb..5d253b1 100644 --- a/fruitshorts-module-content/src/main/java/com/fruitshorts/content/vo/DramaBriefVO.java +++ b/fruitshorts-module-content/src/main/java/com/fruitshorts/content/vo/DramaBriefVO.java @@ -16,5 +16,7 @@ public class DramaBriefVO { private String status; private Integer totalEpisodes; private Integer sort; + /** 分类内展示位置。 */ + private Integer position; private LocalDateTime updatedAt; } diff --git a/fruitshorts-module-content/src/main/java/com/fruitshorts/content/vo/DramaClassificationRespVO.java b/fruitshorts-module-content/src/main/java/com/fruitshorts/content/vo/DramaClassificationRespVO.java index b2fe065..832e143 100644 --- a/fruitshorts-module-content/src/main/java/com/fruitshorts/content/vo/DramaClassificationRespVO.java +++ b/fruitshorts-module-content/src/main/java/com/fruitshorts/content/vo/DramaClassificationRespVO.java @@ -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 locales; + private String layoutType; + private Long revision; private Integer sort; private Integer status; private Integer dramaCount; diff --git a/fruitshorts-module-content/src/main/java/com/fruitshorts/content/vo/DramaClassificationSaveReqVO.java b/fruitshorts-module-content/src/main/java/com/fruitshorts/content/vo/DramaClassificationSaveReqVO.java index 13e69ec..cfc2091 100644 --- a/fruitshorts-module-content/src/main/java/com/fruitshorts/content/vo/DramaClassificationSaveReqVO.java +++ b/fruitshorts-module-content/src/main/java/com/fruitshorts/content/vo/DramaClassificationSaveReqVO.java @@ -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 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; } diff --git a/fruitshorts-module-content/src/main/java/com/fruitshorts/content/vo/DramaRankingItemsReqVO.java b/fruitshorts-module-content/src/main/java/com/fruitshorts/content/vo/DramaRankingItemsReqVO.java new file mode 100644 index 0000000..d03f160 --- /dev/null +++ b/fruitshorts-module-content/src/main/java/com/fruitshorts/content/vo/DramaRankingItemsReqVO.java @@ -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 dramaIds; +} diff --git a/fruitshorts-module-content/src/test/java/com/fruitshorts/content/service/DramaClassificationServiceTest.java b/fruitshorts-module-content/src/test/java/com/fruitshorts/content/service/DramaClassificationServiceTest.java new file mode 100644 index 0000000..9c54c24 --- /dev/null +++ b/fruitshorts-module-content/src/test/java/com/fruitshorts/content/service/DramaClassificationServiceTest.java @@ -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 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 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) { + } +} diff --git a/fruitshorts-module-content/src/test/java/com/fruitshorts/content/service/DramaRankingServiceTest.java b/fruitshorts-module-content/src/test/java/com/fruitshorts/content/service/DramaRankingServiceTest.java new file mode 100644 index 0000000..40d0439 --- /dev/null +++ b/fruitshorts-module-content/src/test/java/com/fruitshorts/content/service/DramaRankingServiceTest.java @@ -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 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; + } +} diff --git a/sql/patch-2026-11-02-recommend-ranking.sql b/sql/patch-2026-11-02-recommend-ranking.sql new file mode 100644 index 0000000..0014da5 --- /dev/null +++ b/sql/patch-2026-11-02-recommend-ranking.sql @@ -0,0 +1,50 @@ +-- Author: fruit.com.cn +-- 推荐榜:运营分类增加稳定语义、展示类型和版本,关联关系增加明确位置 + +ALTER TABLE drama_classification + ADD COLUMN IF NOT EXISTS code VARCHAR(64), + ADD COLUMN IF NOT EXISTS layout_type VARCHAR(16) NOT NULL DEFAULT 'GRID', + ADD COLUMN IF NOT EXISTS revision BIGINT NOT NULL DEFAULT 1; + +UPDATE drama_classification +SET code = 'CLASSIFICATION_' || id +WHERE code IS NULL OR BTRIM(code) = ''; + +UPDATE drama_classification +SET code = 'RECOMMEND_RANKING', + layout_type = 'RANKING' +WHERE id = ( + SELECT id + FROM drama_classification + WHERE name IN ('推荐榜', '榜单') + ORDER BY sort ASC, id ASC + LIMIT 1 +); + +CREATE UNIQUE INDEX IF NOT EXISTS uk_drama_classification_code + ON drama_classification (code); + +ALTER TABLE drama_classification_drama + ADD COLUMN IF NOT EXISTS position INTEGER NOT NULL DEFAULT 0; + +WITH ranked AS ( + SELECT id, + ROW_NUMBER() OVER ( + PARTITION BY classification_id + ORDER BY created_at DESC, id DESC + ) AS next_position + FROM drama_classification_drama +) +UPDATE drama_classification_drama relation +SET position = ranked.next_position +FROM ranked +WHERE relation.id = ranked.id + AND relation.position = 0; + +CREATE INDEX IF NOT EXISTS idx_classification_drama_position + ON drama_classification_drama (classification_id, position, id); + +COMMENT ON COLUMN drama_classification.code IS '稳定语义码,不随多语言名称变化'; +COMMENT ON COLUMN drama_classification.layout_type IS '客户端布局:GRID/RANKING'; +COMMENT ON COLUMN drama_classification.revision IS '内容或顺序版本,变更后递增'; +COMMENT ON COLUMN drama_classification_drama.position IS '分类内展示位置,从 1 开始'; diff --git a/sql/schema-phase1.sql b/sql/schema-phase1.sql index caac683..de238f4 100644 --- a/sql/schema-phase1.sql +++ b/sql/schema-phase1.sql @@ -873,26 +873,33 @@ COMMENT ON TABLE audit_log IS '业务对象变更审计(支付、权益、定 -- ============================================================ CREATE TABLE IF NOT EXISTS drama_classification ( - id BIGINT PRIMARY KEY, - name VARCHAR(64) NOT NULL, - sort INTEGER NOT NULL DEFAULT 0, - status SMALLINT NOT NULL DEFAULT 1, - created_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP + id BIGINT PRIMARY KEY, + name VARCHAR(64) NOT NULL, + code VARCHAR(64), + layout_type VARCHAR(16) NOT NULL DEFAULT 'GRID', + revision BIGINT NOT NULL DEFAULT 1, + sort INTEGER NOT NULL DEFAULT 0, + status SMALLINT NOT NULL DEFAULT 1, + created_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP ); CREATE UNIQUE INDEX IF NOT EXISTS uk_drama_classification_name ON drama_classification (name); +CREATE UNIQUE INDEX IF NOT EXISTS uk_drama_classification_code ON drama_classification (code); COMMENT ON TABLE drama_classification IS '运营分类;与短剧类型(drama_category)相互独立'; CREATE TABLE IF NOT EXISTS drama_classification_drama ( id BIGINT PRIMARY KEY, classification_id BIGINT NOT NULL, drama_id BIGINT NOT NULL, + position INTEGER NOT NULL DEFAULT 0, created_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP ); CREATE UNIQUE INDEX IF NOT EXISTS uk_classification_drama ON drama_classification_drama (classification_id, drama_id); CREATE INDEX IF NOT EXISTS idx_classification_drama_drama ON drama_classification_drama (drama_id); +CREATE INDEX IF NOT EXISTS idx_classification_drama_position + ON drama_classification_drama (classification_id, position, id); COMMENT ON TABLE drama_classification_drama IS '分类与短剧的关联关系'; -- ============================================================