feat(phase-5): 后管京东数据库接口与页面+用户端采集入口——v1.4 Phase 5

This commit is contained in:
2026-11-14 12:47:08 +08:00
parent 6ce995f19e
commit ff859d25bc
42 changed files with 4839 additions and 37 deletions
@@ -0,0 +1,496 @@
package com.nanri.aiimage.modules.jd.controller;
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.security.AdminAuthSupport;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.modules.jd.mapper.JdProductImageMapper;
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.JdProductImageEntity;
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.JdProductQueryService;
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.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
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;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* v1.4 Phase 5:后管「京东数据库」只读接口(列表/详情/导出)与分组管理入口。
*
* <p>结构判据(照 {@code AdminAppearancePatentCleanItemsControllerTest} 双形态):
* 端点只读、鉴权 seam、公司隔离正门、snake 参数带默认值、SQL 只落 XML;
* 行为样本:mock HttpServletRequest 把 company 参数交给 readCompanyIdOrOwn 并装进 200 信封、
* 分页钳制 offset/limit(page=Long.MAX_VALUE 不得负,铁律 15)、详情 attr_json
* tabs→attrGroups 解析与非法形状兜底(AC-7)。</p>
*/
class AdminJdProductControllerTest {
private static final Path MODULE = Path.of("").toAbsolutePath();
private static final Path MAIN = MODULE.resolve("src/main/java/com/nanri/aiimage");
private static final Path CONTROLLER =
MAIN.resolve("modules/jd/controller/AdminJdProductController.java");
private static final Path GROUP_CONTROLLER =
MAIN.resolve("modules/jd/controller/AdminJdProductGroupController.java");
private static final Path MAPPER = MAIN.resolve("modules/jd/mapper/JdProductMapper.java");
private static final String COLUMN_KEY = "admin_jd_database";
private static final String ROUTE_PATH = "jd-center/database";
// ===================== 结构判据 =====================
@Test
void 控制器与只读端点就位() throws IOException {
assertTrue(Files.exists(CONTROLLER), "控制器必须落在 " + CONTROLLER);
String source = stripComments(Files.readString(CONTROLLER));
assertTrue(source.contains("/api/admin/jd-products"), "端点必须挂在 /api/admin/jd-products");
assertTrue(source.contains("@GetMapping"), "查询端点必须落在 @GetMapping");
assertTrue(source.contains("\"/{id}\""), "详情端点必须是 GET /{id}");
assertTrue(source.contains("\"/export\""), "导出端点必须是 GET /export");
// 本页只读(出表走导出端点):禁 POST/PUT/DELETE,分组管理另有同款鉴权闸的分组控制器。
assertFalse(source.contains("@PostMapping") || source.contains("@PutMapping")
|| source.contains("@DeleteMapping"),
"京东数据库页只读:不得有 POST/PUT/DELETE(分组 CRUD 落 AdminJdProductGroupController)");
}
@Test
void 鉴权闸照外观专利只读页私有require形状() throws IOException {
String source = stripComments(Files.readString(CONTROLLER));
for (String seam : List.of("requireUser", "X-Internal-Token", "isSuper",
"getUserColumnPermissions", COLUMN_KEY, ROUTE_PATH, "requireJdAccess")) {
assertTrue(source.contains(seam), "鉴权闸缺接缝 " + seam
+ "——照 AdminAppearancePatentCleanItemsController 私有 requireXxxAccess 形状"
+ "(JWT→内部令牌回退→超管放行→菜单双匹配)");
}
assertTrue(source.contains("getColumnKey") && source.contains("getRoutePath"),
"菜单权限必须 column_key/route_path 双匹配(默认不命中即拒)");
assertTrue(source.contains("无权访问京东数据库"), "拒绝文案必须点名京东数据库");
}
@Test
void 公司隔离走readCompanyIdOrOwn() throws IOException {
String source = stripComments(Files.readString(CONTROLLER));
assertTrue(source.contains("DataReadScope"), "公司隔离唯一出口是 DataReadScope");
assertTrue(source.contains("readCompanyIdOrOwn"),
"读侧必须走 readCompanyIdOrOwn:超管显式传才收窄,非超管强制本公司");
assertFalse(source.contains("superAdminScopedCompanyId"),
"不得走 superAdminScopedCompanyId:它对非超管返回 null=按行 company_id 查询时把整张表交给每一家");
}
@Test
void 分页参数snake且带默认值() throws IOException {
String source = stripComments(Files.readString(CONTROLLER));
for (String param : List.of("page_size", "shop_name", "product_code", "title_keyword",
"sale_status", "group_id", "synced_from", "synced_to", "company_id")) {
assertTrue(source.contains(param), "查询参数必须 snake_case:" + param);
}
assertTrue(source.contains("PageDefaults"), "page/page_size 默认值必须取 PageDefaults"
+ "(page_size 默认 20=PageDefaults.JD_PRODUCTS_PAGE_SIZE);"
+ "page 钳制防 (page-1)*page_size 溢出的行为样本见查询服务钳制支(铁律 15)");
}
@Test
void 查询SQL只落XML不写注解SQL() throws IOException {
assertTrue(Files.exists(MAPPER), "查询必须走 JdProductMapper(铁律 1)");
String mapperSource = stripComments(Files.readString(MAPPER));
assertFalse(mapperSource.matches("(?s).*@(Select|Insert|Update|Delete)\\s*\\(.*"),
"不得新写注解 SQL(铁律 1:查询 SQL 全部落 XML Mapper)");
assertTrue(mapperSource.contains("@Mapper"), "mapper 接口必须带 @Mapper");
Path xml = findJdProductMapperXml();
assertNotNull(xml, "mapper XML 必须落在 src/main/resources/mapper/**(铁律 1)");
String xmlText = stripComments(Files.readString(xml));
assertTrue(xmlText.contains("countProducts"), "XML 必须有 countProducts(只读页总数)");
assertTrue(xmlText.contains("selectProductPage"), "XML 必须有 selectProductPage(只读页分页)");
assertFalse(xmlText.contains("LIMIT #{page}"),
"分页只收服务钳制后的 offset/limit,绝不 LIMIT #{page} 直拼(铁律 15)");
assertTrue(xmlText.contains("ORDER BY p.synced_at DESC, p.id DESC"),
"排序必须是 synced_at 倒序(同外观专利只读页口径)");
}
@Test
void 分组控制器与同款鉴权闸就位() throws IOException {
assertTrue(Files.exists(GROUP_CONTROLLER),
"分组控制器必须落在 " + GROUP_CONTROLLER + "(AC-9:普通授权用户可读写分组)");
String source = stripComments(Files.readString(GROUP_CONTROLLER));
assertTrue(source.contains("/api/admin/jd-product-groups"), "分组端点必须挂在 /api/admin/jd-product-groups");
for (String seam : List.of("requireUser", "X-Internal-Token", "isSuper",
"getUserColumnPermissions", COLUMN_KEY, ROUTE_PATH, "requireJdAccess")) {
assertTrue(source.contains(seam), "分组鉴权闸缺接缝 " + seam + "(与商品页同款)");
}
// 普通(非超管)授权用户可读写分组:菜单双匹配那道闸在两个控制器上逐字同源。
for (String verb : List.of("@PostMapping", "@PutMapping", "@DeleteMapping")) {
assertTrue(source.contains(verb), "分组 CRUD 必须有 " + verb + "(AC-9)");
}
}
// ===================== 行为样本 =====================
@Test
void 控制器把公司参数交给readCompanyIdOrOwn并把结果装进200信封() {
JdProductQueryService queryService = mock(JdProductQueryService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
DataReadScope dataReadScope = mock(DataReadScope.class);
AdminJdProductController controller = new AdminJdProductController(
queryService, authSupport, permissionMenuService, dataReadScope);
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");
// 超管显式传 company_id=5 ⇒ 正门把 5 交出来(不传时正门给 null=全量,同一行为样本家族)。
when(dataReadScope.readCompanyIdOrOwn(operator, 5L)).thenReturn(5L);
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, 5L, null, null, null, null, null, null, null)).thenReturn(pageVo);
ApiResponse<JdProductPageVo> response = controller.page(1L, 20L, null, null, null, null, null,
null, null, 5L, request);
verify(dataReadScope).readCompanyIdOrOwn(operator, 5L);
verify(queryService).page(1L, 20L, 5L, null, null, null, null, null, null, null);
assertEquals(Boolean.TRUE, response.isSuccess(), "拒绝走 403 业务码,放行必须是 success 信封(B80-03)");
assertEquals(pageVo, response.getData());
}
@Test
void 控制器详情走同一鉴权正门并回详情() {
JdProductQueryService queryService = mock(JdProductQueryService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
DataReadScope dataReadScope = mock(DataReadScope.class);
AdminJdProductController controller = new AdminJdProductController(
queryService, authSupport, mock(PermissionMenuService.class), dataReadScope);
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");
// 详情不收 company 参数:超管不传=全量可见;非超管由正门强制本公司(服务按返回值收口)。
when(dataReadScope.readCompanyIdOrOwn(operator, null)).thenReturn(null);
JdProductDetailVo detailVo = new JdProductDetailVo();
detailVo.setId(11L);
when(queryService.detail(11L, null)).thenReturn(detailVo);
ApiResponse<JdProductDetailVo> response = controller.detail(11L, request);
verify(dataReadScope).readCompanyIdOrOwn(operator, null);
verify(queryService).detail(11L, null);
assertEquals(Boolean.TRUE, response.isSuccess());
assertEquals(detailVo, response.getData());
}
@Test
void 控制器导出走同一正门并回Excel响应() {
JdProductQueryService queryService = mock(JdProductQueryService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
DataReadScope dataReadScope = mock(DataReadScope.class);
AdminJdProductController controller = new AdminJdProductController(
queryService, authSupport, mock(PermissionMenuService.class), dataReadScope);
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(dataReadScope.readCompanyIdOrOwn(operator, 5L)).thenReturn(5L);
byte[] payload = "xlsx-bytes".getBytes(java.nio.charset.StandardCharsets.UTF_8);
when(queryService.export(5L, null, null, null, null, null, null, null)).thenReturn(payload);
ResponseEntity<byte[]> response = controller.export(null, null, null, null, null, null, null,
5L, request);
verify(dataReadScope).readCompanyIdOrOwn(operator, 5L);
verify(queryService).export(5L, null, null, null, null, null, null, null);
assertEquals(MediaType.parseMediaType(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
response.getHeaders().getContentType(), "导出必须是 xlsx Content-Type");
assertTrue(response.getHeaders().getFirst(HttpHeaders.CONTENT_DISPOSITION).contains("filename*=UTF-8''"),
"中文文件名必须带 filename* UTF-8 轨(DownloadHeaderUtil 双轨口径)");
assertArrayEquals(payload, response.getBody(), "响应体必须原样是服务侧产出的字节");
}
@Test
void 查询服务分页钳制防溢出() {
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
when(mapper.countProducts(any(), any(), 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, 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(),
isNull(), isNull(), offset.capture(), limit.capture());
assertEquals(0L, offset.getValue());
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, 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(),
any(), any(), offsetMax.capture(), limitMax.capture());
assertEquals(999_900L, offsetMax.getValue(), "(page-1)*page_size 最大 999_900,钳制后不得溢出变负");
assertEquals(100, limitMax.getValue());
}
@Test
void 查询服务同步起止倒挂拒绝() {
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
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, null, null, from, to));
assertTrue(ex.getMessage().contains("开始时间不能晚于结束时间"), "倒挂时间按业务异常拒绝");
verify(mapper, never()).countProducts(any(), any(), any(), any(), any(), any(), any(), any());
// 导出与分页共用同一过滤面校验(同一个拒绝时机:不碰 mapper)。
BusinessException exportEx = assertThrows(BusinessException.class,
() -> service.export(null, null, null, null, null, null, from, to));
assertTrue(exportEx.getMessage().contains("开始时间不能晚于结束时间"),
"导出端点必须同样拒绝倒挂时间,不得绕过分页页签的校验口径");
}
@Test
void 查询服务过滤面原样直传且空串归null() {
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(0L);
// 超管显式传 5 ⇒ 按公司 5 筛(收窄);groupId ≤0 按没选分组处理;文本两侧空白剥掉。
service.page(1L, 20L, 5L, " 店铺甲 ", " SKU-1 ", " 连衣裙 ", "上架中", 0L, null, null);
verify(mapper).countProducts(eq(5L), eq("店铺甲"), eq("SKU-1"), eq("连衣裙"), eq("上架中"),
isNull(), isNull(), isNull());
// 全量(scopedCompanyId=null)⇒ companyId 不过滤。
service.page(1L, 20L, null, null, null, null, null, null, null, null);
verify(mapper).countProducts(isNull(), isNull(), isNull(), isNull(), isNull(), isNull(),
isNull(), isNull());
}
@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.JdProductGroupMapper.class));
JdProductEntity row = productEntity(11L);
// 客户端实拍契约:tabs[{tab, attrs[{key,label,value}]}];value 允许数字型 JSON 值(转字符串)。
row.setAttrJson("{\"tabs\":["
+ "{\"tab\":\"商品基本信息\",\"attrs\":["
+ "{\"key\":\"款号\",\"label\":\"货号\",\"value\":\"A123\"},"
+ "{\"key\":\"颜色\",\"label\":\"颜色分类\",\"value\":3}]},"
+ "{\"tab\":\"规格\",\"attrs\":[{\"key\":\"size\",\"label\":\"尺码\",\"value\":\"M\"}]}],"
+ "\"images\":[],\"productCode\":\"A123\"}");
when(mapper.selectById(11L)).thenReturn(row);
JdProductImageEntity image = new JdProductImageEntity();
image.setProductId(11L);
image.setImageType("MAIN");
image.setSortNo(0);
image.setUrl("https://oss.aishufu.top/jd-products/a.jpg");
image.setByteSize(1024L);
image.setWidth(800);
image.setHeight(800);
when(imageMapper.selectList(any())).thenReturn(List.of(image));
JdProductDetailVo vo = service.detail(11L, 5L);
assertEquals(2, vo.getAttrGroups().size(), "tabs 数组逐个映射成 attrGroups(groupName=tab 字段)");
assertEquals("商品基本信息", vo.getAttrGroups().get(0).getGroupName());
assertEquals(2, vo.getAttrGroups().get(0).getAttrs().size());
assertEquals("货号", vo.getAttrGroups().get(0).getAttrs().get(0).getLabel());
assertEquals("A123", vo.getAttrGroups().get(0).getAttrs().get(0).getValue());
assertEquals("3", vo.getAttrGroups().get(0).getAttrs().get(1).getValue(),
"数字型 value 转字符串下发(读侧不丢键)");
assertEquals("规格", vo.getAttrGroups().get(1).getGroupName());
assertNull(vo.getAttrJsonRaw(), "契约形状解析成功时不带原文兜底(原文只在不识别时透出)");
assertEquals(1, vo.getImages().size());
assertEquals("MAIN", vo.getImages().get(0).getImageType());
assertEquals("https://oss.aishufu.top/jd-products/a.jpg", vo.getImages().get(0).getUrl(),
"图片 URL 100% 自有域名(AC-4)");
// 主表高频列直接从 entity 映射,不走 JSON。
assertEquals("A123", vo.getProductCode());
assertEquals(new BigDecimal("129.00"), vo.getPriceMin());
}
@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.JdProductGroupMapper.class));
// 形状一:非法 JSON(解析异常)。
JdProductEntity broken = productEntity(11L);
broken.setAttrJson("{\"tabs\": [broken");
when(mapper.selectById(11L)).thenReturn(broken);
JdProductDetailVo brokenVo = service.detail(11L, 5L);
assertTrue(brokenVo.getAttrGroups().isEmpty(), "解析异常落空 attrGroups,不抛 500(AC-7)");
assertEquals("{\"tabs\": [broken", brokenVo.getAttrJsonRaw(), "原文进 attrJsonRaw 兜底展示");
// 形状二:合法 JSON 但没有 tabs(形状不识别)。
JdProductEntity foreign = productEntity(11L);
foreign.setAttrJson("{\"attrs\":[{\"key\":\"x\",\"value\":\"y\"}]}");
when(mapper.selectById(11L)).thenReturn(foreign);
JdProductDetailVo foreignVo = service.detail(11L, 5L);
assertTrue(foreignVo.getAttrGroups().isEmpty(), "非契约形状落空 attrGroups");
assertEquals("{\"attrs\":[{\"key\":\"x\",\"value\":\"y\"}]}", foreignVo.getAttrJsonRaw(),
"未识别属性不丢弃:原文兜底透出(AC-7)");
// 形状三:attr_json 为空 ⇒ 空分组、无原文兜底。
JdProductEntity blank = productEntity(11L);
blank.setAttrJson(null);
when(mapper.selectById(11L)).thenReturn(blank);
JdProductDetailVo blankVo = service.detail(11L, 5L);
assertTrue(blankVo.getAttrGroups().isEmpty());
assertNull(blankVo.getAttrJsonRaw());
}
@Test
void 详情公司越界按不存在拒绝() {
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
JdProductEntity row = productEntity(11L);
row.setCompanyId(6L);
when(mapper.selectById(11L)).thenReturn(row);
// 非超管(scopedCompanyId=5):行属公司 6 ⇒ 按「商品不存在」拒绝,不泄露跨公司行的存在性。
BusinessException ex = assertThrows(BusinessException.class, () -> service.detail(11L, 5L));
assertTrue(ex.getMessage().contains("商品不存在"));
// 超管不选公司(null)=全量可见。
assertNotNull(service.detail(11L, null));
// id 非法同样拒绝。
assertThrows(BusinessException.class, () -> service.detail(0L, null));
}
@Test
void 导出超上限按业务错误拒绝且不取数() {
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any()))
.thenReturn(JdProductQueryService.EXPORT_MAX_ROWS + 1);
BusinessException ex = assertThrows(BusinessException.class,
() -> service.export(null, null, null, null, null, null, null, null));
assertTrue(ex.getMessage().contains("超过导出上限"),
"超上限必须给「缩小筛选范围」的可读文案,不能让用户等一次注定 OOM 的全量查询");
verify(mapper, never()).selectProductPage(any(), any(), any(), any(), any(), any(), any(),
any(), anyLong(), anyInt());
}
@Test
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),
groupMapper);
JdProductEntity grouped = productEntity(1L);
grouped.setGroupId(3L);
JdProductEntity missing = productEntity(2L);
missing.setGroupId(99L);
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(2L);
when(mapper.selectProductPage(any(), any(), 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));
JdProductPageVo vo = service.page(1L, 20L, 5L, null, null, null, null, null, null, null);
assertEquals("秋冬款", vo.getItems().get(0).getGroupName(), "行集 group_id 一次取齐分组名(无逐行查询)");
assertNull(vo.getItems().get(1).getGroupName(), "分组已删=不猜名字(铁律 30),前端展示 -");
verify(groupMapper, times(1)).selectBatchIds(any());
}
// ---------------------------------------------------------------- 助手
/** 列表/详情用例共用的商品行夹具:归属公司 5,主字段齐备便于按字段对撞。 */
private static JdProductEntity productEntity(long id) {
JdProductEntity entity = new JdProductEntity();
entity.setId(id);
entity.setCompanyId(5L);
entity.setShopId("shop-1");
entity.setShopName("测试店铺");
entity.setProductCode("A123");
entity.setSkuId("SKU-1");
entity.setTitle("测试连衣裙");
entity.setBrand("Anker");
entity.setCategoryPath("女装 > 连衣裙 > 碎花裙");
entity.setPriceMin(new BigDecimal("129.00"));
entity.setPriceMax(new BigDecimal("159.00"));
entity.setStockTotal(300);
entity.setSaleStatus("上架中");
entity.setListTab("ONSALE");
entity.setAttrCount(12);
entity.setImageCount(1);
entity.setSyncedAt(LocalDateTime.of(2026, 11, 14, 10, 30));
return entity;
}
private static Path findJdProductMapperXml() throws IOException {
Path resources = MODULE.resolve("src/main/resources/mapper");
if (!Files.exists(resources)) {
return null;
}
try (Stream<Path> files = Files.walk(resources)) {
return files.filter(path -> path.getFileName().toString()
.equals("JdProductMapper.xml")).findFirst().orElse(null);
}
}
private static String stripComments(String source) {
String noBlock = source.replaceAll("(?s)/\\*.*?\\*/", "");
StringBuilder out = new StringBuilder();
for (String line : noBlock.split("\n", -1)) {
int idx = line.indexOf("//");
out.append(idx >= 0 ? line.substring(0, idx) : line).append('\n');
}
return out.toString();
}
}
@@ -0,0 +1,244 @@
package com.nanri.aiimage.modules.jd.service;
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.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.JdProductGroupEntity;
import com.nanri.aiimage.modules.jd.model.vo.JdProductGroupVo;
import com.nanri.aiimage.testutil.UpdateWrapperProbe;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.time.LocalDateTime;
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;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/**
* v1.4 Phase 5(R4/AC-8/AC-9):京东商品自定义分组业务规则。
*
* <p>判据:同公司重名拒绝不落库(409)、删除先把商品 group_id 置 NULL 再删分组行
* (事务两步,AC-8)、越公司 id 操作按不存在拒绝(不泄露存在性)、productCount
* 读侧现算统计(分组下拉展示用)。</p>
*/
class JdProductGroupServiceTest {
private final JdProductGroupMapper groupMapper = mock(JdProductGroupMapper.class);
private final JdProductMapper productMapper = mock(JdProductMapper.class);
private final JdProductGroupService service = new JdProductGroupService(groupMapper, productMapper);
@BeforeEach
void initTableInfo() {
// 探针要读 LambdaUpdateWrapper 的 SET/WHERE 段:裸单测 JVM 里 lambda 列缓存不初始化就解析不了,
// AccountExpiryServiceTest 同款(无 GlobalConfig 下 underCamel=false,列名归一由探针兜)。
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
JdProductEntity.class);
}
// ===================== 新建 =====================
@Test
void 新建同公司重名拒绝且不落库() {
when(groupMapper.selectCount(any())).thenReturn(1L);
BusinessException ex = assertThrows(BusinessException.class,
() -> service.create(5L, " 秋冬款 ", 2));
assertEquals(409, ex.getCode(), "重名冲突=409(语义正确的资源冲突码,仓内 DeviceLogService 有先例)");
assertTrue(ex.getMessage().contains("同名分组"), "重名必须给可读文案,不拿 DB 唯一键异常撞 500");
verify(groupMapper, never()).insert(any(JdProductGroupEntity.class));
}
@Test
void 新建成功落公司归属与归一名() {
when(groupMapper.selectCount(any())).thenReturn(0L);
when(groupMapper.insert(any(JdProductGroupEntity.class))).thenAnswer(invocation -> {
JdProductGroupEntity group = invocation.getArgument(0);
group.setId(9L);
return 1;
});
Long id = service.create(5L, " 秋冬款 ", 2);
assertEquals(9L, id);
ArgumentCaptor<JdProductGroupEntity> captor = ArgumentCaptor.forClass(JdProductGroupEntity.class);
verify(groupMapper).insert(captor.capture());
JdProductGroupEntity saved = captor.getValue();
assertEquals(5L, saved.getCompanyId(), "归属公司来自隔离正门的 scopedCompanyId,不是请求体");
assertEquals("秋冬款", saved.getName(), "名字 trim 后落库");
assertEquals(2, saved.getSortOrder());
}
@Test
void 新建缺公司或空名直接拒绝() {
// 超管没选公司(scopedCompanyId=null)=分组没有归属公司,直接拒绝。
BusinessException noCompany = assertThrows(BusinessException.class,
() -> service.create(null, "秋冬款", null));
assertEquals(400, noCompany.getCode());
BusinessException blankName = assertThrows(BusinessException.class,
() -> service.create(5L, " ", null));
assertEquals(400, blankName.getCode());
verifyNoInteractions(groupMapper);
}
@Test
void 新建排序缺省归零() {
when(groupMapper.selectCount(any())).thenReturn(0L);
service.create(5L, "默认排序", null);
ArgumentCaptor<JdProductGroupEntity> captor = ArgumentCaptor.forClass(JdProductGroupEntity.class);
verify(groupMapper).insert(captor.capture());
assertEquals(0, captor.getValue().getSortOrder(), "sortOrder 缺省 0(下拉按 sort_order, id 升序)");
}
// ===================== 改名 =====================
@Test
void 改名越公司id按不存在拒绝() {
JdProductGroupEntity group = groupEntity(1L, 6L, "别家的组");
when(groupMapper.selectById(1L)).thenReturn(group);
BusinessException ex = assertThrows(BusinessException.class,
() -> service.rename(1L, 5L, "新名字", null));
assertTrue(ex.getMessage().contains("分组不存在"),
"越界 id 与 id 不存在是同一种响应,不泄露跨公司行的存在性");
verify(groupMapper, never()).updateById(any(JdProductGroupEntity.class));
}
@Test
void 改名重名拒绝且不落库() {
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, 5L, "旧名"));
when(groupMapper.selectCount(any())).thenReturn(1L);
BusinessException ex = assertThrows(BusinessException.class,
() -> service.rename(1L, 5L, "已有名", 3));
assertEquals(409, ex.getCode());
verify(groupMapper, never()).updateById(any(JdProductGroupEntity.class));
}
@Test
void 改名成功带归一名与排序() {
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, 5L, "旧名"));
when(groupMapper.selectCount(any())).thenReturn(0L);
service.rename(1L, 5L, " 新名 ", 7);
ArgumentCaptor<JdProductGroupEntity> captor = ArgumentCaptor.forClass(JdProductGroupEntity.class);
verify(groupMapper).updateById(captor.capture());
assertEquals("新名", captor.getValue().getName());
assertEquals(7, captor.getValue().getSortOrder());
}
@Test
void 改名排序不传保持原值() {
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, 5L, "旧名"));
when(groupMapper.selectCount(any())).thenReturn(0L);
service.rename(1L, 5L, "只改名", null);
ArgumentCaptor<JdProductGroupEntity> captor = ArgumentCaptor.forClass(JdProductGroupEntity.class);
verify(groupMapper).updateById(captor.capture());
assertEquals(3, captor.getValue().getSortOrder(), "sortOrder 不传=保持原值(改名不改排序)");
}
// ===================== 删除(AC-8 事务两步) =====================
@Test
void 删除先把商品组置NULL再删分组行() {
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, 5L, "秋冬款"));
when(productMapper.update(any(), any(Wrapper.class))).thenReturn(3);
int detached = service.delete(1L, 5L);
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);
var whereEq = UpdateWrapperProbe.whereEq(wrapperCaptor.getValue());
assertEquals(5L, ((Number) whereEq.get("company_id")).longValue(), "脱组必须限定本公司");
assertEquals(1L, ((Number) whereEq.get("group_id")).longValue(), "脱组必须限定该组");
verify(groupMapper).deleteById(1L);
}
@Test
void 删除越公司id拒绝且一个字节都不写() {
when(groupMapper.selectById(1L)).thenReturn(groupEntity(1L, 6L, "别家的组"));
assertThrows(BusinessException.class, () -> service.delete(1L, 5L));
verifyNoInteractions(productMapper);
verify(groupMapper, never()).deleteById(anyLong());
}
@Test
void 删除分组不存在直接拒绝() {
when(groupMapper.selectById(404L)).thenReturn(null);
assertThrows(BusinessException.class, () -> service.delete(404L, null));
verifyNoInteractions(productMapper);
}
// ===================== 列表(productCount 统计) =====================
@Test
void 列表按排序返回且productCount现算() {
JdProductGroupEntity first = groupEntity(2L, 5L, "晚出厂");
first.setSortOrder(0);
JdProductGroupEntity second = groupEntity(1L, 5L, "早出厂");
second.setSortOrder(1);
when(groupMapper.selectList(any())).thenReturn(List.of(first, second));
when(productMapper.selectCount(any())).thenReturn(12L, 0L);
List<JdProductGroupVo> items = service.list(5L);
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(1, items.get(1).getSortOrder());
verify(productMapper, times(2)).selectCount(any());
assertNotNull(items.get(0).getCreatedAt());
}
@Test
void 列表超管不选公司查全量() {
when(groupMapper.selectList(any())).thenReturn(List.of());
List<JdProductGroupVo> items = service.list(null);
assertTrue(items.isEmpty());
verify(groupMapper).selectList(any());
}
// ---------------------------------------------------------------- 助手
private static JdProductGroupEntity groupEntity(long id, long companyId, String name) {
JdProductGroupEntity group = new JdProductGroupEntity();
group.setId(id);
group.setCompanyId(companyId);
group.setName(name);
group.setSortOrder(3);
group.setCreatedAt(LocalDateTime.of(2026, 11, 14, 10, 0));
return group;
}
}