feat(jd): 京东店铺分类按数据权限分组隔离(V203)

用户口径:不同组不能看到跨组的分类;当前组只管理员可以编辑分类,同组普通号可以进弹窗看但不能增删;
平台超管全量可见可编辑,公司超管管本公司全部组;归类也按组隔离且不再置人工编辑锁。

数据模型:biz_jd_product_group 加 owner_group_id(NOT NULL DEFAULT 0,
uk_company_owner_name(company_id, owner_group_id, name));新增 biz_jd_product_group_assign
(product_id, owner_group_id, category_id, uk_product_owner) 承接归类,同一商品各组可各自归类;
biz_jd_product.group_id 保留但零读零写。

权限:新增 JdCategoryScopeService(GET /api/admin/jd-product-groups/scope 回可见组 + 每组 editable)
四档矩阵;分类增删改与归类走 requireWritableGroup 403;商品行写(编辑/删除)仍只平台超管。

读面:列表/筛选/详情/归类一律按 owner_group_id,分类筛选 group_id 走归属表 EXISTS 下推
(不在 Java 侧 filter);用户端 /api/jd-collect/groups 按登录用户可见组收窄。

前端:工具栏「分组」下拉(多组才渲染,单组锁定显示);店铺分类弹窗对所有有该页菜单权限的人可见,
但按 editable 隐藏新建/改名/删除/勾选/归入移出;编辑抽屉「分类」下拉下线;只读提示改为
「只读:编辑/删除仅超级管理员可用;分类由本组管理员维护」。

