feat(phase-5): 后管京东数据库接口与页面+用户端采集入口——v1.4 Phase 5
This commit is contained in:
@@ -85,7 +85,10 @@ class MigratedSqlEquivalenceTest {
|
||||
// 105 → 109:2026-11-11「按主管划分」同一 mapper 再落 4 条 select(主管聚合 count/page
|
||||
// +按主管导出 count/page),同样从来没有注解原文可对撞,逐条点名
|
||||
//(SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 151 → 155)。
|
||||
private static final int XML_SELECT_TOTAL = 109;
|
||||
// 109 → 111:v1.4 Phase 5(2026-11-14)后管只读页在 JdProductMapper 新写 2 条只读 select
|
||||
//(countProducts + selectProductPage)。注意本格是「全部 XML 的 select 总数」(不走
|
||||
// NOT_MIGRATED 豁免——豁免只作用于等价性那支),新写 select 也计入本分母。
|
||||
private static final int XML_SELECT_TOTAL = 111;
|
||||
|
||||
/**
|
||||
* 不是「从注解搬过来」的语句:注解时代没有原文可对撞,等价性这支只能跳过它们。
|
||||
@@ -186,7 +189,13 @@ class MigratedSqlEquivalenceTest {
|
||||
// uk_product_image),注解时代没有原文可对撞,逐条点名留痕
|
||||
//(SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 155 → 157)。
|
||||
"JdProductMapper#upsertBatch",
|
||||
"JdProductImageMapper#upsertBatch");
|
||||
"JdProductImageMapper#upsertBatch",
|
||||
// v1.4 Phase 5(2026-11-14):后管只读页在 JdProductMapper 新写 2 条只读 select
|
||||
//(countProducts + selectProductPage,同一过滤面、offset/limit 由服务钳制后传参),
|
||||
// 注解时代没有原文可对撞,逐条点名留痕
|
||||
//(SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 157 → 159)。
|
||||
"JdProductMapper#countProducts",
|
||||
"JdProductMapper#selectProductPage");
|
||||
|
||||
/** 账本 5 列:接口 / 方法 / @Select 种类 / 是否含常量插值 / 注解原文(Java 反转义后那条串)。 */
|
||||
private static final int LEDGER_COLUMNS = 5;
|
||||
|
||||
@@ -112,7 +112,10 @@ class SqlLayeringConventionTest {
|
||||
// JdProductMapper#upsertBatch(覆盖最新,uk_company_shop_code)+
|
||||
// JdProductImageMapper#upsertBatch(图片登记,uk_product_image),全部新写,
|
||||
// 同轮登记进 MigratedSqlEquivalenceTest.NOT_MIGRATED(该文件 XML_SELECT_TOTAL 不动:无 select)。
|
||||
private static final int XML_STATEMENT_TOTAL = 157;
|
||||
// 157 → 159:v1.4 Phase 5 后管只读页在 JdProductMapper 落 2 条只读 select
|
||||
//(countProducts + selectProductPage,同过滤面、offset/limit 由服务钳制后传参),
|
||||
// 同轮登记进 MigratedSqlEquivalenceTest.NOT_MIGRATED(该文件 XML_SELECT_TOTAL 不动)。
|
||||
private static final int XML_STATEMENT_TOTAL = 159;
|
||||
|
||||
/**
|
||||
* wrapper 里夹带函数级 SQL 的现状("这不是简单单表"的证据),文件名 → 条数:
|
||||
|
||||
+17
-11
@@ -65,6 +65,9 @@ class PageDefaultsLedgerTest {
|
||||
// 与明细列表端点同参数名同默认值(按出站点计数、不去重)
|
||||
"AdminAppearancePatentCleanItemsController.java#page=FIRST_PAGE",
|
||||
"AdminAppearancePatentCleanItemsController.java#page_size=CLEAN_ITEMS_PAGE_SIZE",
|
||||
// v1.4 Phase 5(2026-11-14):京东数据库后管只读页分页出站点(page/page_size 默认 20)
|
||||
"AdminJdProductController.java#page=FIRST_PAGE",
|
||||
"AdminJdProductController.java#page_size=JD_PRODUCTS_PAGE_SIZE",
|
||||
"AppearancePatentController.java#limit=DEFAULT_RESULT_LIMIT",
|
||||
"CollectDataController.java#page=FIRST_PAGE",
|
||||
"CollectDataController.java#page_size=TASK_LIST_PAGE_SIZE",
|
||||
@@ -115,11 +118,12 @@ class PageDefaultsLedgerTest {
|
||||
List<String> constants = actual.stream().filter(s -> !s.contains("LITERAL")).sorted().toList();
|
||||
|
||||
assertThat(constants)
|
||||
.as("58 处分页/条数出站点的具名默认值必须与台账一一对应"
|
||||
+ "(56→58:2026-11-11 /supervisors 主管聚合卡片页的 page/page_size 两处出站点)")
|
||||
.as("60 处分页/条数出站点的具名默认值必须与台账一一对应"
|
||||
+ "(58→60:v1.4 Phase 5 京东数据库后管只读页 AdminJdProductController 的"
|
||||
+ " page/page_size 两处出站点)")
|
||||
.isEqualTo(LEDGER.stream().sorted().toList());
|
||||
// 同口径非零对照:台账不是空的,扫描器也确实数得出 58 处
|
||||
assertThat(constants).hasSize(58);
|
||||
// 同口径非零对照:台账不是空的,扫描器也确实数得出 60 处
|
||||
assertThat(constants).hasSize(60);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -134,13 +138,14 @@ class PageDefaultsLedgerTest {
|
||||
void oneSemanticCannotGrowASecondDefault() {
|
||||
List<String> actual = sites();
|
||||
assertThat(kindsUsing(actual, "page", "FIRST_PAGE"))
|
||||
.as("页码口径只有一套:全部从 1 起(25→26:2026-11-11 /supervisors 主管聚合卡片页也是分页出站点)")
|
||||
.isEqualTo(26);
|
||||
.as("页码口径只有一套:全部从 1 起(26→27:v1.4 Phase 5 京东数据库只读页也是分页出站点)")
|
||||
.isEqualTo(27);
|
||||
assertThat(distinctConstants(actual, "page_size"))
|
||||
.as("page_size 的默认容量集合:10/15/20/50/1000 五种各自登记,新来第六种要红"
|
||||
+ "(10 是 v1.3 无侵权只读页,蓝图 §3.2 拍板、与前端 OldPagination 首屏同值)")
|
||||
.as("page_size 的默认容量集合:10/15/20/50/1000 各自登记(20 有两把名字:超管台 "
|
||||
+ "ADMIN_LIST_PAGE_SIZE 与 v1.4 京东数据库 JD_PRODUCTS_PAGE_SIZE),新语义要红")
|
||||
.containsExactlyInAnyOrder("USER_LIST_PAGE_SIZE", "ADMIN_LIST_PAGE_SIZE",
|
||||
"TASK_LIST_PAGE_SIZE", "FULL_EXPORT_PAGE_SIZE", "CLEAN_ITEMS_PAGE_SIZE");
|
||||
"TASK_LIST_PAGE_SIZE", "FULL_EXPORT_PAGE_SIZE", "CLEAN_ITEMS_PAGE_SIZE",
|
||||
"JD_PRODUCTS_PAGE_SIZE");
|
||||
// 同一个语义有两种拼写(@RequestParam(name = "page_size") 与 camelCase 的 pageSize),
|
||||
// 而两种拼写实际用到的常量本来就不同。原来把同一个四项清单套在两种拼写上,
|
||||
// 红的是台账写法而不是有人新增了默认值——2026-10-10 出包前对平这一条。
|
||||
@@ -151,10 +156,10 @@ class PageDefaultsLedgerTest {
|
||||
bothSpellings.addAll(distinctConstants(actual, "page_size"));
|
||||
bothSpellings.addAll(distinctConstants(actual, "pageSize"));
|
||||
assertThat(bothSpellings)
|
||||
.as("两种拼写合起来仍只许那五种容量:谁长出第六种,这里就红")
|
||||
.as("两种拼写合起来仍只许那几把容量:谁长出第七种,这里就红")
|
||||
.containsExactlyInAnyOrderElementsOf(java.util.List.of("USER_LIST_PAGE_SIZE",
|
||||
"ADMIN_LIST_PAGE_SIZE", "TASK_LIST_PAGE_SIZE", "FULL_EXPORT_PAGE_SIZE",
|
||||
"CLEAN_ITEMS_PAGE_SIZE"));
|
||||
"CLEAN_ITEMS_PAGE_SIZE", "JD_PRODUCTS_PAGE_SIZE"));
|
||||
assertThat(distinctConstants(actual, "limit"))
|
||||
.as("limit 是「本次最多返回几条」,不许和 page_size 混用同一批常量")
|
||||
.containsExactlyInAnyOrder("DEFAULT_RESULT_LIMIT", "ADMIN_SCAN_LIMIT");
|
||||
@@ -186,6 +191,7 @@ class PageDefaultsLedgerTest {
|
||||
assertPair(PageDefaults.FULL_EXPORT_PAGE_SIZE, PageDefaults.FULL_EXPORT_PAGE_SIZE_INT);
|
||||
assertPair(PageDefaults.DEFAULT_RESULT_LIMIT, PageDefaults.DEFAULT_RESULT_LIMIT_INT);
|
||||
assertPair(PageDefaults.ADMIN_SCAN_LIMIT, PageDefaults.ADMIN_SCAN_LIMIT_INT);
|
||||
assertPair(PageDefaults.JD_PRODUCTS_PAGE_SIZE, PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -69,7 +69,11 @@ class CatchSilenceRatchetTest {
|
||||
// LOG_ONLY 与 EMPTY 一格没涨(逐处记名见 STRICT_TOTAL 上方注释)——改的是"查不到"怎么表达,不是把它藏起来。
|
||||
// 11-10 v1.3 外观专利无侵权同步链抬 608 -> 611:三枚不重抛(同步服务两枚+控制器内部令牌回退一枚),
|
||||
// 逐处记名见 STRICT_TOTAL 上方注释;LOG_ONLY 宽口径格 251 没动(宽口径实测已落到 193,离上限很远)。
|
||||
static final int GIVEN_NOT_RETHROW = 611;
|
||||
// 11-14 v1.4 京东数据库抬 611 -> 615:三枚不重抛(Phase 5 后管两处 resolveInternalOperator 返回 null
|
||||
// + parseAttrGroups 的 attr_json 兜底;Phase 2/4 的 7 枚全是 RETHROW、Phase 2 的 scope 行
|
||||
// DuplicateKeyException 是 LOG_ONLY,都不占本格),逐处记名见 STRICT_TOTAL 上方注释;
|
||||
// LOG_ONLY 宽口径格 251 没动(宽口径实测 194,离上限很远)。
|
||||
static final int GIVEN_NOT_RETHROW = 615;
|
||||
static final int GIVEN_LOG_ONLY = 251;
|
||||
static final int GIVEN_EMPTY = 56;
|
||||
|
||||
@@ -324,7 +328,31 @@ class CatchSilenceRatchetTest {
|
||||
// 本格与 NOT_RETHROW/LOG_ONLY/EMPTY 都不动)。误差方向:导出请求的 IO 失败必须给用户
|
||||
// 可读业务错误而不是 500 裸堆栈;反向对照——改成往外抛 IOException=前端拿到 Spring 兜底文案,
|
||||
// 改成吞掉返回空字节=用户拿到 0 字节 xlsx 还以为导出成功(比报错更贵)。
|
||||
static final int STRICT_TOTAL = 1074;
|
||||
// 11-14 v1.4 京东数据库抬 1074 -> 1090,十六枚逐处记名(Phase 2 采集域 7 枚与 Phase 4 通用化
|
||||
// 3 枚随各自 commit 落码、当时未进点名册,Phase 5 收尾跑全量时由本棘轮一次性抓出,此处并册):
|
||||
// 【Phase 4 通用化预签名,3 枚全 RETHROW】`OssStorageService.presignObjectUpload` /
|
||||
// `objectSize`(ErrorResponseException 非 404 分支 + Exception 兜底,共 2 枚):全部转
|
||||
// `storageFailure`——预签名/对撞失败必须给可读业务错误,静默 return null 会让客户端拿
|
||||
// null uploadUrl 直传炸得更深。
|
||||
// 【Phase 2 采集域,7 枚】`JdCollectTaskService`:① 建单载荷序列化 `catch Exception` →
|
||||
// BusinessException(RETHROW);② scope 行 `catch DuplicateKeyException` → log.info 复用
|
||||
// 先到行(LOG_ONLY +1,并发建单幂等语义,不吞成败);③④ `readCreateRequest` 的
|
||||
// `catch BusinessException → throw ex` + `catch Exception → BusinessException`(RETHROW,
|
||||
// 载荷损坏按异常拒绝回传不静默兜)。`JdResultIngestService`:⑤⑥ `parseState`/`writeJson`
|
||||
// → BusinessException(RETHROW,台账损坏显形);⑦ `toSummary` `catch IllegalArgumentException`
|
||||
// → BusinessException 带字段消息(RETHROW)。
|
||||
// 【Phase 5 后管,6 枚】① `AdminJdProductController.resolveOperator` 与 ②
|
||||
// `AdminJdProductGroupController.resolveOperator`:`catch BusinessException` ⇒ 先试内部令牌
|
||||
// 回退,回退失败把原鉴权异常原样重抛(RETHROW +2)。③④ 同两文件的
|
||||
// `resolveInternalOperator`:`catch NumberFormatException | BusinessException` ⇒ 返回 null ⇒
|
||||
// 上层把原 401/403 原样抛回(NOT_RETHROW +2)。⑤ `JdProductQueryService.parseAttrGroups`:
|
||||
// attr_json 解析 `catch Exception` ⇒ log.warn 带 productId + 空分组 + 原文透 attrJsonRaw
|
||||
// 兜底(AC-7 未识别属性不丢弃;NOT_RETHROW +1)。反向对照:改成往外抛=一条脏 attr_json
|
||||
// 让整行详情 500;改成静默空分组不带原文=用户看到的属性被悄悄吞掉。⑥
|
||||
// `JdProductQueryService.writeExportWorkbook`:SXSSF 落盘 `catch Exception` →
|
||||
// BusinessException「导出京东数据库失败,请稍后重试」(RETHROW +1,与 11-11 外观专利导出同款)。
|
||||
// 本批复核办法:单跑实测 total 1090、notRethrow 614、logOnly 194、empty 56(EMPTY 一格没涨)。
|
||||
static final int STRICT_TOTAL = 1090;
|
||||
/**
|
||||
* 重抛型 catch 的**下限**(不是上限):本轮把两处吞异常改成重抛之后实测 388。
|
||||
* 这一格只能涨不能跌——它是"异常会往外走"的总量,把它钉成"只许减"就等于拦着别人修吞异常。
|
||||
@@ -453,7 +481,12 @@ class CatchSilenceRatchetTest {
|
||||
// 11-05 密钥余额三面:五枚 NOT_RETHROW(1065->1069 那批),严格口径实测 603 -> 608;
|
||||
// 上一格 604 是**上限**而实测量一直低它一枚,这次新增把那一枚额度用掉又超上去——逐处见 STRICT_TOTAL 上方。
|
||||
// 11-10 v1.3 同步链:严格口径实测 608 -> 611(三枚不重抛),出处见 STRICT_TOTAL 上方注释。
|
||||
static final int STRICT_NOT_RETHROW = 611;
|
||||
// 11-14 v1.4 京东数据库后管:严格口径实测 611 -> 614(三枚不重抛:两处 resolveInternalOperator
|
||||
// 返回 null + parseAttrGroups 的 attr_json 兜底),出处见 STRICT_TOTAL 上方注释。
|
||||
// 本格含 LOG_ONLY(incl 口径):同批 Phase 2 建单 scope 行那枚 DuplicateKeyException 复用
|
||||
// 先到行把 LOG_ONLY 抬 193 -> 194 时连带占本格一枚额度 ⇒ 614 -> 615(出处同 STRICT_TOTAL
|
||||
// 上方注释;这是本格**含 LOG_ONLY** 口径的连带,不是又一枚新的不重抛)。
|
||||
static final int STRICT_NOT_RETHROW = 615;
|
||||
/**
|
||||
* 10-17 抬 172 -> 173,出处就是上面点名过的 {@code TaskHeartbeatLivenessService.stamp()}:
|
||||
* 块体只有「取到 key 名 + log.warn」一句,写心跳证据失败时既不重试也不抛出——
|
||||
@@ -487,7 +520,7 @@ class CatchSilenceRatchetTest {
|
||||
* 同日 Phase 5.1 再抬 189 -> 190:登记行落库失败后的对象回收失败只 WARN(同上锚点),
|
||||
* 主错误仍由外层转业务错误;不吞主错误。
|
||||
*/
|
||||
static final int STRICT_LOG_ONLY = 193; // 严格口径:块内每条顶层语句都是 log 调用才算(11-01 重试两处兜底 +2、11-10 v1.3 同步服务 syncFromResult +1,见 STRICT_TOTAL 上方)
|
||||
static final int STRICT_LOG_ONLY = 194; // 严格口径:块内每条顶层语句都是 log 调用才算(11-01 重试两处兜底 +2、11-10 v1.3 同步服务 syncFromResult +1、11-14 v1.4 建单 scope 行 DuplicateKeyException 复用先到行 +1,见 STRICT_TOTAL 上方)
|
||||
static final int STRICT_EMPTY = 56;
|
||||
|
||||
/**
|
||||
|
||||
+496
@@ -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();
|
||||
}
|
||||
}
|
||||
+244
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user