验证:后端 mvn -o test 整量 5610 例 0 失败 19 skip;后管 npx vue-tsc 绿 / node --test 1919 绿 /
vitest 132 绿;用户端 vue-tsc 绿;python scripts/_push_gate.py --fast overall=pass。
迁移实跑与真机页面验收留发版窗口(本机无 MySQL/OSS);V203 需与另一路 V202 同窗口发布。
This commit is contained in:
2026-11-16 21:09:44 +08:00
parent e621deea58
commit 61ab844e5d
39 changed files with 2330 additions and 627 deletions
@@ -80,6 +80,31 @@ class JdSchemaContractTest {
assertFalse(sql.contains("user_column_permission"), "菜单迁移不得插授权行(默认仅 super_admin,V190 惯例)");
}
@Test
void V203_分类按数据权限分组归属_归属列与归属表形状() {
String sql = read(DB_DIR.resolve("V203__jd_product_group_owner_group.sql"));
assertTrue(sql.contains("biz_jd_product_group"), "缺分类表");
// 归属列:NOT NULL DEFAULT 0(0=历史公共行,读侧不可见;显式默认值避免存量行 NULL 撞唯一键)。
assertTrue(linesContaining(sql, "`owner_group_id`").stream()
.anyMatch(line -> line.contains("NOT NULL") && line.contains("DEFAULT 0")),
"owner_group_id 必须 NOT NULL DEFAULT 0(铁律 30:缺件沿用前值,NULL 会让唯一键失效)");
// 唯一键三件套:同公司同组内重名拒绝、不同组可同名。
assertTrue(sql.contains("uk_company_owner_name"), "同公司同组重名唯一键缺失");
assertTrue(linesContaining(sql, "uk_company_owner_name").stream()
.anyMatch(line -> line.contains("company_id") && line.contains("owner_group_id")
&& line.contains("name")),
"唯一键必须是 (company_id, owner_group_id, name)");
// 一组一商品一行:同一商品各组可各自归类。
assertTrue(sql.contains("biz_jd_product_group_assign"), "缺归类归属表");
assertTrue(sql.contains("uk_product_owner"), "一组一商品唯一键缺失(uk_product_owner)");
for (String column : List.of("product_id", "owner_group_id", "category_id", "company_id", "created_by")) {
assertFalse(linesContaining(sql, "`" + column + "`").isEmpty(), "V203 归属表缺列: " + column);
}
// 可重跑:两次迁移之间不会因为列/键已存在而炸(information_schema 守卫)。
assertTrue(sql.contains("information_schema"), "必须带 information_schema 幂等守卫(可重跑)");
assertTrue(sql.contains("迁移 V203"), "头注释必须是 `-- 迁移 V203…`(MigrationInventoryTest 口径)");
}
@Test
void 配置_独立图片桶不落默认桶() {
String appYml = read(RESOURCES.resolve("application.yml"));
@@ -4,20 +4,28 @@ import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.api.PageDefaults;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.model.entity.ShopManageGroupEntity;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupAssignMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductImageMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper;
import com.nanri.aiimage.modules.jd.model.dto.JdProductBatchAssignGroupRequest;
import com.nanri.aiimage.modules.jd.model.dto.JdProductBatchDeleteRequest;
import com.nanri.aiimage.modules.jd.model.dto.JdProductGroupSaveRequest;
import com.nanri.aiimage.modules.jd.model.dto.JdProductUpdateRequest;
import com.nanri.aiimage.modules.jd.model.entity.JdProductEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupAssignEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductImageEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductSkuEntity;
import com.nanri.aiimage.modules.jd.model.vo.JdCategoryGroupOptionVo;
import com.nanri.aiimage.modules.jd.model.vo.JdProductCategoryVo;
import com.nanri.aiimage.modules.jd.model.vo.JdProductDeleteVo;
import com.nanri.aiimage.modules.jd.model.vo.JdProductDetailVo;
import com.nanri.aiimage.modules.jd.model.vo.JdProductPageVo;
import com.nanri.aiimage.modules.jd.service.JdCategoryScopeService;
import com.nanri.aiimage.modules.jd.service.JdProductDeleteService;
import com.nanri.aiimage.modules.jd.service.JdProductGroupService;
import com.nanri.aiimage.modules.jd.service.JdProductQueryService;
@@ -25,7 +33,6 @@ import com.nanri.aiimage.modules.jd.service.JdProductUpdateService;
import com.nanri.aiimage.modules.permission.model.vo.PermissionMenuItemVo;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.ibatis.annotations.Mapper;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.web.multipart.MultipartFile;
@@ -66,6 +73,13 @@ import static org.mockito.Mockito.when;
* 分页钳制 offset/limit(page=Long.MAX_VALUE 不得负,铁律 15)、详情 attr_json
* tabs→attrGroups 解析与非法形状兜底(AC-7)。
* 导出端点与 sale_status 筛选参数已随 2026-11-15 客户口径整段下线(反向钉住防回潜)。</p>
*
* <p><b>V203 分类按数据权限分组隔离(2026-11-16 用户口径)</b>:分类归属存
* {@code biz_jd_product_group_assign} 的 (product_id, owner_group_id) 一行,读面靠
* {@code owner_group_id} 取「当前分组」的分类(缺省=作用域默认分组),归类的写权限
* 由 {@link JdCategoryScopeService} 判「该组可写」——商品行编辑/删除仍只平台超管。
* 本类把作用域服务整体 mock 掉(四档角色矩阵在 {@code JdCategoryScopeServiceTest} 里钉),
* 只钉控制器怎么用它、以及拒绝语义不被吞。</p>
*/
class AdminJdProductControllerTest {
@@ -79,6 +93,10 @@ class AdminJdProductControllerTest {
private static final String COLUMN_KEY = "admin_jd_database";
private static final String ROUTE_PATH = "jd-center/database";
/** 用例里的「当前分组」:数据权限分组 10,归属公司 5。 */
private static final long GROUP_ID = 10L;
private static final long COMPANY_ID = 5L;
// ===================== 结构判据 =====================
@Test
@@ -102,6 +120,9 @@ class AdminJdProductControllerTest {
// (AdminJdProductController 的 @PutMapping("/{id}",JdProductUpdateService 承接);商品行
// 采集回传覆盖链不变,人工改名只走这条 PUT。分组改排序仍落 AdminJdProductGroupController。
assertTrue(source.contains("@PutMapping"), "编辑商品端点必须落在 @PutMapping(\"/{id}\")");
// V203:读面「当前分组」一律走 owner_group_id(不叫 company_id——前端 company-tab 绊线钉住)。
assertTrue(source.contains("\"owner_group_id\""),
"分页/详情必须收 owner_group_id(当前数据权限分组)");
}
@Test
@@ -138,7 +159,7 @@ class AdminJdProductControllerTest {
void 分页参数snake且带默认值() throws IOException {
String source = stripComments(Files.readString(CONTROLLER));
for (String param : List.of("page_size", "product_code", "title_keyword",
"group_id", "synced_from", "synced_to")) {
"group_id", "owner_group_id", "synced_from", "synced_to")) {
assertTrue(source.contains(param), "查询参数必须 snake_case:" + param);
}
assertFalse(source.contains("@RequestParam(name = \"ungrouped\""));
@@ -166,7 +187,13 @@ class AdminJdProductControllerTest {
String xmlText = stripComments(Files.readString(xml)).replaceAll("(?s)<!--.*?-->", "");
assertTrue(xmlText.contains("countProducts"), "XML 必须有 countProducts(只读页总数)");
assertTrue(xmlText.contains("selectProductPage"), "XML 必须有 selectProductPage(只读页分页)");
assertTrue(xmlText.contains("AND p.group_id = #{groupId}"), "自定义分类必须下推 SQL");
// V203:分类归属在 biz_jd_product_group_assign(一组一商品一行),过滤必须下推成 EXISTS 子查询。
assertTrue(xmlText.contains("FROM biz_jd_product_group_assign"),
"自定义分类必须下推 SQL(V203 归属表 EXISTS 子查询)");
assertTrue(xmlText.contains("a.product_id = p.id") && xmlText.contains("a.category_id = #{groupId}"),
"EXISTS 子查询必须同时按商品与分类关联");
assertFalse(xmlText.contains("p.group_id = #{groupId}"),
"商品行 group_id 列已随 V203 停用(分类按组归属),不得回潜");
assertFalse(xmlText.contains("ungrouped"));
assertFalse(xmlText.contains("grouped"));
assertEquals(2, xmlText.split("<include refid=\"productConds\"", -1).length - 1,
@@ -187,29 +214,34 @@ class AdminJdProductControllerTest {
"getUserColumnPermissions", COLUMN_KEY, ROUTE_PATH, "requireJdAccess")) {
assertTrue(source.contains(seam), "分组鉴权闸缺接缝 " + seam + "(与商品页同款)");
}
// 读列表按菜单权限放行,写(新建/改名/删除)2026-11-16 起收窄到平台超管(用户口径
// 「京东数据库只有超管有编辑删除权限」;AC-9「普通授权用户可读写分组」已被该口径推翻)。
// V203 起写权限不再收窄到平台超管:本组管理员 / 公司超管 / 平台超管都可写(作用域服务判)。
for (String verb : List.of("@PostMapping", "@PutMapping", "@DeleteMapping")) {
assertTrue(source.contains(verb), "分组 CRUD 必须有 " + verb);
}
assertEquals(3, count(source, "requirePlatformSuperAdminWrite(request)"),
"分组列表外的三个写端点都必须走超管写闸");
assertEquals(2, count(source, "requireJdAccess(request)"),
"分组列表与写闸内部各走一处菜单权限正门");
assertTrue(source.contains("仅平台超级管理员可以修改京东数据库分类"),
"非超管写分类的 403 文案必须点名平台超管");
assertEquals(5, count(source, "requireJdAccess(request)"),
"列表/作用域/新建/改名/删除五条路由都走同一菜单正门(写权限在作用域服务里判)");
assertFalse(source.contains("requirePlatformSuperAdminWrite"),
"分类写权限已改由 JdCategoryScopeService 判「该组可写」,超管专属闸必须已摘除");
assertTrue(source.contains("requireWritableGroup(") && source.contains("canWrite("),
"新建走 requireWritableGroup,改名/删除走 canWrite 归属校验");
assertTrue(source.contains("/scope") && source.contains("scopeVo("),
"必须提供 GET /scope 给前端渲染「分组」下拉与可写标记");
assertTrue(source.contains("仅该分组的管理员可以修改它的分类"),
"非本组管理员写分类的 403 文案必须点名分组管理员");
assertTrue(source.contains("\"owner_group_id\""), "列表必须收 owner_group_id(当前分组)");
}
// ===================== 写权限分档(2026-11-16) =====================
// ===================== 写权限分档(2026-11-16 / V203) =====================
/** 写端点越权闸的结构判据:五条写路由逐条走 requirePlatformSuperAdminWrite,读三条仍走菜单正门。 */
/** 写端点越权闸的结构判据:商品行四条写路由走超管闸,读三条走菜单正门。 */
@Test
void 商品页读写权限分档_写端点逐条走超管闸() throws IOException {
void 商品页读写权限分档_商品行写端点逐条走超管闸() throws IOException {
String source = stripComments(Files.readString(CONTROLLER));
assertEquals(5, count(source, "requirePlatformSuperAdminWrite(request)"),
"编辑/上传图片/单行删除/批量归类/批量删除五条写路由必须逐条走超管写闸");
assertEquals(4, count(source, "requireJdAccess(request)"),
"列表/类目/详情三条读路由与写闸内部共四处菜单权限正门");
assertEquals(4, count(source, "requirePlatformSuperAdminWrite(request)"),
"编辑/上传图片/单行删除/批量删除四条商品行写路由必须逐条走超管写闸"
+ "(归类不在此列:V203 起归本组管理员可做)");
assertEquals(5, count(source, "requireJdAccess(request)"),
"列表/类目/详情/归类四条读+组内写路由,与超管写闸内部一处,共五处菜单权限正门");
assertTrue(source.contains("仅平台超级管理员可以编辑或删除京东数据库数据"),
"非超管写商品的 403 文案必须点名平台超管");
assertTrue(source.contains("operator.superAdmin()"),
@@ -217,35 +249,41 @@ class AdminJdProductControllerTest {
}
@Test
void 非超管有菜单权限时读放行_写一律403且不触服务() {
void 非超管有菜单权限时读放行_商品行写一律403且不触服务() {
JdProductQueryService queryService = mock(JdProductQueryService.class);
JdProductDeleteService deleteService = mock(JdProductDeleteService.class);
JdProductUpdateService updateService = mock(JdProductUpdateService.class);
JdProductGroupService groupService = mock(JdProductGroupService.class);
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
AdminJdProductController controller = new AdminJdProductController(
queryService, deleteService, updateService, authSupport, permissionMenuService);
queryService, deleteService, updateService, groupService, scopeService,
authSupport, permissionMenuService);
AdminUserEntity operator = new AdminUserEntity();
operator.setId(9L);
operator.setUsername("company-admin");
HttpServletRequest request = mock(HttpServletRequest.class);
when(authSupport.requireUser(request)).thenReturn(operator);
// 非超管(管理员 / 公司超管同形):拿到 admin_jd_database 菜单权限后读可进、写仍拒。
// 非超管(管理员 / 公司超管同形):拿到 admin_jd_database 菜单权限后读可进、商品行写仍拒。
when(authSupport.currentRole(operator)).thenReturn("admin");
PermissionMenuItemVo grant = new PermissionMenuItemVo();
grant.setColumnKey(COLUMN_KEY);
grant.setRoutePath(ROUTE_PATH);
when(permissionMenuService.getUserColumnPermissions(9L, "admin")).thenReturn(List.of(grant));
JdCategoryScopeService.JdCategoryScope scope = readOnlyScope(GROUP_ID, COMPANY_ID);
when(scopeService.resolve(operator)).thenReturn(scope);
when(scopeService.readGroupOrNull(scope, null)).thenReturn(GROUP_ID);
// 读:菜单权限命中即放行(公共库一人一份全量)。
JdProductPageVo pageVo = new JdProductPageVo();
pageVo.setItems(List.of());
when(queryService.page(1L, 20L, null, null, null, null, null, null)).thenReturn(pageVo);
assertEquals(Boolean.TRUE, controller.page(1L, 20L, null, null, null, null, null, null, request).isSuccess(),
"非超管有菜单权限时读必须放行(读写分档只收窄写)");
when(queryService.page(1L, 20L, null, null, null, null, null, null, GROUP_ID)).thenReturn(pageVo);
assertEquals(Boolean.TRUE, controller.page(1L, 20L, null, null, null, null, null, null, null, request)
.isSuccess(), "非超管有菜单权限时读必须放行(读写分档只收窄写)");
// 写:五条写入口一律 403,且业务服务一次都没被调到(不能「先写再拒」)。
// 商品行写:四条写入口一律 403,且业务服务一次都没被调到(不能「先写再拒」)。
JdProductUpdateRequest updateBody = new JdProductUpdateRequest();
updateBody.setTitle("标题");
BusinessException updateEx = assertThrows(BusinessException.class,
@@ -262,14 +300,6 @@ class AdminJdProductControllerTest {
() -> controller.batchDelete(batchBody, request));
assertTrue(batchEx.getMessage().contains("仅平台超级管理员"));
JdProductBatchAssignGroupRequest assignBody = new JdProductBatchAssignGroupRequest();
assignBody.setIds(List.of(11L));
assignBody.setGroupId(3L);
BusinessException assignEx = assertThrows(BusinessException.class,
() -> controller.batchAssignGroup(assignBody, request));
assertTrue(assignEx.getMessage().contains("仅平台超级管理员"),
"批量归类会置人工编辑锁=写动作,必须同闸");
BusinessException uploadEx = assertThrows(BusinessException.class,
() -> controller.uploadImage(11L, mock(MultipartFile.class), "MAIN", null, null, request));
assertTrue(uploadEx.getMessage().contains("仅平台超级管理员"),
@@ -277,17 +307,18 @@ class AdminJdProductControllerTest {
verify(updateService, never()).update(any(), any());
verify(updateService, never()).uploadImage(any(), any(), any(), any(), any());
verify(updateService, never()).assignGroup(any(), any());
verify(updateService, never()).assignGroup(any(), any(), any(), any(), any());
verify(deleteService, never()).delete(any());
}
@Test
void 非超管有菜单权限时分组写一律403_读列表仍放行() {
void 不可写组的分组写一律403且不触服务() {
JdProductGroupService groupService = mock(JdProductGroupService.class);
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
AdminJdProductGroupController controller = new AdminJdProductGroupController(
groupService, authSupport, permissionMenuService);
groupService, scopeService, authSupport, permissionMenuService);
AdminUserEntity operator = new AdminUserEntity();
operator.setId(9L);
@@ -297,57 +328,146 @@ class AdminJdProductControllerTest {
PermissionMenuItemVo grant = new PermissionMenuItemVo();
grant.setColumnKey(COLUMN_KEY);
when(permissionMenuService.getUserColumnPermissions(9L, "admin")).thenReturn(List.of(grant));
when(groupService.list()).thenReturn(List.of());
// 普通号:组可见但不可写(四档矩阵在 JdCategoryScopeServiceTest 里钉,这里只钉控制器接线)。
JdCategoryScopeService.JdCategoryScope scope = readOnlyScope(GROUP_ID, COMPANY_ID);
when(scopeService.resolve(operator)).thenReturn(scope);
when(scopeService.readGroupOrNull(scope, null)).thenReturn(GROUP_ID);
when(groupService.list(GROUP_ID)).thenReturn(List.of());
when(groupService.requireCategory(7L)).thenReturn(category(7L, GROUP_ID));
// 真实作用域服务对「可见但不可写」的组回 403;mock 掉它只验控制器不吞、不触业务服务。
when(scopeService.requireWritableGroup(any(), any()))
.thenThrow(new BusinessException(403, "仅该分组的管理员可以修改它的分类"));
assertEquals(Boolean.TRUE, controller.list(request).isSuccess(),
"分类列表是读端点,菜单权限命中即放行(筛选下拉要能用)");
assertEquals(Boolean.TRUE, controller.list(null, request).isSuccess(),
"分类列表是读端点,菜单权限命中即放行(同组普通号也能开弹窗看)");
JdProductGroupSaveRequest saveBody = new JdProductGroupSaveRequest();
saveBody.setName("新分类");
saveBody.setSortOrder(0);
BusinessException createEx = assertThrows(BusinessException.class,
() -> controller.create(saveBody, request));
assertTrue(createEx.getMessage().contains("仅平台超级管理员"));
assertTrue(createEx.getMessage().contains("仅该分组的管理员"),
"新建成分类的 403 文案必须点名分组管理员");
// 改名/删除:控制器自己按分类归属判 canWrite(作用域不可写 ⇒ 403,业务服务不被调到)。
BusinessException renameEx = assertThrows(BusinessException.class,
() -> controller.rename(7L, saveBody, request));
assertTrue(renameEx.getMessage().contains("仅平台超级管理员"));
assertTrue(renameEx.getMessage().contains("仅该分组的管理员"));
BusinessException deleteEx = assertThrows(BusinessException.class,
() -> controller.delete(7L, request));
assertTrue(deleteEx.getMessage().contains("仅平台超级管理员"));
assertTrue(deleteEx.getMessage().contains("仅该分组的管理员"));
verify(groupService, never()).create(any(), any());
verify(groupService, never()).create(any(), any(), any(), any());
verify(groupService, never()).rename(any(), any(), any());
verify(groupService, never()).delete(any());
}
@Test
void 本组管理员可归类本组_组内写权限不再只归平台超管() {
JdProductQueryService queryService = mock(JdProductQueryService.class);
JdProductUpdateService updateService = mock(JdProductUpdateService.class);
JdProductGroupService groupService = mock(JdProductGroupService.class);
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
AdminJdProductController controller = new AdminJdProductController(
queryService, mock(JdProductDeleteService.class), updateService, groupService,
scopeService, authSupport, permissionMenuService);
AdminUserEntity operator = new AdminUserEntity();
operator.setId(9L);
HttpServletRequest request = mock(HttpServletRequest.class);
when(authSupport.requireUser(request)).thenReturn(operator);
// 组长(admin,非平台超管):拿到菜单权限即可归类自己带的组。
when(authSupport.currentRole(operator)).thenReturn("admin");
PermissionMenuItemVo grant = new PermissionMenuItemVo();
grant.setColumnKey(COLUMN_KEY);
when(permissionMenuService.getUserColumnPermissions(9L, "admin")).thenReturn(List.of(grant));
JdCategoryScopeService.JdCategoryScope scope = writableScope(GROUP_ID, COMPANY_ID);
when(scopeService.resolve(operator)).thenReturn(scope);
when(scopeService.requireWritableGroup(any(), any())).thenReturn(shopGroup(GROUP_ID, COMPANY_ID));
when(updateService.assignGroup(GROUP_ID, COMPANY_ID, List.of(11L, 12L), 3L, 9L)).thenReturn(2);
JdProductBatchAssignGroupRequest body = new JdProductBatchAssignGroupRequest();
body.setIds(List.of(11L, 12L));
body.setGroupId(3L);
ApiResponse<Integer> response = controller.batchAssignGroup(body, request);
verify(updateService).assignGroup(GROUP_ID, COMPANY_ID, List.of(11L, 12L), 3L, 9L);
assertEquals(Boolean.TRUE, response.isSuccess(), "放行必须是 success 信封(B80-03)");
assertEquals(2, response.getData(), "回执=实际写入的归属行数");
// 业务失败(目标分类不属于当前分组)文案原样透出,不吞。
when(updateService.assignGroup(GROUP_ID, COMPANY_ID, List.of(11L), 404L, 9L))
.thenThrow(new BusinessException(403, "该分类不属于当前分组,请刷新后重试"));
JdProductBatchAssignGroupRequest ghostBody = new JdProductBatchAssignGroupRequest();
ghostBody.setIds(List.of(11L));
ghostBody.setGroupId(404L);
BusinessException ex = assertThrows(BusinessException.class,
() -> controller.batchAssignGroup(ghostBody, request));
assertTrue(ex.getMessage().contains("不属于当前分组"));
}
@Test
void 分类筛选越组请求403且不触查询服务() {
JdProductQueryService queryService = mock(JdProductQueryService.class);
JdProductGroupService groupService = mock(JdProductGroupService.class);
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
AdminJdProductController controller = new AdminJdProductController(
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class),
groupService, scopeService, authSupport, mock(PermissionMenuService.class));
AdminUserEntity operator = new AdminUserEntity();
operator.setId(7L);
HttpServletRequest request = mock(HttpServletRequest.class);
when(authSupport.requireUser(request)).thenReturn(operator);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
JdCategoryScopeService.JdCategoryScope scope = readOnlyScope(GROUP_ID, COMPANY_ID);
when(scopeService.resolve(operator)).thenReturn(scope);
when(scopeService.readGroupOrNull(scope, null)).thenReturn(GROUP_ID);
// 分类 8 属于别组(ownerGroupId=20):按「当前分组」不可见 ⇒ 403,不放成空结果。
when(groupService.requireCategory(8L)).thenReturn(category(8L, 20L));
BusinessException ex = assertThrows(BusinessException.class,
() -> controller.page(1L, 20L, null, null, null, 8L, null, null, null, request));
assertTrue(ex.getMessage().contains("无权查看该分组的分类"),
"跨组分类筛选必须 403 点名分组,不做空结果降级");
verify(queryService, never()).page(any(), any(), any(), any(), any(), any(), any(), any(), any());
}
// ===================== 行为样本 =====================
@Test
void 控制器列表走requireJdAccess正门并把查询结果装进200信封() {
JdProductQueryService queryService = mock(JdProductQueryService.class);
JdProductGroupService groupService = mock(JdProductGroupService.class);
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
AdminJdProductController controller = new AdminJdProductController(
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class), authSupport,
permissionMenuService);
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class),
groupService, scopeService, authSupport, mock(PermissionMenuService.class));
AdminUserEntity operator = new AdminUserEntity();
operator.setId(7L);
HttpServletRequest request = mock(HttpServletRequest.class);
when(authSupport.requireUser(request)).thenReturn(operator);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
JdCategoryScopeService.JdCategoryScope scope = writableScope(GROUP_ID, COMPANY_ID);
when(scopeService.resolve(operator)).thenReturn(scope);
when(scopeService.readGroupOrNull(scope, GROUP_ID)).thenReturn(GROUP_ID);
JdProductPageVo pageVo = new JdProductPageVo();
pageVo.setItems(List.of());
pageVo.setTotal(0L);
pageVo.setPage(1L);
pageVo.setPageSize((long) PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT);
when(queryService.page(1L, 20L, null, null, null, null, null, null)).thenReturn(pageVo);
when(queryService.page(1L, 20L, null, null, null, null, null, null, GROUP_ID)).thenReturn(pageVo);
// 2026-11-16 起请求面没有 company_id:任何授权身份看到的都是同一份全量。
ApiResponse<JdProductPageVo> response = controller.page(1L, 20L, null, null, null, null, null,
null, request);
// 请求面没有 company_id:任何授权身份看到的都是同一份全量;分类列按 owner_group_id 取。
ApiResponse<JdProductPageVo> response = controller.page(1L, 20L, null, null, null, null,
GROUP_ID, null, null, request);
verify(queryService).page(1L, 20L, null, null, null, null, null, null);
verify(queryService).page(1L, 20L, null, null, null, null, null, null, GROUP_ID);
assertEquals(Boolean.TRUE, response.isSuccess(), "拒绝走 403 业务码,放行必须是 success 信封(B80-03)");
assertEquals(pageVo, response.getData());
}
@@ -355,10 +475,12 @@ class AdminJdProductControllerTest {
@Test
void 旧分类筛选参数明确拒绝并提示刷新() {
JdProductQueryService queryService = mock(JdProductQueryService.class);
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
AdminJdProductController controller = new AdminJdProductController(
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class),
authSupport, mock(PermissionMenuService.class));
mock(JdProductGroupService.class), scopeService, authSupport,
mock(PermissionMenuService.class));
AdminUserEntity operator = new AdminUserEntity();
operator.setId(7L);
HttpServletRequest request = mock(HttpServletRequest.class);
@@ -369,12 +491,12 @@ class AdminJdProductControllerTest {
for (String value : List.of("true", "false", "")) {
when(request.getParameter(name)).thenReturn(value);
BusinessException ex = assertThrows(BusinessException.class,
() -> controller.page(1L, 20L, null, null, null, 7L, null, null, request));
() -> controller.page(1L, 20L, null, null, null, 7L, null, null, null, request));
assertTrue(ex.getMessage().contains("刷新页面"));
when(request.getParameter(name)).thenReturn(null);
}
}
verify(queryService, never()).page(any(), any(), any(), any(), any(), any(), any(), any());
verify(queryService, never()).page(any(), any(), any(), any(), any(), any(), any(), any(), any());
}
@Test
@@ -382,7 +504,8 @@ class AdminJdProductControllerTest {
JdProductQueryService queryService = mock(JdProductQueryService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
AdminJdProductController controller = new AdminJdProductController(
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class), authSupport,
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class),
mock(JdProductGroupService.class), mock(JdCategoryScopeService.class), authSupport,
mock(PermissionMenuService.class));
AdminUserEntity operator = new AdminUserEntity();
@@ -406,9 +529,11 @@ class AdminJdProductControllerTest {
@Test
void 控制器详情走同一鉴权正门并回详情且不问公司() {
JdProductQueryService queryService = mock(JdProductQueryService.class);
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
AdminJdProductController controller = new AdminJdProductController(
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class), authSupport,
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class),
mock(JdProductGroupService.class), scopeService, authSupport,
mock(PermissionMenuService.class));
AdminUserEntity operator = new AdminUserEntity();
@@ -416,14 +541,18 @@ class AdminJdProductControllerTest {
HttpServletRequest request = mock(HttpServletRequest.class);
when(authSupport.requireUser(request)).thenReturn(operator);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
JdCategoryScopeService.JdCategoryScope scope = writableScope(GROUP_ID, COMPANY_ID);
when(scopeService.resolve(operator)).thenReturn(scope);
when(scopeService.readGroupOrNull(scope, null)).thenReturn(GROUP_ID);
JdProductDetailVo detailVo = new JdProductDetailVo();
detailVo.setId(11L);
when(queryService.detail(11L)).thenReturn(detailVo);
when(queryService.detail(11L, GROUP_ID)).thenReturn(detailVo);
ApiResponse<JdProductDetailVo> response = controller.detail(11L, request);
ApiResponse<JdProductDetailVo> response = controller.detail(11L, null, request);
// 公共库详情没有公司维度(DataReadScope 反向钉在结构判据支,2026-11-16 已整批摘除)。
verify(queryService).detail(11L);
// 公共库详情没有公司维度(DataReadScope 反向钉在结构判据支,2026-11-16 已整批摘除);
// 分类字段按「当前分组」取(V203)。
verify(queryService).detail(11L, GROUP_ID);
assertEquals(Boolean.TRUE, response.isSuccess());
assertEquals(detailVo, response.getData());
}
@@ -434,7 +563,8 @@ class AdminJdProductControllerTest {
JdProductDeleteService deleteService = mock(JdProductDeleteService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
AdminJdProductController controller = new AdminJdProductController(
queryService, deleteService, mock(JdProductUpdateService.class), authSupport,
queryService, deleteService, mock(JdProductUpdateService.class),
mock(JdProductGroupService.class), mock(JdCategoryScopeService.class), authSupport,
mock(PermissionMenuService.class));
AdminUserEntity operator = new AdminUserEntity();
@@ -462,7 +592,8 @@ class AdminJdProductControllerTest {
JdProductDeleteService deleteService = mock(JdProductDeleteService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
AdminJdProductController controller = new AdminJdProductController(
queryService, deleteService, mock(JdProductUpdateService.class), authSupport,
queryService, deleteService, mock(JdProductUpdateService.class),
mock(JdProductGroupService.class), mock(JdCategoryScopeService.class), authSupport,
mock(PermissionMenuService.class));
AdminUserEntity operator = new AdminUserEntity();
@@ -483,13 +614,11 @@ class AdminJdProductControllerTest {
@Test
void 查询服务分页钳制防溢出() {
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
JdProductQueryService service = queryService(mapper);
when(mapper.countProducts(any(), any(), any(), any(), any(), any())).thenReturn(1L);
// page=0 / size=null ⇒ 归一为第 1 页、默认 20 条;offset = 0。
service.page(0L, null, null, null, null, null, null, null);
service.page(0L, null, null, null, null, null, null, null, null);
ArgumentCaptor<Long> offset = ArgumentCaptor.forClass(Long.class);
ArgumentCaptor<Integer> limit = ArgumentCaptor.forClass(Integer.class);
verify(mapper).selectProductPage(isNull(), isNull(), isNull(), isNull(), isNull(), isNull(),
@@ -498,7 +627,7 @@ class AdminJdProductControllerTest {
assertEquals(PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT, limit.getValue());
// page=Long.MAX_VALUE / size=500 ⇒ 钳到 10_000 页、100 条;乘积 999_900 不得变负(铁律 15)。
service.page(Long.MAX_VALUE, 500L, null, null, null, null, null, null);
service.page(Long.MAX_VALUE, 500L, null, null, null, null, null, null, null);
ArgumentCaptor<Long> offsetMax = ArgumentCaptor.forClass(Long.class);
ArgumentCaptor<Integer> limitMax = ArgumentCaptor.forClass(Integer.class);
verify(mapper, times(2)).selectProductPage(any(), any(), any(), any(), any(), any(),
@@ -510,13 +639,11 @@ class AdminJdProductControllerTest {
@Test
void 查询服务同步起止倒挂拒绝() {
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
JdProductQueryService service = queryService(mapper);
LocalDateTime from = LocalDateTime.of(2026, 11, 14, 12, 0);
LocalDateTime to = LocalDateTime.of(2026, 11, 14, 8, 0);
BusinessException ex = assertThrows(BusinessException.class,
() -> service.page(1L, 20L, null, null, null, null, from, to));
() -> service.page(1L, 20L, null, null, null, null, from, to, null));
assertTrue(ex.getMessage().contains("开始时间不能晚于结束时间"), "倒挂时间按业务异常拒绝");
verify(mapper, never()).countProducts(any(), any(), any(), any(), any(), any());
}
@@ -524,65 +651,22 @@ class AdminJdProductControllerTest {
@Test
void 查询服务过滤面原样直传且空串归null() {
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
JdProductQueryService service = queryService(mapper);
when(mapper.countProducts(any(), any(), any(), any(), any(), any())).thenReturn(1L);
service.page(1L, 20L, " SKU-1 ", " 连衣裙 ", " 艺考形体服 ", 7L, null, null);
service.page(1L, 20L, " SKU-1 ", " 连衣裙 ", " 艺考形体服 ", 7L, null, null, null);
verify(mapper).countProducts("SKU-1", "连衣裙", "艺考形体服", 7L, null, null);
verify(mapper).selectProductPage("SKU-1", "连衣裙", "艺考形体服", 7L, null, null, 0L, 20);
service.page(1L, 20L, " ", null, null, 0L, null, null);
service.page(1L, 20L, " ", null, null, 0L, null, null, null);
verify(mapper).countProducts(null, null, null, null, null, null);
verify(mapper).selectProductPage(null, null, null, null, null, null, 0L, 20);
}
@Test
void 批量归类端点走同一鉴权正门且参数透传() {
JdProductQueryService queryService = mock(JdProductQueryService.class);
JdProductUpdateService updateService = mock(JdProductUpdateService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
AdminJdProductController controller = new AdminJdProductController(
queryService, mock(JdProductDeleteService.class), updateService, authSupport,
mock(PermissionMenuService.class));
AdminUserEntity operator = new AdminUserEntity();
operator.setId(7L);
HttpServletRequest request = mock(HttpServletRequest.class);
when(authSupport.requireUser(request)).thenReturn(operator);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
when(updateService.assignGroup(List.of(11L, 12L), 3L)).thenReturn(2);
com.nanri.aiimage.modules.jd.model.dto.JdProductBatchAssignGroupRequest body =
new com.nanri.aiimage.modules.jd.model.dto.JdProductBatchAssignGroupRequest();
body.setIds(List.of(11L, 12L));
body.setGroupId(3L);
ApiResponse<Integer> response = controller.batchAssignGroup(body, request);
// 公共库写侧没有公司维度(结构判据支反向钉 company_id/DataReadScope 不得回流)。
verify(updateService).assignGroup(List.of(11L, 12L), 3L);
assertEquals(Boolean.TRUE, response.isSuccess(), "放行必须是 success 信封(B80-03)");
assertEquals(2, response.getData(), "回执=实际更新的行数");
// 业务失败(目标分类不存在)文案原样透出,不吞。
when(updateService.assignGroup(List.of(11L), 404L))
.thenThrow(new BusinessException("分类不存在,请刷新分类后重试"));
com.nanri.aiimage.modules.jd.model.dto.JdProductBatchAssignGroupRequest ghostBody =
new com.nanri.aiimage.modules.jd.model.dto.JdProductBatchAssignGroupRequest();
ghostBody.setIds(List.of(11L));
ghostBody.setGroupId(404L);
BusinessException ex = assertThrows(BusinessException.class,
() -> controller.batchAssignGroup(ghostBody, request));
assertTrue(ex.getMessage().contains("分类不存在"));
}
@Test
void 详情解析attr_json的tabs映射成attrGroups() {
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductImageMapper imageMapper = mock(JdProductImageMapper.class);
JdProductQueryService service = new JdProductQueryService(mapper, imageMapper,
mock(com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
JdProductQueryService service = queryService(mapper, imageMapper);
JdProductEntity row = productEntity(11L);
// 客户端实拍契约:tabs[{tab, attrs[{key,label,value}]}];value 允许数字型 JSON 值(转字符串)。
@@ -603,7 +687,7 @@ class AdminJdProductControllerTest {
image.setHeight(800);
when(imageMapper.selectList(any())).thenReturn(List.of(image));
JdProductDetailVo vo = service.detail(11L);
JdProductDetailVo vo = service.detail(11L, null);
assertEquals(2, vo.getAttrGroups().size(), "tabs 数组逐个映射成 attrGroups(groupName=tab 字段)");
assertEquals("商品基本信息", vo.getAttrGroups().get(0).getGroupName());
@@ -626,15 +710,13 @@ class AdminJdProductControllerTest {
@Test
void 详情非法attr_json落空分组且原文兜底不抛500() {
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
JdProductQueryService service = queryService(mapper);
// 形状一:非法 JSON(解析异常)。
JdProductEntity broken = productEntity(11L);
broken.setAttrJson("{\"tabs\": [broken");
when(mapper.selectById(11L)).thenReturn(broken);
JdProductDetailVo brokenVo = service.detail(11L);
JdProductDetailVo brokenVo = service.detail(11L, null);
assertTrue(brokenVo.getAttrGroups().isEmpty(), "解析异常落空 attrGroups,不抛 500(AC-7)");
assertEquals("{\"tabs\": [broken", brokenVo.getAttrJsonRaw(), "原文进 attrJsonRaw 兜底展示");
@@ -642,7 +724,7 @@ class AdminJdProductControllerTest {
JdProductEntity foreign = productEntity(11L);
foreign.setAttrJson("{\"attrs\":[{\"key\":\"x\",\"value\":\"y\"}]}");
when(mapper.selectById(11L)).thenReturn(foreign);
JdProductDetailVo foreignVo = service.detail(11L);
JdProductDetailVo foreignVo = service.detail(11L, null);
assertTrue(foreignVo.getAttrGroups().isEmpty(), "非契约形状落空 attrGroups");
assertEquals("{\"attrs\":[{\"key\":\"x\",\"value\":\"y\"}]}", foreignVo.getAttrJsonRaw(),
"未识别属性不丢弃:原文兜底透出(AC-7)");
@@ -651,7 +733,7 @@ class AdminJdProductControllerTest {
JdProductEntity blank = productEntity(11L);
blank.setAttrJson(null);
when(mapper.selectById(11L)).thenReturn(blank);
JdProductDetailVo blankVo = service.detail(11L);
JdProductDetailVo blankVo = service.detail(11L, null);
assertTrue(blankVo.getAttrGroups().isEmpty());
assertNull(blankVo.getAttrJsonRaw());
}
@@ -659,11 +741,8 @@ class AdminJdProductControllerTest {
@Test
void 详情下发SKU矩阵_销售属性JSON解析成键值对() {
JdProductMapper mapper = mock(JdProductMapper.class);
com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper skuMapper =
mock(com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper.class);
JdProductQueryService service = new JdProductQueryService(mapper,
mock(JdProductImageMapper.class), skuMapper,
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
JdProductSkuMapper skuMapper = mock(JdProductSkuMapper.class);
JdProductQueryService service = queryService(mapper, mock(JdProductImageMapper.class), skuMapper);
when(mapper.selectById(11L)).thenReturn(productEntity(11L));
@@ -683,7 +762,7 @@ class AdminJdProductControllerTest {
brokenJson.setSaleAttrsJson("[{\"name\":");
when(skuMapper.selectList(any())).thenReturn(List.of(first, brokenJson));
JdProductDetailVo vo = service.detail(11L);
JdProductDetailVo vo = service.detail(11L, null);
assertEquals(2, vo.getSkus().size(), "京麦那 12 行矩阵按入库行下发(抽屉渲染的唯一来源)");
JdProductDetailVo.SkuVo sku = vo.getSkus().get(0);
@@ -702,55 +781,158 @@ class AdminJdProductControllerTest {
@Test
void 详情按公共库直取_缺失按不存在拒绝() {
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
JdProductQueryService service = queryService(mapper);
// 公共库(2026-11-15 用户定案):详情没有公司维度,别家公司时代的行照样可读。
JdProductEntity row = productEntity(11L);
row.setCompanyId(6L);
when(mapper.selectById(11L)).thenReturn(row);
assertNotNull(service.detail(11L));
assertNotNull(service.detail(11L, null));
// 行不存在 ⇒ 按「商品不存在」拒绝。
when(mapper.selectById(11L)).thenReturn(null);
BusinessException ex = assertThrows(BusinessException.class, () -> service.detail(11L));
BusinessException ex = assertThrows(BusinessException.class, () -> service.detail(11L, null));
assertTrue(ex.getMessage().contains("商品不存在"));
// id 非法同样拒绝。
assertThrows(BusinessException.class, () -> service.detail(0L));
assertThrows(BusinessException.class, () -> service.detail(0L, null));
}
@Test
void 列表行分组名批量补齐且读不到不猜() {
void 列表行分类名按当前分组批量补齐且读不到不猜() {
JdProductMapper mapper = mock(JdProductMapper.class);
com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper groupMapper =
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class);
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper.class),
groupMapper);
JdProductGroupMapper categoryMapper = mock(JdProductGroupMapper.class);
JdProductGroupAssignMapper assignMapper = mock(JdProductGroupAssignMapper.class);
JdProductQueryService service = queryService(mapper, mock(JdProductImageMapper.class),
mock(JdProductSkuMapper.class), categoryMapper, assignMapper);
JdProductEntity grouped = productEntity(1L);
grouped.setGroupId(3L);
JdProductEntity categorized = productEntity(1L);
JdProductEntity missing = productEntity(2L);
missing.setGroupId(99L);
when(mapper.countProducts(any(), any(), any(), any(), any(), any())).thenReturn(2L);
when(mapper.selectProductPage(any(), any(), any(), any(), any(), any(),
anyLong(), anyInt())).thenReturn(List.of(grouped, missing));
com.nanri.aiimage.modules.jd.model.entity.JdProductGroupEntity group =
new com.nanri.aiimage.modules.jd.model.entity.JdProductGroupEntity();
group.setId(3L);
group.setName("秋冬款");
when(groupMapper.selectBatchIds(any())).thenReturn(List.of(group));
anyLong(), anyInt())).thenReturn(List.of(categorized, missing));
when(assignMapper.selectList(any())).thenReturn(List.of(
assign(1L, GROUP_ID, 3L), assign(2L, GROUP_ID, 99L)));
JdProductGroupEntity category = new JdProductGroupEntity();
category.setId(3L);
category.setName("秋冬款");
when(categoryMapper.selectBatchIds(any())).thenReturn(List.of(category));
JdProductPageVo vo = service.page(1L, 20L, null, null, null, null, null, null);
JdProductPageVo vo = service.page(1L, 20L, null, null, null, null, null, null, GROUP_ID);
assertEquals("秋冬款", vo.getItems().get(0).getGroupName(), "行集 group_id 一次取齐分组名(无逐行查询)");
assertNull(vo.getItems().get(1).getGroupName(), "分组已删=不猜名字(铁律 30),前端展示 -");
verify(groupMapper, times(1)).selectBatchIds(any());
assertEquals(3L, vo.getItems().get(0).getGroupId(), "分类 id 取本组归属行");
assertEquals("秋冬款", vo.getItems().get(0).getGroupName(), "行集归属一次取齐分类名(无逐行查询)");
assertNull(vo.getItems().get(1).getGroupName(), "分类已删=不猜名字(铁律 30),前端展示 -");
verify(assignMapper, times(1)).selectList(any());
verify(categoryMapper, times(1)).selectBatchIds(any());
}
@Test
void 列表无当前分组时分类列全空且不发归属查询() {
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductGroupAssignMapper assignMapper = mock(JdProductGroupAssignMapper.class);
JdProductQueryService service = queryService(mapper, mock(JdProductImageMapper.class),
mock(JdProductSkuMapper.class), mock(JdProductGroupMapper.class), assignMapper);
when(mapper.countProducts(any(), any(), any(), any(), any(), any())).thenReturn(1L);
when(mapper.selectProductPage(any(), any(), any(), any(), any(), any(),
anyLong(), anyInt())).thenReturn(List.of(productEntity(1L)));
JdProductPageVo vo = service.page(1L, 20L, null, null, null, null, null, null, null);
assertNull(vo.getItems().get(0).getGroupId(), "不属于任何分组的账号:分类列一律空(未分类)");
assertNull(vo.getItems().get(0).getGroupName());
verify(assignMapper, never()).selectList(any());
}
@Test
void 详情分类按当前分组取_别的组归类不可见() {
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductGroupAssignMapper assignMapper = mock(JdProductGroupAssignMapper.class);
JdProductGroupMapper categoryMapper = mock(JdProductGroupMapper.class);
JdProductQueryService service = queryService(mapper, mock(JdProductImageMapper.class),
mock(JdProductSkuMapper.class), categoryMapper, assignMapper);
when(mapper.selectById(11L)).thenReturn(productEntity(11L));
// 本组(10)没归类:detail 的 selectOne 回 null ⇒ 分类字段空。
when(assignMapper.selectOne(any())).thenReturn(null);
JdProductDetailVo untouched = service.detail(11L, GROUP_ID);
assertNull(untouched.getGroupId(), "本组没归类=未分类,不拿别组的归属顶上");
assertNull(untouched.getGroupName());
// 本组归类到 3:取到分类名。
when(assignMapper.selectOne(any())).thenReturn(assign(11L, GROUP_ID, 3L));
JdProductGroupEntity category = new JdProductGroupEntity();
category.setId(3L);
category.setName("秋冬款");
when(categoryMapper.selectBatchIds(any())).thenReturn(List.of(category));
JdProductDetailVo categorized = service.detail(11L, GROUP_ID);
assertEquals(3L, categorized.getGroupId());
assertEquals("秋冬款", categorized.getGroupName());
}
// ---------------------------------------------------------------- 助手
/** 查询服务夹具:默认四个从属 mapper 全 mock,只有 assign mapper 可注入。 */
private static JdProductQueryService queryService(JdProductMapper mapper) {
return queryService(mapper, mock(JdProductImageMapper.class), mock(JdProductSkuMapper.class),
mock(JdProductGroupMapper.class), mock(JdProductGroupAssignMapper.class));
}
private static JdProductQueryService queryService(JdProductMapper mapper, JdProductImageMapper imageMapper) {
return queryService(mapper, imageMapper, mock(JdProductSkuMapper.class),
mock(JdProductGroupMapper.class), mock(JdProductGroupAssignMapper.class));
}
private static JdProductQueryService queryService(JdProductMapper mapper, JdProductImageMapper imageMapper,
JdProductSkuMapper skuMapper) {
return queryService(mapper, imageMapper, skuMapper,
mock(JdProductGroupMapper.class), mock(JdProductGroupAssignMapper.class));
}
private static JdProductQueryService queryService(JdProductMapper mapper, JdProductImageMapper imageMapper,
JdProductSkuMapper skuMapper, JdProductGroupMapper categoryMapper,
JdProductGroupAssignMapper assignMapper) {
return new JdProductQueryService(mapper, imageMapper, skuMapper, categoryMapper, assignMapper);
}
/** 可写作用域(组长/公司超管/平台超管同形:可见组=可写组)。 */
private static JdCategoryScopeService.JdCategoryScope writableScope(long groupId, long companyId) {
return new JdCategoryScopeService.JdCategoryScope(false, companyId,
List.of(groupId), List.of(groupId),
List.of(new JdCategoryGroupOptionVo(groupId, "默认组", "默认组", true)));
}
/** 只读作用域(组内普通号:可见不可写)。 */
private static JdCategoryScopeService.JdCategoryScope readOnlyScope(long groupId, long companyId) {
return new JdCategoryScopeService.JdCategoryScope(false, companyId,
List.of(groupId), List.of(),
List.of(new JdCategoryGroupOptionVo(groupId, "默认组", "默认组", false)));
}
private static ShopManageGroupEntity shopGroup(long id, long companyId) {
ShopManageGroupEntity group = new ShopManageGroupEntity();
group.setId(id);
group.setCompanyId(companyId);
group.setGroupName("默认组");
return group;
}
private static JdProductGroupEntity category(long id, long ownerGroupId) {
JdProductGroupEntity entity = new JdProductGroupEntity();
entity.setId(id);
entity.setOwnerGroupId(ownerGroupId);
entity.setCompanyId(COMPANY_ID);
entity.setName("分类-" + id);
return entity;
}
private static JdProductGroupAssignEntity assign(long productId, long ownerGroupId, long categoryId) {
JdProductGroupAssignEntity entity = new JdProductGroupAssignEntity();
entity.setProductId(productId);
entity.setOwnerGroupId(ownerGroupId);
entity.setCategoryId(categoryId);
return entity;
}
/** 列表/详情用例共用的商品行夹具:归属公司 5,主字段齐备便于按字段对撞。 */
private static JdProductEntity productEntity(long id) {
JdProductEntity entity = new JdProductEntity();
@@ -2,7 +2,9 @@ package com.nanri.aiimage.modules.jd.controller;
import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.jd.model.vo.JdCategoryGroupOptionVo;
import com.nanri.aiimage.modules.jd.model.vo.JdProductGroupVo;
import com.nanri.aiimage.modules.jd.service.JdCategoryScopeService;
import com.nanri.aiimage.modules.jd.service.JdCollectBoardService;
import com.nanri.aiimage.modules.jd.service.JdCollectTaskService;
import com.nanri.aiimage.modules.jd.service.JdProductGroupService;
@@ -32,30 +34,38 @@ import static org.mockito.Mockito.when;
* 用户侧「店铺分类」只读端点(2026-11-16 客户口径「管理员弄了多少店铺分类 普通账户都能看到」)。
*
* <p>「获取店铺数据」页把管理员在后管京东数据库建的分类展示给普通账号:GET /api/jd-collect/groups,
* 与 categories 端点同形(登录用户即可读、fail-closed 401;分组全平台一份、无公司维度)。
* 只读不写——分类的增删改仍只在后管 AdminJdProductGroupController。结构判据(照
* {@code AdminJdProductControllerTest} 双形态的第一半)+行为样本(200 信封装 list、鉴权先过)。</p>
* 与 categories 端点同形(登录用户即可读、fail-closed 401)。
* <b>V203 起按数据权限分组隔离</b>:只下发登录用户<b>可见组</b>的分类(「不同组不能看到跨组的分类」),
* 收窄由 {@code JdCategoryScopeService.resolveByUserId} 出,本端点不自己判角色。
* 只读不写——分类的增删改仍只在后管 AdminJdProductGroupController。</p>
*/
class JdCollectGroupsEndpointTest {
private static final Path CONTROLLER = Path.of("").toAbsolutePath()
.resolve("src/main/java/com/nanri/aiimage/modules/jd/controller/JdCollectController.java");
private static final long USER_ID = 1L;
private static final long GROUP_ID = 10L;
@Test
void 结构判据_groups端点只读且复用分组服务公共口径() throws IOException {
void 结构判据_groups端点只读且按可见组收窄() throws IOException {
assertTrue(Files.exists(CONTROLLER), "控制器必须落在 " + CONTROLLER);
String source = Files.readString(CONTROLLER);
assertTrue(source.contains("@GetMapping(\"/groups\")"),
"用户侧分类列表必须是 GET /groups(categories 同形)");
assertTrue(source.contains("jdProductGroupService.list()"),
"必须复用 JdProductGroupService.list()(与后管分组管理同一条读出口,不另造查询)");
assertTrue(source.contains("jdCategoryScopeService.resolveByUserId(userId)"),
"可见组必须由 JdCategoryScopeService 按登录用户解析(端点不自己判角色)");
assertTrue(source.contains("jdProductGroupService.listForGroups(scope.visibleGroupIds())"),
"必须按可见组取分类(listForGroups),不得退回 list() 全量下发"
+ "——否则普通号仍能看到别组的分类");
assertTrue(source.contains("adminAuthSupport.requireOwnershipUserId(httpRequest, null)"),
"登录用户即可读但必须 fail-closed:解析不出会话身份就 401(与 categories 同口径)");
}
@Test
void 行为样本_鉴权先过且200信封装分组全量() {
void 行为样本_鉴权先过且200信封只装可见组的分类() {
JdProductGroupService groupService = mock(JdProductGroupService.class);
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
JdCollectController controller = new JdCollectController(
mock(JdCollectTaskService.class),
@@ -63,6 +73,7 @@ class JdCollectGroupsEndpointTest {
mock(JdResultIngestService.class),
mock(JdProductQueryService.class),
groupService,
scopeService,
mock(TaskHeartbeatService.class),
mock(TaskHeartbeatPositionService.class),
mock(TaskProgressOwnershipSupport.class),
@@ -72,9 +83,11 @@ class JdCollectGroupsEndpointTest {
JdProductGroupVo vo = new JdProductGroupVo();
vo.setId(7L);
vo.setName("ASSS");
vo.setOwnerGroupId(GROUP_ID);
vo.setProductCount(20L);
when(authSupport.requireOwnershipUserId(same(request), isNull())).thenReturn(1L);
when(groupService.list()).thenReturn(List.of(vo));
when(authSupport.requireOwnershipUserId(same(request), isNull())).thenReturn(USER_ID);
when(scopeService.resolveByUserId(USER_ID)).thenReturn(scope(GROUP_ID));
when(groupService.listForGroups(List.of(GROUP_ID))).thenReturn(List.of(vo));
ApiResponse<List<JdProductGroupVo>> response = controller.groups(request);
@@ -83,9 +96,44 @@ class JdCollectGroupsEndpointTest {
assertNotNull(response.getData());
assertEquals(1, response.getData().size());
assertEquals("ASSS", response.getData().get(0).getName());
assertEquals(GROUP_ID, response.getData().get(0).getOwnerGroupId());
assertEquals(20L, response.getData().get(0).getProductCount());
// 鉴权闸先行:解析不出会话身份就 401,读不到任何数据。
verify(authSupport).requireOwnershipUserId(same(request), isNull());
verify(groupService).list();
verify(scopeService).resolveByUserId(USER_ID);
verify(groupService).listForGroups(List.of(GROUP_ID));
}
@Test
void 行为样本_不属于任何分组时下发空列表() {
JdProductGroupService groupService = mock(JdProductGroupService.class);
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
JdCollectController controller = new JdCollectController(
mock(JdCollectTaskService.class),
mock(JdCollectBoardService.class),
mock(JdResultIngestService.class),
mock(JdProductQueryService.class),
groupService,
scopeService,
mock(TaskHeartbeatService.class),
mock(TaskHeartbeatPositionService.class),
mock(TaskProgressOwnershipSupport.class),
authSupport);
HttpServletRequest request = mock(HttpServletRequest.class);
when(authSupport.requireOwnershipUserId(same(request), isNull())).thenReturn(USER_ID);
when(scopeService.resolveByUserId(USER_ID)).thenReturn(JdCategoryScopeService.JdCategoryScope.empty());
when(groupService.listForGroups(List.of())).thenReturn(List.of());
ApiResponse<List<JdProductGroupVo>> response = controller.groups(request);
assertTrue(response.isSuccess());
assertTrue(response.getData().isEmpty(), "一个可见组都没有 ⇒ 空列表(不降级成全平台分类)");
verify(groupService).listForGroups(List.of());
}
private static JdCategoryScopeService.JdCategoryScope scope(long groupId) {
return new JdCategoryScopeService.JdCategoryScope(false, 5L, List.of(groupId), List.of(),
List.of(new JdCategoryGroupOptionVo(groupId, "默认组", "默认组", false)));
}
}
@@ -0,0 +1,272 @@
package com.nanri.aiimage.modules.jd.service;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.mapper.ShopManageGroupMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.model.entity.ShopManageGroupEntity;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.modules.company.mapper.CompanyMapper;
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
import com.nanri.aiimage.modules.jd.model.vo.JdCategoryGroupOptionVo;
import com.nanri.aiimage.modules.jd.model.vo.JdCategoryScopeVo;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
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.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* 京东数据库分类「当前分组」作用域判据(V203;2026-11-16 用户口径)。
*
* <p>四档矩阵:平台超管=全部公司全部组可读可写;公司超管=本公司全部组;
* 管理员(组长)=自己带的组可写、自己所属组的组长带的分组只读;
* 普通号=与管理员同可见、<b>零可写</b>(能开弹窗看,不能增删改分类、不能归类)。
* 另钉三条收敛语义:不可见组读 403(不做空结果降级)、无分组上下文读回 null(页面照常可用)、
* 写侧在「无可写组 / 多可写组未选 / 该组不可写 / 组行不存在」四种形状下的文案。</p>
*/
@ExtendWith(MockitoExtension.class)
class JdCategoryScopeServiceTest {
private static final long USER_ID = 9L;
private static final long COMPANY_ID = 5L;
@Mock
private AdminAuthSupport adminAuthSupport;
@Mock
private DataReadScope dataReadScope;
@Mock
private AdminUserMapper adminUserMapper;
@Mock
private ShopManageGroupMapper shopManageGroupMapper;
@Mock
private CompanyMapper companyMapper;
@InjectMocks
private JdCategoryScopeService service;
// ---------------------------------------------------------------- 四档矩阵
@Test
void 平台超管_可见并可写全部公司全部组且组名带公司前缀() {
AdminUserEntity operator = user(USER_ID, COMPANY_ID);
when(adminAuthSupport.currentRole(operator)).thenReturn("super_admin");
when(dataReadScope.isPlatformSuperAdmin(operator)).thenReturn(true);
when(shopManageGroupMapper.selectAllGroups()).thenReturn(List.of(
group(10L, 1L, "A组"), group(20L, 2L, "B组")));
CompanyEntity first = new CompanyEntity();
first.setId(1L);
first.setCompanyName("甲公司");
CompanyEntity second = new CompanyEntity();
second.setId(2L);
second.setCompanyName("乙公司");
when(companyMapper.selectBatchIds(any())).thenReturn(List.of(first, second));
JdCategoryScopeService.JdCategoryScope scope = service.resolve(operator);
assertThat(scope.platformSuperAdmin()).isTrue();
assertThat(scope.visibleGroupIds()).containsExactly(10L, 20L);
assertThat(scope.writableGroupIds()).containsExactly(10L, 20L);
assertThat(scope.defaultGroupId()).isEqualTo(10L);
assertThat(scope.groups()).extracting(JdCategoryGroupOptionVo::getLabel)
.containsExactly("甲公司 / A组", "乙公司 / B组");
assertThat(scope.groups()).allMatch(JdCategoryGroupOptionVo::isEditable);
assertThat(scope.canRead(20L)).isTrue();
assertThat(scope.canWrite(20L)).isTrue();
}
@Test
void 公司超管_本公司全部组可读可写() {
AdminUserEntity operator = user(USER_ID, COMPANY_ID);
when(adminAuthSupport.currentRole(operator)).thenReturn("company_super_admin");
when(dataReadScope.isPlatformSuperAdmin(operator)).thenReturn(false);
when(shopManageGroupMapper.selectList(any())).thenReturn(List.of(
group(10L, COMPANY_ID, "A组"), group(11L, COMPANY_ID, "B组")));
JdCategoryScopeService.JdCategoryScope scope = service.resolve(operator);
assertThat(scope.platformSuperAdmin()).isFalse();
assertThat(scope.visibleGroupIds()).containsExactly(10L, 11L);
assertThat(scope.writableGroupIds()).containsExactly(10L, 11L);
assertThat(scope.groups()).extracting(JdCategoryGroupOptionVo::getLabel)
.containsExactly("A组", "B组");
// 公司超管的公司维只用来取组,不随 scope 下发公司字段给前端(label 里已拼好)。
verify(companyMapper, never()).selectBatchIds(any());
}
@Test
void 组长_自己带的组可写_自己所属组的组长带的分组只读() {
AdminUserEntity operator = user(USER_ID, COMPANY_ID);
when(adminAuthSupport.currentRole(operator)).thenReturn("admin");
when(dataReadScope.isPlatformSuperAdmin(operator)).thenReturn(false);
when(shopManageGroupMapper.selectLedGroups(USER_ID)).thenReturn(List.of(group(10L, COMPANY_ID, "自己的组")));
when(shopManageGroupMapper.selectLeaderIdsByMemberUserId(USER_ID)).thenReturn(List.of(3L));
when(shopManageGroupMapper.selectLedGroups(3L)).thenReturn(List.of(group(11L, COMPANY_ID, "上司的组")));
JdCategoryScopeService.JdCategoryScope scope = service.resolve(operator);
assertThat(scope.visibleGroupIds()).containsExactly(10L, 11L);
assertThat(scope.writableGroupIds()).containsExactly(10L);
assertThat(scope.canRead(11L)).isTrue();
assertThat(scope.canWrite(11L)).isFalse();
}
@Test
void 普通号_可见同组长但零可写() {
AdminUserEntity operator = user(USER_ID, COMPANY_ID);
when(adminAuthSupport.currentRole(operator)).thenReturn("normal");
when(dataReadScope.isPlatformSuperAdmin(operator)).thenReturn(false);
when(shopManageGroupMapper.selectLedGroups(USER_ID)).thenReturn(List.of());
when(shopManageGroupMapper.selectLeaderIdsByMemberUserId(USER_ID)).thenReturn(List.of(3L));
when(shopManageGroupMapper.selectLedGroups(3L)).thenReturn(List.of(group(10L, COMPANY_ID, "A组")));
JdCategoryScopeService.JdCategoryScope scope = service.resolve(operator);
assertThat(scope.visibleGroupIds()).containsExactly(10L);
assertThat(scope.writableGroupIds()).isEmpty();
assertThat(scope.groups()).singleElement()
.satisfies(option -> assertThat(option.isEditable()).isFalse());
}
@Test
void 不属于任何分组的账号_空作用域不报错() {
AdminUserEntity operator = user(USER_ID, COMPANY_ID);
when(adminAuthSupport.currentRole(operator)).thenReturn("normal");
when(dataReadScope.isPlatformSuperAdmin(operator)).thenReturn(false);
when(shopManageGroupMapper.selectLedGroups(USER_ID)).thenReturn(List.of());
when(shopManageGroupMapper.selectLeaderIdsByMemberUserId(USER_ID)).thenReturn(List.of());
JdCategoryScopeService.JdCategoryScope scope = service.resolve(operator);
assertThat(scope.visibleGroupIds()).isEmpty();
assertThat(scope.defaultGroupId()).isNull();
assertThat(scope.groups()).isEmpty();
}
// ---------------------------------------------------------------- 入参收敛
@Test
void 读侧_缺省取默认分组且不可见组403() {
JdCategoryScopeService.JdCategoryScope scope = scope(List.of(10L, 11L), List.of(), List.of(10L, 11L));
assertThat(service.readGroupOrNull(scope, null)).isEqualTo(10L);
assertThat(service.readGroupOrNull(scope, 11L)).isEqualTo(11L);
assertThatThrownBy(() -> service.readGroupOrNull(scope, 20L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("无权查看该分组的分类");
// 空作用域:页面照常可用(商品全平台公共),分类列全空,不打 403。
assertThat(service.readGroupOrNull(JdCategoryScopeService.JdCategoryScope.empty(), null)).isNull();
}
@Test
void 写侧_无可写组拒绝_缺省收敛到当前分组() {
JdCategoryScopeService.JdCategoryScope readOnly = scope(List.of(10L), List.of(), List.of(10L));
assertThatThrownBy(() -> service.requireWritableGroup(readOnly, null))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("你还没有可管理的数据权限分组");
// 两个可写组 + 没带 ownerGroupId ⇒ 落到「当前分组」(下拉默认第一项=组名序首个)。
JdCategoryScopeService.JdCategoryScope twoGroups = scope(List.of(10L, 11L), List.of(10L, 11L),
List.of(10L, 11L));
when(shopManageGroupMapper.selectById(10L)).thenReturn(group(10L, COMPANY_ID, "A组"));
assertThat(service.requireWritableGroup(twoGroups, null).getId()).isEqualTo(10L);
// 明确选另一个也照办。
when(shopManageGroupMapper.selectById(11L)).thenReturn(group(11L, COMPANY_ID, "B组"));
assertThat(service.requireWritableGroup(twoGroups, 11L).getId()).isEqualTo(11L);
}
@Test
void 写侧_当前分组不可写且没指定时要求先选组() {
// 可见组的第一项(默认分组 10)是只读的上司组,可写的是 11/12 两个 ⇒ 不带 ownerGroupId 不能瞎猜。
// (只有一个可写组时不用选——组长那一档直接用它,见上一条用例。)
JdCategoryScopeService.JdCategoryScope scope = scope(List.of(10L, 11L, 12L), List.of(11L, 12L),
List.of(10L, 11L, 12L));
assertThatThrownBy(() -> service.requireWritableGroup(scope, null))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("请先选择要管理的分组");
}
@Test
void 写侧_不可写组与组行不存在分别拒绝() {
JdCategoryScopeService.JdCategoryScope scope = scope(List.of(10L, 11L), List.of(10L),
List.of(10L, 11L));
assertThatThrownBy(() -> service.requireWritableGroup(scope, 11L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("仅该分组的管理员可以修改它的分类");
// 作用域认为可写但组行已被删:明确拒绝(不静默落 0 号组)。
when(shopManageGroupMapper.selectById(10L)).thenReturn(null);
assertThatThrownBy(() -> service.requireWritableGroup(scope, 10L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("分组不存在");
}
// ---------------------------------------------------------------- 用户端 / scope 回执
@Test
void 按uid解析_账号不存在按空作用域() {
when(adminUserMapper.selectById(USER_ID)).thenReturn(null);
assertThat(service.resolveByUserId(USER_ID).visibleGroupIds()).isEmpty();
assertThat(service.resolveByUserId(null).visibleGroupIds()).isEmpty();
assertThat(service.resolveByUserId(0L).visibleGroupIds()).isEmpty();
// null/0 直接回空,只有正数 uid 才查账号表。
verify(adminUserMapper, org.mockito.Mockito.times(1)).selectById(anyLong());
}
@Test
void scope回执_带平台超管标记与每组可写标记() {
AdminUserEntity operator = user(USER_ID, COMPANY_ID);
when(adminAuthSupport.currentRole(operator)).thenReturn("admin");
when(dataReadScope.isPlatformSuperAdmin(operator)).thenReturn(false);
when(shopManageGroupMapper.selectLedGroups(USER_ID)).thenReturn(List.of(group(10L, COMPANY_ID, "A组")));
when(shopManageGroupMapper.selectLeaderIdsByMemberUserId(USER_ID)).thenReturn(List.of());
JdCategoryScopeVo vo = service.scopeVo(operator);
assertThat(vo.isPlatformSuperAdmin()).isFalse();
assertThat(vo.getDefaultGroupId()).isEqualTo(10L);
assertThat(vo.getGroups()).singleElement().satisfies(option -> {
assertThat(option.getId()).isEqualTo(10L);
assertThat(option.getName()).isEqualTo("A组");
assertThat(option.isEditable()).isTrue();
});
}
// ---------------------------------------------------------------- 助手
private static AdminUserEntity user(long id, long companyId) {
AdminUserEntity user = new AdminUserEntity();
user.setId(id);
user.setCompanyId(companyId);
return user;
}
private static ShopManageGroupEntity group(long id, long companyId, String name) {
ShopManageGroupEntity group = new ShopManageGroupEntity();
group.setId(id);
group.setCompanyId(companyId);
group.setGroupName(name);
return group;
}
/** 直接构作用域(跳过解析):可见组 / 可写组 / 下拉项三者按入参给。 */
private static JdCategoryScopeService.JdCategoryScope scope(List<Long> visible, List<Long> writable,
List<Long> optionGroupIds) {
List<JdCategoryGroupOptionVo> options = optionGroupIds.stream()
.map(id -> new JdCategoryGroupOptionVo(id, "组" + id, "组" + id, writable.contains(id)))
.toList();
return new JdCategoryScopeService.JdCategoryScope(false, COMPANY_ID, visible, writable, options);
}
}
@@ -2,6 +2,7 @@ package com.nanri.aiimage.modules.jd.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupAssignMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductImageMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper;
@@ -50,6 +51,8 @@ class JdCollectBoardServiceTest {
private JdProductImageMapper jdProductImageMapper;
@Mock
private JdProductSkuMapper jdProductSkuMapper;
@Mock
private JdProductGroupAssignMapper jdProductGroupAssignMapper;
@Spy
private ObjectMapper objectMapper = new ObjectMapper();
@@ -73,6 +76,8 @@ class JdCollectBoardServiceTest {
com.nanri.aiimage.modules.task.model.entity.FileTaskEntity.class);
com.baomidou.mybatisplus.core.metadata.TableInfoHelper.initTableInfo(assistant,
com.nanri.aiimage.modules.task.model.entity.TaskScopeStateEntity.class);
com.baomidou.mybatisplus.core.metadata.TableInfoHelper.initTableInfo(assistant,
com.nanri.aiimage.modules.jd.model.entity.JdProductGroupAssignEntity.class);
}
private FileTaskEntity task(long id, long userId, String status) {
@@ -171,6 +176,7 @@ class JdCollectBoardServiceTest {
assertThatThrownBy(() -> service.deleteTask(88L, 7L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("任务不存在");
verify(jdProductGroupAssignMapper, never()).delete(any());
verify(jdProductMapper, never()).delete(any());
verify(fileTaskMapper, never()).deleteById(any(java.io.Serializable.class));
}
@@ -187,7 +193,8 @@ class JdCollectBoardServiceTest {
service.deleteTask(88L, 7L);
// sku/image 子行 → 主行 → scope → 任务行,五次删除一次不落
// 归类归属(V203)→ sku/image 子行 → 主行 → scope → 任务行,六次删除一次不落
verify(jdProductGroupAssignMapper, times(1)).delete(any());
verify(jdProductSkuMapper, times(1)).delete(any());
verify(jdProductImageMapper, times(1)).delete(any());
verify(jdProductMapper, times(1)).delete(any());
@@ -4,9 +4,10 @@ import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupAssignMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
import com.nanri.aiimage.modules.jd.model.entity.JdProductEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupAssignEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupEntity;
import com.nanri.aiimage.modules.jd.model.vo.JdProductGroupVo;
import com.nanri.aiimage.testutil.UpdateWrapperProbe;
@@ -20,7 +21,6 @@ import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -33,78 +33,105 @@ import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/**
* v1.4 Phase 5(R4/AC-8/AC-9):京东商品自定义分组业务规则。
* v1.4 Phase 5(R4/AC-8)+V203:京东商品自定义分类业务规则(按数据权限分组归属)。
*
* <p>判据(2026-11-15 用户定案「分组和亚马逊功能一样」=全平台一份,V200 退键后的服务形状):
* 全局重名拒绝不落库(409)、删除先把商品 group_id 置 NULL 再删分组行(事务两步,AC-8,
* 且脱组谓词不带 company_id)、越界 id 操作按不存在拒绝、company_id 列读写两侧都不再引用
* (新行不带公司,DB DEFAULT 0 兜底)、productCount 读侧现算统计(分组下拉展示用)。</p>
* <p>判据(2026-11-16 用户口径「不同组不能看到跨组的分类,当前组只管理员可以编辑分类」):
* 分类归属一个数据权限分组({@code owner_group_id}),<b>同组内</b>重名拒绝(409,不同组可同名)、
* 删除只解挂归属行({@code biz_jd_product_group_assign})不删商品、商品数按归属表
* {@code category_id} 现算、越界 id 按不存在拒绝。<b>作用域(谁能读/写哪个组)不在本类</b>——
* 那是 {@code JdCategoryScopeServiceTest} 的事,本类只钉「按给定组取/写」的语义。</p>
*/
class JdProductGroupServiceTest {
private static final long GROUP_ID = 10L;
private static final long COMPANY_ID = 5L;
private final JdProductGroupMapper groupMapper = mock(JdProductGroupMapper.class);
private final JdProductMapper productMapper = mock(JdProductMapper.class);
private final JdProductGroupService service = new JdProductGroupService(groupMapper, productMapper);
private final JdProductGroupAssignMapper assignMapper = mock(JdProductGroupAssignMapper.class);
private final JdProductGroupService service = new JdProductGroupService(groupMapper, assignMapper);
@BeforeAll
static void initTableInfo() {
// 探针要读 LambdaUpdateWrapper 的 SET/WHERE 段:裸单测 JVM 里 lambda 列缓存不初始化就解析不了,
// 探针要读 Lambda wrapper 的 SET/WHERE 段:裸单测 JVM 里 lambda 列缓存不初始化就解析不了,
// AccountExpiryServiceTest 同款(无 GlobalConfig 下 underCamel=false,列名归一由探针兜)。
MapperBuilderAssistant assistant = new MapperBuilderAssistant(new MybatisConfiguration(), "");
TableInfoHelper.initTableInfo(assistant, JdProductEntity.class);
TableInfoHelper.initTableInfo(assistant, JdProductGroupEntity.class);
TableInfoHelper.initTableInfo(assistant, JdProductGroupAssignEntity.class);
}
// ===================== 新建 =====================
@Test
void 新建重名拒绝且不落库() {
void 新建同组重名拒绝且不落库() {
when(groupMapper.selectCount(any())).thenReturn(1L);
BusinessException ex = assertThrows(BusinessException.class,
() -> service.create(" 秋冬款 ", 2));
() -> service.create(GROUP_ID, COMPANY_ID, " 秋冬款 ", 2));
assertEquals(409, ex.getCode(), "重名冲突=409(语义正确的资源冲突码,仓内 DeviceLogService 有先例)");
assertTrue(ex.getMessage().contains("同名分类"), "重名必须给可读文案,不拿 DB 唯一键异常撞 500(2026-11-15 起界面措辞「分类」)");
assertTrue(ex.getMessage().contains("本组已存在同名分类"),
"重名必须给可读文案并点名「本组」,不拿 DB 唯一键异常撞 500");
verify(groupMapper, never()).insert(any(JdProductGroupEntity.class));
}
@Test
void 新建成功落归一名与排序且不带公司() {
void 新建成功落归属分组与公司() {
when(groupMapper.selectCount(any())).thenReturn(0L);
when(groupMapper.insert(any(JdProductGroupEntity.class))).thenAnswer(invocation -> {
JdProductGroupEntity group = invocation.getArgument(0);
group.setId(9L);
JdProductGroupEntity category = invocation.getArgument(0);
category.setId(9L);
return 1;
});
Long id = service.create(" 秋冬款 ", 2);
Long id = service.create(GROUP_ID, COMPANY_ID, " 秋冬款 ", 2);
assertEquals(9L, id);
ArgumentCaptor<JdProductGroupEntity> captor = ArgumentCaptor.forClass(JdProductGroupEntity.class);
verify(groupMapper).insert(captor.capture());
JdProductGroupEntity saved = captor.getValue();
assertNull(saved.getCompanyId(), "公共库新行不带公司(实体字段不赋值,DB DEFAULT 0=平台公共)");
assertEquals(GROUP_ID, saved.getOwnerGroupId(), "必须落在当前数据权限分组上(跨组不可见)");
assertEquals(COMPANY_ID, saved.getCompanyId(), "公司随组落(唯一键 uk_company_owner_name 的左段)");
assertEquals("秋冬款", saved.getName(), "名字 trim 后落库");
assertEquals(2, saved.getSortOrder());
// 重名查询必须是「同公司 + 同组」口径:不同公司/不同组可同名。
ArgumentCaptor<Wrapper<JdProductGroupEntity>> wrapperCaptor = ArgumentCaptor.forClass(Wrapper.class);
verify(groupMapper).selectCount(wrapperCaptor.capture());
var whereEq = UpdateWrapperProbe.whereEq(wrapperCaptor.getValue());
assertEquals(GROUP_ID, ((Number) whereEq.get("owner_group_id")).longValue(),
"重名查询必须钉 owner_group_id(同组才冲突)");
assertEquals(COMPANY_ID, ((Number) whereEq.get("company_id")).longValue(),
"重名查询必须钉 company_id(唯一键左段)");
}
@Test
void 新建无分组直接拒绝() {
BusinessException ex = assertThrows(BusinessException.class,
() -> service.create(null, COMPANY_ID, "秋冬款", null));
assertEquals(400, ex.getCode());
assertTrue(ex.getMessage().contains("请先选择分组再新建分类"));
verifyNoInteractions(groupMapper);
}
@Test
void 新建空名直接拒绝() {
BusinessException blankName = assertThrows(BusinessException.class,
() -> service.create(" ", null));
() -> service.create(GROUP_ID, COMPANY_ID, " ", null));
assertEquals(400, blankName.getCode());
verifyNoInteractions(groupMapper);
}
@Test
void 新建排序缺省归零() {
void 新建排序缺省归零且公司缺省按0() {
when(groupMapper.selectCount(any())).thenReturn(0L);
service.create("默认排序", null);
service.create(GROUP_ID, null, "默认排序", null);
ArgumentCaptor<JdProductGroupEntity> captor = ArgumentCaptor.forClass(JdProductGroupEntity.class);
verify(groupMapper).insert(captor.capture());
assertEquals(0, captor.getValue().getSortOrder(), "sortOrder 缺省 0(下拉按 sort_order, id 升序)");
assertEquals(0L, captor.getValue().getCompanyId(),
"公司为空按 0 落(唯一键非空列;组本身取自可写组,正常不会为空)");
}
// ===================== 改名 =====================
@@ -121,7 +148,7 @@ class JdProductGroupServiceTest {
@Test
void 改名重名拒绝且不落库() {
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, "旧名"));
when(groupMapper.selectById(1L)).thenReturn(categoryEntity(1L, "旧名"));
when(groupMapper.selectCount(any())).thenReturn(1L);
BusinessException ex = assertThrows(BusinessException.class,
@@ -132,7 +159,7 @@ class JdProductGroupServiceTest {
@Test
void 改名成功带归一名与排序() {
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, "旧名"));
when(groupMapper.selectById(1L)).thenReturn(categoryEntity(1L, "旧名"));
when(groupMapper.selectCount(any())).thenReturn(0L);
service.rename(1L, " 新名 ", 7);
@@ -141,11 +168,13 @@ class JdProductGroupServiceTest {
verify(groupMapper).updateById(captor.capture());
assertEquals("新名", captor.getValue().getName());
assertEquals(7, captor.getValue().getSortOrder());
assertEquals(GROUP_ID, captor.getValue().getOwnerGroupId(),
"改名不得把归属组改走(沿用原行的 owner_group_id 查重名)");
}
@Test
void 改名排序不传保持原值() {
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, "旧名"));
when(groupMapper.selectById(1L)).thenReturn(categoryEntity(1L, "旧名"));
when(groupMapper.selectCount(any())).thenReturn(0L);
service.rename(1L, "只改名", null);
@@ -155,27 +184,21 @@ class JdProductGroupServiceTest {
assertEquals(3, captor.getValue().getSortOrder(), "sortOrder 不传=保持原值(改名不改排序)");
}
// ===================== 删除(AC-8 事务两步) =====================
// ===================== 删除(只解挂归属,不删商品) =====================
@Test
void 删除先把商品组置NULL再删分组行() {
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, "秋冬款"));
when(productMapper.update(any(), any(Wrapper.class))).thenReturn(3);
void 删除只解挂归属行再删分类行_商品一个不删() {
when(groupMapper.selectById(1L)).thenReturn(categoryEntity(1L, "秋冬款"));
when(assignMapper.delete(any())).thenReturn(3);
int detached = service.delete(1L);
assertEquals(3, detached, "返回实际脱组的商品行数(前端拿它做反馈,不猜)");
ArgumentCaptor<Wrapper<JdProductEntity>> wrapperCaptor = ArgumentCaptor.forClass(Wrapper.class);
verify(productMapper).update(any(), wrapperCaptor.capture());
// 置 NULL 语义必须落在 SET group_id=NULL(商品保留,脱组即「未分组」)。
var setValues = UpdateWrapperProbe.setValues(wrapperCaptor.getValue());
assertTrue(setValues.containsKey("group_id") && setValues.get("group_id") == null,
"删除分组必须把商品 group_id 置 NULL(SET group_id=NULL),不是删商品行:实得 " + setValues);
// 公共库:脱组谓词只限定该组,不带 company_id。
assertEquals(3, detached, "返回实际解挂的商品归属行数(前端拿它做反馈,不猜)");
ArgumentCaptor<Wrapper<JdProductGroupAssignEntity>> wrapperCaptor = ArgumentCaptor.forClass(Wrapper.class);
verify(assignMapper).delete(wrapperCaptor.capture());
var whereEq = UpdateWrapperProbe.whereEq(wrapperCaptor.getValue());
assertEquals(1L, ((Number) whereEq.get("group_id")).longValue(), "脱组必须限定该组");
assertTrue(!whereEq.containsKey("company_id"),
"分组公共化后脱组谓词不得再带 company_id:实得 " + whereEq);
assertEquals(1L, ((Number) whereEq.get("category_id")).longValue(),
"解挂谓词必须限定该分类(商品保留在公共库,回到未分类)");
verify(groupMapper).deleteById(1L);
}
@@ -184,56 +207,115 @@ class JdProductGroupServiceTest {
when(groupMapper.selectById(1L)).thenReturn(null);
assertThrows(BusinessException.class, () -> service.delete(1L));
verifyNoInteractions(productMapper);
verifyNoInteractions(assignMapper);
verify(groupMapper, never()).deleteById(anyLong());
}
@Test
void 删除分组不存在直接拒绝() {
when(groupMapper.selectById(404L)).thenReturn(null);
void 删除越界id直接拒绝() {
assertThrows(BusinessException.class, () -> service.delete(404L));
verifyNoInteractions(productMapper);
verifyNoInteractions(assignMapper);
}
// ===================== 列表(productCount 统计) =====================
// ===================== 列表(按组取 + productCount 统计) =====================
@Test
@SuppressWarnings("unchecked")
void 列表全平台一份不带公司谓词且productCount现算() {
JdProductGroupEntity first = groupEntity(2L, "晚出厂");
void 列表按当前分组取且productCount按归属表现算() {
JdProductGroupEntity first = categoryEntity(2L, "晚出厂");
first.setSortOrder(0);
JdProductGroupEntity second = groupEntity(1L, "早出厂");
JdProductGroupEntity second = categoryEntity(1L, "早出厂");
second.setSortOrder(1);
when(groupMapper.selectList(any())).thenReturn(List.of(first, second));
when(productMapper.selectCount(any())).thenReturn(12L, 0L);
when(assignMapper.selectCount(any())).thenReturn(12L, 0L);
List<JdProductGroupVo> items = service.list();
List<JdProductGroupVo> items = service.list(GROUP_ID);
assertEquals(2, items.size());
assertEquals("晚出厂", items.get(0).getName(), "selectList 的排序由 wrapper 决定,服务不重排");
assertEquals(12L, items.get(0).getProductCount(), "productCount 用 JdProductMapper selectCount 现算");
assertEquals(0L, items.get(1).getProductCount(), "空组也是 0,不是 null(下拉展示口径)");
assertEquals(GROUP_ID, items.get(0).getOwnerGroupId(), "归属组随行下发(前端按它锁分组)");
assertEquals(12L, items.get(0).getProductCount(),
"productCount 按归属表 category_id 现算(同一商品可在别组另归一类,这里只数本分类)");
assertEquals(0L, items.get(1).getProductCount(), "空分类也是 0,不是 null(下拉展示口径)");
assertEquals(1, items.get(1).getSortOrder());
verify(productMapper, times(2)).selectCount(any());
verify(assignMapper, times(2)).selectCount(any());
assertNotNull(items.get(0).getCreatedAt());
// 公共库:列表 wrapper 不带 company_id 谓词(历史行的 company_id 只是溯源标记)。
// 按组取:wrapper 钉 owner_group_id(.in 谓词,取值从参数表取证),且不再按 company_id 过滤。
ArgumentCaptor<Wrapper<JdProductGroupEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(groupMapper).selectList(captor.capture());
assertTrue(!captor.getValue().getSqlSegment().contains("company_id"),
"分组列表不得再按公司过滤(2026-11-15 公共化):实得 " + captor.getValue().getSqlSegment());
assertEquals(List.of(GROUP_ID), inParams(captor.getValue()),
"列表必须只取当前分组的分类(跨组不可见)");
assertTrue(!captor.getValue().getSqlSegment().toLowerCase().contains("company"),
"列表不再按公司过滤(同一公司的组已由 owner_group_id 区分):实得 "
+ captor.getValue().getSqlSegment());
}
@Test
void 列表无分组上下文回空且不查库() {
assertTrue(service.list(null).isEmpty(), "没有当前分组=空列表(页面分类列全空,不打 403)");
assertTrue(service.list(0L).isEmpty());
verifyNoInteractions(groupMapper);
verifyNoInteractions(assignMapper);
}
@Test
void 多组并集取分类_空清单不生成IN查询() {
JdProductGroupEntity row = categoryEntity(2L, "晚出厂");
when(groupMapper.selectList(any())).thenReturn(List.of(row));
when(assignMapper.selectCount(any())).thenReturn(0L);
List<JdProductGroupVo> items = service.listForGroups(java.util.Arrays.asList(10L, 11L, 10L, null, 0L));
assertEquals(1, items.size(), "用户端一个普通号可能同时在多个组里:并集只读展示");
ArgumentCaptor<Wrapper<JdProductGroupEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(groupMapper).selectList(captor.capture());
String segment = captor.getValue().getSqlSegment();
assertTrue(segment.toUpperCase().contains(" IN "), "多组走 IN 谓词:实得 " + segment);
// 参数表是 HashMap,序不可依赖:按集合语义断言。
java.util.List<Object> inValues = inParams(captor.getValue());
assertEquals(2, inValues.size(), "10/11/10/null/0 ⇒ 去重去脏后只剩两个有效组:实得 " + inValues);
assertTrue(inValues.containsAll(List.of(10L, 11L)), "只留 10、11:实得 " + inValues);
assertTrue(service.listForGroups(List.of()).isEmpty(), "空清单直接回空,不生成 IN ()");
assertTrue(service.listForGroups(null).isEmpty());
}
// ---------------------------------------------------------------- 助手
private static JdProductGroupEntity groupEntity(long id, String name) {
JdProductGroupEntity group = new JdProductGroupEntity();
group.setId(id);
group.setCompanyId(5L);
group.setName(name);
group.setSortOrder(3);
group.setCreatedAt(LocalDateTime.of(2026, 11, 14, 10, 0));
return group;
private static JdProductGroupEntity categoryEntity(long id, String name) {
JdProductGroupEntity category = new JdProductGroupEntity();
category.setId(id);
category.setOwnerGroupId(GROUP_ID);
category.setCompanyId(COMPANY_ID);
category.setName(name);
category.setSortOrder(3);
category.setCreatedAt(LocalDateTime.of(2026, 11, 14, 10, 0));
return category;
}
/**
* wrapper 参数表里的字面值(IN 集合按元素展开成多个 paramNameValuePairs 条目;
* 若某版 MP 把整个集合塞一个条目,这里按集合展开——两种形状都认)。
*
* <p>MP 的 SQL 段与参数表都是惰性构建:必须先触发 {@code getSqlSegment()},否则
* {@code paramNameValuePairs} 还是空表(原测试里那条「先触发再读」的注释同源)。</p>
*/
private static List<Object> inParams(Wrapper<?> wrapper) {
if (wrapper instanceof com.baomidou.mybatisplus.core.conditions.AbstractWrapper<?, ?, ?> abstractWrapper) {
abstractWrapper.getSqlSegment();
}
List<Object> out = new java.util.ArrayList<>();
for (Object value : UpdateWrapperProbe.paramNameValuePairs(wrapper).values()) {
if (value == null) {
continue;
}
if (value instanceof java.util.Collection<?> collection) {
out.addAll(collection);
} else {
out.add(value);
}
}
return out;
}
}
@@ -6,12 +6,14 @@ import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupAssignMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductImageMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper;
import com.nanri.aiimage.modules.jd.model.dto.JdProductUpdateRequest;
import com.nanri.aiimage.modules.jd.model.entity.JdProductEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupAssignEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductGroupEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductImageEntity;
import com.nanri.aiimage.modules.jd.model.entity.JdProductSkuEntity;
@@ -64,6 +66,8 @@ class JdProductUpdateServiceTest {
@Mock
private JdProductGroupMapper jdProductGroupMapper;
@Mock
private JdProductGroupAssignMapper jdProductGroupAssignMapper;
@Mock
private OssStorageService ossStorageService;
private JdProductUpdateService service;
@@ -76,12 +80,13 @@ class JdProductUpdateServiceTest {
TableInfoHelper.initTableInfo(assistant, JdProductSkuEntity.class);
TableInfoHelper.initTableInfo(assistant, JdProductImageEntity.class);
TableInfoHelper.initTableInfo(assistant, JdProductGroupEntity.class);
TableInfoHelper.initTableInfo(assistant, JdProductGroupAssignEntity.class);
}
@BeforeEach
void setUp() {
service = new JdProductUpdateService(jdProductMapper, jdProductSkuMapper,
jdProductImageMapper, jdProductGroupMapper, ossStorageService);
jdProductImageMapper, jdProductGroupMapper, jdProductGroupAssignMapper, ossStorageService);
ReflectionTestUtils.setField(service, "bucket", "jd-products");
ReflectionTestUtils.setField(service, "keyPrefix", "jd-products/");
}
@@ -104,7 +109,6 @@ class JdProductUpdateServiceTest {
JdProductUpdateRequest body = new JdProductUpdateRequest();
body.setTitle(" 新标题 ");
body.setBrand(" 新品牌 ");
body.setGroupId(null);
return body;
}
@@ -160,78 +164,133 @@ class JdProductUpdateServiceTest {
}
@Test
void 分组必须存在_公共组无公司维度() {
void 编辑不再写分组列_分类只走弹窗归类() {
givenOwnedRow();
JdProductUpdateRequest body = mainFieldsOnly();
body.setGroupId(7L);
// 分组 2026-11-15 起全平台一份:别家时代建的组(company_id=99)照样能挂。
JdProductGroupEntity group = new JdProductGroupEntity();
group.setId(7L);
group.setCompanyId(99L);
when(jdProductGroupMapper.selectById(7L)).thenReturn(group);
when(jdProductMapper.update(isNull(), any(Wrapper.class))).thenReturn(1);
assertThat(service.update(PRODUCT_ID, body)).isEqualTo(PRODUCT_ID);
// 分组不存在 ⇒ 拒绝且零写(2026-11-15 起界面措辞「分类」)。
JdProductUpdateRequest ghost = mainFieldsOnly();
ghost.setGroupId(404L);
when(jdProductGroupMapper.selectById(404L)).thenReturn(null);
assertThatThrownBy(() -> service.update(PRODUCT_ID, ghost))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("分类不存在");
// update 只剩成功挂组那 1 次:ghost 分支零写点(同用例前半段已成功写过一次,不能按 never 数)。
verify(jdProductMapper, org.mockito.Mockito.times(1)).update(isNull(), any(Wrapper.class));
}
service.update(PRODUCT_ID, mainFieldsOnly());
// ---------- 批量归类(店铺分类弹窗,2026-11-15) ----------
/** 取批量归类落下的 SET 键值对(paramNameValuePairs),供断言 groupId/ids 落值。 */
@SuppressWarnings("unchecked")
private Map<String, Object> capturedAssignValues() {
ArgumentCaptor<Wrapper<JdProductEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(jdProductMapper).update(isNull(), captor.capture());
LambdaUpdateWrapper<JdProductEntity> wrapper = (LambdaUpdateWrapper<JdProductEntity>) captor.getValue();
return (Map<String, Object>) ReflectionTestUtils.getField(wrapper, "paramNameValuePairs");
String sqlSet = ((LambdaUpdateWrapper<JdProductEntity>) captor.getValue()).getSqlSet();
// V203:分类不在编辑面(归属在 biz_jd_product_group_assign 的按组行上,
// 商品行的 group_id 列已停用),编辑保存一个字都不许往那一列写。
assertThat(sqlSet).doesNotContain("group_id");
// 也不再去查分类表(旧「分组必须存在」校验已随分类移出编辑面撤掉)。
verify(jdProductGroupMapper, never()).selectById(any());
}
// ---------- 批量归类(店铺分类弹窗;V203 起按组写归属表,不置锁) ----------
/** 归属表插入行的夹具校验:一次 insert 一行 (product_id, owner_group_id)。 */
private java.util.List<JdProductGroupAssignEntity> capturedAssignInserts() {
ArgumentCaptor<JdProductGroupAssignEntity> captor =
ArgumentCaptor.forClass(JdProductGroupAssignEntity.class);
verify(jdProductGroupAssignMapper, org.mockito.Mockito.atLeastOnce()).insert(captor.capture());
return captor.getAllValues();
}
@Test
void 批量归类成功_置分类并落人工编辑锁() {
JdProductGroupEntity group = new JdProductGroupEntity();
group.setId(7L);
when(jdProductGroupMapper.selectById(7L)).thenReturn(group);
when(jdProductMapper.update(isNull(), any(Wrapper.class))).thenReturn(3);
void 批量归类写归属表_一组一商品一行且不置人工锁() {
JdProductGroupEntity category = new JdProductGroupEntity();
category.setId(7L);
category.setOwnerGroupId(10L);
when(jdProductGroupMapper.selectById(7L)).thenReturn(category);
when(jdProductGroupAssignMapper.selectList(any())).thenReturn(List.of());
when(jdProductGroupAssignMapper.insert(any(JdProductGroupAssignEntity.class))).thenReturn(1);
// 入参含重复 id:去重后 1/2/3 三行
int updated = service.assignGroup(List.of(1L, 1L, 2L, 3L), 7L);
// 入参含重复 id:去重后 1/2 两行
int written = service.assignGroup(10L, COMPANY_ID, List.of(1L, 1L, 2L), 7L, 99L);
assertThat(updated).isEqualTo(3);
ArgumentCaptor<Wrapper<JdProductEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(jdProductMapper).update(isNull(), captor.capture());
LambdaUpdateWrapper<JdProductEntity> wrapper = (LambdaUpdateWrapper<JdProductEntity>) captor.getValue();
// SET 段必须同时带 group_id 与 manual_locked(归类即人工干预:置锁后覆盖清理不再删行)
assertThat(wrapper.getSqlSet()).contains("group_id").contains("manual_locked");
// WHERE 段(IN ids)惰性构参:先触发 getSqlSegment 再读参数表,IN 值才落进 paramNameValuePairs。
wrapper.getSqlSegment();
Map<String, Object> values = capturedAssignValues();
assertThat(values.values()).contains(7L, 1L, 2L, 3L);
assertThat(written).isEqualTo(2);
java.util.List<JdProductGroupAssignEntity> inserted = capturedAssignInserts();
assertThat(inserted).hasSize(2);
assertThat(inserted.get(0).getProductId()).isEqualTo(1L);
assertThat(inserted.get(0).getOwnerGroupId()).isEqualTo(10L);
assertThat(inserted.get(0).getCategoryId()).isEqualTo(7L);
assertThat(inserted.get(0).getCompanyId()).isEqualTo(COMPANY_ID);
assertThat(inserted.get(0).getCreatedBy()).isEqualTo(99L);
assertThat(inserted.get(1).getProductId()).isEqualTo(2L);
// 归类不再置人工编辑锁(2026-11-16 用户拍板):商品行一个字节都不写,
// 锁只会让共享行的价格/库存对所有组停更(分类不在商品行上,采集冲不掉它)。
verify(jdProductMapper, never()).update(isNull(), any(Wrapper.class));
verify(jdProductGroupAssignMapper, never()).update(any(), any());
}
@Test
void 批量归类目标分类不存在拒绝且零写() {
when(jdProductGroupMapper.selectById(404L)).thenReturn(null);
void 批量归类换组改归属行不新增() {
JdProductGroupEntity category = new JdProductGroupEntity();
category.setId(7L);
category.setOwnerGroupId(10L);
when(jdProductGroupMapper.selectById(7L)).thenReturn(category);
JdProductGroupAssignEntity existing = new JdProductGroupAssignEntity();
existing.setProductId(1L);
existing.setOwnerGroupId(10L);
existing.setCategoryId(3L);
when(jdProductGroupAssignMapper.selectList(any())).thenReturn(List.of(existing));
when(jdProductGroupAssignMapper.update(any(), any())).thenReturn(1);
assertThatThrownBy(() -> service.assignGroup(List.of(1L, 2L), 404L))
int written = service.assignGroup(10L, COMPANY_ID, List.of(1L), 7L, 99L);
assertThat(written).isEqualTo(1);
ArgumentCaptor<Wrapper<JdProductGroupAssignEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(jdProductGroupAssignMapper).update(isNull(), captor.capture());
assertThat(com.nanri.aiimage.testutil.UpdateWrapperProbe.setValues(captor.getValue()))
.containsEntry("category_id", 7L);
verify(jdProductGroupAssignMapper, never()).insert(any(JdProductGroupAssignEntity.class));
}
@Test
void 批量归类目标分类不存在或跨组拒绝且零写() {
when(jdProductGroupMapper.selectById(404L)).thenReturn(null);
assertThatThrownBy(() -> service.assignGroup(10L, COMPANY_ID, List.of(1L, 2L), 404L, 99L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("分类不存在");
// 分类存在于别的组(ownerGroupId=20)⇒ 403,不许跨组归类。
JdProductGroupEntity foreign = new JdProductGroupEntity();
foreign.setId(8L);
foreign.setOwnerGroupId(20L);
when(jdProductGroupMapper.selectById(8L)).thenReturn(foreign);
assertThatThrownBy(() -> service.assignGroup(10L, COMPANY_ID, List.of(1L), 8L, 99L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("该分类不属于当前分组");
verify(jdProductGroupAssignMapper, never()).insert(any(JdProductGroupAssignEntity.class));
verify(jdProductGroupAssignMapper, never()).update(any(), any());
verify(jdProductGroupAssignMapper, never()).delete(any());
verify(jdProductMapper, never()).update(isNull(), any(Wrapper.class));
}
@Test
void 批量归类空清单与超上限可读拒绝() {
assertThatThrownBy(() -> service.assignGroup(List.of(), null))
void 移出分类_删本组归属行且商品行不动() {
when(jdProductGroupAssignMapper.delete(any())).thenReturn(2);
int removed = service.assignGroup(10L, COMPANY_ID, List.of(5L, 6L), null, 99L);
assertThat(removed).isEqualTo(2);
ArgumentCaptor<Wrapper<JdProductGroupAssignEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(jdProductGroupAssignMapper).delete(captor.capture());
var whereEq = com.nanri.aiimage.testutil.UpdateWrapperProbe.whereEq(captor.getValue());
assertThat(((Number) whereEq.get("owner_group_id")).longValue()).isEqualTo(10L);
// 只删本组、只删勾选行:IN 集合按元素落参数表(MP 逐个 formatParam),取值逐一取证。
assertThat(captor.getValue().getSqlSegment().toUpperCase()).contains(" IN ");
java.util.List<Object> params = new java.util.ArrayList<>(
com.nanri.aiimage.testutil.UpdateWrapperProbe
.paramNameValuePairs(captor.getValue()).values());
assertThat(params).contains(10L).contains(5L).contains(6L);
// 移出分类不查分类表、不写商品行。
verify(jdProductGroupMapper, never()).selectById(any());
verify(jdProductGroupAssignMapper, never()).insert(any(JdProductGroupAssignEntity.class));
verify(jdProductMapper, never()).update(isNull(), any(Wrapper.class));
}
@Test
void 批量归类空清单超上限与无当前分组可读拒绝() {
assertThatThrownBy(() -> service.assignGroup(10L, COMPANY_ID, List.of(), null, 1L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("请先选择要归类的商品");
assertThatThrownBy(() -> service.assignGroup(List.of(0L, -1L), null))
assertThatThrownBy(() -> service.assignGroup(10L, COMPANY_ID, List.of(0L, -1L), null, 1L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("请先选择要归类的商品");
@@ -239,28 +298,19 @@ class JdProductUpdateServiceTest {
for (long i = 1; i <= 201; i++) {
tooMany.add(i);
}
assertThatThrownBy(() -> service.assignGroup(tooMany, null))
assertThatThrownBy(() -> service.assignGroup(10L, COMPANY_ID, tooMany, null, 1L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("单次最多归类 200");
// 没有「当前分组」就没有归属可写:403 点名先选组(V203)。
assertThatThrownBy(() -> service.assignGroup(null, COMPANY_ID, List.of(1L), null, 1L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("请先选择分组再归类");
verify(jdProductGroupAssignMapper, never()).insert(any(JdProductGroupAssignEntity.class));
verify(jdProductGroupAssignMapper, never()).delete(any());
verify(jdProductMapper, never()).update(isNull(), any(Wrapper.class));
}
@Test
void 移出分类_groupId置空仍落人工编辑锁() {
when(jdProductMapper.update(isNull(), any(Wrapper.class))).thenReturn(2);
int updated = service.assignGroup(List.of(5L, 6L), null);
assertThat(updated).isEqualTo(2);
ArgumentCaptor<Wrapper<JdProductEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(jdProductMapper).update(isNull(), captor.capture());
LambdaUpdateWrapper<JdProductEntity> wrapper = (LambdaUpdateWrapper<JdProductEntity>) captor.getValue();
// groupId=null 也显式落 SET(group_id=NULL=回到未分类),锁照落。
assertThat(wrapper.getSqlSet()).contains("group_id").contains("manual_locked");
// 移出分类没有目标组:不查分组表。
verify(jdProductGroupMapper, never()).selectById(any());
}
@Test
void 属性重建只覆写tabs段其余顶层键保留() {
givenOwnedRow();