feat(公司tab): 批次 2/3/4 再接 8 页,注册表收到 16 页——用户页回流 company_id 按新边界改写反向钉

「切 tab 数据还一样」的根因一直是分母小于现实:批次 1 只登记 8 页,本轮按控制方
三次点名扩到 16 页(company-scope.ts 是唯一清单,routes.ts 的 companyScoped 逐页对平)。

批次 2(五页 ASIN 中心):去重总数据 / 不符合ASIN / 查询ASIN / 最低价ASIN / 商品类目。
批次 3(两页店铺中心):撞款监控、店铺数据记录。这两页没有归属列可筛,归属口径是
「本公司账号名下的店铺」——后端由 DataReadScope 推公司 → 成员账号 → biz_shop_manage.
created_by_id,前端只把 activeId 当 company_id 送下去。空成员集必须交空集合,绝不能
退化成 null(null 在这里=全量,那样第二家会看到全部数据)。
批次 4(用户管理):后端早就认 company_id(只对站点超管生效,公司超管恒锁本公司),
断的是前端——UserListQuery 里连这个字段都没有,三家 tab 看的是同一份全量列表。

三处口径改动,逐条说明:
1)company-user-list.test.ts 的反向钉被改写。2026-10-04 定案把公司维度从用户页整体摘掉,
   那条钉的原文是「列表查询/筛选/行渲染不允许出现公司维度」。控制方 2026-10-05 明确要
   用户管理区分公司 tab,所以钉的边界收窄成两半:渲染层(行级公司列、「所属公司」标签、
   筛选状态、顶栏公司名)仍不得回流;请求层的 company_id 是这次加回来的,尺子换成
   「取值口唯一」——页面每处 companyId 都必须等于 companyTab.requestCompanyId,且
   normalizeUserPageParams/toUserListQuery 两只白名单构造器体内不许出现公司值。
   新增一支行为钉:往归一化里传 companyId 必须被丢掉,这是 users.ts 读原始入参的全部理由
   (写成 normalized.companyId 时 TS 照样绿、运行时恒 undefined)。
2)align-dup-console 那条 watch 看守的 token 扩到含 reload。变异自证里「删掉 void
   loadConsole()」当场全绿:体里的清筛选项守住了,重新取数那半没人守。批次 3/4 三对
   token 一起写到 reload 为止(批次 1/2 的老条目不动)。
3)公司管理页补正/反向两把尺子:company-config-entry-super-only 新增「吃公司 tab 的页面
   集合恰好等于 COMPANY_SCOPED_PAGES 的 pageFiles」——按代码真值比,不按清单比,所以
   清单不改一字而往 CompaniesPage.vue 里塞 store 也会红。谓词带括号,否则 import 行也算消费者。

菜单权限(admin_columns)本轮不动:MenusPage 只消费 /api/admin/permission-menus 这一份全局
菜单字典,切 tab 一样是数据本身全局,不是筛选坏了。真问题在写侧——PermissionMenuService
create/update/delete 只有 ensureAdminOperatorIfPresent(isAdmin 即放行),公司管理员改的是
全平台的菜单行。收窄为仅站点超管 vs 给 permission_menu 加归属列,两种改法代价差一个量级,
留给控制方定档。

护栏:G1 发送口 22 个 / 页面分组 17、watch 体看守 10 对、operation-guide 的 tab 文案 15 页
(撞款监控是显式豁免,另有一条自检盯「豁免落空」)。
变异自证 12/12 全杀(前端 10 + 公司管理反向钉 2),分母钉死在 27 例。
门禁:后端全量 3823 例 / 0 失败 / 0 错误 / 7 skipped,BUILD SUCCESS;admin-frontend-vue
1741 例 / 0 红;vue-tsc rc=0。首轮后端 4 红是另一路 task_partial 改动与本轮编译抢跑,
单跑 13 例已绿,本笔不含他们的任何文件。

未上线:jar 与 admin-vue 都没出包,V147 未在生产执行。
This commit is contained in:
2026-10-06 02:32:59 +08:00
parent e5e36aa713
commit 16583f578d
87 changed files with 3519 additions and 459 deletions
+7 -5
View File
@@ -1,14 +1,16 @@
# Flyway 迁移盘点(task-193)
> 生成方式:`src/test/java/com/nanri/aiimage/config/MigrationInventoryTest.java`(只读审计,可重复)。
> 快照日期:2026-10-01;2026-10-03 随 V142 追加时同步过概览数字与取号起点;2026-10-04 随 V143 同步;2026-10-04 随 V144 同步;2026-10-04 15:1x 随 V145 同步;2026-10-05 随 V146 同步。
> 快照日期:2026-10-01;2026-10-03 随 V142 追加时同步过概览数字与取号起点;2026-10-04 随 V143 同步;2026-10-04 随 V144 同步;2026-10-04 15:1x 随 V145 同步;2026-10-05 随 V146 同步;2026-10-05 23:0x 随 V147 同步。
## 概览
- 版本化迁移文件数:**145**(`src/main/resources/db/V*.sql`,其中整数版本 144 个 + 小版本 V25_1)
- 整数版本范围:**V1..V146**,其中 V132/V133 为已退役空号(见下),其余连续
- 版本化迁移文件数:**146**(`src/main/resources/db/V*.sql`,其中整数版本 145 个 + 小版本 V25_1)
- 整数版本范围:**V1..V147**,其中 V132/V133 为已退役空号(见下),其余连续
- 历史遗留小版本:**V25_1__shop_manage_group_bind_user.sql**(Flyway 语义 25.1,紧跟在 V25 之后、V26 之前执行,属历史命名,保留)
- 最新版本:**V146__users_expires_at_admin_expiry.sql**(上一版 **V145__brand_dedupe_company_scope.sql**;V142 已于 10-03 18:23 应用、V143 已于 10-04 10:48 应用、**V144 已于 10-04 13:22 应用**;V145/V146 待下一次 jar 发版执行)
- 最新版本:**V147__product_category_company_scope.sql**(上一版 **V146__users_expires_at_admin_expiry.sql**,再上一版 **V145__brand_dedupe_company_scope.sql**)
- 待下一次 jar 发版执行的三条:`V145__brand_dedupe_company_scope.sql`、`V146__users_expires_at_admin_expiry.sql`、`V147__product_category_company_scope.sql`
- 已应用:V142(10-03 18:23)、V143(10-04 10:48)、**V144(10-04 13:22)**
- 重复版本:无
- 迁移命名:全部符合 `V<整数>(_<子版本>)?__<描述>.sql`,无空格
@@ -20,7 +22,7 @@
本地曾存在 `V132__web_config_add_is_latest.sql`、`V133__hide_redundant_indexes_invisible.sql`,与另一分支已在生产落库的 V134/V135 冲突。因 Flyway 未开启 `out-of-order`,把任何迁移编到 132/133 会在启动期报 "resolved migration not applied";因此这两条改为 **V136/V137**,132/133 永久退役,不可回填。
后续新增迁移从 **V147** 起取号(只认"当前最大值 + 1",不要为还没写出来的迁移预留号段——预留会在 1..max 里留洞,`integerVersionsSequentialFromOne` 会红)。
后续新增迁移从 **V148** 起取号(只认"当前最大值 + 1",不要为还没写出来的迁移预留号段——预留会在 1..max 里留洞,`integerVersionsSequentialFromOne` 会红)。V148 的第一件已知待办就是摘掉 `biz_product_category.company_id` 的 DEFAULT(一条 `ALTER … ALTER COLUMN company_id DROP DEFAULT`,禁 MODIFY),前提是同批 jar 已双节点上线且写侧都显式落公司。
原先挂在待办里的"V137 冗余索引 DROP"迁移计划取 V139,该号已被 `V139__asin_result_cache.sql` 占用,顺延到 V140;V140 已被品牌补测队列表 `V140__collectdata_brand_recheck.sql` 落用。
@@ -0,0 +1,42 @@
-- 回滚 V147(人工补丁,不放进 src/main/resources/db/——那里是 Flyway 扫描路径,
-- 任何 V*.sql 都会在应用下次启动时自动执行;把回滚编成版本化迁移等于让"决定回滚"这件事
-- 在没有人工执行的情况下自己发生。)
--
-- 顺序:停两台应用 → 执行本脚本 → DELETE FROM flyway_schema_history WHERE version='147'
-- → 回滚 jar → 起应用。
-- 漏掉"删历史行"那步,将来重装带 V147 的 jar 时 Flyway 判定"已应用"直接跳过,列与键都不会重建,
-- 而 Java 侧实体照常读写 company_id ⇒ 运行期 Unknown column。
--
-- ⚠ 本脚本默认只做「保留新列、把唯一键退回全局」这一档。
-- 退回全局唯一键要求"跨公司没有同名 category_key"。V147 之前该键是全平台唯一,所以【回填那一刻】
-- 必然满足;但批次 2/3(每公司自建类目)上线之后这一前提不再由代码保证——两家各自建了同名
-- 自定义类目时,generateCategoryKey(parentId, name) 会算出同一串。所以先跑第 0 段那条预检查询。
-- 报 1062 说明确实已经有跨公司同名行:此时【不要】硬删数据,改走"保留新键、只回滚 jar"
-- (新列对新 jar 是惰性的,不读写就不影响)。
-- ---------- 0. 预检(必须先跑,返回 0 行才允许第 1 段) ----------
-- SELECT company_id, category_key, COUNT(*) c
-- FROM `biz_product_category`
-- GROUP BY company_id, category_key
-- HAVING COUNT(*) > 1;
-- -> 期望 0 行。非 0 就是"跨公司已有同名键",第 1 段会撞 1062。
-- SELECT SUM(is_builtin = 1 AND company_id <> 0) AS bad_builtin
-- FROM `biz_product_category`;
-- -> 期望 0。非 0 说明有内置节点被当成公司自建,回滚后这些节点在旧 jar 里仍会出现在每一家的树上,
-- 与 V147 之前的行为一致,不影响回滚本身,但要记进核对清单。
-- ---------- 1. 唯一键退回全局(先加旧键、后删新键,理由同 V147:中间任一步都至少有一个唯一键在守并发) ----------
ALTER TABLE `biz_product_category`
ADD UNIQUE KEY `uk_product_category_key` (`category_key`),
ALGORITHM = INPLACE, LOCK = NONE;
ALTER TABLE `biz_product_category`
DROP INDEX `uk_company_category_key`,
ALGORITHM = INPLACE, LOCK = NONE;
-- ---------- 2. 真的要把列也删掉才解开下面这行(不可逆,先备份) ----------
-- company_id 上写着"哪个自定义节点是哪一家建的",而这张表没有任何账号列(V147 §2:事后无法反推),
-- 一旦 DROP 就只能靠"全表填 1"重建 ⇒ 第 2 家自建的类目会全部划归第 1 家,且再没有证据能分回去。
-- 另外哨兵那条纪律在这里同样成立:摘 DEFAULT 用 ALTER COLUMN ... DROP DEFAULT,
-- 任何时候都不要写 MODIFY COLUMN(重建表会按"当时的列默认值"物化历史行)。
-- ALTER TABLE `biz_product_category` DROP COLUMN `company_id`;
@@ -49,6 +49,26 @@ public class CompanyScopeSupport {
return companyId;
}
/**
* 后台自动写入路径(货源 chunk 回传、品牌补测调度器)专用的宽容版:账号已经不存在时返回 null,
* 而不是像 {@link #requireCompanyId(Long)} 那样抛。
*
* <p>这两个入口的锚点是 {@code biz_file_task.user_id},而账号是**物理删**的:2026-10-05 生产只读
* 取证,2026-06 以来的 716 条任务里 108 条的 user_id 在 users 里查不到(货源 174 条里 2 条)。
* 在这里抛等于让整单采集提交失败——比归属失真更糟。调用方拿到 null 必须记一条可巡检的日志、
* 并放弃这批写入,不许把 null 传进实体让 DEFAULT 1 静默兜住。</p>
*/
public Long companyIdOrNull(Long userId) {
if (userId == null || userId <= 0) {
return null;
}
AdminUserEntity user = adminUserMapper.selectById(userId);
if (user == null || user.getCompanyId() == null || user.getCompanyId() <= 0) {
return null;
}
return user.getCompanyId();
}
/** 行级归属闸门:跨公司写/删的第一道,消息由调用方给(前端按它显示,别在这里编文案)。 */
public void assertSameCompany(Long operatorCompanyId, Long rowCompanyId, String deniedMessage) {
if (rowCompanyId == null || !rowCompanyId.equals(operatorCompanyId)) {
@@ -39,4 +39,26 @@ public class DataReadScope {
List<Long> base = userDataScopeSupport.resolveVisibleUserIds(operator.getId());
return ReadScope.users(ReadScope.users(companyScope.memberUserIds(own)).userIdsOr(base));
}
/**
* 归属已经**物化成 company_id 列**的表(品牌库 biz_invalid_asin_data)用的谓词出口:
* 返回要筛的公司 id,null = 不筛。
*
* <p>这些表不能走 {@link #readScope} 的账号集合:2026-10-05 生产只读取证,品牌库 14,801 行里
* {@code uploader_user_id} 非空的有 <b>0</b> 行(实体没这字段、批量 INSERT 的列清单也没带,
* V145 补的列一直是空的),按账号筛等于把全部历史从每一个公司 tab 里静默删掉。
* 而 {@code company_id} 那一列虽然是被 DEFAULT 1 盖上去的,对历史却是诚实的:
* 第 2 家公司 10-04 14:55 才开通,它名下账号历史任务 0 条、去重库上传 0 行,
* 所以「建号之前存在的行都归第 1 家」是可证的事实,不是猜。</p>
*
* <p>非超管返回 null(不筛):他们的可见集本来就锁在自己的分组上,叠一层公司会把
* 「靠分组可见」的行整批删掉(同 {@code ShopManageController} 的口径)。
* 超管的 company_id 是视图开关不是安全边界(spec §4),所以这里不需要再校验它属于谁。</p>
*/
public Long readCompanyId(AdminUserEntity operator, Long requestedCompanyId) {
if (!SUPER_ADMIN.equals(adminAuthSupport.currentRole(operator))) {
return null;
}
return requestedCompanyId != null && requestedCompanyId > 0 ? requestedCompanyId : null;
}
}
@@ -44,12 +44,38 @@ public final class ExcelStreamReader {
} else {
EasyExcel.read(inputStream, listener).sheet(0).headRowNumber(1).doRead();
}
} catch (WrappedRuntimeException ex) {
if (ex.getCause() instanceof IOException ioException) {
} catch (RuntimeException ex) {
// EasyExcel/POI 的解析异常是 RuntimeException,原样冒到接口层会变成 HTTP 500;
// 本工具的契约是 IOException,调用方已按 IOException 给用户回 400。
throw toContractException(listener.handlerFailure(), ex);
}
}
private static IOException toContractException(Exception handlerFailure, RuntimeException readFailure) throws IOException {
if (handlerFailure != null) {
// 调用方自己抛的不算"文件坏了":运行时异常原样透传,保住 BusinessException 的 400 语义。
if (handlerFailure instanceof IOException ioException) {
throw ioException;
}
throw ex;
if (handlerFailure instanceof RuntimeException runtimeException) {
throw runtimeException;
}
throw new IOException("Excel 行处理失败:" + describe(handlerFailure), handlerFailure);
}
throw new IOException("Excel 解析失败:" + describe(readFailure), readFailure);
}
private static String describe(Throwable ex) {
Throwable deepest = ex;
String message = ex.getMessage();
while (deepest.getCause() != null) {
deepest = deepest.getCause();
String current = deepest.getMessage();
if (current != null && !current.isBlank()) {
message = current;
}
}
return message == null || message.isBlank() ? ex.getClass().getSimpleName() : message;
}
public interface SheetRowHandler {
@@ -70,11 +96,27 @@ public final class ExcelStreamReader {
private final SheetRowHandler handler;
private Map<Integer, String> currentHeaderMap = Map.of();
private Exception handlerFailure;
private StreamingListener(SheetRowHandler handler) {
this.handler = handler;
}
private Exception handlerFailure() {
return handlerFailure;
}
/** 记下调用方抛出的异常,好让 runRead 分得清「文件解析坏了」和「行处理被调用方拒了」。 */
private RuntimeException recordHandlerFailure(Exception ex) {
if (handlerFailure == null) {
handlerFailure = ex;
}
if (ex instanceof RuntimeException runtimeException) {
return runtimeException;
}
return new WrappedRuntimeException(ex);
}
@Override
public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
Map<Integer, String> normalizedHeadMap = new LinkedHashMap<>();
@@ -85,10 +127,8 @@ public final class ExcelStreamReader {
try {
handler.onHeader(sheetName(context), sheetNo(context), currentHeaderMap);
handler.onSheetTotal(sheetName(context), sheetNo(context), approximateTotalRows(context));
} catch (RuntimeException ex) {
throw ex;
} catch (Exception ex) {
throw new WrappedRuntimeException(ex);
throw recordHandlerFailure(ex);
}
}
@@ -106,10 +146,8 @@ public final class ExcelStreamReader {
currentHeaderMap,
normalizedRow
);
} catch (RuntimeException ex) {
throw ex;
} catch (Exception ex) {
throw new WrappedRuntimeException(ex);
throw recordHandlerFailure(ex);
}
}
@@ -1039,7 +1039,8 @@ public class BrandTaskService {
} catch (BusinessException ex) {
throw ex;
} catch (IOException ex) {
throw new BusinessException("读取 Excel 失败");
log.warn("[brand] Excel 解析失败 file={} err={}", inputFile.getName(), ex.getMessage(), ex);
throw new BusinessException("读取 Excel 失败", ex);
}
return context.finish();
}
@@ -111,7 +111,7 @@ public class CollectDataBrandRecheckInjector {
List<CollectDataResultRowVo> chunkRejected = rowsOfBrands(rows, rejectedBrands);
if (!chunkRejected.isEmpty()) {
// INSERT IGNORE 幂等:重复补测同品牌不会在无效品牌表翻倍
rejectedRows += invalidAsinBatchWriter.writeBatch(chunkRejected);
rejectedRows += invalidAsinBatchWriter.writeBatch(chunkRejected, task.getUserId());
}
}
if (cleanBrands.isEmpty()) {
@@ -896,7 +896,7 @@ public class CollectDataService {
// 8 行查询失败被写表后误杀,最终结果 Excel 0 行)。rejected 为空时
// 不触发任何写入,避免空批次无意义调用。
if (!brandOutcome.rejected().isEmpty()) {
invalidAsinBatchWriter.writeBatch(brandOutcome.rejected());
invalidAsinBatchWriter.writeBatch(brandOutcome.rejected(), task.getUserId());
}
List<CollectDataResultRowVo> accepted = brandOutcome.accepted();
// 结果明细改为 chunk 级存储:整个 chunk 的 accepted 行共享一个
@@ -1,5 +1,6 @@
package com.nanri.aiimage.modules.collectdata.util;
import com.nanri.aiimage.common.service.CompanyScopeSupport;
import com.nanri.aiimage.modules.collectdata.model.vo.CollectDataResultRowVo;
import com.nanri.aiimage.modules.invalidasin.mapper.InvalidAsinDataMapper;
import com.nanri.aiimage.modules.invalidasin.model.entity.InvalidAsinDataEntity;
@@ -15,30 +16,52 @@ import java.util.regex.Pattern;
/**
* invalid ASIN 批量写入器:把不合规 ASIN 行按批次批量 INSERT IGNORE 写入
* biz_invalid_asin_data,替代逐行 insert + 捕获唯一键异常的旧路径。
* 幂等由唯一键 (data_value, brand) + INSERT IGNORE 语义保证;批量失败时
* 幂等由唯一键 (company_id, data_value, brand) + INSERT IGNORE 语义保证;批量失败时
* 跳过该批(记录计数,不中断提交流程),恢复后继续后续批次。
* 空输入、无合法 data_value/brand 的行、null 行均安全跳过,不发起调用。
*
* <p>归属(company_id + uploader_user_id)由调用方给任务发起账号,本类负责推公司:
* 此前实体与 INSERT 列清单都不带这两列,V145 补的 company_id 全靠 DEFAULT 1 盖,
* 于是第 2 家公司跑货源产生的行会被记成第 1 家,且事后分不开。</p>
*/
@Slf4j
@Component
public class CollectDataInvalidAsinBatchWriter {
/** 巡检可 grep 的标记:账号已不存在、推不出公司,这批 rejected 品牌整批不写。 */
static final String OWNER_UNRESOLVED_MARKER = "INVALID_ASIN_OWNER_UNRESOLVED";
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
private final InvalidAsinDataMapper invalidAsinDataMapper;
private final CompanyScopeSupport companyScopeSupport;
private final int batchSize;
public CollectDataInvalidAsinBatchWriter(InvalidAsinDataMapper invalidAsinDataMapper,
CompanyScopeSupport companyScopeSupport,
@Value("${aiimage.collect-data.invalid-asin-batch-size:100}") int batchSize) {
this.invalidAsinDataMapper = invalidAsinDataMapper;
this.companyScopeSupport = companyScopeSupport;
this.batchSize = Math.max(1, batchSize);
}
/** 批量写入并返回实际尝试写入的行数(INSERT IGNORE 忽略重复,幂等)。 */
public int writeBatch(List<CollectDataResultRowVo> rows) {
/**
* 批量写入并返回实际尝试写入的行数(INSERT IGNORE 忽略重复,幂等)。
*
* @param uploaderUserId 任务发起账号(biz_file_task.user_id);推不出公司时整批不写并打
* {@link #OWNER_UNRESOLVED_MARKER}——宁可少记一条黑名单,
* 也不把行盖成别家公司(那会让另一家的正常品牌被静默过滤)
*/
public int writeBatch(List<CollectDataResultRowVo> rows, Long uploaderUserId) {
if (rows == null || rows.isEmpty()) {
return 0;
}
Long companyId = companyScopeSupport.companyIdOrNull(uploaderUserId);
if (companyId == null) {
log.warn("{} 无法按账号推出处置公司,本批不写入无效品牌表 rows={} userId={}",
OWNER_UNRESOLVED_MARKER, rows.size(), uploaderUserId);
return 0;
}
int written = 0;
for (int start = 0; start < rows.size(); start += batchSize) {
int end = Math.min(start + batchSize, rows.size());
@@ -47,6 +70,8 @@ public class CollectDataInvalidAsinBatchWriter {
for (CollectDataResultRowVo row : batch) {
InvalidAsinDataEntity entity = toEntity(row);
if (entity != null) {
entity.setCompanyId(companyId);
entity.setUploaderUserId(uploaderUserId);
entities.add(entity);
}
}
@@ -20,7 +20,9 @@ import java.util.Map;
* 唯一理由是发布期的旧 jar,§8.2 / V145 头注释)。正因为它安静,所以由代码来喊,而不是靠人记得。</p>
*
* <p>盯的列随迁移增长:V143 给 {@code users} 加过一版(DEFAULT 已由 V144 摘),V145 给两张规则库
* 各加一版。一张表一行都插不进来的时候才是"摘干净",所以这里探的是【清单】而不是单个列名。</p>
* 各加一版,V147 给 {@code biz_product_category} 加一版。一张表一行都插不进来的时候才是"摘干净",
* 所以这里探的是【清单】而不是单个列名。清单与探针 SQL 的 IN 列表由 {@code CompanyDefaultGuardTest}
* 双向钉同源:只钉"清单里的都在 SQL 里"会漏掉"SQL 里有、清单漏了"那一半,而那一半才是静默的形状。</p>
*
* <p>标记串({@link #ALARM} / {@link #PROBE_FAILED})是纯 ASCII:巡检脚本要在 docker logs 里
* grep 它,中文一旦在容器里变了编码就整条签名失效。</p>
@@ -39,14 +41,17 @@ public class CompanyDefaultGuard {
/**
* 该带 company_id 且历史上可能被塞过 DEFAULT 的表。新增一列就要在这里登记一条——
* 漏登记的后果不是报错,是哨兵对着一个不存在的列一声不响({@link #check} 会把它当探不到处理)。
* V147 的 {@code biz_product_category} 是第四条:它的 DEFAULT 1 同样只为同批旧 jar 存在,
* 摘除动作与上面三张同形(一条元数据操作,禁 MODIFY)。
*/
static final List<String> WATCHED_TABLES = List.of(
"users", "biz_invalid_asin_data", "biz_dedupe_total_data");
"users", "biz_invalid_asin_data", "biz_dedupe_total_data", "biz_product_category");
private static final String COLUMN_DEFAULT_SQL = """
SELECT TABLE_NAME, COLUMN_DEFAULT FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND COLUMN_NAME = 'company_id'
AND TABLE_NAME IN ('users', 'biz_invalid_asin_data', 'biz_dedupe_total_data')
AND TABLE_NAME IN ('users', 'biz_invalid_asin_data', 'biz_dedupe_total_data',
'biz_product_category')
""";
private final CompanyMapper companyMapper;
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.dedupe.controller;
import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.common.util.DownloadHeaderUtil;
import com.nanri.aiimage.modules.dedupe.model.dto.DedupeTotalDataCreateRequest;
import com.nanri.aiimage.modules.dedupe.model.dto.DedupeTotalDataUpdateRequest;
@@ -48,6 +49,7 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.util.List;
@RestController
@RequiredArgsConstructor
@@ -65,6 +67,7 @@ public class DedupeTotalDataController {
private final DedupeTotalDataService dedupeTotalDataService;
private final AdminAuthSupport adminAuthSupport;
private final PermissionMenuService permissionMenuService;
private final DataReadScope dataReadScope;
@@ -86,10 +89,16 @@ public class DedupeTotalDataController {
@Parameter(description = "国家代码(如 DE、UK)") @RequestParam(name = "country", required = false) String country,
@Parameter(description = "顺序翻页游标(上一页返回的 nextLastId;传了就忽略 page 偏移)")
@RequestParam(name = "last_id", required = false) Long lastId,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
HttpServletRequest request) {
RequestOperator operator = requireDedupeTotalDataAccess(request);
AdminUserEntity user = operator.user();
List<Long> memberIds = operator.superAdmin()
? dataReadScope.readScope(user, companyId).userIdsOr(null)
: null;
return ApiResponse.success(dedupeTotalDataService.page(
page, pageSize, keyword, username, startDate, endDate, groupId, country, lastId, operator.id()));
page, pageSize, keyword, username, startDate, endDate, groupId, country, lastId,
operator.id(), memberIds));
}
@GetMapping("/export")
@@ -102,19 +111,27 @@ public class DedupeTotalDataController {
@RequestParam(name = "end_date", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
@Parameter(description = "分组 ID") @RequestParam(name = "group_id", required = false) Long groupId,
@Parameter(description = "国家代码(如 DE、UK)") @RequestParam(name = "country", required = false) String country,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
HttpServletRequest request) {
if (startDate != null && endDate != null && startDate.isAfter(endDate)) {
throw new BusinessException(400, "invalid export date range");
}
RequestOperator operator = requireDedupeTotalDataAccess(request);
AdminUserEntity user = operator.user();
Long operatorId = operator.id();
List<Long> memberIds = operator.superAdmin()
? dataReadScope.readScope(user, companyId).userIdsOr(null)
: null;
boolean monthlyZip = isCrossMonthRange(startDate, endDate);
String filename = "dedupe-total-data-" + LocalDateTime.now().format(EXPORT_FILENAME_FORMATTER)
+ (monthlyZip ? ".zip" : ".xlsx");
// 两个分支的实参表都不许出现嵌套括号(operator.id() 那种写法护栏 G2 的单层括号判据看不穿,
// 会把它当成"范围没交给任何调用"而假红),所以 operatorId 先在局部变量里落好。
StreamingResponseBody body = monthlyZip
? outputStream -> dedupeTotalDataService.writeMonthlyZipExport(
outputStream, username, startDate, endDate, groupId, country, operator.id())
outputStream, username, startDate, endDate, groupId, country, operatorId, memberIds)
: outputStream -> dedupeTotalDataService.writeExport(
outputStream, username, startDate, endDate, groupId, country, operator.id());
outputStream, username, startDate, endDate, groupId, country, operatorId, memberIds);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, DownloadHeaderUtil.contentDisposition(filename))
.contentType(MediaType.parseMediaType(monthlyZip ? ZIP_CONTENT_TYPE : XLSX_CONTENT_TYPE))
@@ -224,7 +241,7 @@ public class DedupeTotalDataController {
if (!superAdmin && !hasDedupeTotalDataPermission(operator)) {
throw new BusinessException(403, "无权访问数据去重总数据");
}
return new RequestOperator(operator.getId(), superAdmin);
return new RequestOperator(operator.getId(), superAdmin, operator);
}
private AdminUserEntity resolveOperator(HttpServletRequest request) {
@@ -267,7 +284,13 @@ public class DedupeTotalDataController {
private record RequestOperator(Long id, boolean superAdmin) {
// 公司 tab 的读范围就地算在 handler 里,不留私有收口方法:G2 的断言 A 只在这支 handler 的
// 块内找 readScope(,私有方法在它自己的闭括号处收口、不算在内(CompanyIdParamGoesThroughReadScopeTest
// 类注释第 5、7 条),挪进去 = 这一页的 tab 没人看守。收窄只给超管:非超管已由 resolveAccessScope
// 按会话裁剪,且他的可见集里含「靠分组可见」的行,叠一层账号 IN 会把那批行静默删掉
// (同 ShopManageController 的口径)。
private record RequestOperator(Long id, boolean superAdmin, AdminUserEntity user) {
}
private boolean isTrustedInternalRequest(String suppliedToken) {
return adminAuthSupport.isTrustedSuppliedToken(suppliedToken);
@@ -160,16 +160,18 @@ public class DedupeTotalDataService {
public DedupeTotalDataPageVo page(long page, long pageSize, String keyword, String username,
LocalDate startDate, LocalDate endDate, Long groupId, String country, Long operatorId) {
return page(page, pageSize, keyword, username, startDate, endDate, groupId, country, null, operatorId);
return page(page, pageSize, keyword, username, startDate, endDate, groupId, country, null, operatorId, null);
}
/**
* @param lastId keyset 游标(上一页返回的 nextLastId);非空时忽略 page 偏移,
* 直接按 id 倒序取"比它小"的一页,避免深分页 offset 扫索引的代价
* @param companyMemberIds 公司 tab 收窄后的成员账号集({@code DataReadScope} 给出);
* null = 不筛(超管没选公司 / 非超管走会话范围)
*/
public DedupeTotalDataPageVo page(long page, long pageSize, String keyword, String username,
LocalDate startDate, LocalDate endDate, Long groupId, String country,
Long lastId, Long operatorId) {
Long lastId, Long operatorId, List<Long> companyMemberIds) {
if (startDate != null && endDate != null && startDate.isAfter(endDate)) {
throw new BusinessException("开始日期不能晚于结束日期");
}
@@ -194,6 +196,7 @@ public class DedupeTotalDataService {
endDate == null ? null : endDate.plusDays(1).atStartOfDay())
.orderByDesc(DedupeTotalDataEntity::getId);
applyGroupScope(query, scope, groupId);
applyCompanyScope(query, companyMemberIds);
Long total = dedupeTotalDataMapper.selectCount(query);
boolean keyset = lastId != null && lastId > 0;
if (keyset) {
@@ -256,6 +259,17 @@ public class DedupeTotalDataService {
Long groupId,
String country,
Long operatorId) {
writeExport(outputStream, username, startDate, endDate, groupId, country, operatorId, null);
}
public void writeExport(OutputStream outputStream,
String username,
LocalDate startDate,
LocalDate endDate,
Long groupId,
String country,
Long operatorId,
List<Long> companyMemberIds) {
if (outputStream == null) {
throw new BusinessException("导出输出流不能为空");
}
@@ -264,7 +278,8 @@ public class DedupeTotalDataService {
}
String safeUsername = username == null ? "" : username.trim();
AccessScope scope = resolveAccessScope(operatorId);
buildExportWorkbook(outputStream, safeUsername, startDate, endDate, groupId, country, scope);
buildExportWorkbook(outputStream, safeUsername, startDate, endDate, groupId, country, scope, false,
companyMemberIds);
}
public void writeMonthlyZipExport(OutputStream outputStream,
@@ -283,11 +298,22 @@ public class DedupeTotalDataService {
Long groupId,
String country,
Long operatorId) {
writeMonthlyZipExport(outputStream, username, startDate, endDate, groupId, country, operatorId, null);
}
public void writeMonthlyZipExport(OutputStream outputStream,
String username,
LocalDate startDate,
LocalDate endDate,
Long groupId,
String country,
Long operatorId,
List<Long> companyMemberIds) {
if (outputStream == null) {
throw new BusinessException("export output stream cannot be null");
}
if (startDate == null || endDate == null || YearMonth.from(startDate).equals(YearMonth.from(endDate))) {
writeExport(outputStream, username, startDate, endDate, groupId, country, operatorId);
writeExport(outputStream, username, startDate, endDate, groupId, country, operatorId, companyMemberIds);
return;
}
if (startDate.isAfter(endDate)) {
@@ -311,7 +337,7 @@ public class DedupeTotalDataService {
LocalDate entryEndDate = endDate.isBefore(monthEnd) ? endDate : monthEnd;
zipOutputStream.putNextEntry(new ZipEntry(monthlyExportEntryName(currentMonth)));
buildExportWorkbook(zipOutputStream, safeUsername, entryStartDate, entryEndDate,
groupId, safeCountry, scope, groupPrevalidated);
groupId, safeCountry, scope, groupPrevalidated, companyMemberIds);
zipOutputStream.closeEntry();
currentMonth = currentMonth.plusMonths(1);
}
@@ -330,7 +356,7 @@ public class DedupeTotalDataService {
Long groupId,
String country,
AccessScope scope) {
buildExportWorkbook(outputStream, username, startDate, endDate, groupId, country, scope, false);
buildExportWorkbook(outputStream, username, startDate, endDate, groupId, country, scope, false, null);
}
private void buildExportWorkbook(OutputStream outputStream,
@@ -340,7 +366,8 @@ public class DedupeTotalDataService {
Long groupId,
String country,
AccessScope scope,
boolean groupPrevalidated) {
boolean groupPrevalidated,
List<Long> companyMemberIds) {
try (SXSSFWorkbook workbook = new SXSSFWorkbook(100)) {
Sheet sheet = workbook.createSheet("DedupeTotalData");
Row header = sheet.createRow(0);
@@ -354,7 +381,7 @@ public class DedupeTotalDataService {
int rowIndex = 1;
while (true) {
LambdaQueryWrapper<DedupeTotalDataEntity> pageQuery = buildExportQuery(
username, startDate, endDate, groupId, country, scope, groupPrevalidated);
username, startDate, endDate, groupId, country, scope, groupPrevalidated, companyMemberIds);
if (lastId != null) {
pageQuery.lt(DedupeTotalDataEntity::getId, lastId);
}
@@ -402,7 +429,7 @@ public class DedupeTotalDataService {
LocalDate endDate,
Long groupId,
AccessScope scope) {
return buildExportQuery(username, startDate, endDate, groupId, null, scope, false);
return buildExportQuery(username, startDate, endDate, groupId, null, scope, false, null);
}
private LambdaQueryWrapper<DedupeTotalDataEntity> buildExportQuery(String username,
@@ -411,7 +438,8 @@ public class DedupeTotalDataService {
Long groupId,
String country,
AccessScope scope,
boolean groupPrevalidated) {
boolean groupPrevalidated,
List<Long> companyMemberIds) {
String safeUsername = username == null ? "" : username.trim();
String safeCountry = country == null ? "" : country.trim();
LambdaQueryWrapper<DedupeTotalDataEntity> query = new LambdaQueryWrapper<DedupeTotalDataEntity>()
@@ -425,6 +453,7 @@ public class DedupeTotalDataService {
endDate == null ? null : endDate.plusDays(1).atStartOfDay())
.orderByDesc(DedupeTotalDataEntity::getId);
applyGroupScope(query, scope, groupId, groupPrevalidated);
applyCompanyScope(query, companyMemberIds);
return query;
}
@@ -1252,6 +1281,26 @@ public class DedupeTotalDataService {
});
}
/**
* 公司 tab 收窄:本表按「上传账号」认公司——{@code uploader_user_id} 是 NOT NULL(V75 先回灌再收紧),
* 且有 idx_uploader_user_id_id 可走点查。
*
* <p>不读 V145 新加的 company_id:写入侧实体没有该字段、{@code insertBatchIgnore} 的列清单也不带,
* 全靠 MySQL 的 DEFAULT 1 兜底,所以第 2 家账号新导入的行今天仍会被盖成公司 1。那一列不能当读侧依据。</p>
*
* <p>空集给一条不可能命中的条件而不是"不筛":tab 选了这家公司却看得到全平台,比看不到更坏。</p>
*/
private void applyCompanyScope(LambdaQueryWrapper<DedupeTotalDataEntity> query, List<Long> companyMemberIds) {
if (companyMemberIds == null) {
return;
}
if (companyMemberIds.isEmpty()) {
query.eq(DedupeTotalDataEntity::getId, -1L);
return;
}
query.in(DedupeTotalDataEntity::getUploaderUserId, companyMemberIds);
}
private ShopManageGroupEntity resolveWritableGroup(Long groupId, AdminUserEntity operator) {
if (groupId == null || groupId <= 0) {
throw new BusinessException("请选择分组");
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.invalidasin.controller;
import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.modules.invalidasin.model.dto.InvalidAsinDataCreateRequest;
import com.nanri.aiimage.modules.invalidasin.model.dto.InvalidAsinDataUpdateRequest;
import com.nanri.aiimage.modules.invalidasin.model.vo.InvalidAsinDataItemVo;
@@ -49,6 +50,7 @@ public class InvalidAsinDataController {
private final InvalidAsinDataService invalidAsinDataService;
private final AdminAuthSupport adminAuthSupport;
private final PermissionMenuService permissionMenuService;
private final DataReadScope dataReadScope;
@GetMapping
@Operation(summary = "分页查询不符合ASIN数据", description = "分页查询不符合ASIN数据,支持按 ASIN/品牌 模糊搜索。")
@@ -62,10 +64,14 @@ public class InvalidAsinDataController {
@Parameter(description = "ASIN 模糊搜索") @RequestParam(name = "data_value", required = false) String dataValue,
@Parameter(description = "品牌模糊搜索") @RequestParam(name = "brand", required = false) String brand,
@Parameter(description = "分组 ID") @RequestParam(name = "group_id", required = false) Long groupId,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
HttpServletRequest request) {
RequestOperator operator = requireInvalidAsinDataAccess(request);
AdminUserEntity user = operator.user();
Long scopedCompanyId = dataReadScope.readCompanyId(user, companyId);
return ApiResponse.success(invalidAsinDataService.page(
page, pageSize, keyword, dataValue, brand, groupId, operator.id(), operator.superAdmin()));
page, pageSize, keyword, dataValue, brand, groupId, operator.id(), operator.superAdmin(),
scopedCompanyId));
}
@PostMapping
@@ -121,7 +127,7 @@ public class InvalidAsinDataController {
if (!superAdmin && !hasInvalidAsinDataPermission(operator)) {
throw new BusinessException(403, "无权访问品牌数据库");
}
return new RequestOperator(operator.getId(), superAdmin);
return new RequestOperator(operator.getId(), superAdmin, operator);
}
private AdminUserEntity resolveOperator(HttpServletRequest request) {
@@ -164,7 +170,7 @@ public class InvalidAsinDataController {
private record RequestOperator(Long id, boolean superAdmin) {
private record RequestOperator(Long id, boolean superAdmin, AdminUserEntity user) {
}
private boolean isTrustedInternalRequest(String suppliedToken) {
return adminAuthSupport.isTrustedSuppliedToken(suppliedToken);
@@ -12,18 +12,22 @@ import java.util.List;
public interface InvalidAsinDataMapper extends BaseMapper<InvalidAsinDataEntity> {
/**
* 批量 INSERT IGNORE:命中唯一键 (data_value, brand) 的重复行静默跳过,幂等。
* 批量 INSERT IGNORE:命中唯一键 (company_id, data_value, brand) 的重复行静默跳过,幂等。
* created_at/updated_at 不显式写入:依赖列的 DEFAULT CURRENT_TIMESTAMP。
* 显式传 null 会绕过默认值,在宽松 SQL 模式下落为 '0000-00-00 00:00:00',
* 随后在 NO_ZERO_DATE 模式(生产已启用)下读取即报 Zero date value prohibited。
*
* <p>company_id 与 uploader_user_id 由调用方填好:company_id 是 NOT NULL,
* 这一列显式传 null 不会走 DEFAULT 1,而是直接报错(上面 created_at 那段说的正是这类列的
* "宽松模式才静默"),所以归属推不出来时调用方必须整批不写,而不是塞 null 进来。</p>
*/
@Insert("""
<script>
INSERT IGNORE INTO biz_invalid_asin_data
(data_value, brand, record_source)
(data_value, brand, record_source, company_id, uploader_user_id)
VALUES
<foreach collection="rows" item="row" separator=",">
(#{row.dataValue}, #{row.brand}, #{row.recordSource})
(#{row.dataValue}, #{row.brand}, #{row.recordSource}, #{row.companyId}, #{row.uploaderUserId})
</foreach>
</script>
""")
@@ -18,6 +18,13 @@ public class InvalidAsinDataEntity {
private String dataValue;
private String brand;
private Long groupId;
/**
* 归属公司(company.id)。列由 V145 物化,但**实体与批量 INSERT 的列清单此前都没带它**,
* 所以 2026-10-05 生产只读取证 14,801 行全是被 DEFAULT 1 盖出来的。写入侧从本版本起显式盖章。
*/
private Long companyId;
/** 归属账号:AUTO 行取 task.user_id、MANUAL 行取操作人;V145 之前的历史行为 NULL(无从追溯)。 */
private Long uploaderUserId;
private String recordSource;
private LocalDateTime createdAt;
/**
@@ -2,6 +2,7 @@ package com.nanri.aiimage.modules.invalidasin.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.service.CompanyScopeSupport;
import com.nanri.aiimage.modules.invalidasin.mapper.InvalidAsinDataMapper;
import com.nanri.aiimage.modules.invalidasin.model.dto.InvalidAsinDataCreateRequest;
import com.nanri.aiimage.modules.invalidasin.model.dto.InvalidAsinDataUpdateRequest;
@@ -30,8 +31,10 @@ public class InvalidAsinDataService {
private final InvalidAsinDataMapper invalidAsinDataMapper;
private final ShopManageGroupService shopManageGroupService;
private final CompanyScopeSupport companyScopeSupport;
public InvalidAsinDataPageVo page(long page, long pageSize, String keyword, String dataValue, String brand, Long groupId, Long operatorId, boolean superAdmin) {
public InvalidAsinDataPageVo page(long page, long pageSize, String keyword, String dataValue, String brand,
Long groupId, Long operatorId, boolean superAdmin, Long companyFilterId) {
long safePage = Math.max(page, 1);
long safePageSize = Math.min(Math.max(pageSize, 1), 100);
String safeKeyword = keyword == null ? "" : keyword.trim();
@@ -45,6 +48,9 @@ public class InvalidAsinDataService {
.like(!safeDataValue.isEmpty(), InvalidAsinDataEntity::getDataValue, safeDataValue)
.like(!safeBrand.isEmpty(), InvalidAsinDataEntity::getBrand, safeBrand)
.orderByDesc(InvalidAsinDataEntity::getId);
if (companyFilterId != null) {
query.eq(InvalidAsinDataEntity::getCompanyId, companyFilterId);
}
if (!superAdmin) {
Long fixedGroupId = resolveFixedAccessibleGroupId(operatorId);
if (fixedGroupId == null) {
@@ -79,13 +85,17 @@ public class InvalidAsinDataService {
@Transactional
public InvalidAsinDataItemVo create(InvalidAsinDataCreateRequest request, Long operatorId, boolean superAdmin) {
ShopManageGroupEntity group = resolveManualWriteGroup(request.getGroupId(), operatorId, superAdmin);
// 归属从操作者会话推导,不读请求里的公司:超管在哪个 tab 下建都归他自己那家公司(一期定案口径)。
Long companyId = companyScopeSupport.requireCompanyId(operatorId);
String dataValue = normalizeRequired(request.getDataValue(), "ASIN 不能为空");
String brand = normalizeRequired(request.getBrand(), "品牌不能为空").toLowerCase(Locale.ROOT);
ensureUnique(dataValue, null);
ensureUnique(dataValue, null, companyId);
InvalidAsinDataEntity entity = new InvalidAsinDataEntity();
entity.setDataValue(dataValue);
entity.setBrand(brand);
entity.setGroupId(group.getId());
entity.setCompanyId(companyId);
entity.setUploaderUserId(operatorId);
entity.setRecordSource(RECORD_SOURCE_MANUAL);
invalidAsinDataMapper.insert(entity);
return toItemVo(getById(entity.getId()), group.getGroupName());
@@ -104,7 +114,7 @@ public class InvalidAsinDataService {
}
String dataValue = normalizeRequired(request.getDataValue(), "ASIN 不能为空");
String brand = normalizeRequired(request.getBrand(), "品牌不能为空").toLowerCase(Locale.ROOT);
ensureUnique(dataValue, id);
ensureUnique(dataValue, id, entity.getCompanyId());
entity.setDataValue(dataValue);
entity.setBrand(brand);
String groupName = "";
@@ -142,8 +152,13 @@ public class InvalidAsinDataService {
return entity;
}
private void ensureUnique(String dataValue, Long excludeId) {
/**
* 应用层的重复预检必须与 V145 放宽后的唯一键同宽——(company_id, data_value, brand)。
* 少了公司这一维,第 2 家永远无法新增第 1 家已有的品牌(跨公司误报「ASIN 已存在」)。
*/
private void ensureUnique(String dataValue, Long excludeId, Long companyId) {
LambdaQueryWrapper<InvalidAsinDataEntity> query = new LambdaQueryWrapper<InvalidAsinDataEntity>()
.eq(companyId != null, InvalidAsinDataEntity::getCompanyId, companyId)
.eq(InvalidAsinDataEntity::getDataValue, dataValue)
.last("LIMIT 1");
InvalidAsinDataEntity exists = invalidAsinDataMapper.selectOne(query);
@@ -1,6 +1,8 @@
package com.nanri.aiimage.modules.productcategory.controller;
import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.common.util.DownloadHeaderUtil;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.productcategory.model.dto.ProductCategorySaveRequest;
@@ -8,6 +10,7 @@ import com.nanri.aiimage.modules.productcategory.model.vo.ProductCategoryItemVo;
import com.nanri.aiimage.modules.productcategory.model.vo.ProductCategoryListVo;
import com.nanri.aiimage.modules.productcategory.service.ProductCategoryService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
@@ -38,14 +41,17 @@ public class ProductCategoryController {
private final ProductCategoryService productCategoryService;
private final AdminAuthSupport adminAuthSupport;
private final DataReadScope dataReadScope;
@GetMapping("/product-categories")
@Operation(summary = "查询商品类目树")
public ApiResponse<ProductCategoryListVo> list(
HttpServletRequest request,
@RequestParam(value = "keyword", required = false) String keyword) {
adminAuthSupport.requireAdminOrInternal(request);
return ApiResponse.success(productCategoryService.list(keyword));
@RequestParam(value = "keyword", required = false) String keyword,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
Long scopedCompanyId = dataReadScope.readCompanyId(operator, companyId);
return ApiResponse.success(productCategoryService.list(keyword, scopedCompanyId));
}
@GetMapping("/product-categories/children")
@@ -54,9 +60,11 @@ public class ProductCategoryController {
HttpServletRequest request,
@RequestParam(value = "parent_id", required = false) Long parentId,
@RequestParam(value = "page", defaultValue = "1") Long page,
@RequestParam(value = "page_size", defaultValue = "20") Long pageSize) {
adminAuthSupport.requireAdminOrInternal(request);
return ApiResponse.success(productCategoryService.children(parentId, page, pageSize));
@RequestParam(value = "page_size", defaultValue = "20") Long pageSize,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
Long scopedCompanyId = dataReadScope.readCompanyId(operator, companyId);
return ApiResponse.success(productCategoryService.children(parentId, page, pageSize, scopedCompanyId));
}
@GetMapping("/product-categories/search")
@@ -65,18 +73,22 @@ public class ProductCategoryController {
HttpServletRequest request,
@RequestParam(value = "keyword", required = false) String keyword,
@RequestParam(value = "page", defaultValue = "1") Long page,
@RequestParam(value = "page_size", defaultValue = "20") Long pageSize) {
adminAuthSupport.requireAdminOrInternal(request);
return ApiResponse.success(productCategoryService.search(keyword, page, pageSize));
@RequestParam(value = "page_size", defaultValue = "20") Long pageSize,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
Long scopedCompanyId = dataReadScope.readCompanyId(operator, companyId);
return ApiResponse.success(productCategoryService.search(keyword, page, pageSize, scopedCompanyId));
}
@GetMapping("/product-categories/export")
@Operation(summary = "导出商品类目")
public ResponseEntity<byte[]> export(
HttpServletRequest request,
@RequestParam(value = "keyword", required = false) String keyword) {
adminAuthSupport.requireAdminOrInternal(request);
byte[] bytes = productCategoryService.export(keyword);
@RequestParam(value = "keyword", required = false) String keyword,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
Long scopedCompanyId = dataReadScope.readCompanyId(operator, companyId);
byte[] bytes = productCategoryService.export(keyword, scopedCompanyId);
String filename = "product-categories-" + LocalDateTime.now().format(EXPORT_FILENAME_FORMATTER) + ".xlsx";
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, DownloadHeaderUtil.contentDisposition(filename))
@@ -90,8 +102,10 @@ public class ProductCategoryController {
public ApiResponse<ProductCategoryItemVo> create(
HttpServletRequest request,
@Valid @RequestBody ProductCategorySaveRequest body) {
adminAuthSupport.requireAdminOrInternal(request);
return ApiResponse.success("创建成功", productCategoryService.create(body));
// 归属只从会话推(请求体一律不带 company_id):service 里 requireCompanyId 取不到就抛,
// 不让 V147 的 DEFAULT 1 静默兜住。
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
return ApiResponse.success("创建成功", productCategoryService.create(body, operator.getId()));
}
@PutMapping("/product-category/{id}")
@@ -13,6 +13,14 @@ public class ProductCategoryEntity {
@TableId(type = IdType.AUTO)
private Long id;
/**
* 归属公司(V147)。{@code 0} = 平台内置共享节点(不是 company 表里的行),其余是那一家的自建节点。
*
* <p>写侧必须显式盖章:这一列在 V147 里带着<b>临时</b>的 {@code DEFAULT 1}(旧 jar 的实体没这字段),
* 漏传不会报错、会被静默塞进厦门米椿花。{@code ProductCategoryService.create} 因此走
* {@code CompanyScopeSupport.requireCompanyId}(取不到就抛),不依赖这一默认值。</p>
*/
private Long companyId;
private Long parentId;
private String name;
private String categoryKey;
@@ -4,6 +4,7 @@ import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.service.CompanyScopeSupport;
import com.nanri.aiimage.modules.productcategory.mapper.ProductCategoryMapper;
import com.nanri.aiimage.modules.productcategory.model.dto.ProductCategorySaveRequest;
import com.nanri.aiimage.modules.productcategory.model.entity.ProductCategoryEntity;
@@ -34,63 +35,109 @@ public class ProductCategoryService {
private static final DateTimeFormatter EXPORT_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private final ProductCategoryMapper productCategoryMapper;
/**
* 内置节点的哨兵归属(V147 回填):它不是公司表里的行,而是"所有公司都看得见、谁都不拥有"的那半棵树。
*
* <p>取 0 是因为 {@code company.id} 从 1 起自增,而 {@code CompanyScopeSupport.requireCompanyId}
* 对 {@code <= 0} 直接抛 ⇒ 没有任何账号会被登记成 0 号公司,这个值和真实公司永不撞。</p>
*/
static final long SHARED_BUILTIN_COMPANY_ID = 0L;
private final ProductCategoryMapper productCategoryMapper;
private final CompanyScopeSupport companyScopeSupport;
/**
* 全平台类目树——<b>不按公司筛,且不许改成按公司筛</b>。
*
* <p>唯一的消费者是货源/外观的类目归类({@code SimilarAsinLlmService:215 CategoryTree.load(list())})。
* 那一侧按公司切会同时改两件事:候选节点变少(分类结果按公司分叉)与 prompt 里的类目表变化(影响 LLM 成本)。
* 后台的公司 tab 走 {@link #list(String, Long)},两件事别混。</p>
*/
public ProductCategoryListVo list() {
return list(null);
}
/** 不筛公司(超管没选 tab 时的口径,与改造前一致)。 */
public ProductCategoryListVo list(String keyword) {
List<ProductCategoryEntity> rows = productCategoryMapper.selectList(new LambdaQueryWrapper<ProductCategoryEntity>()
.orderByAsc(ProductCategoryEntity::getParentId)
.orderByAsc(ProductCategoryEntity::getSortOrder)
.orderByAsc(ProductCategoryEntity::getId));
return list(keyword, null);
}
/**
* @param companyId 要收窄到的公司;null = 不筛。内置节点({@value #SHARED_BUILTIN_COMPANY_ID})
* 在任何公司的视图里都可见,否则第 2 家的类目树会是空的、连一个自建根都挂不上。
*/
public ProductCategoryListVo list(String keyword, Long companyId) {
List<ProductCategoryEntity> rows = productCategoryMapper.selectList(applyCompanyScope(
new LambdaQueryWrapper<ProductCategoryEntity>()
.orderByAsc(ProductCategoryEntity::getParentId)
.orderByAsc(ProductCategoryEntity::getSortOrder)
.orderByAsc(ProductCategoryEntity::getId),
companyId));
rows = filterRowsByKeyword(rows, keyword);
return buildListVo(rows);
}
public ProductCategoryListVo children(Long parentId, long page, long pageSize) {
return children(parentId, page, pageSize, null);
}
public ProductCategoryListVo children(Long parentId, long page, long pageSize, Long companyId) {
long safePage = Math.max(page, 1);
long safePageSize = normalizePageSize(pageSize);
Long normalizedParentId = normalizeParentId(parentId);
LambdaQueryWrapper<ProductCategoryEntity> countQuery = new LambdaQueryWrapper<>();
LambdaQueryWrapper<ProductCategoryEntity> countQuery = applyCompanyScope(new LambdaQueryWrapper<>(), companyId);
applyParentFilter(countQuery, normalizedParentId);
Long total = productCategoryMapper.selectCount(countQuery);
LambdaQueryWrapper<ProductCategoryEntity> pageQuery = new LambdaQueryWrapper<ProductCategoryEntity>()
.orderByAsc(ProductCategoryEntity::getSortOrder)
.orderByAsc(ProductCategoryEntity::getId)
LambdaQueryWrapper<ProductCategoryEntity> pageQuery = applyCompanyScope(
new LambdaQueryWrapper<ProductCategoryEntity>()
.orderByAsc(ProductCategoryEntity::getSortOrder)
.orderByAsc(ProductCategoryEntity::getId),
companyId)
.last("LIMIT " + ((safePage - 1) * safePageSize) + ", " + safePageSize);
applyParentFilter(pageQuery, normalizedParentId);
List<ProductCategoryEntity> rows = productCategoryMapper.selectList(pageQuery);
return buildPageVo(rows, total, safePage, safePageSize);
return buildPageVo(rows, total, safePage, safePageSize, companyId);
}
public ProductCategoryListVo search(String keyword, long page, long pageSize) {
return search(keyword, page, pageSize, null);
}
public ProductCategoryListVo search(String keyword, long page, long pageSize, Long companyId) {
String normalized = normalizeSearchKeyword(keyword);
if (normalized.isBlank()) {
return emptyPageVo(Math.max(page, 1), normalizePageSize(pageSize));
}
long safePage = Math.max(page, 1);
long safePageSize = normalizePageSize(pageSize);
LambdaQueryWrapper<ProductCategoryEntity> countQuery = buildSearchQuery(normalized);
Long total = productCategoryMapper.selectCount(countQuery);
List<ProductCategoryEntity> rows = productCategoryMapper.selectList(buildSearchQuery(normalized)
Long total = productCategoryMapper.selectCount(buildSearchQuery(normalized, companyId));
List<ProductCategoryEntity> rows = productCategoryMapper.selectList(buildSearchQuery(normalized, companyId)
.orderByAsc(ProductCategoryEntity::getParentId)
.orderByAsc(ProductCategoryEntity::getSortOrder)
.orderByAsc(ProductCategoryEntity::getId)
.last("LIMIT " + ((safePage - 1) * safePageSize) + ", " + safePageSize));
return buildSearchPageVo(rows, total, safePage, safePageSize);
return buildSearchPageVo(rows, total, safePage, safePageSize, companyId);
}
/**
* 归属由<b>操作者会话</b>推导(请求体/查询参数一律不带 company_id):漏了这一句,新类目就会被
* V147 的 {@code DEFAULT 1} 静默塞进厦门米椿花——那是"归属失真且不报错",而 {@code requireCompanyId}
* 取不到公司时是抛,不会返回 null。所以这里<b>不保留</b>不带操作者的重载:留着它等于留着一个
* "调用方忘了传也照样绿"的出口。
*
* @param operatorId 操作者账号 id
*/
@Transactional
public ProductCategoryItemVo create(ProductCategorySaveRequest request) {
public ProductCategoryItemVo create(ProductCategorySaveRequest request, Long operatorId) {
String name = normalizeRequired(request.getName(), "类目名称不能为空");
Long parentId = normalizeParentId(request.getParentId());
ensureParentExists(parentId, null);
ensureSiblingNameUnique(parentId, name, null);
Long companyId = companyScopeSupport.requireCompanyId(operatorId);
ensureParentVisible(parentId, null, companyId);
ensureSiblingNameUnique(parentId, name, null, companyId);
ProductCategoryEntity entity = new ProductCategoryEntity();
entity.setCompanyId(companyId);
entity.setParentId(parentId);
entity.setName(name);
entity.setCategoryKey(generateCategoryKey(parentId, name));
@@ -106,8 +153,11 @@ public class ProductCategoryService {
ProductCategoryEntity entity = getById(id);
String name = normalizeRequired(request.getName(), "类目名称不能为空");
Long parentId = normalizeParentId(request.getParentId());
ensureParentExists(parentId, id);
ensureSiblingNameUnique(parentId, name, id);
// 改行时" Acting 公司"取行自己的归属,不取 tab:内置行归 0、自建行归那一家,
// 换父级时不能把行挪到可见集外的节点下面(那会让它从原本看得见它的 tab 里消失)。
Long companyId = entity.getCompanyId();
ensureParentVisible(parentId, id, companyId);
ensureSiblingNameUnique(parentId, name, id, companyId);
entity.setParentId(parentId);
entity.setName(name);
@@ -163,8 +213,8 @@ public class ProductCategoryService {
return vo;
}
private ProductCategoryListVo buildPageVo(List<ProductCategoryEntity> rows, Long total, long page, long pageSize) {
Map<Long, Integer> childCountById = buildChildCountById(rows);
private ProductCategoryListVo buildPageVo(List<ProductCategoryEntity> rows, Long total, long page, long pageSize, Long companyId) {
Map<Long, Integer> childCountById = buildChildCountById(rows, companyId);
List<ProductCategoryItemVo> items = rows.stream()
.map(row -> toItemVo(row, childCountById.getOrDefault(row.getId(), 0)))
.toList();
@@ -178,8 +228,13 @@ public class ProductCategoryService {
return vo;
}
/** 导出的行集合必须与页面列表同源:都走 {@link #list(String, Long)},否则"tab 里看不见但导出里有"就是第二个真相源。 */
public byte[] export(String keyword) {
ProductCategoryListVo list = list(keyword);
return export(keyword, null);
}
public byte[] export(String keyword, Long companyId) {
ProductCategoryListVo list = list(keyword, companyId);
List<ProductCategoryItemVo> rows = list.getItems() == null ? List.of() : list.getItems();
Map<Long, String> nameById = buildExportNameById(rows);
try (SXSSFWorkbook workbook = new SXSSFWorkbook(100);
@@ -198,8 +253,8 @@ public class ProductCategoryService {
}
}
private ProductCategoryListVo buildSearchPageVo(List<ProductCategoryEntity> rows, Long total, long page, long pageSize) {
Map<Long, Integer> childCountById = buildChildCountById(rows);
private ProductCategoryListVo buildSearchPageVo(List<ProductCategoryEntity> rows, Long total, long page, long pageSize, Long companyId) {
Map<Long, Integer> childCountById = buildChildCountById(rows, companyId);
List<ProductCategoryItemVo> items = rows.stream()
.map(row -> {
ProductCategoryItemVo item = toItemVo(row, childCountById.getOrDefault(row.getId(), 0));
@@ -305,15 +360,23 @@ public class ProductCategoryService {
return time == null ? "" : time.format(EXPORT_TIME_FORMATTER);
}
private Map<Long, Integer> buildChildCountById(List<ProductCategoryEntity> rows) {
/**
* 列表页的「子类目数」徽章走的是<b>全表聚合</b>(不是内存里那批行),所以它必须和公司视图同源:
* 不加这一段,第 1 家的父节点上会显示"3 个子类目"而 tab 里只列得出一两个——
* 数字来自别人的公司,点开却是自己的树。
*/
private Map<Long, Integer> buildChildCountById(List<ProductCategoryEntity> rows, Long companyId) {
Map<Long, Integer> childCountById = new HashMap<>();
if (rows.isEmpty()) {
return childCountById;
}
List<Map<String, Object>> countRows = productCategoryMapper.selectMaps(new QueryWrapper<ProductCategoryEntity>()
QueryWrapper<ProductCategoryEntity> countQuery = new QueryWrapper<ProductCategoryEntity>()
.select("parent_id", "count(*) AS child_count")
.isNotNull("parent_id")
.groupBy("parent_id"));
.isNotNull("parent_id");
if (companyId != null) {
countQuery.in("company_id", visibleCompanyIds(companyId));
}
List<Map<String, Object>> countRows = productCategoryMapper.selectMaps(countQuery.groupBy("parent_id"));
for (Map<String, Object> countRow : countRows) {
Object parentId = countRow.get("parent_id");
Object childCount = countRow.get("child_count");
@@ -333,13 +396,40 @@ public class ProductCategoryService {
}
}
private LambdaQueryWrapper<ProductCategoryEntity> buildSearchQuery(String keyword) {
return new LambdaQueryWrapper<ProductCategoryEntity>()
.like(ProductCategoryEntity::getName, keyword)
.or()
.like(ProductCategoryEntity::getCategoryKey, keyword)
.or()
.like(ProductCategoryEntity::getDescription, keyword);
/**
* 关键字命中三条列任一即算命中,但<b>整条 OR 必须包起来再 AND 公司</b>:MyBatis-Plus 的
* {@code or()} 只改"下一个连接符",直接在这串后面 {@code .in(company_id, ...)} 会拼成
* {@code name LIKE ? OR key LIKE ? OR (desc LIKE ? AND company_id IN ...)} —— SQL 里 AND 结合更紧,
* 结果前两条列命中的行<b>不受公司约束</b>,这一页的筛选就成了假的(且不报错)。
*/
private LambdaQueryWrapper<ProductCategoryEntity> buildSearchQuery(String keyword, Long companyId) {
LambdaQueryWrapper<ProductCategoryEntity> query = new LambdaQueryWrapper<ProductCategoryEntity>()
.and(group -> group
.like(ProductCategoryEntity::getName, keyword)
.or()
.like(ProductCategoryEntity::getCategoryKey, keyword)
.or()
.like(ProductCategoryEntity::getDescription, keyword));
return applyCompanyScope(query, companyId);
}
/**
* 公司视图的唯一落点:null = 不筛(超管没选 tab、非超管、以及 {@link #list()} 那棵给 LLM 的全局树);
* 否则 {@code company_id IN (0, X)} —— 哨兵 0 那批内置节点在任何公司视图里都必须在,
* 不然第 2 家的类目页是一棵空树,它自建不出任何子级(父级只能挂在这批上面)。
*/
private LambdaQueryWrapper<ProductCategoryEntity> applyCompanyScope(
LambdaQueryWrapper<ProductCategoryEntity> query, Long companyId) {
if (companyId != null) {
query.in(ProductCategoryEntity::getCompanyId, visibleCompanyIds(companyId));
}
return query;
}
private List<Long> visibleCompanyIds(Long companyId) {
return companyId == SHARED_BUILTIN_COMPANY_ID
? List.of(SHARED_BUILTIN_COMPANY_ID)
: List.of(SHARED_BUILTIN_COMPANY_ID, companyId);
}
private List<ProductCategoryEntity> filterRowsByKeyword(List<ProductCategoryEntity> rows, String keyword) {
@@ -495,7 +585,14 @@ public class ProductCategoryService {
return entity;
}
private void ensureParentExists(Long parentId, Long currentId) {
/**
* 父级必须"存在且在这一公司的可见集里"。
*
* <p>只查存在性是不够的:把行的 parent_id 指到别家公司的节点上,这一行就从原本看得见它的
* tab 里消失(读侧按父级子树裁),而 {@code parent_id} 没有外键、库里一声不响。
* companyId 为 null 时不校验——那是改造前/内部调用的口径,不是"允许跨公司挂"。</p>
*/
private void ensureParentVisible(Long parentId, Long currentId, Long companyId) {
if (parentId == null) {
return;
}
@@ -506,6 +603,9 @@ public class ProductCategoryService {
if (parent == null) {
throw new BusinessException("父级类目不存在");
}
if (companyId != null && !visibleCompanyIds(companyId).contains(parent.getCompanyId())) {
throw new BusinessException(403, "父级类目不属于当前公司");
}
Set<Long> visited = new HashSet<>();
Long cursor = parent.getParentId();
while (cursor != null) {
@@ -520,9 +620,17 @@ public class ProductCategoryService {
}
}
private void ensureSiblingNameUnique(Long parentId, String name, Long excludeId) {
/**
* 同级重名检查的范围 = 这一家的<b>可见集</b>(自建 + 内置),不是只查自建。
*
* <p>只查自建会让第 2 家在内置父级"护肤品"下建出一个也叫"面霜"的节点,和内置的那个
* 同层同名——页面上一排两个"面霜",而货源归类按名字回填时不知道落到哪一个。
* 反过来,跨家的同名要放行:那正是 {@code uk_company_category_key} 换掉全平台唯一键要解决的问题。</p>
*/
private void ensureSiblingNameUnique(Long parentId, String name, Long excludeId, Long companyId) {
LambdaQueryWrapper<ProductCategoryEntity> query = new LambdaQueryWrapper<ProductCategoryEntity>()
.eq(ProductCategoryEntity::getName, name);
applyCompanyScope(query, companyId);
if (parentId == null) {
query.isNull(ProductCategoryEntity::getParentId);
} else {
@@ -6,10 +6,12 @@ import com.nanri.aiimage.common.util.DownloadHeaderUtil;
import com.nanri.aiimage.config.HttpClientPool;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import com.nanri.aiimage.modules.shopdatacrawl.model.dto.ShopDataCrawlDownloadRowDto;
import com.nanri.aiimage.modules.shopdatacrawl.service.ShopDataCrawlAdminTasksService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@@ -76,6 +78,7 @@ public class AdminShopDataCrawlTasksController {
private final AdminAuthSupport adminAuthSupport;
private final PermissionMenuService permissionMenuService;
private final ShopDataCrawlAdminTasksService adminTasksService;
private final DataReadScope dataReadScope;
@GetMapping
@Operation(summary = "店铺数据抓取记录:按店铺分组分页列表(每店最新结果文件)")
@@ -87,13 +90,19 @@ public class AdminShopDataCrawlTasksController {
@RequestParam(name = "group_name", required = false) String groupName,
@RequestParam(name = "country", required = false) String country,
@RequestParam(name = "created_from", required = false) String createdFrom,
@RequestParam(name = "created_to", required = false) String createdTo) {
@RequestParam(name = "created_to", required = false) String createdTo,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity operator = requireShopDataCrawlTaskAccess(request);
int safePage = Math.max(1, parseInt(page, 1, "page 参数不合法"));
int safePageSize = Math.min(PAGE_SIZE_MAX,
Math.max(10, parseInt(pageSize, PAGE_SIZE_DEFAULT, "page_size 参数不合法")));
boolean superAdmin = "super_admin".equals(adminAuthSupport.currentRole(operator));
List<String> visibleShopKeys = superAdmin ? null : resolveVisibleShopNameKeys(operator.getId());
// 成员集就地算,且只在超管这一支算(口径同最低价ASIN/查询ASIN);null = 不筛=今天的超管全量。
List<Long> companyMemberIds = superAdmin
? dataReadScope.readScope(operator, companyId).userIdsOr(null)
: null;
List<String> visibleShopKeys = adminTasksService.resolveVisibleShopKeys(
operator.getId(), superAdmin, companyMemberIds);
Map<String, Object> payload = adminTasksService.listShopGroups(
safePage, safePageSize, shopName, groupName, country, createdFrom, createdTo, visibleShopKeys);
return ApiResponse.success(payload);
@@ -282,11 +291,6 @@ public class AdminShopDataCrawlTasksController {
return operator;
}
/** 非超管返回其可管店铺名(trim+小写去重,与撞款可见口径一致);超管调用方传 null 表示全量。 */
private List<String> resolveVisibleShopNameKeys(Long operatorId) {
return adminTasksService.resolveVisibleShopNameKeys(operatorId);
}
private AdminUserEntity resolveInternalOperator(HttpServletRequest request) {
String suppliedToken = request.getHeader("X-Internal-Token");
if (!isTrustedInternalRequest(suppliedToken)) {
@@ -222,9 +222,26 @@ public class ShopDataCrawlAdminTasksService {
return rows;
}
/** 非超管可管店铺名(trim+小写去重,与撞款可见口径一致);超管调用方传 null 表示全量。 */
public List<String> resolveVisibleShopNameKeys(Long operatorId) {
List<String> names = managedShopNamesPort.selectManagedShopNames(operatorId);
/**
* 可见店铺名 key 集(trim+小写去重,与撞款页口径一致);返回 {@code null} 表示全量。
*
* <p>公司条件只在超管这一支生效({@code companyMemberIds} 由 controller 经 {@code DataReadScope} 算好传入),
* 非超管一律按分组关系推——他在这一页看到的范围不随 tab 变化,这条与撞款页逐字一致,
* 也与 {@code ShopManageService.page} 的注释同源:给非超管叠 created_by IN 成员会把
* 「只挂了 user_id 的分组」那批店铺静默删掉。</p>
*/
public List<String> resolveVisibleShopKeys(Long operatorId, boolean superAdmin, List<Long> companyMemberIds) {
if (!superAdmin) {
return shopNameKeys(managedShopNamesPort.selectManagedShopNames(operatorId));
}
if (companyMemberIds == null) {
return null;
}
// 端口对空成员集返回空列表 ⇒ 这里自然得到空列表("这家没有店铺"),不会退化成 null("全量")。
return shopNameKeys(managedShopNamesPort.selectShopNamesOwnedByMembers(companyMemberIds));
}
private static List<String> shopNameKeys(List<String> names) {
if (names == null || names.isEmpty()) {
return List.of();
}
@@ -11,4 +11,12 @@ public interface ManagedShopNamesPort {
/** 该操作人可管的店铺名;传 null 表示全量(超管调用方)。 */
List<String> selectManagedShopNames(Long operatorId);
/**
* 某家公司的店铺名(按店铺行自己的负责人推,口径同「店铺管理」页的公司 tab)。
*
* <p>空成员集必须由调用方挡住:这条是给「切到第 2 家」用的,成员为空=这家公司一家店铺都没有,
* 该返回空集合(页面显示"没有店铺"),而不是把空 IN 丢进 SQL。</p>
*/
List<String> selectShopNamesOwnedByMembers(List<Long> memberIds);
}
@@ -5,12 +5,14 @@ import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.util.DownloadHeaderUtil;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import com.nanri.aiimage.modules.shopduplicatecheck.service.ShopDataDuplicateCheckImportService;
import com.nanri.aiimage.modules.shopduplicatecheck.service.ShopDataDuplicateCheckQueryService;
import com.nanri.aiimage.modules.shopduplicatecheck.service.ShopDataDuplicateCheckScanService;
import com.nanri.aiimage.modules.shopduplicatecheck.service.ShopDataDuplicateCheckScanService.DuplicateScanView;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@@ -30,6 +32,7 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -51,12 +54,14 @@ public class AdminShopDataDuplicateCheckController {
private final ShopDataDuplicateCheckScanService scanService;
private final ShopDataDuplicateCheckQueryService queryService;
private final ShopDataDuplicateCheckImportService importService;
private final DataReadScope dataReadScope;
@GetMapping("/duplicate-check-overview")
@Operation(summary = "撞款指标与店铺分布(force=1 触发同步重扫)")
public ApiResponse<Object> overview(
HttpServletRequest request,
@RequestParam(name = "force", required = false) String force) {
@RequestParam(name = "force", required = false) String force,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
RequestOperator operator = requireDuplicateCheckAccess(request);
boolean forced = force != null && ("1".equals(force.trim().toLowerCase())
|| "true".equals(force.trim().toLowerCase()) || "yes".equals(force.trim().toLowerCase()));
@@ -68,7 +73,11 @@ public class AdminShopDataDuplicateCheckController {
if (view == null) {
return ApiResponse.success(queryService.pendingOverview());
}
Set<String> visibleKeys = queryService.resolveVisibleShopKeys(operator.id(), operator.superAdmin());
List<Long> companyMemberIds = operator.superAdmin()
? dataReadScope.readScope(operator.user(), companyId).userIdsOr(null)
: null;
Set<String> visibleKeys = queryService.resolveVisibleShopKeys(
operator.id(), operator.superAdmin(), companyMemberIds);
return ApiResponse.success(queryService.overviewData(view, visibleKeys));
}
@@ -84,7 +93,8 @@ public class AdminShopDataDuplicateCheckController {
@RequestParam(name = "country", required = false) String country,
@RequestParam(name = "site", required = false) String site,
@RequestParam(name = "date_from", required = false) String dateFrom,
@RequestParam(name = "date_to", required = false) String dateTo) {
@RequestParam(name = "date_to", required = false) String dateTo,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
RequestOperator operator = requireDuplicateCheckAccess(request);
int safePage = parsePage(page);
int safeSize = clamp(parseSize(pageSize, 20), 10, 100);
@@ -95,7 +105,11 @@ public class AdminShopDataDuplicateCheckController {
if (scan == null) {
return ApiResponse.success(queryService.pendingList(safePage, safeSize));
}
Set<String> visibleKeys = queryService.resolveVisibleShopKeys(operator.id(), operator.superAdmin());
List<Long> companyMemberIds = operator.superAdmin()
? dataReadScope.readScope(operator.user(), companyId).userIdsOr(null)
: null;
Set<String> visibleKeys = queryService.resolveVisibleShopKeys(
operator.id(), operator.superAdmin(), companyMemberIds);
return ApiResponse.success(queryService.itemsData(scan, visibleKeys, safePage, safeSize, viewMode, filters));
}
@@ -110,7 +124,8 @@ public class AdminShopDataDuplicateCheckController {
@RequestParam(name = "country", required = false) String country,
@RequestParam(name = "site", required = false) String site,
@RequestParam(name = "date_from", required = false) String dateFrom,
@RequestParam(name = "date_to", required = false) String dateTo) {
@RequestParam(name = "date_to", required = false) String dateTo,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
RequestOperator operator = requireDuplicateCheckAccess(request);
int safePage = parsePage(page);
int safeSize = clamp(parseSize(pageSize, 6), 1, 24);
@@ -120,7 +135,11 @@ public class AdminShopDataDuplicateCheckController {
if (scan == null) {
return ApiResponse.success(queryService.pendingDetail(safePage, safeSize));
}
Set<String> visibleKeys = queryService.resolveVisibleShopKeys(operator.id(), operator.superAdmin());
List<Long> companyMemberIds = operator.superAdmin()
? dataReadScope.readScope(operator.user(), companyId).userIdsOr(null)
: null;
Set<String> visibleKeys = queryService.resolveVisibleShopKeys(
operator.id(), operator.superAdmin(), companyMemberIds);
return ApiResponse.success(queryService.detailData(scan, visibleKeys, safePage, safeSize, filters));
}
@@ -134,7 +153,8 @@ public class AdminShopDataDuplicateCheckController {
@RequestParam(name = "country", required = false) String country,
@RequestParam(name = "site", required = false) String site,
@RequestParam(name = "date_from", required = false) String dateFrom,
@RequestParam(name = "date_to", required = false) String dateTo) {
@RequestParam(name = "date_to", required = false) String dateTo,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
RequestOperator operator = requireDuplicateCheckAccess(request);
ShopDataDuplicateCheckQueryService.Filters filters =
ShopDataDuplicateCheckQueryService.Filters.clean(asin, shopName, country, site, dateFrom, dateTo);
@@ -142,7 +162,11 @@ public class AdminShopDataDuplicateCheckController {
if (scan == null) {
return ApiResponse.success(queryService.pendingConsole());
}
Set<String> visibleKeys = queryService.resolveVisibleShopKeys(operator.id(), operator.superAdmin());
List<Long> companyMemberIds = operator.superAdmin()
? dataReadScope.readScope(operator.user(), companyId).userIdsOr(null)
: null;
Set<String> visibleKeys = queryService.resolveVisibleShopKeys(
operator.id(), operator.superAdmin(), companyMemberIds);
Set<String> effectiveKeys = queryService.withGroupFilter(visibleKeys, scan, group);
return ApiResponse.success(queryService.consoleData(scan, effectiveKeys, filters));
}
@@ -161,7 +185,8 @@ public class AdminShopDataDuplicateCheckController {
@RequestParam(name = "country", required = false) String country,
@RequestParam(name = "site", required = false) String site,
@RequestParam(name = "date_from", required = false) String dateFrom,
@RequestParam(name = "date_to", required = false) String dateTo) {
@RequestParam(name = "date_to", required = false) String dateTo,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
RequestOperator operator = requireDuplicateCheckAccess(request);
int safePage = parsePage(page);
int safeSize = clamp(parseSize(pageSize, 100), 1, 200);
@@ -171,7 +196,11 @@ public class AdminShopDataDuplicateCheckController {
if (scan == null) {
return ApiResponse.success(queryService.pendingLedger(safePage, safeSize));
}
Set<String> visibleKeys = queryService.resolveVisibleShopKeys(operator.id(), operator.superAdmin());
List<Long> companyMemberIds = operator.superAdmin()
? dataReadScope.readScope(operator.user(), companyId).userIdsOr(null)
: null;
Set<String> visibleKeys = queryService.resolveVisibleShopKeys(
operator.id(), operator.superAdmin(), companyMemberIds);
Set<String> effectiveKeys = queryService.withGroupFilter(visibleKeys, scan, group);
return ApiResponse.success(queryService.ledgerData(scan, effectiveKeys, safePage, safeSize, sortKey, sortDir, filters));
}
@@ -187,7 +216,8 @@ public class AdminShopDataDuplicateCheckController {
@RequestParam(name = "country", required = false) String country,
@RequestParam(name = "site", required = false) String site,
@RequestParam(name = "date_from", required = false) String dateFrom,
@RequestParam(name = "date_to", required = false) String dateTo) {
@RequestParam(name = "date_to", required = false) String dateTo,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
RequestOperator operator = requireDuplicateCheckAccess(request);
DuplicateScanView scan = scanService.loadLatest();
if (scan == null) {
@@ -196,7 +226,11 @@ public class AdminShopDataDuplicateCheckController {
String viewMode = view == null ? "monitor" : view.trim().toLowerCase();
ShopDataDuplicateCheckQueryService.Filters filters =
ShopDataDuplicateCheckQueryService.Filters.clean(asin, shopName, country, site, dateFrom, dateTo);
Set<String> visibleKeys = queryService.resolveVisibleShopKeys(operator.id(), operator.superAdmin());
List<Long> companyMemberIds = operator.superAdmin()
? dataReadScope.readScope(operator.user(), companyId).userIdsOr(null)
: null;
Set<String> visibleKeys = queryService.resolveVisibleShopKeys(
operator.id(), operator.superAdmin(), companyMemberIds);
try {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
DownloadHeaderUtil.setAttachment(response, "shop-data-duplicate-check.xlsx");
@@ -241,7 +275,15 @@ public class AdminShopDataDuplicateCheckController {
}
}
private record RequestOperator(Long id, boolean superAdmin) {
/**
* 带上操作者实体:{@code DataReadScope.readScope} 只认 {@code AdminUserEntity}(它要读这一行的
* company_id 和角色),而 G2 护栏要求 {@code readScope(} 落在<b>每支 handler 体内</b>(私有收口方法
* 不算证据——那一支可以整批不接出口还跟着别人的绿),所以成员集只能就地算。
*/
private record RequestOperator(AdminUserEntity user, boolean superAdmin) {
Long id() {
return user.getId();
}
}
private RequestOperator requireDuplicateCheckAccess(HttpServletRequest request) {
@@ -256,7 +298,7 @@ public class AdminShopDataDuplicateCheckController {
}
permissionMenuService.requireShopDataCrawlTaskAccess(operator);
boolean superAdmin = "super_admin".equals(adminAuthSupport.currentRole(operator));
return new RequestOperator(operator.getId(), superAdmin);
return new RequestOperator(operator, superAdmin);
}
private AdminUserEntity resolveInternalOperator(HttpServletRequest request) {
@@ -96,4 +96,25 @@ public interface ShopDuplicateCheckSourceMapper {
)
""")
List<String> selectManagedShopNames(@Param("operatorId") Long operatorId);
/**
* 公司 tab 的店铺名集:按店铺自己的负责人({@code biz_shop_manage.created_by_id})落在这批成员里推。
*
* <p>口径与「店铺管理」页 {@code ShopManageService.page} 的 companyMemberIds 那一段逐字同一把尺子:
* 同一个 tab 在店铺中心的两页上推出两个不同的店铺集合,比看到空页更糟(后者至少不会骗人)。
* 这里【不】走 {@code listCompanyGroupIds} 那条分组归属路线——分组归属认 created_by_id 与 user_id 两列,
* 而店铺管理页只认店铺行的 created_by_id;跟着已上线那页走,才不会出现「店铺管理看不到、撞款看得到」。</p>
*
* <p>空成员集不在这条 SQL 里兜:IN () 是语法错,调用方必须在 memberIds 为空时直接给空集合。</p>
*/
@Select("""
<script>
SELECT DISTINCT TRIM(sm.shop_name)
FROM biz_shop_manage sm
WHERE TRIM(COALESCE(sm.shop_name, '')) &lt;&gt; ''
AND sm.created_by_id IN
<foreach collection="memberIds" item="mid" open="(" separator="," close=")">#{mid}</foreach>
</script>
""")
List<String> selectShopNamesOwnedBy(@Param("memberIds") List<Long> memberIds);
}
@@ -20,4 +20,12 @@ public class ManagedShopNamesPortAdapter implements ManagedShopNamesPort {
public List<String> selectManagedShopNames(Long operatorId) {
return sourceMapper.selectManagedShopNames(operatorId);
}
@Override
public List<String> selectShopNamesOwnedByMembers(List<Long> memberIds) {
if (memberIds == null || memberIds.isEmpty()) {
return List.of();
}
return sourceMapper.selectShopNamesOwnedBy(memberIds);
}
}
@@ -74,13 +74,34 @@ public class ShopDataDuplicateCheckQueryService {
return (shopName == null ? "" : shopName.trim()).toLowerCase(Locale.ROOT);
}
/** 主管可见店铺 key 集;超管用 null 表示全量。 */
public Set<String> resolveVisibleShopKeys(Long operatorId, boolean superAdmin) {
if (superAdmin) {
/**
* 可见店铺 key 集;{@code null} = 全量(超管没切公司 tab 时的今天)。
*
* <p>{@code companyMemberIds} 只在超管这一支由 controller 算好传入(非超管一律 null:他的范围本来就锁在
* 分组关系上,叠一层 created_by IN 成员会把「只挂了 user_id 的分组」下的店铺整批静默删掉——
* 口径与「店铺管理/查询ASIN/最低价ASIN」三页逐字一致)。tab 是视图开关,不是安全边界。</p>
*
* <p><b>公司 tab 下的可见集是「店铺表里有、且负责人属于这家公司」的店铺</b>:扫描结果里那些
* 没登记进 biz_shop_manage 的店铺名(历史上传文件留下的)在任何公司 tab 下都不出现,
* 只有回到「全部」才看得到。这是按负责人推归属的必然代价,不是筛选坏了。</p>
*/
public Set<String> resolveVisibleShopKeys(Long operatorId, boolean superAdmin, List<Long> companyMemberIds) {
if (!superAdmin) {
return shopKeys(sourceMapper.selectManagedShopNames(operatorId));
}
if (companyMemberIds == null) {
return null;
}
// 空成员集=这家公司一个账号都没有=一家店铺都没有:必须给空集合(页面显示"没有店铺"),
// 绝不能退化成 null——null 在这里是"全量",会让第 2 家看到全部数据。
return companyMemberIds.isEmpty()
? new LinkedHashSet<>()
: shopKeys(sourceMapper.selectShopNamesOwnedBy(companyMemberIds));
}
private static Set<String> shopKeys(List<String> names) {
Set<String> keys = new LinkedHashSet<>();
for (String name : sourceMapper.selectManagedShopNames(operatorId)) {
for (String name : names) {
if (name != null && !name.isBlank()) {
keys.add(shopKey(name));
}
@@ -44,6 +44,7 @@ public class QueryAsinController {
private final QueryAsinService queryAsinService;
private final AdminAuthSupport adminAuthSupport;
private final com.nanri.aiimage.common.service.DataReadScope dataReadScope;
/** 解析当前操作者(JWT 或内部令牌通道),权限与数据范围一律以该身份为准。 */
private AdminUserEntity requireOperator(HttpServletRequest request) {
@@ -51,7 +52,7 @@ public class QueryAsinController {
}
@GetMapping
@Operation(summary = "分页查询 ASIN")
@Operation(summary = "分页查询 ASIN", description = "company_id 只收窄可见集、不放大,跨公司查看仅超管")
public ApiResponse<QueryAsinPageVo> page(
HttpServletRequest request,
@Parameter(description = "页码") @RequestParam(name = "page", defaultValue = "1") Long page,
@@ -59,8 +60,14 @@ public class QueryAsinController {
@Parameter(description = "分组ID") @RequestParam(name = "group_id", required = false) Long groupId,
@Parameter(description = "店铺名") @RequestParam(name = "shop_name", required = false) String shopName,
@Parameter(description = "商品 ASIN") @RequestParam(name = "asin", required = false) String asin,
@Parameter(description = "国家代码(DE/UK/FR/IT/ES)") @RequestParam(name = "country", required = false) String country) {
@Parameter(description = "国家代码(DE/UK/FR/IT/ES)") @RequestParam(name = "country", required = false) String country,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity operator = requireOperator(request);
// 成员集就地算,且只在超管这一支算(非超管靠分组关系推,叠 created_by_id IN 成员会把
// 「只挂了 user_id 的分组」那批行从每个 tab 里静默删掉——口径与店铺管理逐字一致)。
java.util.List<Long> memberIds = isSuper(operator)
? dataReadScope.readScope(operator, companyId).userIdsOr(null)
: null;
return ApiResponse.success(queryAsinService.page(
page,
pageSize,
@@ -69,20 +76,25 @@ public class QueryAsinController {
asin,
country,
operator.getId(),
isSuper(operator)));
isSuper(operator),
memberIds));
}
@GetMapping("/export")
@Operation(summary = "导出查询 ASIN")
@Operation(summary = "导出查询 ASIN", description = "导出与列表同一个 company_id 范围,否则 tab 筛了表格、导出全量=越权泄露")
public ResponseEntity<byte[]> export(
HttpServletRequest request,
@Parameter(description = "分组ID") @RequestParam(name = "group_id", required = false) Long groupId,
@Parameter(description = "店铺名") @RequestParam(name = "shop_name", required = false) String shopName,
@Parameter(description = "商品 ASIN") @RequestParam(name = "asin", required = false) String asin,
@Parameter(description = "国家代码(DE/UK/FR/IT/ES)") @RequestParam(name = "country", required = false) String country) {
@Parameter(description = "国家代码(DE/UK/FR/IT/ES)") @RequestParam(name = "country", required = false) String country,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity operator = requireOperator(request);
java.util.List<Long> memberIds = isSuper(operator)
? dataReadScope.readScope(operator, companyId).userIdsOr(null)
: null;
byte[] bytes = queryAsinService.export(groupId, shopName, asin, country,
operator.getId(), isSuper(operator));
operator.getId(), isSuper(operator), memberIds);
String filename = "query-asin-" + LocalDateTime.now().format(EXPORT_FILENAME_FORMATTER) + ".xlsx";
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, DownloadHeaderUtil.contentDisposition(filename))
@@ -45,6 +45,7 @@ public class SkipPriceAsinController {
private final SkipPriceAsinService skipPriceAsinService;
private final AdminAuthSupport adminAuthSupport;
private final com.nanri.aiimage.common.service.DataReadScope dataReadScope;
/** 解析当前操作者(JWT 或内部令牌通道),权限与数据范围一律以该身份为准。 */
private AdminUserEntity requireOperator(HttpServletRequest request) {
@@ -62,8 +63,14 @@ public class SkipPriceAsinController {
@Parameter(description = "商品 ASIN") @RequestParam(name = "asin", required = false) String asin,
@Parameter(description = "国家代码(DE/UK/FR/IT/ES)") @RequestParam(name = "country", required = false) String country,
@Parameter(description = "最低价下限") @RequestParam(name = "minimum_price_from", required = false) BigDecimal minimumPriceFrom,
@Parameter(description = "最低价上限") @RequestParam(name = "minimum_price_to", required = false) BigDecimal minimumPriceTo) {
@Parameter(description = "最低价上限") @RequestParam(name = "minimum_price_to", required = false) BigDecimal minimumPriceTo,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity operator = requireOperator(request);
// 成员集就地算,且只在超管这一支算(非超管靠分组关系推,叠 created_by_id IN 成员会把
// 「只挂了 user_id 的分组」那批行从每个 tab 里静默删掉——口径与店铺管理逐字一致)。
java.util.List<Long> memberIds = isSuper(operator)
? dataReadScope.readScope(operator, companyId).userIdsOr(null)
: null;
return ApiResponse.success(skipPriceAsinService.page(
page,
pageSize,
@@ -74,7 +81,8 @@ public class SkipPriceAsinController {
minimumPriceFrom,
minimumPriceTo,
operator.getId(),
isSuper(operator)));
isSuper(operator),
memberIds));
}
@GetMapping("/export")
@@ -86,10 +94,14 @@ public class SkipPriceAsinController {
@Parameter(description = "商品 ASIN") @RequestParam(name = "asin", required = false) String asin,
@Parameter(description = "国家代码(DE/UK/FR/IT/ES)") @RequestParam(name = "country", required = false) String country,
@Parameter(description = "最低价下限") @RequestParam(name = "minimum_price_from", required = false) BigDecimal minimumPriceFrom,
@Parameter(description = "最低价上限") @RequestParam(name = "minimum_price_to", required = false) BigDecimal minimumPriceTo) {
@Parameter(description = "最低价上限") @RequestParam(name = "minimum_price_to", required = false) BigDecimal minimumPriceTo,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity operator = requireOperator(request);
java.util.List<Long> memberIds = isSuper(operator)
? dataReadScope.readScope(operator, companyId).userIdsOr(null)
: null;
byte[] bytes = skipPriceAsinService.export(groupId, shopName, asin, country, minimumPriceFrom, minimumPriceTo,
operator.getId(), isSuper(operator));
operator.getId(), isSuper(operator), memberIds);
String filename = "skip-price-asin-" + LocalDateTime.now().format(EXPORT_FILENAME_FORMATTER) + ".xlsx";
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, DownloadHeaderUtil.contentDisposition(filename))
@@ -95,10 +95,10 @@ public class QueryAsinService {
private static final java.time.Duration IMPORT_STATE_TTL = java.time.Duration.ofHours(3);
public QueryAsinPageVo page(long page, long pageSize, Long groupId, String shopName, String asin,
String country, Long operatorId, boolean superAdmin) {
String country, Long operatorId, boolean superAdmin, List<Long> companyMemberIds) {
long safePage = Math.max(page, 1);
long safePageSize = Math.min(Math.max(pageSize, 1), 100);
Long total = countFilteredRows(groupId, shopName, asin, country, operatorId, superAdmin);
Long total = countFilteredRows(groupId, shopName, asin, country, operatorId, superAdmin, companyMemberIds);
List<QueryAsinEntity> rows = listFilteredRows(
groupId,
shopName,
@@ -106,6 +106,7 @@ public class QueryAsinService {
country,
operatorId,
superAdmin,
companyMemberIds,
(safePage - 1) * safePageSize,
safePageSize);
@@ -123,12 +124,14 @@ public class QueryAsinService {
return vo;
}
public byte[] export(Long groupId, String shopName, String asin, String country, Long operatorId, boolean superAdmin) {
Long total = countFilteredRows(groupId, shopName, asin, country, operatorId, superAdmin);
public byte[] export(Long groupId, String shopName, String asin, String country, Long operatorId,
boolean superAdmin, List<Long> companyMemberIds) {
Long total = countFilteredRows(groupId, shopName, asin, country, operatorId, superAdmin, companyMemberIds);
if (total != null && total > MAX_EXPORT_ROWS) {
throw new BusinessException("导出数据超过上限 " + MAX_EXPORT_ROWS + " 行,请缩小筛选范围");
}
List<QueryAsinEntity> rows = listFilteredRows(groupId, shopName, asin, country, operatorId, superAdmin, null, null);
List<QueryAsinEntity> rows = listFilteredRows(groupId, shopName, asin, country, operatorId, superAdmin,
companyMemberIds, null, null);
Map<Long, String> groupNameById = shopManageGroupService.buildGroupNameMap(rows.stream()
.map(QueryAsinEntity::getGroupId)
.filter(id -> id != null && id > 0)
@@ -150,26 +153,30 @@ public class QueryAsinService {
}
}
private Long countFilteredRows(Long groupId, String shopName, String asin, String country, Long operatorId, boolean superAdmin) {
return queryAsinMapper.selectCount(buildFilterQuery(groupId, shopName, asin, country, operatorId, superAdmin));
private Long countFilteredRows(Long groupId, String shopName, String asin, String country, Long operatorId,
boolean superAdmin, List<Long> companyMemberIds) {
return queryAsinMapper.selectCount(
buildFilterQuery(groupId, shopName, asin, country, operatorId, superAdmin, companyMemberIds));
}
private List<QueryAsinEntity> listFilteredRows(Long groupId, String shopName, String asin, String country,
Long operatorId, boolean superAdmin,
Long operatorId, boolean superAdmin, List<Long> companyMemberIds,
Long offset, Long limit) {
LambdaQueryWrapper<QueryAsinEntity> query = buildFilterQuery(groupId, shopName, asin, country, operatorId, superAdmin);
LambdaQueryWrapper<QueryAsinEntity> query = buildFilterQuery(
groupId, shopName, asin, country, operatorId, superAdmin, companyMemberIds);
if (offset != null && limit != null) {
query.last("LIMIT " + Math.max(0L, offset) + ", " + Math.max(1L, limit));
}
return queryAsinMapper.selectList(query);
}
private LambdaQueryWrapper<QueryAsinEntity> buildFilterQuery(Long groupId, String shopName, String asin, String country,
Long operatorId, boolean superAdmin) {
private LambdaQueryWrapper<QueryAsinEntity> buildFilterQuery(Long groupId, String shopName, String asin,
String country, Long operatorId, boolean superAdmin,
List<Long> companyMemberIds) {
String safeShopName = normalizeBlank(shopName);
String safeAsin = normalizeBlank(asin);
String safeCountry = normalizeBlank(country).toUpperCase(Locale.ROOT);
Set<Long> accessibleGroupIds = superAdmin ? Set.of() : shopManageGroupService.listAccessibleGroupIds(operatorId, false);
Set<Long> visibleGroupIds = visibleGroupIds(operatorId, superAdmin, companyMemberIds);
LambdaQueryWrapper<QueryAsinEntity> query = new LambdaQueryWrapper<QueryAsinEntity>()
.eq(groupId != null && groupId > 0, QueryAsinEntity::getGroupId, groupId)
.like(!safeShopName.isEmpty(), QueryAsinEntity::getShopName, safeShopName)
@@ -190,16 +197,36 @@ public class QueryAsinService {
SFunction<QueryAsinEntity, ?> countryColumn = queryAsinCountryColumn(safeCountry);
query.isNotNull(countryColumn).ne(countryColumn, "");
}
if (!superAdmin) {
if (accessibleGroupIds.isEmpty()) {
// null = 不筛(超管没选公司,与今天逐字一致);空集 = 这一档公司一行都不该出现,用恒不成立的 id 兜住。
if (visibleGroupIds != null) {
if (visibleGroupIds.isEmpty()) {
query.eq(QueryAsinEntity::getId, -1L);
} else {
query.in(QueryAsinEntity::getGroupId, accessibleGroupIds);
query.in(QueryAsinEntity::getGroupId, visibleGroupIds);
}
}
return query;
}
/**
* 这一页能看哪些分组:非超管沿用既有可见集,公司 tab 只**收窄**它、不放大
* (放大等于把操作员本来看不到的分组端出来,比少看更坏)。
*
* @return null = 不筛分组
*/
private Set<Long> visibleGroupIds(Long operatorId, boolean superAdmin, List<Long> companyMemberIds) {
if (companyMemberIds == null) {
return superAdmin ? null : shopManageGroupService.listAccessibleGroupIds(operatorId, false);
}
Set<Long> companyGroupIds = shopManageGroupService.listCompanyGroupIds(companyMemberIds);
if (superAdmin) {
return companyGroupIds;
}
Set<Long> narrowed = new java.util.LinkedHashSet<>(shopManageGroupService.listAccessibleGroupIds(operatorId, false));
narrowed.retainAll(companyGroupIds);
return narrowed;
}
private SFunction<QueryAsinEntity, ?> queryAsinCountryColumn(String country) {
return switch (country) {
case "DE" -> QueryAsinEntity::getAsinDe;
@@ -97,6 +97,30 @@ public class ShopManageGroupService {
.collect(Collectors.toCollection(LinkedHashSet::new));
}
/**
* 属于这批账号的分组 id——公司 tab 在「只有 group_id、没有账号列」的表上推归属的唯一口径。
*
* <p><b>必须两列一起认</b>:生产 12 个分组里 10 个只有 {@code created_by_id},另外 2 个
* (周丽娥 id=2 / 郭亚芳 id=3)只有 {@code user_id}。只按 {@code created_by_id} 筛会把这 2 个分组
* 从每一个 tab 里静默删掉(不报错、不 403),而它们下面挂着 查询ASIN 4,525 行中的 4,512 行、
* 最低价ASIN 30,963 行中的 29,229 行——那会让「切到本公司」看起来像数据被删了 99%。</p>
*/
public Set<Long> listCompanyGroupIds(List<Long> companyMemberIds) {
if (companyMemberIds == null || companyMemberIds.isEmpty()) {
return Set.of();
}
return groupMapper.selectList(new LambdaQueryWrapper<ShopManageGroupEntity>()
.select(ShopManageGroupEntity::getId)
// 自成一组:MP 会给 and() 补最外层括号,这里再嵌一层 or 才不会让
// created_by_id 那半边逃出公司条件(AND 优先)。
.and(w -> w.in(ShopManageGroupEntity::getCreatedById, companyMemberIds)
.or(x -> x.in(ShopManageGroupEntity::getUserId, companyMemberIds))))
.stream()
.map(ShopManageGroupEntity::getId)
.filter(id -> id != null && id > 0)
.collect(Collectors.toCollection(LinkedHashSet::new));
}
public Set<Long> listAccessibleCreatorUserIds(Long operatorId, boolean superAdmin) {
if (superAdmin) {
return Set.of();
@@ -97,10 +97,11 @@ public class SkipPriceAsinService {
public SkipPriceAsinPageVo page(long page, long pageSize, Long groupId, String shopName, String asin,
String country, BigDecimal minimumPriceFrom, BigDecimal minimumPriceTo,
Long operatorId, boolean superAdmin) {
Long operatorId, boolean superAdmin, List<Long> companyMemberIds) {
long safePage = Math.max(page, 1);
long safePageSize = Math.min(Math.max(pageSize, 1), 100);
Long total = countFilteredRows(groupId, shopName, asin, country, minimumPriceFrom, minimumPriceTo, operatorId, superAdmin);
Long total = countFilteredRows(groupId, shopName, asin, country, minimumPriceFrom, minimumPriceTo,
operatorId, superAdmin, companyMemberIds);
List<SkipPriceAsinEntity> rows = listFilteredRows(
groupId,
shopName,
@@ -110,6 +111,7 @@ public class SkipPriceAsinService {
minimumPriceTo,
operatorId,
superAdmin,
companyMemberIds,
(safePage - 1) * safePageSize,
safePageSize);
@@ -129,13 +131,14 @@ public class SkipPriceAsinService {
public byte[] export(Long groupId, String shopName, String asin, String country,
BigDecimal minimumPriceFrom, BigDecimal minimumPriceTo,
Long operatorId, boolean superAdmin) {
Long total = countFilteredRows(groupId, shopName, asin, country, minimumPriceFrom, minimumPriceTo, operatorId, superAdmin);
Long operatorId, boolean superAdmin, List<Long> companyMemberIds) {
Long total = countFilteredRows(groupId, shopName, asin, country, minimumPriceFrom, minimumPriceTo,
operatorId, superAdmin, companyMemberIds);
if (total != null && total > MAX_EXPORT_ROWS) {
throw new BusinessException("导出数据超过上限 " + MAX_EXPORT_ROWS + " 行,请缩小筛选范围");
}
List<SkipPriceAsinEntity> rows = listFilteredRows(groupId, shopName, asin, country,
minimumPriceFrom, minimumPriceTo, operatorId, superAdmin, null, null);
minimumPriceFrom, minimumPriceTo, operatorId, superAdmin, companyMemberIds, null, null);
Map<Long, String> groupNameById = shopManageGroupService.buildGroupNameMap(rows.stream()
.map(SkipPriceAsinEntity::getGroupId)
.filter(id -> id != null && id > 0)
@@ -159,17 +162,17 @@ public class SkipPriceAsinService {
private Long countFilteredRows(Long groupId, String shopName, String asin, String country,
BigDecimal minimumPriceFrom, BigDecimal minimumPriceTo,
Long operatorId, boolean superAdmin) {
Long operatorId, boolean superAdmin, List<Long> companyMemberIds) {
return skipPriceAsinMapper.selectCount(buildFilterQuery(groupId, shopName, asin, country,
minimumPriceFrom, minimumPriceTo, operatorId, superAdmin));
minimumPriceFrom, minimumPriceTo, operatorId, superAdmin, companyMemberIds));
}
private List<SkipPriceAsinEntity> listFilteredRows(Long groupId, String shopName, String asin, String country,
BigDecimal minimumPriceFrom, BigDecimal minimumPriceTo,
Long operatorId, boolean superAdmin,
Long operatorId, boolean superAdmin, List<Long> companyMemberIds,
Long offset, Long limit) {
LambdaQueryWrapper<SkipPriceAsinEntity> query = buildFilterQuery(groupId, shopName, asin, country,
minimumPriceFrom, minimumPriceTo, operatorId, superAdmin);
minimumPriceFrom, minimumPriceTo, operatorId, superAdmin, companyMemberIds);
if (offset != null && limit != null) {
query.last("LIMIT " + Math.max(0L, offset) + ", " + Math.max(1L, limit));
}
@@ -178,11 +181,12 @@ public class SkipPriceAsinService {
private LambdaQueryWrapper<SkipPriceAsinEntity> buildFilterQuery(Long groupId, String shopName, String asin, String country,
BigDecimal minimumPriceFrom, BigDecimal minimumPriceTo,
Long operatorId, boolean superAdmin) {
Long operatorId, boolean superAdmin,
List<Long> companyMemberIds) {
String safeShopName = normalizeBlank(shopName);
String safeAsin = normalizeBlank(asin);
String safeCountry = normalizeBlank(country).toUpperCase(Locale.ROOT);
Set<Long> accessibleGroupIds = superAdmin ? Set.of() : shopManageGroupService.listAccessibleGroupIds(operatorId, false);
Set<Long> visibleGroupIds = visibleGroupIds(operatorId, superAdmin, companyMemberIds);
LambdaQueryWrapper<SkipPriceAsinEntity> query = new LambdaQueryWrapper<SkipPriceAsinEntity>()
.eq(groupId != null && groupId > 0, SkipPriceAsinEntity::getGroupId, groupId)
.like(!safeShopName.isEmpty(), SkipPriceAsinEntity::getShopName, safeShopName)
@@ -235,16 +239,38 @@ public class SkipPriceAsinService {
}
}
}
if (!superAdmin) {
if (accessibleGroupIds.isEmpty()) {
// null = 不筛(超管没选公司,与今天逐字一致);空集 = 这一档公司一行都不该出现,用恒不成立的 id 兜住。
if (visibleGroupIds != null) {
if (visibleGroupIds.isEmpty()) {
query.eq(SkipPriceAsinEntity::getId, -1L);
} else {
query.in(SkipPriceAsinEntity::getGroupId, accessibleGroupIds);
query.in(SkipPriceAsinEntity::getGroupId, visibleGroupIds);
}
}
return query;
}
/**
* 这一页能看哪些分组:非超管沿用既有可见集,公司 tab 只**收窄**它、不放大。
* 分组归公司必须 created_by_id 与 user_id 两列一起认,口径在
* {@link ShopManageGroupService#listCompanyGroupIds(java.util.List)} 那一处。
*
* @return null = 不筛分组
*/
private Set<Long> visibleGroupIds(Long operatorId, boolean superAdmin, List<Long> companyMemberIds) {
if (companyMemberIds == null) {
return superAdmin ? null : shopManageGroupService.listAccessibleGroupIds(operatorId, false);
}
Set<Long> companyGroupIds = shopManageGroupService.listCompanyGroupIds(companyMemberIds);
if (superAdmin) {
return companyGroupIds;
}
Set<Long> narrowed = new java.util.LinkedHashSet<>(
shopManageGroupService.listAccessibleGroupIds(operatorId, false));
narrowed.retainAll(companyGroupIds);
return narrowed;
}
private void writeExportHeader(Sheet sheet) {
Row header = sheet.createRow(0);
String[] headers = {
@@ -0,0 +1,129 @@
-- =============================================================
-- 迁移 V147__product_category_company_scope
-- 模板:docs/flyway-migration-template.md
-- 设计:crawler-plugin/docs/ops/brand-dedupe-company-isolation-design-2026-10-04.md §2.2(规则库每公司一套)
-- 需求:2026-10-05「商品类目也要区分公司,切换 tab 数据显示还一样」
--
-- 1. 变更目的:把「商品类目」biz_product_category 从"全平台一棵树"改成"内置节点共享 + 每公司自己的自定义节点"。
-- 现状是这张表一个归属列都没有(2026-10-05 22:29 主机A 只读实查,列清单为
-- id/parent_id/name/category_key/sort_order/description/is_builtin/created_at/updated_at,共 9 列),
-- 所以后台的公司 tab 在这一页是纯装饰:切到哪一家都是同一棵 412 行的树。
-- 同时 uk_product_category_key(category_key) 是【全平台】唯一键——第 2 家公司在第 1 家建过的
-- 父级下重名建类时,generateCategoryKey(parentId, name) 会算出同一个 sha1 前缀而撞键,
-- 这不是"看不到",是"根本建不出来"。company_id 打头的新唯一键解掉它。
--
-- 2. 口径:内置节点取哨兵公司 0,自定义节点归建号那一家。
-- 【为什么是 0 而不是把 18 行内置节点按公司复制一份】
-- - company.id 是 AUTO_INCREMENT,最小值 1,0 永远不会撞上真实公司;
-- CompanyScopeSupport.requireCompanyId 对 <= 0 直接抛 ⇒ 没有任何账号能被登记成公司 0。
-- - 货源/外观的类目归类读的是【全局】那一棵树(SimilarAsinLlmService:215 调 list() 无参重载),
-- 复制成每公司一份会让同一个"面霜"有 N 个 category_key,LLM 的分类结果从此按公司分叉、
-- 并且每一次归类候选都变多——这是成本,不只是口径。
-- - 复制还要回填 394 行自定义节点的父子指向,而 parent_id 是全表 id,改不动。
-- 【代价,必须写明】第 2 家公司的 tab 里只看得见 18 个内置节点,自建节点从 0 开始长;
-- 而 394 行自定义节点全部回填成公司 1——这不是猜:这些行是"手工建的类目",
-- 今天能建类目的只有第 1 家的账号(第 2 家 10-04 14:55 才开通、名下 0 个任务),
-- 且这张表【没有】任何账号列,事后无法反推。所以这一页的写侧必须从本版本起显式落公司
-- (见下方 DEFAULT 的临时性),否则新行又要靠默认值兜、下一次就彻底分不开了。
--
-- 3. 影响表与数据量(2026-10-05 22:29 主机A 业务库只读实查,不是估的):
-- biz_product_category = 412 行(内置 18、自定义 394;parent_id IS NULL 26,其中自定义根 22;MAX(id)=600)
-- 同一 (parent_id, name) 的重复组合 = 0 组 ⇒ 加列与换键都不会撞新唯一键。
-- company / columns / users 与其余业务表一律不动。
--
-- 4. 锁表风险:低。412 行的表,任何形态的 DDL 都在毫秒级。
-- 仍然按 V145 的规矩写:ADD COLUMN 走 ALGORITHM = INSTANT(前提不成立时 MySQL 直接报 1846,
-- 而不是悄悄退化成 COPY——宁可迁移失败走 repair 重跑,也不要一次没人预期的重建);
-- 两条索引操作钉 ALGORITHM = INPLACE, LOCK = NONE。
-- 只有一条 UPDATE:驱动条件是 is_builtin = 1(18 行),不依赖别的表,不碰锁热点表。
-- 索引字节预算(utf8mb4 + DYNAMIC,上限 3072):uk_company_category_key = 8 + 128*4 = 520。
-- 【不加 idx_product_category_company】新唯一键的最左前缀就是 company_id,412 行的
-- WHERE company_id IN (0, ?) 走它或走全表扫描都在同一量级;再单开一个列索引就是 V139 那轮
-- 清理掉的冗余索引形状。
--
-- 5. 回滚步骤:人工补丁 backend-java/docs/rollback-V147-product-category-company.sql(在 Flyway 扫描路径之外,
-- 不写成 V148——版本化回滚等于让"决定回滚"这件事在没有人工执行的情况下自己发生)。
-- 顺序:停两台应用 → 跑脚本 → 删 flyway_schema_history 的 version=147 行 → 回滚 jar → 起应用。
--
-- 6. 上线窗口:随 jar 双节点同窗口发布,金丝雀过了立刻补第二台,把混合版本窗口压到分钟级。
-- DEFAULT 1 是【临时】的,唯一存在理由是同批的旧 jar:它的 ProductCategoryEntity 没有
-- companyId 字段,MyBatis-Plus 的 insert 会整列跳过,严格模式下报 1364。
-- 和 V145 那张 50.7 万行的表不同,本表的历史值是由第 2 段【显式 UPDATE】写进去的,
-- 所以摘 DEFAULT 不需要回填:下一版迁移只需一条元数据操作
-- ALTER TABLE biz_product_category ALTER COLUMN company_id DROP DEFAULT;
-- (禁止写成 MODIFY COLUMN ... NOT NULL——那会重建表,而重建按"当时的列默认值"物化历史行。)
-- 在摘掉之前,启动期 CompanyDefaultGuard 会把本表一并盯住(WATCHED_TABLES 已加入
-- biz_product_category),公司数 > 1 且本列还带 DEFAULT 就打 COMPANY_DEFAULT_STILL_PRESENT,
-- 巡检按这条 ASCII 签名 grep——"漏摘"由代码喊,不靠人记得。
--
-- 【可重跑性】MySQL 的 DDL 不进事务。本迁移若在换键段失败,前面的加列与回填已落库;
-- 按「补数据 → flyway repair → 重启」恢复时 Flyway 从第一条语句重跑整个文件,所以两条 DDL
-- 都先查 information_schema 再 PREPARE,那条 UPDATE 自带 company_id = 1 限定(重跑是 no-op)。
-- 写法首例见 V143 全文件、V145 的加列/换键段。
-- =============================================================
SET @db_name = DATABASE();
-- ---------- 1. 加列(末位 + INSTANT) ----------
SET @col_exists := (SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_product_category' AND COLUMN_NAME = 'company_id');
SET @sql := IF(@col_exists = 0,
'ALTER TABLE `biz_product_category` ADD COLUMN `company_id` bigint NOT NULL DEFAULT 1 COMMENT ''归属公司(company.id):0 = 平台内置共享节点,> 0 = 该公司自建;V147'', ALGORITHM = INSTANT',
'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- ---------- 2. 内置节点改挂哨兵公司 0 ----------
-- 18 行,走 is_builtin 条件而不是 category_key 白名单:V50 的种子后来被删过(种子 24 行、
-- 今天 18 行),按标志位才不会漏也不会多。带 company_id = 1 限定 ⇒ 重跑是 no-op。
UPDATE `biz_product_category`
SET `company_id` = 0
WHERE `is_builtin` = 1
AND `company_id` = 1;
-- ---------- 3. 唯一键按公司放宽(先 ADD 后 DROP:中间任一步失败都至少还有一个唯一键在守并发) ----------
-- 新键是旧键的严格放宽(旧键全平台唯一 ⇒ 新键必唯一),所以这一步不可能因重复而失败。
SET @idx_exists := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_product_category' AND INDEX_NAME = 'uk_company_category_key');
SET @sql := IF(@idx_exists = 0,
'ALTER TABLE `biz_product_category` ADD UNIQUE KEY `uk_company_category_key` (`company_id`, `category_key`), ALGORITHM = INPLACE, LOCK = NONE',
'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @idx_exists := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_product_category' AND INDEX_NAME = 'uk_product_category_key');
SET @sql := IF(@idx_exists > 0,
'ALTER TABLE `biz_product_category` DROP INDEX `uk_product_category_key`, ALGORITHM = INPLACE, LOCK = NONE',
'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- =============================================================
-- 验证 SQL(迁移后在库上执行)
-- SELECT COUNT(*) AS total, SUM(company_id = 0) AS builtin_shared,
-- SUM(company_id = 1) AS company_1, SUM(company_id NOT IN (0, 1)) AS other_company
-- FROM `biz_product_category`;
-- -> 期望 412 / 18 / 394 / 0。builtin_shared 必须等于 SUM(is_builtin = 1):
-- 不等就是回填漏了行,而漏掉的内置节点会从第 2 家的类目树里静默消失。
-- SELECT SUM(is_builtin = 1 AND company_id <> 0) AS bad_builtin,
-- SUM(is_builtin = 0 AND company_id = 0) AS bad_custom
-- FROM `biz_product_category`;
-- -> 期望 0 / 0(哨兵值只给内置行用)
-- SHOW INDEX FROM `biz_product_category`;
-- -> 期望有 uk_company_category_key(company_id, category_key) 且【没有】uk_product_category_key
-- SELECT company_id, category_key, COUNT(*) c FROM `biz_product_category`
-- GROUP BY company_id, category_key HAVING c > 1;
-- -> 期望 0 行(新键能建起来的前提)
-- SELECT COUNT(*) FROM information_schema.COLUMNS
-- WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'biz_product_category'
-- AND COLUMN_NAME = 'company_id' AND COLUMN_DEFAULT IS NOT NULL;
-- -> 本版本发布后期望 1(DEFAULT 1 还在,由 CompanyDefaultGuard 喊);
-- 摘 DEFAULT 的那一版之后必须变 0
-- =============================================================
@@ -93,7 +93,7 @@ import org.junit.jupiter.api.Test;
* ① {@code readScope(} 的结果必须<b>被赋值给一个变量</b>({@code List<Long> scoped = …readScope(…);} 与
* {@code ReadScope s = …readScope(…);} 两种形状都认);找不到赋值目标 = 裸语句、结果被丢掉 ⇒ 红。
* ② 该变量必须出现在 handler 体内<b>另一条方法调用的实参列表</b>里(扣掉它自己那条赋值语句,
* 单层括号够用,今天两页都是这一形)。只要求"在别处被引用一次"不够:
* 实参表按 {@link #callsOf} 的配对括号取,见第 13 条)。只要求"在别处被引用一次"不够:
* {@code if (scoped != null) throw …} 是装饰,不算把范围交给谁 ⇒ 控制语句关键字不认。</li>
* <li><b>调了出口不等于把公司参数交给了出口</b>(本轮新增的断言 D)。现网最难查的一刀是
* {@code dataReadScope.readScope(operator, null)}:参数照样收下(B 绿)、{@code readScope(} 照样写在
@@ -102,18 +102,35 @@ import org.junit.jupiter.api.Test;
* D 因此先按 {@link Block#boundCompanyParam()} 从<b>声明窗口</b>里取出被绑定到
* {@code company_id} 的<b>变量名</b>(不硬编码 {@code companyId}:这一支改叫 {@code orgId} 就用
* {@code orgId} 判),再要求它作为整词实参出现在 {@code readScope}/{@code resolveScope} 的参数表里
* (单层括号,复用 {@link #CALL_ARGUMENTS};私有收口方法 {@code resolveScope(request, companyId)}
* (实参表按 {@link #callsOf} 的配对括号取,见第 13 条;私有收口方法 {@code resolveScope(request, companyId)}
* 那一形算,Task 11 模板鼓励的正是它)。只写在 {@code if (companyId != null)} 里、或只出现在
* {@code @Operation} 文案里,都不算消费——沿用 C 的 {@link #NOT_VALUE_CONSUMERS} 那把尺子,不放宽。
* 射程与 A/B/C 同源:同一个 {@code takesCompanyParam()} 谓词、同一份
* {@link #READ_SCOPE_ALLOWLIST}(一条豁免同时免 A/B/C/D,不许另起第二张表),并且只咬
* {@code viaRequestParam()} 那一族(F-C 的同一把尺子:{@code getParameter("company_id")} 给不出
* 绑定变量名,D 对它无从判定)。取不到绑定名 = 形状不认识 ⇒ 判红并报形状,不许静默放过。
* D 的代价与射程一并交代(本轮报告有逐条清单):{@link #CALL_ARGUMENTS} 只吃单层括号,于是
* {@code readScope(operator, normalize(companyId))} 这种嵌套写法会判红(误伤合规代码,改写法或补宽
* D 的取法都算核对过);非 {@code Long} 型公司参数取不到绑定名,同样判红;而"handler 之外的私有
* D 的代价与射程一并交代:非 {@code Long} 型公司参数取不到绑定名,判红并报形状;而"handler 之外的私有
* 收口方法里把公司参数硬写成 {@code null}"这一族 D 看不见——块边界止于该 handler 自己的闭括号
* (第 7 条),{@code AdminImageVideoTaskController.scopeOf} 正是它,那一处是<b>故意</b>传 null 的。</li>
* <li><b>两条正门,一套判据</b>(批次 2/3 新增)。{@code DataReadScope} 现在有两个出口:
* {@code readScope(} 按账号集合给范围(去重库、查询 ASIN、最低价 ASIN、历史、视频),
* {@code readCompanyId(} 给"归属已物化成 {@code company_id} 列"的表(品牌库、商品类目——
* 那两张表的 {@code uploader_user_id} 在生产是 0 行非空,按账号筛等于把全部历史从每个公司 tab 里
* 静默删掉,理由写在 {@code DataReadScope#readCompanyId} 的注释里)。两条门共用 A/B/C/D 四条判据:
* {@link #SCOPE_DOORS} 供 A 与 C 逐条跑,{@link #SCOPE_CALLEE_NAMES} 供 D 认被调名,
* <b>名单只写一次</b>(红因消息与自检断言咬的是拼出来的同一个标签,两处各写一遍会随哈希顺序漂红)。
* 每条门各自带能红/能绿两向探针(全局约束 15 那把尺子):只在 {@code readScope} 上验过,
* 等于第二道门上的返回值与入参没人看守。</li>
* <li><b>取实参表按配对括号,不按单层括号正则</b>(10-05 批次 2/3 实跑)。原先 C 的第 ② 步与 D 都用
* {@code ([\w$]*)\s*\(([^()]*)\)},实参表里只要还有一次方法调用就整条看不见。而第 7 条把块边界钉死在
* handler 自己的闭括号上、断言 A 因此要求正门调用必须内联,两支约束合起来把合规接线逼成了
* {@code service.page(page, operator.id(), memberIds)} 这一形——本轮实跑 6 记假红
* (DedupeTotalData/InvalidAsin/QueryAsin×2/SkipPriceAsin×2)。判据把合规写法判红的下一步,
* 就是有人为了让它绿而把接线挪回块外的私有方法里,那是护栏逼人拆护栏。
* 现按 {@link #callsOf} 逐字符配对取(深度计数,字符串与字符字面量内的括号不计数,口径同第 5 条),
* 嵌套调用自己也入表。放宽的两枚正探针与一枚"嵌套了但没带公司参数"的负探针
* ({@code readScope(operator, operator.getCompanyId())} 整词大小写敏感、照旧红)成对写死:
* 少了负探针,"放宽"两个字就等于把 C 与 D 关掉。</li>
* </ol>
*
* <p>取样键:可执行行里出现 {@code company_id} <b>或</b> {@code companyId}(裸 token 即入样本,交给逐 handler
@@ -153,13 +170,57 @@ class CompanyIdParamGoesThroughReadScopeTest {
* 断言 C 的<b>射程下限</b>(复评 I-1):Task 8 已经接线的两页必须真被 C 扫到。
* 不钉这一条的话,"取样集非空"自检可以由任何一支别的 handler 满足,而这两页哪天改了
* mapping 注解 / 换了参数形状就会静默脱离射程——分母由本轮自己造,等于没有分母。
*
* <p>10-05 批次 2/3(去重库、品牌库、查询ASIN、最低价ASIN、商品类目)把样本面扩到了
* {@link #READ_COMPANY_ID_CALL} 那条正门上,所以这里补两条同样口径的射程下限:
* 那五页哪天改了参数形状,静默脱离的是这一页的 tab,不是这条用例。</p>
*/
private static final String SCOPE_CAUGHT_HISTORY_KEY =
"com/nanri/aiimage/modules/imagehistory/controller/ImageHistoryController.java#@GetMapping(\"/history\")";
private static final String SCOPE_CAUGHT_VIDEO_KEY =
"com/nanri/aiimage/modules/imagevideo/controller/AdminImageVideoTaskController.java#@GetMapping";
private static final String SCOPE_CAUGHT_INVALID_ASIN_KEY =
"com/nanri/aiimage/modules/invalidasin/controller/InvalidAsinDataController.java#@GetMapping";
private static final String SCOPE_CAUGHT_PRODUCT_CATEGORY_KEY =
"com/nanri/aiimage/modules/productcategory/controller/ProductCategoryController.java#@GetMapping(\"/product-categories\")";
private static final String SCOPE_CAUGHT_DEDUPE_KEY =
"com/nanri/aiimage/modules/dedupe/controller/DedupeTotalDataController.java#@GetMapping";
private static final String SCOPE_CAUGHT_QUERY_ASIN_KEY =
"com/nanri/aiimage/modules/shopkey/controller/QueryAsinController.java#@GetMapping";
private static final String SCOPE_CAUGHT_SKIP_PRICE_ASIN_KEY =
"com/nanri/aiimage/modules/shopkey/controller/SkipPriceAsinController.java#@GetMapping";
/**
* 射程下限的<b>唯一一份</b>名单:C 与 D 两条射程断言共用它,不许各写一份(两处各写就会有一处先漂)。
* 这七支是"切 tab 数据还是一样"这次报障正对着的页面 —— 用户报的五页(去重库、品牌库、最低价ASIN、
* 商品类目、查询ASIN)加批次 1 已接线的两页(图片历史、图片视频任务)。
*/
private static final List<String> WIRED_PAGE_KEYS = List.of(
SCOPE_CAUGHT_HISTORY_KEY,
SCOPE_CAUGHT_VIDEO_KEY,
SCOPE_CAUGHT_DEDUPE_KEY,
SCOPE_CAUGHT_QUERY_ASIN_KEY,
SCOPE_CAUGHT_SKIP_PRICE_ASIN_KEY,
SCOPE_CAUGHT_INVALID_ASIN_KEY,
SCOPE_CAUGHT_PRODUCT_CATEGORY_KEY);
private static final String READ_SCOPE_CALL = "readScope(";
/**
* 第二个被认可的正门(10-05 批次 2/3):{@code DataReadScope.readCompanyId(operator, companyId)}。
*
* <p>它存在的理由不是省事:品牌库 {@code biz_invalid_asin_data} 实测 14,801 行里
* {@code uploader_user_id} 非空 <b>0</b> 行(实体没这字段、批量 INSERT 的列清单也没带,V145 补的列
* 一直是空的),走 {@code readScope} 那批账号集合等于把全部历史从每一个公司 tab 里静默删掉;
* 商品类目 {@code biz_product_category} 更是连账号列都没有(V147 才加的 company_id)。
* 这两页的归属是<b>物化列</b>,正门必须按列给。</p>
*
* <p>两条正门是并列的<b>白名单</b>而不是新的自由口径:判据 A/C/D 与 {@code readScope} 逐字共用,
* 只是把"出现过 readScope("换成"出现过两条正门之一"," companyId 进了 readScope 的实参表"换成
* "进了两条正门之一的实参表"。第三条正门(比如页里自己写 {@code if (companyId != null) ...})
* 依然红。</p>
*/
private static final String READ_COMPANY_ID_CALL = "readCompanyId(";
private static final List<String> SCOPE_DOORS = List.of(READ_SCOPE_CALL, READ_COMPANY_ID_CALL);
private static final String EXPLICIT_PARAM_NAME = "name = \"company_id\"";
private static final String SNAKE_PARAM = "company_id";
private static final String CAMEL_PARAM = "companyId";
@@ -178,9 +239,21 @@ class CompanyIdParamGoesThroughReadScopeTest {
*/
private static final Pattern SCOPE_ASSIGNMENT = Pattern.compile("([A-Za-z_$][\\w$]*)\\s*=(?!=)");
/** 断言 C 第 ② 步的消费形状:{@code 名字(实参)},单层括号(现有两页都是这一形)。 */
private static final Pattern CALL_ARGUMENTS =
Pattern.compile("([A-Za-z_$][\\w$]*)\\s*\\(([^()]*)\\)");
/**
* 断言 C 第 ② 步与断言 D 共用的消费形状:{@code 名字(实参表)}。
*
* <p><b>为什么不再是正则</b>(10-05 批次 2/3 实测):原先用 {@code ([\w$]*)\s*\(([^()]*)\)}
* 只吃单层括号,于是 {@code service.page(page, operator.id(), memberIds)} 这种"实参表里还有一次
* 方法调用"的写法整条看不见——而断言 A 要求正门调用必须写在 handler 块<b>内</b>(私有收口方法在
* 块边界之外不算),恰恰把六支 handler 逼成了这一形(本轮实跑 6 记假红:
* DedupeTotalData/QueryAsin×2/SkipPriceAsin×2/InvalidAsin)。判据把合规写法判红,
* 下一步就是有人为了让它绿而把接线挪回块外——那是护栏逼人拆护栏。
* 现按<b>配对括号</b>逐字符取实参表:深度计数,字符串字面量与字符字面量里的括号不计数
* (口径同第 5 条"方法体开行"的判据,不是新尺子),嵌套调用自己也入表(
* {@code readScope(operator.user(), companyId)} 里的 {@code user()} 也在,但它不是正门、不影响判定)。</p>
*/
private record Call(String callee, String arguments) {
}
/**
* 控制语句关键字:读了变量但<b>没把它交给任何人</b>。{@code if (scoped != null) throw …} 这种装饰
@@ -190,12 +263,21 @@ class CompanyIdParamGoesThroughReadScopeTest {
"if", "for", "while", "switch", "do", "catch", "synchronized", "return", "throw", "else", "try");
/**
* 断言 D 认的两个被调名:{@code readScope} 是唯一出口本身,{@code resolveScope} 是 Task 11 模板
* 鼓励的"controller 里的私有收口方法"那一形(它内部再去 readScope)。除此之外的调用都不算
* "把公司参数交给了出口"——尤其 {@code readScope(operator, null)} 里那个 {@code null}。
* 断言 D 认的三个被调名:{@code readScope} 是按账号集合给范围的唯一出口,
* {@code resolveScope} 是 Task 11 模板鼓励的"controller 里的私有收口方法"那一形(它内部再去
* readScope),{@code readCompanyId} 是归属已物化成 {@code company_id} 列那两张表
* (品牌库、商品类目)的正门(见 {@link #READ_COMPANY_ID_CALL} 的理由)。
* 除此之外的调用都不算"把公司参数交给了出口"——尤其 {@code readScope(operator, null)} 里那个 {@code null}。
*/
private static final String RESOLVE_SCOPE_CALL = "resolveScope(";
private static final Set<String> SCOPE_CALLEES = Set.of("readScope", "resolveScope");
/**
* 名单只写一次:Set 给 D 判定用,拼好的标签给 D 的红因消息与自检断言用。
* 直接从 {@code Set} 拼会随哈希顺序变 ⇒ 消息里的名字顺序不稳定,而自检断言咬的是整串字面量,
* 那就等于一条会自己漂红的用例。
*/
private static final List<String> SCOPE_CALLEE_NAMES = List.of("readScope", "resolveScope", "readCompanyId");
private static final Set<String> SCOPE_CALLEES = Set.copyOf(SCOPE_CALLEE_NAMES);
private static final String SCOPE_CALLEE_LABEL = String.join("/", SCOPE_CALLEE_NAMES);
/**
* 断言 D 的取绑定名(两把锚一起用):先在声明窗口里找 {@code name = "company_id"}
@@ -352,6 +434,95 @@ class CompanyIdParamGoesThroughReadScopeTest {
}
""";
/**
* 第二条正门({@code readCompanyId})的<b>正探针</b>:形状逐字抄现网那一支
* ({@code InvalidAsinDataController.page} —— 先 {@code operator.user()} 把实体取出来,
* 再 {@code Long scopedCompanyId = dataReadScope.readCompanyId(user, companyId);},
* 最后把 {@code scopedCompanyId} 交给 service)。
* <p>它证明的是"判据不是只认 {@code readScope} 那一族":C 的第 ①/② 步和 D 都必须在这一形上判绿,
* 否则五页里靠物化列给范围的那两页会红在护栏上,而不是红在真缺陷上。</p>
*/
private static final String READ_COMPANY_ID_CAUGHT_PROBE = """
@GetMapping("/probe")
public String typedDoor(@RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity user = operator.user();
Long scopedCompanyId = dataReadScope.readCompanyId(user, companyId);
return String.valueOf(invalidAsinDataService.page(1, 15, scopedCompanyId));
}
""";
/**
* 第二条正门的<b>裸语句探针</b>(C 第 ① 步在该门上的"能红"证据):
* {@code scopeCatchFailure} 是对两条门<b>逐条</b>跑那两步的,只在 {@code readScope} 上验过不算验过——
* 少了这一枚,"第二道门根本没人看守它的返回值"就能悄悄进仓。
*/
private static final String READ_COMPANY_ID_DISCARD_PROBE = """
@GetMapping("/probe")
public String typedDoorDiscard(@RequestParam(name = "company_id", required = false) Long companyId) {
dataReadScope.readCompanyId(user, companyId);
return "ok";
}
""";
/**
* 第二条正门的<b>负探针</b>(D 在该门上的存在理由):出口调了、结果接住了、也喂给 service 了,
* 唯独进出口的是 {@code null} —— 与 {@link #SCOPE_PASSED_NULL_PROBE} 同一记刀,只是换了道门。
* A/B/C 三条前提在自检里逐条钉住为绿,才说明这一刀今天确实只有 D 会喊。
*/
private static final String READ_COMPANY_ID_PASSED_NULL_PROBE = """
@GetMapping("/probe")
public String typedDoorNull(@RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity user = operator.user();
Long scopedCompanyId = dataReadScope.readCompanyId(user, null);
return String.valueOf(invalidAsinDataService.page(1, 15, scopedCompanyId));
}
""";
/**
* 断言 C 第 ② 步的<b>嵌套实参探针</b>(形状逐字抄现网:{@code DedupeTotalDataController.page})。
* <p>10-05 批次 2/3 实跑 6 记假红全在这一形上——断言 A 要求正门调用写在 handler 块<b>内</b>,
* 于是"把 operatorId 单独传下去"天然长成 {@code service.page(page, operator.id(), memberIds)}。
* 单层括号的取法看不见 {@code memberIds},判据就把合规接线判红;下一步必然有人为了变绿把
* 整段挪到块外的私有方法里——那是护栏逼人拆护栏。放宽后的判据必须有这枚正样本,
* 否则"放宽"两个字没有可证内容。</p>
*/
private static final String SCOPE_NESTED_ARG_PROBE = """
@GetMapping("/probe")
public String nestedArg(@RequestParam(name = "company_id", required = false) Long companyId) {
List<Long> memberIds = operator.superAdmin()
? dataReadScope.readScope(user, companyId).userIdsOr(null)
: null;
return String.valueOf(dedupeTotalDataService.page(page, memberIds, operator.id()));
}
""";
/**
* 断言 D 的<b>嵌套实参探针</b>(正):公司参数经过一次归一化才进出口。
* 与上一枚同一条放宽,但咬的是 D:{@code readScope} 自己的实参表里嵌套了调用,
* 里面确实带着 {@code companyId} ⇒ 必须绿(旧正则在这一形上判红,那是误伤)。
*/
private static final String SCOPE_NESTED_DOOR_ARG_PROBE = """
@GetMapping("/probe")
public String nestedDoorArg(@RequestParam(name = "company_id", required = false) Long companyId) {
List<Long> scoped = dataReadScope.readScope(operator, normalizeCompany(companyId)).userIdsOr(null);
return String.valueOf(shopService.page(page, scoped));
}
""";
/**
* 断言 D 的<b>嵌套负探针</b>(放宽的边界,与上一枚成对):进出口的是
* {@code operator.getCompanyId()} —— 括号取法宽了,"没带 tab 那个值"这一刀不许跟着宽。
* 整词判据大小写敏感(源码里那个名字是 {@code CompanyId},不是 {@code companyId}),
* 嵌套层里也确实取不到被绑定的那个变量名 ⇒ 照旧红。少了这一枚,上面那条正断言就等于把 D 关掉。
*/
private static final String SCOPE_NESTED_DOOR_ARG_FOREIGN_PROBE = """
@GetMapping("/probe")
public String nestedDoorArgForeign(@RequestParam(name = "company_id", required = false) Long companyId) {
List<Long> scoped = dataReadScope.readScope(operator, operator.getCompanyId()).userIdsOr(null);
return String.valueOf(shopService.page(page, scoped));
}
""";
@Test
@DisplayName("每个收公司 id 参数的 handler 都走唯一出口、显式写了 name = \"company_id\","
+ "而且 tab 传下来的那个值真被交给了出口(A/B/C/D)")
@@ -382,8 +553,8 @@ class CompanyIdParamGoesThroughReadScopeTest {
.isTrue();
assertThat(probe.text())
.as("块边界自检:handler 块必须止于与 mapping 注解同缩进的 } 行 —— "
+ "否则尾随私有方法里的 readScope( 会替这支没接出口的 handler 过关")
.doesNotContain(READ_SCOPE_CALL);
+ "否则尾随私有方法里的正门调用会替这支没接出口的 handler 过关")
.satisfies(text -> assertThat(anyScopeDoor(text)).isFalse());
assertThat(probe.spanText())
.as("块边界自检的反面证据:readScope( 确实写在收口之后的尾随方法里")
.contains(READ_SCOPE_CALL);
@@ -405,6 +576,16 @@ class CompanyIdParamGoesThroughReadScopeTest {
assertThat(scopeProbeReason(SCOPE_TYPE_FORM_PROBE, "SCOPE_TYPE_FORM_PROBE"))
.as("断言 C 自检(第二形):ReadScope s = dataReadScope.readScope(…) 且 s 进了 service.page(…) 的实参 ⇒ 同样要认")
.isNull();
// 第二条正门必须<b>各自</b>有能红/能绿两向证据:C 的判据是对 SCOPE_DOORS 逐条跑的,
// 只在 readScope 上验过,就等于没验过 readCompanyId —— 那一道门上的返回值会没人看守。
assertThat(scopeProbeReason(READ_COMPANY_ID_CAUGHT_PROBE, "READ_COMPANY_ID_CAUGHT_PROBE"))
.as("断言 C 自检(第二道门·正样本):Long scopedCompanyId = dataReadScope.readCompanyId(user, companyId) "
+ "且它进了 service.page(…) 的实参 ⇒ 该判这一形绿,判红就是护栏假红(现网品牌库/商品类目都是这形)")
.isNull();
assertThat(scopeProbeReason(READ_COMPANY_ID_DISCARD_PROBE, "READ_COMPANY_ID_DISCARD_PROBE"))
.as("断言 C 自检(第二道门·负样本):readCompanyId( 写成裸语句、结果当场丢掉 ⇒ 必须判红")
.isNotNull()
.contains("范围算了但没接住");
// 断言 D 的判据自检(两个方向都要,全局约束 15)。负探针要先证明"A/B/C 三条对它都判通过"——
// 这三条前提不成立就说明这段源码本来已经有人看守,D 没有区分度、只是重复劳动。
@@ -422,12 +603,12 @@ class CompanyIdParamGoesThroughReadScopeTest {
assertThat(companyIdArgProbeReason(SCOPE_PASSED_NULL_PROBE, "SCOPE_PASSED_NULL_PROBE", CAMEL_PARAM))
.as("断言 D 自检(负样本):readScope(operator, null) —— 公司参数没进出口 ⇒ 必须判红")
.isNotNull()
.contains("没进任何 readScope/resolveScope 的实参列表");
.contains("没进任何 " + SCOPE_CALLEE_LABEL + " 的实参列表");
assertThat(companyIdArgProbeReason(SCOPE_ONLY_IF_DECOR_PROBE, "SCOPE_ONLY_IF_DECOR_PROBE", CAMEL_PARAM))
.as("断言 D 自检(负样本 2):companyId 只被 if 读了一次、进出口的是 null ⇒ 同样要红"
+ "(控制语句不算消费,与 C 同一把尺子)")
.isNotNull()
.contains("没进任何 readScope/resolveScope 的实参列表");
.contains("没进任何 " + SCOPE_CALLEE_LABEL + " 的实参列表");
assertThat(companyIdArgProbeReason(SCOPE_PASSED_THROUGH_HELPER_PROBE, "SCOPE_PASSED_THROUGH_HELPER_PROBE", CAMEL_PARAM))
.as("断言 D 自检(正样本):companyId 交给同文件私有 resolveScope(request, companyId) ⇒ 判据不许恒红")
.isNull();
@@ -435,6 +616,43 @@ class CompanyIdParamGoesThroughReadScopeTest {
.as("断言 D 自检(改名那一族):参数声明叫 orgId、交出去的也是 orgId ⇒ 不许红"
+ "(这条同时钉住\"D 不许硬编码 companyId\":写死了它就会在这一支假红)")
.isNull();
// 第二道门上的 D:先钉 A/B/C 三条前提对它同样全绿(换了道门不等于换了缺陷形状),再钉 D 必须红。
String typedNullProbeText = String.join("\n", textsOf(sourceLines(READ_COMPANY_ID_PASSED_NULL_PROBE)));
assertThat(typedNullProbeText)
.as("断言 D(第二道门)负样本的前提(断言 A/B):readCompanyId( 在 handler 体内、name = \"company_id\" 也在")
.contains(READ_COMPANY_ID_CALL)
.contains(EXPLICIT_PARAM_NAME);
assertThat(scopeProbeReason(READ_COMPANY_ID_PASSED_NULL_PROBE, "READ_COMPANY_ID_PASSED_NULL_PROBE"))
.as("断言 D(第二道门)负样本的前提(断言 C):结果接进 scopedCompanyId 又喂给了 service ⇒ C 判它绿")
.isNull();
assertThat(companyIdArgProbeReason(
READ_COMPANY_ID_PASSED_NULL_PROBE, "READ_COMPANY_ID_PASSED_NULL_PROBE", CAMEL_PARAM))
.as("断言 D 自检(第二道门·负样本):readCompanyId(user, null) —— 出口调了、门也认了,"
+ "tab 传下来的值仍没进出口 ⇒ 同样必须判红(D 不能只咬 readScope 那一族)")
.isNotNull()
.contains("没进任何 " + SCOPE_CALLEE_LABEL + " 的实参列表");
// 配对括号取实参表(放宽)的成对证据:两枚正样本必须绿(否则 6 支已接线 handler 假红),
// 一枚"嵌套了但没带公司参数"的样本必须照旧红(否则放宽 = 把 D 关掉)。
assertThat(scopeProbeReason(SCOPE_NESTED_ARG_PROBE, "SCOPE_NESTED_ARG_PROBE"))
.as("断言 C 自检(嵌套实参表·正样本):service.page(page, memberIds, operator.id()) —— "
+ "消费方实参表里另有一次方法调用时也必须认得下 memberIds,"
+ "判红即护栏假红(批次 2/3 实测 6 支 handler 全撞这一形)")
.isNull();
assertThat(companyIdArgProbeReason(SCOPE_NESTED_DOOR_ARG_PROBE, "SCOPE_NESTED_DOOR_ARG_PROBE", CAMEL_PARAM))
.as("断言 D 自检(嵌套实参表·正样本):readScope(operator, normalizeCompany(companyId)) —— "
+ "被绑定的名字嵌在一层调用里也算交出去了")
.isNull();
assertThat(scopeProbeReason(SCOPE_NESTED_DOOR_ARG_FOREIGN_PROBE, "SCOPE_NESTED_DOOR_ARG_FOREIGN_PROBE"))
.as("断言 D 负样本的前提:readScope(operator, operator.getCompanyId()) 三步全绿 —— "
+ "接住了、也喂给 service 了,所以这一刀今天只有 D 会喊")
.isNull();
assertThat(companyIdArgProbeReason(
SCOPE_NESTED_DOOR_ARG_FOREIGN_PROBE, "SCOPE_NESTED_DOOR_ARG_FOREIGN_PROBE", CAMEL_PARAM))
.as("断言 D 自检(放宽的边界):进出口的是 operator.getCompanyId(),嵌套层里并没有被绑定的"
+ "那个变量名 ⇒ 必须照旧红。这条不红,上面那条『嵌套也算』就等于把 D 关掉了")
.isNotNull()
.contains("没进任何 " + SCOPE_CALLEE_LABEL + " 的实参列表");
// 断言 C 的分母由本轮实扫得出(不写死数字):扫进射程的 handler 键、走完两步的正样本支数、红因先攒后判。
List<String> scopeCaughtSample = new ArrayList<>();
@@ -469,9 +687,10 @@ class CompanyIdParamGoesThroughReadScopeTest {
boolean takesCompanyParam = handler.takesCompanyParam();
// 断言 A:收了公司 id 参数的 handler 必须在该 handler 体内走唯一出口(handler 级豁免)。
if (takesCompanyParam && !READ_SCOPE_ALLOWLIST.contains(exemptionKey(rel, handler))) {
assertThat(handler.text())
.as(where + " 收了公司 id 参数,但该 handler 体内没有出现 readScope( —— 文件里别处接了不算")
.contains(READ_SCOPE_CALL);
assertThat(anyScopeDoor(handler.text()))
.as(where + " 收了公司 id 参数,但该 handler 体内没走过任一正门 —— "
+ "文件里别处接了不算(私有收口方法在这支 handler 的闭括号之外,不算在内)")
.isTrue();
}
// 断言 B:显式 name= 只咬 @RequestParam 那一族(F-C:getParameter("company_id") 的下划线
// 本来就在串里,那个形状永远给不出 name = "company_id",合规写法不该被逼着改写法才绿)。
@@ -482,7 +701,7 @@ class CompanyIdParamGoesThroughReadScopeTest {
}
// 断言 C(复评 I-1):体内写了 readScope( 只说明"算过",不说明"用出去了"。
// 白名单只免 A 不免 C——被豁免的那支哪天自己算了个范围又丢掉,一样得红。
if (takesCompanyParam && handler.text().contains(READ_SCOPE_CALL)) {
if (takesCompanyParam && anyScopeDoor(handler.text())) {
scopeCaughtSample.add(exemptionKey(rel, handler));
String dropped = handler.scopeCatchFailure();
if (dropped == null) {
@@ -530,23 +749,26 @@ class CompanyIdParamGoesThroughReadScopeTest {
+ " 支 handler,走完『接住变量 → 当实参传出去』两步的是 0 支 —— 判据恒红或形状不认,不可信")
.isPositive();
assertThat(scopeCaughtSample)
.as("断言 C 的射程必须覆盖 Task 8 已接线的两页(改名/换 mapping 会让它静默脱离射程,分母不能自造)")
.contains(SCOPE_CAUGHT_HISTORY_KEY, SCOPE_CAUGHT_VIDEO_KEY);
.as("断言 C 的射程必须覆盖已接线的那 " + WIRED_PAGE_KEYS.size()
+ " 页(改名/换 mapping/换参数形状会让它静默脱离射程,分母不能自造)")
.contains(WIRED_PAGE_KEYS.toArray(new String[0]));
assertThat(scopeDiscarded)
.as("范围算了但没接住(断言 C):readScope( 的结果要么没赋给变量,要么赋了却没交给任何方法调用")
.as("范围算了但没接住(断言 C):两条正门(readScope( / readCompanyId()的结果要么没赋给变量,"
+ "要么赋了却没交给任何方法调用")
.isEmpty();
// 断言 D 的取样自检与分母(与 C 同一族纪律):空样本 = D 空转,射程不含已接线的页 = 静默脱离。
assertThat(companyIdArgSample)
.as("断言 D 取样集非空自检:一支『用 @RequestParam 收了公司 id 参数、体内又调了 "
+ "readScope/resolveScope』的 handler 都没扫到 ⇒ D 一行都没评")
+ SCOPE_CALLEE_LABEL + "』的 handler 都没扫到 ⇒ D 一行都没评")
.isNotEmpty();
assertThat(companyIdArgSample)
.as("断言 D 的射程必须覆盖已接线的那两页(改名/换 mapping 会让它静默脱离射程,分母不能自造)")
.contains(SCOPE_CAUGHT_HISTORY_KEY, SCOPE_CAUGHT_VIDEO_KEY);
.as("断言 D 的射程必须覆盖已接线的那 " + WIRED_PAGE_KEYS.size()
+ " 页(改名/换 mapping/换参数形状会让它静默脱离射程,分母不能自造)")
.contains(WIRED_PAGE_KEYS.toArray(new String[0]));
assertThat(companyIdArgMissing)
.as("公司参数没被交给出口(断言 D):readScope/resolveScope 的实参列表里没有出现被绑定到 "
+ "company_id 的那个变量名 —— 参数收下、出口也调了,tab 却是死的")
.as("公司参数没被交给出口(断言 D):" + SCOPE_CALLEE_LABEL
+ " 的实参列表里没有出现被绑定到 company_id 的那个变量名 —— 参数收下、出口也调了,tab 却是死的")
.isEmpty();
}
@@ -587,9 +809,9 @@ class CompanyIdParamGoesThroughReadScopeTest {
assertThat(handler.takesCompanyParam())
.as(probeName + " 的 handler 没被认成收公司 id 参数,断言 C 根本不会触发 ⇒ 探针失效")
.isTrue();
assertThat(handler.text())
.as(probeName + " 的 handler 体内没有 readScope( ,断言 C 扫不到它 ⇒ 探针失效")
.contains(READ_SCOPE_CALL);
assertThat(anyScopeDoor(handler.text()))
.as(probeName + " 的 handler 体内两条正门都没走(readScope( / readCompanyId(),断言 C 扫不到它 ⇒ 探针失效")
.isTrue();
return handler.scopeCatchFailure();
}
@@ -674,6 +896,91 @@ class CompanyIdParamGoesThroughReadScopeTest {
return line.contains(SNAKE_PARAM) || line.contains(CAMEL_PARAM);
}
/** 两条正门之一有没有在这段文本里出现过(A/C 的判据都走它,不各写一份)。 */
private static boolean anyScopeDoor(String text) {
return SCOPE_DOORS.stream().anyMatch(text::contains);
}
/**
* 逐字符扫出所有 {@code 名字(实参表)}:实参表按<b>配对括号</b>取(深度计数到 0 为止),
* 字符串/字符字面量内的括号不计数。嵌套调用<b>也入表</b>(扫描指针停在 {@code (} 之后而不是
* 跳过整条调用),否则 {@code readScope(operator.user(), companyId)} 里那一层就取不到。
* 括号不配平(切块把一条语句截断了)时,这条调用记到文末为止——宁可多算一次消费,
* 也不让"取不到实参表"变成静默放过;真正的截断形状由结构守卫负责。
*/
private static List<Call> callsOf(String src) {
List<Call> calls = new ArrayList<>();
int i = 0;
while (i < src.length()) {
char c = src.charAt(i);
if (c == '"' || c == '\'') {
i = skipLiteral(src, i, c);
continue;
}
boolean identifierStart = Character.isJavaIdentifierStart(c);
if (!identifierStart) {
i++;
continue;
}
int from = i;
while (i < src.length() && Character.isJavaIdentifierPart(src.charAt(i))) {
i++;
}
int open = i;
while (open < src.length() && Character.isWhitespace(src.charAt(open))) {
open++;
}
if (open >= src.length() || src.charAt(open) != '(') {
continue;
}
int close = matchingClose(src, open);
calls.add(new Call(src.substring(from, i), src.substring(open + 1, close)));
// 不跳到 close:嵌套调用也要被扫到
i = open + 1;
}
return calls;
}
/** 从 {@code quote} 处跳过一段字面量,返回其后的下标(处理 {@code \\} 转义,未闭合则到文末)。 */
private static int skipLiteral(String src, int quote, char marker) {
int i = quote + 1;
while (i < src.length()) {
char c = src.charAt(i);
if (c == '\\') {
i += 2;
continue;
}
if (c == marker) {
return i + 1;
}
i++;
}
return i;
}
/** {@code open} 处的 {@code (} 对应的 {@code )} 下标;取不到(不配平)返回文末。 */
private static int matchingClose(String src, int open) {
int depth = 0;
int i = open;
while (i < src.length()) {
char c = src.charAt(i);
if (c == '"' || c == '\'') {
i = skipLiteral(src, i, c);
continue;
}
if (c == '(') {
depth++;
} else if (c == ')') {
depth--;
if (depth == 0) {
return i;
}
}
i++;
}
return src.length();
}
private static boolean isMappingLine(String line) {
return MAPPING_ANNOTATIONS.stream().anyMatch(line::startsWith);
}
@@ -908,20 +1215,32 @@ class CompanyIdParamGoesThroughReadScopeTest {
*/
String scopeCatchFailure() {
String src = text();
for (int at = src.indexOf(READ_SCOPE_CALL); at >= 0;
at = src.indexOf(READ_SCOPE_CALL, at + READ_SCOPE_CALL.length())) {
for (String door : SCOPE_DOORS) {
String reason = scopeCatchFailureFor(src, door);
if (reason != null) {
return reason;
}
}
return null;
}
/** 逐条正门跑"接住 → 交出去"两步:两条门都得走这两步,第二道门不能成为绕过第一道门判据的后门。 */
private static String scopeCatchFailureFor(String src, String door) {
for (int at = src.indexOf(door); at >= 0;
at = src.indexOf(door, at + door.length())) {
// 语句边界:往前取最近的 ';' 或 '{'(方法体开行),往后取第一个 ';'。
int stmtStart = Math.max(src.lastIndexOf(SEMICOLON, at), src.lastIndexOf(WINDOW_OPEN, at)) + 1;
int stmtEnd = src.indexOf(SEMICOLON, at);
String statement = stmtEnd < 0 ? src.substring(stmtStart) : src.substring(stmtStart, stmtEnd + 1);
String target = assignedTo(statement, at - stmtStart);
if (target == null) {
return " 的 readScope( 是条裸语句:算完了没赋给任何变量,范围算了但没接住"
+ "(要写成 List<Long> scoped = dataReadScope.readScope(…)…; 再把 scoped 交出去)";
return " 的 " + door + " 是条裸语句:算完了没赋给任何变量,范围算了但没接住"
+ "(要写成 List<Long> scoped = dataReadScope." + door.replace("(", "")
+ "(…)…; 再把 scoped 交出去)";
}
String rest = src.substring(0, stmtStart) + (stmtEnd < 0 ? "" : src.substring(stmtEnd + 1));
if (!passedAsArgument(rest, target)) {
return " 的 readScope( 结果赋给了 `" + target + "`,但 handler 体内没有任何方法调用的"
return " 的 " + door + " 结果赋给了 `" + target + "`,但 handler 体内没有任何方法调用的"
+ "实参列表用到 `" + target + "`:范围接住了却没交出去(把 service 那层的实参改成 "
+ "null 就是这个形状)";
}
@@ -940,15 +1259,14 @@ class CompanyIdParamGoesThroughReadScopeTest {
return target;
}
/** {@code id} 有没有落在某个 {@code 名字(…)} 的实参列表里;控制语句关键字读它不算"交出去"。 */
/** {@code id} 有没有落在某个 {@code 名字(…)} 的实参表里;控制语句关键字读它不算"交出去"。 */
private static boolean passedAsArgument(String src, String id) {
Matcher call = CALL_ARGUMENTS.matcher(src);
Pattern use = Pattern.compile("(?<!\\w)" + Pattern.quote(id) + "(?!\\w)");
while (call.find()) {
if (NOT_VALUE_CONSUMERS.contains(call.group(1))) {
for (Call call : callsOf(src)) {
if (NOT_VALUE_CONSUMERS.contains(call.callee())) {
continue;
}
if (use.matcher(call.group(2)).find()) {
if (use.matcher(call.arguments()).find()) {
return true;
}
}
@@ -961,7 +1279,7 @@ class CompanyIdParamGoesThroughReadScopeTest {
*/
boolean hasScopeCall() {
String src = text();
return src.contains(READ_SCOPE_CALL) || src.contains(RESOLVE_SCOPE_CALL);
return anyScopeDoor(src) || src.contains(RESOLVE_SCOPE_CALL);
}
/**
@@ -1005,16 +1323,19 @@ class CompanyIdParamGoesThroughReadScopeTest {
/**
* 断言 D:被绑定到 {@code company_id} 的那个变量名,必须作为<b>整词实参</b>出现在这一支 handler
* 体内某一次 {@code readScope}/{@code resolveScope} 调用的参数表里(单层括号,复用
* {@link #CALL_ARGUMENTS} 的形状,与 A/B/C 同一个 handler 窗口)。
* 体内某一次 {@link #SCOPE_CALLEE_LABEL} 调用的参数表里(实参表由 {@link #callsOf} 按配对括号取,
* 与 A/B/C 同一个 handler 窗口)。
* <ul>
* <li>{@code dataReadScope.readScope(operator, companyId)} ⇒ 绿;</li>
* <li>{@code dataReadScope.readCompanyId(user, companyId)}(第二条正门)⇒ 绿;</li>
* <li>{@code resolveScope(request, companyId)}(私有收口方法内部再去 readScope)⇒ 绿;</li>
* <li>{@code readScope(operator, normalizeCompany(companyId))} ⇒ <b>绿</b>:嵌套写法自 10-05
* 批次 2/3 起算消费(第 13 条:旧单层正则在这一形上判红,而那正是断言 A 逼出来的形状),
* 探针 {@link #SCOPE_NESTED_DOOR_ARG_PROBE};</li>
* <li>{@code dataReadScope.readScope(operator, null)} ⇒ <b>红</b>;</li>
* <li>{@code readScope(operator, operator.getCompanyId())} ⇒ <b>红</b>:源里那个名字是
* {@code CompanyId}(大写 C,整词判据大小写敏感,咬不住它);而 {@link #CALL_ARGUMENTS}
* 只吃单层括号,看不穿 {@code readScope(operator, normalize(companyId))} 这种嵌套写法 ——
* 两种都落在"没进参数表"那一侧(后者是会误伤合规写法的已知形状,见类注释第 11 条与本轮报告);</li>
* {@code CompanyId}(大写 C,整词判据大小写敏感,咬不住它),嵌套层里也确实没有
* {@code companyId} ⇒ 探针 {@link #SCOPE_NESTED_DOOR_ARG_FOREIGN_PROBE},"放宽"的边界由它钉住;</li>
* <li>只在 {@code if (companyId != null)} 里读一次、或只在 {@code @Operation} 文案里提一句
* ⇒ <b>红</b>:控制语句关键字沿用 {@link #NOT_VALUE_CONSUMERS} 那把尺子(与 C 同源,不放宽),
* 而注释与文档行根本进不到 {@link #text()} 里。</li>
@@ -1028,19 +1349,18 @@ class CompanyIdParamGoesThroughReadScopeTest {
+ "Long 变量名 那一形),这支的公司参数是怎么进出口的无从判定 —— 必须人工核对,"
+ "不许当作\"这支没收公司参数\"静默放过";
}
Matcher call = CALL_ARGUMENTS.matcher(text());
Pattern use = Pattern.compile("(?<!\\w)" + Pattern.quote(bound) + "(?!\\w)");
while (call.find()) {
String callee = call.group(1);
// 与 C 同一条纪律:控制语句读它一次不算"把值交给谁";D 只认出口那两个被调名。
for (Call call : callsOf(text())) {
String callee = call.callee();
// 与 C 同一条纪律:控制语句读它一次不算"把值交给谁";D 只认出口那几个被调名。
if (NOT_VALUE_CONSUMERS.contains(callee) || !SCOPE_CALLEES.contains(callee)) {
continue;
}
if (use.matcher(call.group(2)).find()) {
if (use.matcher(call.arguments()).find()) {
return null;
}
}
return " 的公司参数 `" + bound + "` 没进任何 readScope/resolveScope 的实参列表"
return " 的公司参数 `" + bound + "` 没进任何 " + SCOPE_CALLEE_LABEL + " 的实参列表"
+ "(`readScope(operator, null)`、`readScope(operator, operator.getCompanyId())` 就是这个形状:"
+ "参数收下了、出口也调了、算出来的范围也交出去了,唯独 tab 传下来的那个值被换成了别的来源"
+ " ⇒ 接口 200、页面正常、切 tab 数字永远不动,而 A/B/C 三条全绿没人喊)";
@@ -116,4 +116,33 @@ class DataReadScopeTest {
() -> dataReadScope.readScope(user(5L, "admin", null), null))
.isInstanceOf(com.nanri.aiimage.common.exception.BusinessException.class);
}
// ---- 第二条正门:归属已物化成 company_id 列的表(品牌库、商品类目)----
// 这一道门的语义与 readScope 相反方向:返回的是"要筛哪个公司",null = 不筛。
// 非超管一律 null(他们的可见集本来就锁在自己的分组上,再叠一层公司会把"靠分组可见"的行整批删掉,
// 见 DataReadScope#readCompanyId 的注释)。这三条若不写,把 `return null` 改成
// `return companyScope.requireCompanyId(operator)` 不会让任何现有用例变红——而那一改的后果是
// 品牌库里靠分组可见的历史行从每个非超管账号下消失。
@Test
@DisplayName("第二道门:超管选公司 = 原样给回那一列的筛值")
void readCompanyIdForSuperAdminReturnsTheTab() {
assertThat(dataReadScope.readCompanyId(user(1L, "super_admin", 1L), 2L)).isEqualTo(2L);
}
@Test
@DisplayName("第二道门:超管不选 / 选 0 / 选负数都归一化成「不筛」,不是去查 0 号公司")
void readCompanyIdForSuperAdminNormalisesMissingAndNonPositive() {
assertThat(dataReadScope.readCompanyId(user(1L, "super_admin", 1L), null)).isNull();
assertThat(dataReadScope.readCompanyId(user(1L, "super_admin", 1L), 0L)).isNull();
assertThat(dataReadScope.readCompanyId(user(1L, "super_admin", 1L), -3L)).isNull();
}
@Test
@DisplayName("第二道门:非超管一律 null,别家的 tab 也不炸、也不筛")
void readCompanyIdForNonSuperAdminAlwaysMeansNoFilter() {
assertThat(dataReadScope.readCompanyId(user(5L, "admin", 2L), 2L)).isNull();
assertThat(dataReadScope.readCompanyId(user(5L, "admin", 2L), 7L)).isNull();
assertThat(dataReadScope.readCompanyId(user(5L, "admin", 2L), null)).isNull();
}
}
@@ -0,0 +1,185 @@
package com.nanri.aiimage.common.util;
import com.alibaba.excel.EasyExcel;
import com.nanri.aiimage.common.exception.BusinessException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* ExcelStreamReader 的异常出口契约(现网缺陷:带单元格图片的 xlsx 解析失败时
* POI 的 ExcelAnalysisException 原样冒到 GlobalExceptionHandler,用户拿到 HTTP 500 且看不到真因)。
*/
class ExcelStreamReaderParseFailureTest {
@TempDir
Path tempDir;
/** 生产现场形状:xlsx 包里有一个未声明 content type 的 media 部件。 */
@Test
void parseFailureOnMalformedPackageSurfacesAsIoExceptionWithReason() throws Exception {
Path bad = tempDir.resolve("cellimage-no-content-type.xlsx");
Files.write(bad, packageWithUndeclaredMediaPart());
IOException thrown = assertThrows(IOException.class,
() -> ExcelStreamReader.readFirstSheet(bad.toFile(), noopHandler()));
String reason = rawParseFailureMessageOf(bad);
assertTrue(thrown.getMessage().contains(reason),
"消息里要能看到底层真因 [" + reason + "],实际=" + thrown.getMessage());
}
/** 反向钉:读全部 sheet 的入口同样收口(另有 6 个调用点走这条)。 */
@Test
void parseFailureOnReadAllSheetsAlsoSurfacesAsIoException() throws Exception {
Path bad = tempDir.resolve("cellimage-no-content-type-all.xlsx");
Files.write(bad, packageWithUndeclaredMediaPart());
assertThrows(IOException.class, () -> ExcelStreamReader.readAllSheets(bad.toFile(), noopHandler()));
}
/** 反向钉:调用方在 onRow 里抛的业务异常不能被改写成 IOException,否则 400 语义会塌成"文件坏了"。 */
@Test
void handlerBusinessExceptionIsNotRewrittenIntoIoException() throws Exception {
Path good = writeWorkbook();
BusinessException thrown = assertThrows(BusinessException.class, () -> ExcelStreamReader
.readFirstSheet(good.toFile(), rowHandlerThatThrows(
new BusinessException("品牌列缺失,请检查表头"))));
assertEquals("品牌列缺失,请检查表头", thrown.getMessage());
}
/** 调用方抛的运行时异常原样透传,不借"解析失败"这条路被包成 IOException。 */
@Test
void handlerRuntimeExceptionPropagatesUnchanged() throws Exception {
Path good = writeWorkbook();
IllegalStateException failure = new IllegalStateException("行处理失败");
IllegalStateException thrown = assertThrows(IllegalStateException.class,
() -> ExcelStreamReader.readFirstSheet(good.toFile(), rowHandlerThatThrows(failure)));
assertSame(failure, thrown);
}
/** 调用方抛的受检异常走 IOException 契约,且不把内部包装类漏给调用方。 */
@Test
void handlerCheckedExceptionSurfacesAsIoExceptionWithReason() throws Exception {
Path good = writeWorkbook();
IOException thrown = assertThrows(IOException.class, () -> ExcelStreamReader.readFirstSheet(
good.toFile(), rowHandlerThatThrows(new Exception("行数据超出上限 5000"))));
assertTrue(thrown.getMessage().contains("行数据超出上限 5000"),
"消息里要能看到调用方抛出的真因,实际=" + thrown.getMessage());
}
/** 好文件照旧能读完(保证收口没有把正常路径一起改掉)。 */
@Test
void validWorkbookStillReadsRows() throws Exception {
Path good = writeWorkbook();
StringBuilder seen = new StringBuilder();
assertDoesNotThrow(() -> ExcelStreamReader.readFirstSheet(
good.toFile(), (sheetName, sheetNo, rowIndex, headerMap, rowMap) ->
seen.append(rowMap.get(0))));
assertEquals("Nike", seen.toString());
}
private Path writeWorkbook() {
Path file = tempDir.resolve("ok.xlsx");
List<List<String>> head = List.of(List.of("品牌"), List.of("ASIN"));
List<List<String>> data = List.of(List.of("Nike", "B01ABC"));
EasyExcel.write(file.toFile()).head(head).sheet("Sheet1").doWrite(data);
return file;
}
private ExcelStreamReader.SheetRowHandler noopHandler() {
return new ExcelStreamReader.SheetRowHandler() {
@Override
public void onRow(String sheetName, Integer sheetNo, int rowIndex,
Map<Integer, String> headerMap, Map<Integer, String> rowMap) {
}
};
}
private ExcelStreamReader.SheetRowHandler rowHandlerThatThrows(Exception failure) {
return new ExcelStreamReader.SheetRowHandler() {
@Override
public void onRow(String sheetName, Integer sheetNo, int rowIndex,
Map<Integer, String> headerMap, Map<Integer, String> rowMap) throws Exception {
throw failure;
}
};
}
/** 直接喂同一个坏包,取 POI 自己报出来的真因文本,用来断言它没被收口吞掉。 */
private String rawParseFailureMessageOf(Path badFile) throws IOException {
String message = null;
try (var input = Files.newInputStream(badFile)) {
EasyExcel.read(input).sheet(0).headRowNumber(1).doRead();
throw new AssertionError("构造的坏包必须让 EasyExcel 抛异常,否则这条用例证明不了收口");
} catch (RuntimeException ex) {
Throwable deepest = ex;
while (deepest.getCause() != null) {
deepest = deepest.getCause();
}
message = deepest.getMessage();
}
assertTrue(message != null && message.length() > 20,
"底层真因文本应当有信息量,实际=" + message);
return message;
}
private byte[] packageWithUndeclaredMediaPart() throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(bytes, StandardCharsets.UTF_8)) {
put(zip, "[Content_Types].xml", """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Default Extension="xml" ContentType="application/xml"/>
<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>
</Types>""");
put(zip, "_rels/.rels", """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>
</Relationships>""");
put(zip, "xl/workbook.xml", """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheets><sheet name="Sheet1" sheetId="1" r:id="rId1"/></sheets>
</workbook>""");
put(zip, "xl/_rels/workbook.xml.rels", """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/cellImages" Target="cellimages.xml"/>
</Relationships>""");
put(zip, "xl/cellimages.xml", """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cellImages xmlns="http://www.wps.cn/officeDocument/2020/cellImage"/>""");
zip.putNextEntry(new ZipEntry("xl/media/cellimage1.jpeg"));
zip.write(new byte[]{(byte) 0xFF, (byte) 0xD8, (byte) 0xFF, (byte) 0xD9});
zip.closeEntry();
}
return bytes.toByteArray();
}
private void put(ZipOutputStream zip, String name, String content) throws IOException {
zip.putNextEntry(new ZipEntry(name));
zip.write(content.getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
}
@@ -346,7 +346,8 @@ class CompanyScopeMigrationV145Test {
Path doc = ROOT.resolve("docs/migration-inventory.md");
String text = raw(doc);
assertTrue(text.contains(migration().getFileName().toString()), "盘点文档应记录 V145 文件名");
assertTrue(text.contains("V146"), "盘点文档应把取号起点推到 V146");
// 取号起点不在这里钉:原先写死 contains("V146"),而 V146 真落地后它只因文档里还留着
// 那个文件名而巧合为真。派生尺子=MigrationInventoryTest#inventoryDocNumberingStartIsMaxPlusOne。
assertTrue(text.contains("1833593804"), "盘点文档应记下 V144 的生产存量校验和");
assertTrue(text.contains("1539570901"), "盘点文档应保留 V143 的生产存量校验和");
}
@@ -142,6 +142,35 @@ class MigrationInventoryTest {
}
}
/**
* 盘点文档的「起取号」必须是目录当前最大值 + 1 —— 派生式,不写死数字。
*
* <p>破坏点两条:加了 V148 却没改文档 ⇒ 后来人照文档取号撞上刚落地的 V148(改已应用版本=两台都起不来);
* 文档把号位改超前 ⇒ 1..max 留洞,{@link #integerVersionsSequentialFromOne} 会红。
* 各迁移自己的审计类原先把「起点推到 V14x」写死在 assertTrue 里,那种断言在 V14x 真落地那天就
* 只因文档里还留着同名文件而恒为真(基线自己过期)。尺子挪到这里、只对「本轮目录」求值,
* 才不需要每加一版都有人记得回来改一个数字。</p>
*/
@Test
void inventoryDocNumberingStartIsMaxPlusOne() throws IOException {
String text = Files.readString(Path.of(System.getProperty("user.dir"), "docs/migration-inventory.md"));
String marker = "从 **V";
int hits = 0, cursor = -1;
while ((cursor = text.indexOf(marker, cursor + 1)) >= 0) hits++;
assertEquals(1, hits, "「从 **V<号>** 起取号」应只有一条可解析的取号规则," + hits + " 条=后来人不知道按哪条取号");
int digitsFrom = text.indexOf(marker) + marker.length();
int digitsTo = digitsFrom;
while (digitsTo < text.length() && Character.isDigit(text.charAt(digitsTo))) digitsTo++;
assertTrue(digitsTo > digitsFrom, "取号规则里 V 之后必须是数字(解析不出=本用例恒绿)");
int stated = Integer.parseInt(text.substring(digitsFrom, digitsTo));
int maxMajor = parseAll(versionFiles()).stream().filter(Migration::isInteger)
.mapToInt(Migration::major).max().orElse(0);
assertEquals(maxMajor + 1, stated,
"取号起点应是目录最大值 V" + maxMajor + " 的下一号,实际文档写 V" + stated);
}
@Test
void checksumStableAcrossReads() throws IOException {
Map<String, String> first = sha256All(versionFiles());
@@ -0,0 +1,285 @@
package com.nanri.aiimage.config;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* V147({@code biz_product_category} 加 company_id + 唯一键按公司放宽)的文件审计。
* 需求:2026-10-05 控制方点名「商品类目切换 tab 数据显示还一样」;设计见迁移文件头 §1–§6。
*
* <p>为什么必须单独有一支:V143/V144/V145/V146 每版都有自己的审计类,而 V147 落盘后
* 只有消费侧的两支 service/controller 用例——迁移文件本身(加列形状、哨兵回填、换键顺序、
* 可重跑守卫、回滚补丁、盘点文档取号起点)在 3788 例里一处都没被钉。也就是说
* 「把 ADD COLUMN 改成可空」「把 DROP INDEX 排到 ADD UNIQUE KEY 前面」「把哨兵改成 -1」
* 都能全绿进 jar,而这三条里前两条是运行期静默错、第三条是让第 2 家看不见 18 个内置类目。</p>
*
* <p>本仓 pom 无 H2、无 testcontainers,迁移跑不起来,所以文件审计是唯一能守住的层,
* 与 {@link CompanyScopeMigrationV145Test} 同口径:断言打在剥掉注释后的可执行 SQL 上,
* {@code stripComments}/{@code normalize} 逐字沿用那一份实现(注释里的 {@code --} 与字符串字面量里的
* {@code --} 是两件事,另写一版简化实现会让断言打在残缺 SQL 上)。</p>
*/
class ProductCategoryMigrationV147Test {
private static final Path ROOT = Path.of(System.getProperty("user.dir"));
private static final Path DB_DIR = ROOT.resolve("src/main/resources/db");
private static final String TABLE = "biz_product_category";
private static final String NEW_KEY = "uk_company_category_key";
private static final String OLD_KEY = "uk_product_category_key";
// ---------------------------------------------------------------- 取文件
private static List<Path> versionFiles() throws IOException {
try (Stream<Path> s = Files.list(DB_DIR)) {
return s.filter(p -> p.getFileName().toString().matches("^V\\d+(?:_\\d+)?__.*\\.sql$"))
.sorted()
.toList();
}
}
private static Path migration() throws IOException {
List<Path> hits = versionFiles().stream()
.filter(p -> p.getFileName().toString().startsWith("V147__"))
.toList();
assertEquals(1, hits.size(),
"V147 必须恰好一个迁移文件,实际 " + hits.size() + " 个(0 个=类目还没落公司口径;2 个=撞号,Flyway 启动即失败)");
return hits.get(0);
}
private static String raw(Path file) throws IOException {
return Files.readString(file, StandardCharsets.UTF_8);
}
private static String statements() throws IOException {
return normalize(stripComments(raw(migration())));
}
// ------------------------------------------------------------ SQL 预处理
// 与 CompanyScopeMigrationV145Test / CompanyMigrationV144Test 逐字同实现,理由见类注释。
private static String stripComments(String sql) {
StringBuilder out = new StringBuilder(sql.length());
int i = 0;
while (i < sql.length()) {
char c = sql.charAt(i);
if (c == '\'') {
int end = i + 1;
while (end < sql.length()) {
if (sql.charAt(end) == '\'') {
if (end + 1 < sql.length() && sql.charAt(end + 1) == '\'') {
end += 2;
continue;
}
break;
}
end++;
}
out.append(sql, i, Math.min(end + 1, sql.length()));
i = end + 1;
continue;
}
if (c == '-' && i + 1 < sql.length() && sql.charAt(i + 1) == '-') {
while (i < sql.length() && sql.charAt(i) != '\n') {
i++;
}
continue;
}
if (c == '/' && i + 1 < sql.length() && sql.charAt(i + 1) == '*') {
int end = sql.indexOf("*/", i + 2);
i = end < 0 ? sql.length() : end + 2;
continue;
}
out.append(c);
i++;
}
return out.toString();
}
private static String normalize(String sql) {
return sql.replaceAll("\\s+", " ").trim();
}
// ------------------------------------------------------------------ 用例
/** 破坏点:取到已应用的 146(原地改=两台都起不来),或把这一版编成 V148(V147 就被跳开,类目列永远不加)。 */
@Test
void migrationIsVersionedOneFourSeven() throws IOException {
Path file = migration();
Matcher m = Pattern.compile("^V(\\d+)(?:_\\d+)?__").matcher(file.getFileName().toString());
assertTrue(m.find(), "文件名应能抽出整数版本:" + file.getFileName());
assertEquals(147, Integer.parseInt(m.group(1)), "本迁移必须是 V147(V146 之后的下一号)");
assertTrue(file.getFileName().toString().matches("^V147__[A-Za-z0-9_.-]+\\.sql$"),
"命名应 V147__<snake 描述>.sql:" + file.getFileName());
}
/**
* 破坏点:把列加成可空 ⇒ 混合版本窗口里旧 jar 写进来的类目行 company_id 为 NULL,
* 而 {@code readCompanyId} 返回 null 的分支是「不裁剪」,这些行会同时出现在每一家的树上;
* 把 {@code MODIFY COLUMN} 写进来 ⇒ 重建表并按"当时的列默认值"物化历史行(§6 明令禁止)。
* DEFAULT 1 必须**在场**:它是同批旧 jar 唯一能插进这张表的通道,摘它的是下一版而不是这一版。
*/
@Test
void addsANotNullCompanyColumnWithInstantAndNeverModify() throws IOException {
String sql = statements();
assertTrue(sql.contains("ALTER TABLE `" + TABLE + "` ADD COLUMN `company_id` bigint NOT NULL DEFAULT 1"),
TABLE + " 应一次到位加成 NOT NULL DEFAULT 1(DEFAULT 只为同批旧 jar 存在,摘除是下一版)");
assertTrue(sql.contains("ALGORITHM = INSTANT"),
"加列必须钉 INSTANT:前提不成立时 MySQL 直接报 1846,而不是悄悄退化成 COPY(§4)");
assertFalse(sql.contains("MODIFY COLUMN"), "禁 MODIFY COLUMN——它会重建表并按当时的默认值物化历史行(§6)");
assertFalse(sql.contains("ALTER TABLE `" + TABLE + "` DROP COLUMN"),
"本版本不删列:归属信息一旦删掉就无法再分清是第几家公司建的(§2)");
}
/**
* 破坏点 ①:删掉那条 UPDATE ⇒ 18 行内置节点留在公司 1,第 2 家的类目树只剩自己自建的 0 行,
* 「切 tab 这一页空白」就是这么来的。破坏点 ②:哨兵值写成 1 或 -1 ⇒ 要么和真实公司 1 混在一起
* (第 1 家的自建类目被当成平台内置、别家也能改),要么被 {@code requireCompanyId} 的 <=0 判定挡在门外。
* 破坏点 ③:这张表除这一条 UPDATE 外不该有任何别的 DML——没有账号列,任何"按人回填"都是编数据。
*/
@Test
void builtinRowsGoToSentinelZeroAndThatIsTheOnlyDml() throws IOException {
String sql = statements();
Pattern dml = Pattern.compile("\\b(UPDATE|INSERT|DELETE|REPLACE)\\b", Pattern.CASE_INSENSITIVE);
Matcher d = dml.matcher(sql);
int hits = 0;
while (d.find()) {
hits++;
}
assertEquals(1, hits, TABLE + " 的可执行段应当只有那一条回填 UPDATE,实际命中 " + hits + " 条 DML 关键字");
assertTrue(sql.contains("SET `company_id` = 0"), "内置节点应挂哨兵公司 0");
assertTrue(sql.contains("WHERE `is_builtin` = 1"),
"驱动条件必须是 is_builtin 而不是 category_key 白名单:V50 的种子后来被删过(种子 24 行、今天 18 行)");
assertTrue(sql.contains("AND `company_id` = 1"),
"回填必须自带 company_id = 1 限定 ⇒ DDL 段失败后 repair 重跑时这条是 no-op(§可重跑性)");
}
/**
* 破坏点:把 DROP 旧键排到 ADD 新键之前 ⇒ 中间那一刻这张表没有任何唯一键在守并发,
* 两个账号同时建同名类目就会落两行;把新键的第二列换掉或把 company_id 挪到第二位 ⇒
* {@code WHERE company_id IN (0, ?)} 走不到这个键,而 §4 明写「不加单独的列索引」,
* 于是这一页的每次列表查询都退化成扫描。
*/
@Test
void swapsTheUniqueKeyCompanyFirstAndAddsBeforeDropping() throws IOException {
String sql = statements();
int add = sql.indexOf("ADD UNIQUE KEY `" + NEW_KEY + "` (`company_id`, `category_key`)");
int drop = sql.indexOf("DROP INDEX `" + OLD_KEY + "`");
assertTrue(add >= 0, "新唯一键应是 (company_id, category_key) 这个顺序,实际串:" + sql.substring(0, Math.min(sql.length(), 400)));
assertTrue(drop >= 0, "旧的全平台唯一键 " + OLD_KEY + " 必须被删掉,否则第 2 家在同一个父级下重名建类会撞 1062");
assertTrue(add < drop, "换键顺序必须先 ADD 后 DROP:中间任一步失败都至少还有一个唯一键在守并发");
assertEquals(2, count(sql, "ALGORITHM = INPLACE, LOCK = NONE"),
"两条索引操作各钉一次 INPLACE + LOCK = NONE(§4:这张表 412 行,但仍不许默默锁表)");
assertFalse(sql.contains("ADD INDEX") || sql.contains("ADD KEY"),
"不该再单开列索引:新唯一键的最左前缀就是 company_id,再开一个就是 V139 那轮清掉的冗余形状");
}
/**
* 破坏点:把两条 DDL 的存在性守卫删掉 ⇒ DDL 不进事务,中途失败后 repair 重跑会撞
* 1060(重复列)/1061(重复键)而彻底起不来,只能人工进库删。
* 计数取 3 而不是「大于 0」:本文件的可执行段恰好查三次 information_schema
* (一次列、两次索引),少一次就是一处守卫没了。
*/
@Test
void bothDdlStatementsAreGuardedByExistenceChecks() throws IOException {
String sql = statements();
assertEquals(3, count(sql, "information_schema"),
"可执行段应查 3 次 information_schema(列存在 + 新键存在 + 旧键存在),实际次数见消息");
assertTrue(sql.contains("COLUMN_NAME = 'company_id'"), "加列的守卫要按列名查");
assertTrue(sql.contains("INDEX_NAME = '" + NEW_KEY + "'"), "加新键的守卫要按新键名查");
assertTrue(sql.contains("INDEX_NAME = '" + OLD_KEY + "'"), "删旧键的守卫要按旧键名查");
assertTrue(count(sql, "PREPARE stmt FROM @sql") == 3 && count(sql, "EXECUTE stmt") == 3,
"三段条件 DDL 都必须走 PREPARE/EXECUTE(MySQL 不能在 IF 里直接写 DDL)");
}
/**
* 破坏点:回滚脚本没跟着写 ⇒ 出问题只能手工现编 SQL,而"漏删 flyway_schema_history 的 147 行"
* 这一手会让重装带 V147 的 jar 时 Flyway 判定已应用直接跳过——列和键都不重建,
* 而 Java 侧实体照常读写 company_id,运行期报 Unknown column。
*
* <p>与 V145 那份同形:{@code DROP COLUMN} 必须留在注释里由人工解开(这张表没有账号列,
* 删了就再也分不出哪一家),而"回滚不得版本化"由 {@link CompanyScopeMigrationV145Test
* #rollbackStaysOutOfFlywayScanAndCoversTheHistoryRow} 那支按全目录扫,本类不重复实现,
* 只在下面那支按文件名把本迁移钉进盘点文档(号位起点由 {@link MigrationInventoryTest
* #inventoryDocNumberingStartIsMaxPlusOne} 派生式盯着)。</p>
*/
@Test
void rollbackIsAHumanPatchOutsideTheFlywayScanPath() throws IOException {
Path doc = ROOT.resolve("docs/rollback-V147-product-category-company.sql");
assertTrue(Files.isRegularFile(doc), "V147 的人工回滚补丁必须存在:" + doc);
String whole = raw(doc);
assertTrue(whole.contains("flyway_schema_history"), "回滚必须写明删 version='147' 的历史行");
String executable = normalize(stripComments(whole));
assertTrue(executable.contains("ADD UNIQUE KEY `" + OLD_KEY + "` (`category_key`)"),
"回滚要把全平台唯一键加回来(新键是旧键的严格放宽,回填那一刻必然不撞)");
assertTrue(executable.contains("DROP INDEX `" + NEW_KEY + "`"), "回滚要摘掉按公司的新唯一键");
assertTrue(executable.indexOf("ADD UNIQUE KEY") < executable.indexOf("DROP INDEX"),
"回滚也必须先加旧键后删新键,理由与迁移同一半:中间时刻不许没有唯一键");
assertFalse(executable.contains("DROP COLUMN"),
"DROP COLUMN 是丢归属信息的动作,必须留在注释里由人工解开");
assertFalse(executable.contains("MODIFY COLUMN"), "同上:任何时候不要写 MODIFY COLUMN");
}
/**
* 破坏点:V147 的 DEFAULT 1 没进启动期哨兵清单 ⇒ "下一次记得摘"这件事没人喊,
* 而巡检按 {@code COMPANY_DEFAULT_STILL_PRESENT} 这条 ASCII 签名 grep docker logs。
*/
@Test
void startupSentinelWatchesTheProductCategoryColumn() throws IOException {
Path guard = ROOT.resolve("src/main/java/com/nanri/aiimage/modules/company/service/CompanyDefaultGuard.java");
assertTrue(Files.isRegularFile(guard), "启动期 DEFAULT 哨兵应存在:" + guard);
String text = raw(guard);
assertTrue(text.contains("COMPANY_DEFAULT_STILL_PRESENT"), "哨兵标记串必须保持 ASCII 原样(巡检按它 grep)");
assertTrue(text.contains("'" + TABLE + "'"),
"探针 SQL 的 IN 列表要含 " + TABLE + "(不在 IN 里就查不到这一列,哨兵等于没探)");
assertTrue(text.contains("\"" + TABLE + "\""),
"WATCHED_TABLES 清单要含 " + TABLE + "(查到了却不在清单里,就没人去喊那条签名)");
}
/**
* 破坏点:盘点文档没跟着改 ⇒ 下一个人按"取号起点"取号就撞号,或者按"最新版本"漏掉本文件。
* 这里把 V145/V146/V147 三个文件名同时钉住:只钉最新一条会重演
* 「推进第 11 行时把 V145 挤掉」那一次回归(本轮真实发生过)。
* 号位起点不写在这里——写死 "V148" 到 V148 落地那天就自己过期,改由
* {@link MigrationInventoryTest#inventoryDocNumberingStartIsMaxPlusOne} 按「本轮目录最大值 + 1」求值。
*/
@Test
void inventoryDocTracksV147AndTheEarlierFilenamesTogether() throws IOException {
Path doc = ROOT.resolve("docs/migration-inventory.md");
String text = raw(doc);
for (String keep : List.of("V145__brand_dedupe_company_scope.sql",
"V146__users_expires_at_admin_expiry.sql",
migration().getFileName().toString())) {
assertTrue(text.contains(keep), "盘点文档应逐字保留文件名:" + keep);
}
assertTrue(text.contains("1833593804"), "盘点文档应记下 V144 的生产存量校验和");
}
/** 自检:本用例集扫的是真文件,且 normalize 后仍能命中关键串(0 命中的断言是恒绿的)。 */
@Test
void scannedSignaturesAreActuallyPresent() throws IOException {
String sql = statements();
assertTrue(sql.length() > 800, "剥注释后的 SQL 太短,说明预处理把内容吃掉了:" + sql.length());
assertTrue(count(sql, "ALTER TABLE") >= 3 && count(sql, "information_schema") > 0,
"关键签名 0 命中=预处理或文件路径坏了,本类的断言全部不可信");
}
private static int count(String haystack, String needle) {
int n = 0, i = haystack.indexOf(needle);
while (i >= 0) {
n++;
i = haystack.indexOf(needle, i + needle.length());
}
return n;
}
}
@@ -142,7 +142,7 @@ class CollectDataBrandRecheckInjectorTest {
List.of(chunk(1, "s1", "hash1", "ptr1")));
when(transientPayloadStorageService.resolvePayload(eq("ptr1"), anyString())).thenReturn(
"[{\"asin\":\"B01\",\"brand\":\"Zara\"},{\"asin\":\"B02\",\"brand\":\"Zara\"}]");
when(invalidAsinBatchWriter.writeBatch(anyList())).thenReturn(2);
when(invalidAsinBatchWriter.writeBatch(anyList(), eq(961L))).thenReturn(2);
GroupOutcome outcome = injector.apply(task(100L), Map.of("zara", RecheckVerdict.REJECTED));
@@ -208,7 +208,7 @@ class CollectDataServiceTxBoundaryTest {
service.submitResult(TASK_ID, submitRequest());
verify(invalidAsinBatchWriter).writeBatch(any());
verify(invalidAsinBatchWriter).writeBatch(any(), eq(USER_ID));
}
@Test
@@ -220,7 +220,7 @@ class CollectDataServiceTxBoundaryTest {
service.submitResult(TASK_ID, submitRequest());
verify(invalidAsinBatchWriter, never()).writeBatch(any());
verify(invalidAsinBatchWriter, never()).writeBatch(any(), any());
}
@Test
@@ -232,7 +232,7 @@ class CollectDataServiceTxBoundaryTest {
service.submitResult(TASK_ID, submitRequest());
verify(invalidAsinBatchWriter, never()).writeBatch(any());
verify(invalidAsinBatchWriter, never()).writeBatch(any(), any());
}
@Test
@@ -1,5 +1,6 @@
package com.nanri.aiimage.modules.collectdata.util;
import com.nanri.aiimage.common.service.CompanyScopeSupport;
import com.nanri.aiimage.modules.collectdata.model.vo.CollectDataResultRowVo;
import com.nanri.aiimage.modules.invalidasin.mapper.InvalidAsinDataMapper;
import com.nanri.aiimage.modules.invalidasin.model.entity.InvalidAsinDataEntity;
@@ -26,16 +27,29 @@ import static org.mockito.Mockito.when;
* biz_invalid_asin_data(INSERT IGNORE,按唯一键幂等),空批次/无合法
* data_value 的批次不发起任何 insertBatchIgnore 调用;远程失败降级记录
* 计数(跳过写入),可恢复后继续,不抛出中断整个提交流程的异常。
*
* <p>归属那一笔(10-05 批次 3):实体与 INSERT 列清单此前都不带 company_id/uploader_user_id,
* V145 补的列全靠 DEFAULT 1 盖 ⇒ 第 2 家公司跑货源产生的行被记成第 1 家。写入器现在按
* 调用方给的任务发起账号推公司,<b>推不出公司就整批不写</b>(宁可少一条黑名单,也不把行盖成
* 别家公司 —— 那会让另一家的正常品牌被静默过滤)。</p>
*/
class CollectDataInvalidAsinBatchWriterTest {
/** 任务发起账号(biz_file_task.user_id)。 */
private static final Long UPLOADER = 7L;
/** 该账号归属的公司 —— 必须与 UPLOADER 不同值,否则断言分不清写进去的是哪个。 */
private static final Long UPLOADER_COMPANY = 2L;
private InvalidAsinDataMapper invalidAsinDataMapper;
private CompanyScopeSupport companyScopeSupport;
private CollectDataInvalidAsinBatchWriter writer;
@BeforeEach
void setUp() {
invalidAsinDataMapper = mock(InvalidAsinDataMapper.class);
writer = new CollectDataInvalidAsinBatchWriter(invalidAsinDataMapper, 10);
companyScopeSupport = mock(CompanyScopeSupport.class);
when(companyScopeSupport.companyIdOrNull(UPLOADER)).thenReturn(UPLOADER_COMPANY);
writer = new CollectDataInvalidAsinBatchWriter(invalidAsinDataMapper, companyScopeSupport, 10);
}
@Test
@@ -46,7 +60,7 @@ class CollectDataInvalidAsinBatchWriterTest {
int written = writer.writeBatch(List.of(
row("B000000001", "Zara"),
row("B000000002", "nike")
));
), UPLOADER);
assertEquals(2, written, "两行都写入");
ArgumentCaptor<List<InvalidAsinDataEntity>> captor = ArgumentCaptor.forClass(List.class);
@@ -68,7 +82,7 @@ class CollectDataInvalidAsinBatchWriterTest {
rows.add(row("B" + String.format("%09d", i + 1), "brand-" + (i % 7)));
}
int written = writer.writeBatch(rows);
int written = writer.writeBatch(rows, UPLOADER);
assertEquals(100, written, "全部写入");
ArgumentCaptor<List<InvalidAsinDataEntity>> captor = ArgumentCaptor.forClass(List.class);
@@ -95,8 +109,8 @@ class CollectDataInvalidAsinBatchWriterTest {
row("B000000003", "")
);
int first = writer.writeBatch(rows);
int second = writer.writeBatch(rows);
int first = writer.writeBatch(rows, UPLOADER);
int second = writer.writeBatch(rows, UPLOADER);
assertEquals(2, first, "首轮 2 个合法行写入");
assertEquals(2, second, "重复执行同样只写合法行(幂等键由 SQL 保证)");
@@ -108,11 +122,11 @@ class CollectDataInvalidAsinBatchWriterTest {
@Test
void test_task_048_asin_boundary_empty_input() {
// 空输入:空列表与全空行均不发起任何批量写入调用,返回 0。
int written = writer.writeBatch(null);
int written = writer.writeBatch(null, UPLOADER);
assertEquals(0, written, "null 输入返回 0");
verify(invalidAsinDataMapper, never()).insertBatchIgnore(anyList());
int blankWritten = writer.writeBatch(List.of(row("", "nike"), row("B000000001", "")));
int blankWritten = writer.writeBatch(List.of(row("", "nike"), row("B000000001", "")), UPLOADER);
assertEquals(0, blankWritten, "无合法行返回 0");
verify(invalidAsinDataMapper, never()).insertBatchIgnore(anyList());
}
@@ -122,7 +136,7 @@ class CollectDataInvalidAsinBatchWriterTest {
// 单元素:单行单品牌正常批量写入;批次大小 1 的边界也正常。
when(invalidAsinDataMapper.insertBatchIgnore(anyList())).thenReturn(1);
int written = writer.writeBatch(List.of(row("B000000001", "solo")));
int written = writer.writeBatch(List.of(row("B000000001", "solo")), UPLOADER);
assertEquals(1, written, "单行写入成功");
ArgumentCaptor<List<InvalidAsinDataEntity>> captor = ArgumentCaptor.forClass(List.class);
@@ -137,13 +151,13 @@ class CollectDataInvalidAsinBatchWriterTest {
when(invalidAsinDataMapper.insertBatchIgnore(anyList())).thenAnswer(
invocation -> ((List<?>) invocation.getArgument(0)).size());
CollectDataInvalidAsinBatchWriter smallWriter =
new CollectDataInvalidAsinBatchWriter(invalidAsinDataMapper, 3);
new CollectDataInvalidAsinBatchWriter(invalidAsinDataMapper, companyScopeSupport, 3);
List<CollectDataResultRowVo> rows = new ArrayList<>();
for (int i = 0; i < 10; i++) {
rows.add(row("B" + String.format("%09d", i + 1), "brand"));
}
int written = smallWriter.writeBatch(rows);
int written = smallWriter.writeBatch(rows, UPLOADER);
assertEquals(10, written, "全部写入");
ArgumentCaptor<List<InvalidAsinDataEntity>> captor = ArgumentCaptor.forClass(List.class);
@@ -164,7 +178,7 @@ class CollectDataInvalidAsinBatchWriterTest {
rows.add(row("B000000001", null));
rows.add(row(" B000000002 ", " nike "));
int written = writer.writeBatch(rows);
int written = writer.writeBatch(rows, UPLOADER);
assertEquals(1, written, "仅完全合法的 1 行写入");
ArgumentCaptor<List<InvalidAsinDataEntity>> captor = ArgumentCaptor.forClass(List.class);
@@ -187,7 +201,7 @@ class CollectDataInvalidAsinBatchWriterTest {
rows.add(row("B" + String.format("%09d", i + 1), "brand"));
}
int written = writer.writeBatch(rows);
int written = writer.writeBatch(rows, UPLOADER);
assertEquals(2, written, "首批失败跳过,第二批 2 行写入");
verify(invalidAsinDataMapper, times(2)).insertBatchIgnore(anyList());
@@ -196,6 +210,38 @@ class CollectDataInvalidAsinBatchWriterTest {
assertTrue(captor.getAllValues().get(1).size() > 0, "恢复后批次非空");
}
@Test
void test_batch_3_asin_normal_ownership_is_stamped_on_every_row() {
// 归属由任务发起账号推:每一行都带 company_id + uploader_user_id,
// 而不是留空让 DEFAULT 1 去盖(那会把第 2 家的行记成第 1 家,事后分不开)。
when(invalidAsinDataMapper.insertBatchIgnore(anyList())).thenAnswer(
invocation -> ((List<?>) invocation.getArgument(0)).size());
when(companyScopeSupport.companyIdOrNull(UPLOADER)).thenReturn(UPLOADER_COMPANY);
writer.writeBatch(List.of(row("B000000001", "nike"), row("B000000002", "zara")), UPLOADER);
ArgumentCaptor<List<InvalidAsinDataEntity>> captor = ArgumentCaptor.forClass(List.class);
verify(invalidAsinDataMapper).insertBatchIgnore(captor.capture());
List<InvalidAsinDataEntity> entities = captor.getValue();
assertEquals(2, entities.size());
for (InvalidAsinDataEntity entity : entities) {
assertEquals(UPLOADER_COMPANY, entity.getCompanyId(), "company_id 来自发起账号,不是 DEFAULT");
assertEquals(UPLOADER, entity.getUploaderUserId(), "uploader_user_id 一并落,处置可回溯到人");
}
}
@Test
void test_batch_3_asin_invalid_owner_unresolved_skips_whole_batch() {
// 推不出公司(账号已删/没有公司):整批不写、返回 0、一次 insertBatchIgnore 都不发。
// 这一族的替代方案是"照常写、让 DEFAULT 盖一家",那是静默串数据,必须判红。
when(companyScopeSupport.companyIdOrNull(UPLOADER)).thenReturn(null);
int written = writer.writeBatch(List.of(row("B000000001", "nike"), row("B000000002", "zara")), UPLOADER);
assertEquals(0, written, "归属推不出 ⇒ 一行都不写");
verify(invalidAsinDataMapper, never()).insertBatchIgnore(anyList());
}
private static CollectDataResultRowVo row(String asin, String brand) {
CollectDataResultRowVo row = new CollectDataResultRowVo();
row.setAsin(asin);
@@ -19,6 +19,8 @@ import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
@@ -34,8 +36,10 @@ import static org.mockito.Mockito.when;
* 还没摘,此后每个没显式传公司的写入都会被静默塞进默认那家——不报错、不丢数据,只在后台列表里
* 表现成"这条数据怎么在别家公司"。所以必须用代码在启动期喊出来,而不是写在注释里等人记得。</p>
*
* <p>V145 之后盯的是【三张表】(users + 两张规则库),不是一列:漏登记的那张表等于没人盯,
* 所以"探不到列"也要出声(见 {@link #unwatchedTableIsAnnouncedInsteadOfLookingClean})。</p>
* <p>V145 之后盯的是【一张清单】(users + 两张规则库 + V147 的 biz_product_category),不是一列:
* 漏登记的那张表等于没人盯,所以"探不到列"也要出声(见
* {@link #unwatchedTableIsAnnouncedInsteadOfLookingClean})。清单与探针 SQL 的 IN 列表双向同源由
* {@link #watchedTablesMatchTheProbeSql} 钉住。</p>
*/
class CompanyDefaultGuardTest {
@@ -66,20 +70,49 @@ class CompanyDefaultGuardTest {
when(companyMapper.selectCount(null)).thenReturn(count);
}
/** 一条探针结果都没有=这些表在 information_schema 里查不到 company_id。 */
/**
* 一条探针结果都没有=这些表在 information_schema 里查不到 company_id。
*
* <p>未被点名的表按"已摘掉"自动补齐:清单哪天加第五条,本文件那几支"一声不响"的用例不会
* 因为漏了一张而红在 {@link #unwatchedTableIsAnnouncedInsteadOfLookingClean} 的同一条 WARN 上——
* 那种红会把人引去改哨兵,而哨兵是对的。要演"探不到"那一族,用 {@link #probeReturnsOnly}。</p>
*/
private void probeReturns(String... tableAndDefault) {
Map<String, String> given = new LinkedHashMap<>();
for (String entry : tableAndDefault) {
int split = entry.indexOf('=');
given.put(entry.substring(0, split), split + 1 >= entry.length() ? null : entry.substring(split + 1));
}
List<Map<String, Object>> rows = new ArrayList<>();
for (String table : CompanyDefaultGuard.WATCHED_TABLES) {
if (!given.containsKey(table)) {
rows.add(row(table, null));
} else {
rows.add(row(table, given.get(table)));
}
}
when(jdbcTemplate.queryForList(anyString())).thenReturn(rows);
}
/** 只给这几条结果,不补清单:用来演"某一列在 information_schema 里查不到"。 */
private void probeReturnsOnly(String... tableAndDefault) {
List<Map<String, Object>> rows = new ArrayList<>();
for (String entry : tableAndDefault) {
int split = entry.indexOf('=');
Map<String, Object> row = new LinkedHashMap<>();
row.put("TABLE_NAME", entry.substring(0, split));
row.put("COLUMN_DEFAULT", split + 1 >= entry.length() || "null".equals(entry.substring(split + 1))
? null : entry.substring(split + 1));
rows.add(row);
rows.add(row(entry.substring(0, split),
split + 1 >= entry.length() || "null".equals(entry.substring(split + 1))
? null : entry.substring(split + 1)));
}
when(jdbcTemplate.queryForList(anyString())).thenReturn(rows);
}
private static Map<String, Object> row(String table, String columnDefault) {
Map<String, Object> row = new LinkedHashMap<>();
row.put("TABLE_NAME", table);
row.put("COLUMN_DEFAULT", "null".equals(columnDefault) ? null : columnDefault);
return row;
}
private String messageAt(Level level) {
return appender.list.stream()
.filter(e -> e.getLevel() == level)
@@ -194,19 +227,39 @@ class CompanyDefaultGuardTest {
@DisplayName("盯不到的那张表要出声,不能装作检查过了")
void unwatchedTableIsAnnouncedInsteadOfLookingClean() {
companies(2);
probeReturns("users=null");
probeReturnsOnly("users=null");
guard.check();
assertThat(messageAt(Level.ERROR)).isEmpty();
assertThat(messageAt(Level.WARN))
.contains(CompanyDefaultGuard.PROBE_FAILED)
.contains("biz_invalid_asin_data")
.contains("biz_dedupe_total_data");
String warn = messageAt(Level.WARN);
assertThat(warn).contains(CompanyDefaultGuard.PROBE_FAILED);
// 逐条点名而不是挑两条写死:清单里每一条都必须出现在"探不到"的名单里,
// 新登记表漏进 SQL 之外的任何一侧都会在这一支红。
for (String table : CompanyDefaultGuard.WATCHED_TABLES) {
if (!"users".equals(table)) {
assertThat(warn).contains(table);
}
}
}
@Test
@DisplayName("探的是这三张表的 company_id 列,表名列名写错就等于没探")
@DisplayName("V147 的 biz_product_category 也在盯的清单里:摘 DEFAULT 那一步不许把它落下")
void productCategoryTableIsWatchedToo() {
companies(2);
probeReturns("biz_product_category=1");
guard.check();
assertThat(messageAt(Level.ERROR))
.contains(CompanyDefaultGuard.ALARM)
.contains("biz_product_category.company_id DEFAULT=1")
.contains("ALTER TABLE biz_product_category ALTER COLUMN company_id DROP DEFAULT")
.doesNotContain("MODIFY");
}
@Test
@DisplayName("探的是清单里这几张表的 company_id 列,表名列名写错就等于没探")
void probeReadsTheRightColumns() {
companies(2);
probeReturns("users=null", "biz_invalid_asin_data=null", "biz_dedupe_total_data=null");
@@ -218,19 +271,38 @@ class CompanyDefaultGuardTest {
assertThat(sql.getValue())
.contains("information_schema.COLUMNS")
.contains("DATABASE()")
.contains("'company_id'")
.contains("'users'")
.contains("'biz_invalid_asin_data'")
.contains("'biz_dedupe_total_data'");
.contains("'company_id'");
for (String table : CompanyDefaultGuard.WATCHED_TABLES) {
assertThat(sql.getValue()).contains("'" + table + "'");
}
}
/**
* 双向钉同源。只钉"清单里的都在 SQL 里"会漏掉另一侧:有人往 SQL 的 IN 列表加了一张表、
* 却没加进 {@code WATCHED_TABLES},那么 {@link #check} 的逐表循环根本不会走到它——
* 探针查得到、判定查不到,Outcome 是"这张表没人盯"而一声不响,正是本哨兵要消灭的那个形状。
*/
@Test
@DisplayName("清单与探针 SQL 的 IN 列表必须同源:漏一条就是那张表没人盯")
@DisplayName("清单与探针 SQL 的 IN 列表必须同源:两个方向都钉,漏一条就是那张表没人盯")
void watchedTablesMatchTheProbeSql() {
String probeSql = probeSqlText();
for (String table : CompanyDefaultGuard.WATCHED_TABLES) {
assertThat(probeSql).contains("'" + table + "'");
}
assertThat(inListTables(probeSql)).containsExactlyInAnyOrder(
CompanyDefaultGuard.WATCHED_TABLES.toArray(new String[0]));
}
/** 取 {@code TABLE_NAME IN ('a', 'b')} 里那批单引号表名(只认 IN 那一段,别把 'company_id' 也算进来)。 */
private static List<String> inListTables(String probeSql) {
Matcher inList = Pattern.compile("TABLE_NAME\\s+IN\\s*\\(([^)]*)\\)").matcher(probeSql);
assertThat(inList.find()).as("探针 SQL 里没有 TABLE_NAME IN (…) 这一段,取不到清单").isTrue();
List<String> tables = new ArrayList<>();
Matcher quoted = Pattern.compile("'([^']+)'").matcher(inList.group(1));
while (quoted.find()) {
tables.add(quoted.group(1));
}
return tables;
}
private String probeSqlText() {
@@ -2,9 +2,12 @@ package com.nanri.aiimage.modules.dedupe.controller;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.common.service.ReadScope;
import com.nanri.aiimage.modules.dedupe.service.DedupeTotalDataService;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import com.nanri.aiimage.modules.permission.model.vo.PermissionMenuItemVo;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
@@ -15,6 +18,7 @@ import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBo
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.time.LocalDate;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -38,9 +42,11 @@ class DedupeTotalDataControllerTest {
DedupeTotalDataService service = mock(DedupeTotalDataService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
DataReadScope dataReadScope = mock(DataReadScope.class);
HttpServletRequest request = mock(HttpServletRequest.class);
DedupeTotalDataController controller = new DedupeTotalDataController(
service, authSupport, permissionMenuService);
service, authSupport, permissionMenuService, dataReadScope);
when(dataReadScope.readScope(any(), any())).thenReturn(ReadScope.unfiltered());
AdminUserEntity operator = new AdminUserEntity();
operator.setId(8L);
operator.setRole("super_admin");
@@ -57,7 +63,8 @@ class DedupeTotalDataControllerTest {
eq(LocalDate.of(2026, 7, 31)),
eq(3L),
isNull(),
eq(8L));
eq(8L),
isNull());
ResponseEntity<StreamingResponseBody> response = controller.export(
"member",
@@ -65,6 +72,7 @@ class DedupeTotalDataControllerTest {
LocalDate.of(2026, 7, 31),
3L,
null,
null,
request);
assertNotNull(response.getBody());
@@ -87,9 +95,10 @@ class DedupeTotalDataControllerTest {
eq(LocalDate.of(2026, 7, 31)),
eq(3L),
isNull(),
eq(8L));
eq(8L),
isNull());
verify(service, never()).writeMonthlyZipExport(
any(OutputStream.class), any(), any(), any(), any(), any(), any());
any(OutputStream.class), any(), any(), any(), any(), any(), any(), any());
verifyNoInteractions(permissionMenuService);
}
@@ -98,9 +107,11 @@ class DedupeTotalDataControllerTest {
DedupeTotalDataService service = mock(DedupeTotalDataService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
DataReadScope dataReadScope = mock(DataReadScope.class);
HttpServletRequest request = mock(HttpServletRequest.class);
DedupeTotalDataController controller = new DedupeTotalDataController(
service, authSupport, permissionMenuService);
service, authSupport, permissionMenuService, dataReadScope);
when(dataReadScope.readScope(any(), any())).thenReturn(ReadScope.unfiltered());
AdminUserEntity operator = new AdminUserEntity();
operator.setId(8L);
operator.setRole("super_admin");
@@ -113,6 +124,7 @@ class DedupeTotalDataControllerTest {
LocalDate.of(2026, 8, 2),
3L,
null,
null,
request);
assertEquals(MediaType.parseMediaType(
@@ -130,9 +142,10 @@ class DedupeTotalDataControllerTest {
eq(LocalDate.of(2026, 8, 2)),
eq(3L),
isNull(),
eq(8L));
eq(8L),
isNull());
verify(service, never()).writeMonthlyZipExport(
any(OutputStream.class), any(), any(), any(), any(), any(), any());
any(OutputStream.class), any(), any(), any(), any(), any(), any(), any());
}
@Test
@@ -140,9 +153,11 @@ class DedupeTotalDataControllerTest {
DedupeTotalDataService service = mock(DedupeTotalDataService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
DataReadScope dataReadScope = mock(DataReadScope.class);
HttpServletRequest request = mock(HttpServletRequest.class);
DedupeTotalDataController controller = new DedupeTotalDataController(
service, authSupport, permissionMenuService);
service, authSupport, permissionMenuService, dataReadScope);
when(dataReadScope.readScope(any(), any())).thenReturn(ReadScope.unfiltered());
AdminUserEntity operator = new AdminUserEntity();
operator.setId(8L);
operator.setRole("super_admin");
@@ -159,7 +174,8 @@ class DedupeTotalDataControllerTest {
eq(LocalDate.of(2026, 8, 2)),
eq(3L),
isNull(),
eq(8L));
eq(8L),
isNull());
ResponseEntity<StreamingResponseBody> response = controller.export(
"member",
@@ -167,6 +183,7 @@ class DedupeTotalDataControllerTest {
LocalDate.of(2026, 8, 2),
3L,
null,
null,
request);
assertEquals(MediaType.parseMediaType("application/zip"), response.getHeaders().getContentType());
@@ -184,8 +201,9 @@ class DedupeTotalDataControllerTest {
eq(LocalDate.of(2026, 8, 2)),
eq(3L),
isNull(),
eq(8L));
verify(service, never()).writeExport(any(OutputStream.class), any(), any(), any(), any(), any(), any());
eq(8L),
isNull());
verify(service, never()).writeExport(any(OutputStream.class), any(), any(), any(), any(), any(), any(), any());
}
@Test
@@ -193,9 +211,11 @@ class DedupeTotalDataControllerTest {
DedupeTotalDataService service = mock(DedupeTotalDataService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
DataReadScope dataReadScope = mock(DataReadScope.class);
HttpServletRequest request = mock(HttpServletRequest.class);
DedupeTotalDataController controller = new DedupeTotalDataController(
service, authSupport, permissionMenuService);
service, authSupport, permissionMenuService, dataReadScope);
when(dataReadScope.readScope(any(), any())).thenReturn(ReadScope.unfiltered());
BusinessException exception = assertThrows(BusinessException.class, () -> controller.export(
"member",
@@ -203,9 +223,62 @@ class DedupeTotalDataControllerTest {
LocalDate.of(2026, 7, 15),
3L,
null,
null,
request));
assertEquals(400, exception.getCode());
verifyNoInteractions(service, authSupport, permissionMenuService);
}
@Test
void companyTabNarrowsSuperAdminToListOfMemberAccounts() {
// 超管点公司 tab ⇒ 成员集必须一路传到 service 的最后一个实参。
// 这一记盯的是"参数收了、readScope 也调了、结果却喂了 null"那种假接线(tab 恒不动的现网形状)。
DedupeTotalDataService service = mock(DedupeTotalDataService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
DataReadScope dataReadScope = mock(DataReadScope.class);
HttpServletRequest request = mock(HttpServletRequest.class);
DedupeTotalDataController controller = new DedupeTotalDataController(
service, authSupport, permissionMenuService, dataReadScope);
AdminUserEntity operator = new AdminUserEntity();
operator.setId(8L);
operator.setRole("super_admin");
when(authSupport.requireUser(request)).thenReturn(operator);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
when(dataReadScope.readScope(operator, 2L)).thenReturn(ReadScope.users(List.of(11L, 12L)));
controller.page(1L, 15L, null, "member", null, null, null, null, null, 2L, request);
verify(service).page(eq(1L), eq(15L), isNull(), eq("member"),
isNull(), isNull(), isNull(), isNull(), isNull(), eq(8L), eq(List.of(11L, 12L)));
}
@Test
void nonSuperAdminStaysUnfilteredEvenWhenCompanyTabIsSent() {
// 非超管:刻意<b>不</b>按公司收窄。他的可见集里含"靠分组权限可见"的行,
// 叠一层账号 IN 会把那批行静默删掉(口径同 ShopManageController)。
// 这条是反向钉:哪天有人给非超管也加上成员集,这里必须红。
DedupeTotalDataService service = mock(DedupeTotalDataService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
DataReadScope dataReadScope = mock(DataReadScope.class);
HttpServletRequest request = mock(HttpServletRequest.class);
DedupeTotalDataController controller = new DedupeTotalDataController(
service, authSupport, permissionMenuService, dataReadScope);
AdminUserEntity operator = new AdminUserEntity();
operator.setId(9L);
operator.setRole("admin");
when(authSupport.requireUser(request)).thenReturn(operator);
when(authSupport.currentRole(operator)).thenReturn("admin");
PermissionMenuItemVo granted = new PermissionMenuItemVo();
granted.setColumnKey("admin_dedupe_total_data");
when(permissionMenuService.getUserColumnPermissions(9L, "admin")).thenReturn(List.of(granted));
controller.page(1L, 15L, null, null, null, null, null, null, null, 2L, request);
verify(service).page(eq(1L), eq(15L), isNull(), isNull(),
isNull(), isNull(), isNull(), isNull(), isNull(), eq(9L), isNull());
verify(dataReadScope, never()).readScope(any(), any());
}
}
@@ -652,7 +652,7 @@ class DedupeTotalDataServiceTest {
rows.add(second);
when(dedupeTotalDataMapper.selectList(any())).thenReturn(rows);
DedupeTotalDataPageVo vo = service.page(3, 15, "", "", null, null, null, null, 1000L, 1L);
DedupeTotalDataPageVo vo = service.page(3, 15, "", "", null, null, null, null, 1000L, 1L, null);
ArgumentCaptor<LambdaQueryWrapper<DedupeTotalDataEntity>> queryCaptor =
ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
@@ -36,6 +36,8 @@ class InvalidAsinDataControllerTest {
private AdminAuthSupport adminAuthSupport;
@Mock
private PermissionMenuService permissionMenuService;
@Mock
private com.nanri.aiimage.common.service.DataReadScope dataReadScope;
@InjectMocks
private InvalidAsinDataController controller;
@@ -58,12 +60,13 @@ class InvalidAsinDataControllerTest {
when(adminAuthSupport.currentRole(operator)).thenReturn(null);
when(permissionMenuService.getUserColumnPermissions(7L, "admin"))
.thenReturn(List.of(invalidAsinDataPermission()));
when(invalidAsinDataService.page(1L, 15L, "", "", "", 3L, 7L, false))
when(invalidAsinDataService.page(1L, 15L, "", "", "", 3L, 7L, false, null))
.thenReturn(new InvalidAsinDataPageVo());
when(dataReadScope.readCompanyId(operator, null)).thenReturn(null);
controller.page(1L, 15L, "", "", "", 3L, request);
controller.page(1L, 15L, "", "", "", 3L, null, request);
verify(invalidAsinDataService).page(1L, 15L, "", "", "", 3L, 7L, false);
verify(invalidAsinDataService).page(1L, 15L, "", "", "", 3L, 7L, false, null);
}
@Test
@@ -73,7 +76,7 @@ class InvalidAsinDataControllerTest {
request.addParameter("superAdmin", "true");
when(adminAuthSupport.requireUser(request)).thenThrow(new BusinessException(401, "未登录"));
assertThrows(BusinessException.class, () -> controller.page(1L, 15L, "", "", "", 3L, request));
assertThrows(BusinessException.class, () -> controller.page(1L, 15L, "", "", "", 3L, null, request));
verifyNoInteractions(invalidAsinDataService);
verify(permissionMenuService, never()).requireUserOperator(any());
@@ -86,13 +89,50 @@ class InvalidAsinDataControllerTest {
AdminUserEntity operator = user(1L, "super_admin");
when(adminAuthSupport.requireUser(request)).thenReturn(operator);
when(adminAuthSupport.currentRole(operator)).thenReturn("super_admin");
when(invalidAsinDataService.page(1L, 15L, "", "", "", 3L, 1L, true))
when(invalidAsinDataService.page(1L, 15L, "", "", "", 3L, 1L, true, 2L))
.thenReturn(new InvalidAsinDataPageVo());
when(dataReadScope.readCompanyId(operator, 2L)).thenReturn(2L);
controller.page(1L, 15L, "", "", "", 3L, 2L, request);
verify(invalidAsinDataService).page(1L, 15L, "", "", "", 3L, 1L, true, 2L);
verify(permissionMenuService, never()).getUserColumnPermissions(eq(1L), eq("admin"));
}
@Test
void superAdminWithoutCompanyTabStaysUnfiltered() {
// 反向钉:tab 没传公司(companyId=null)⇒ 交给 service 的筛值必须是 null(= 不筛)。
// 哪天有人把它硬写成某个默认公司,全量视图会静默变成一家的视图。
MockHttpServletRequest request = new MockHttpServletRequest();
AdminUserEntity operator = user(1L, "super_admin");
when(adminAuthSupport.requireUser(request)).thenReturn(operator);
when(adminAuthSupport.currentRole(operator)).thenReturn("super_admin");
when(dataReadScope.readCompanyId(operator, null)).thenReturn(null);
when(invalidAsinDataService.page(1L, 15L, "", "", "", 3L, 1L, true, null))
.thenReturn(new InvalidAsinDataPageVo());
controller.page(1L, 15L, "", "", "", 3L, request);
controller.page(1L, 15L, "", "", "", 3L, null, request);
verify(invalidAsinDataService).page(1L, 15L, "", "", "", 3L, 1L, true);
verify(permissionMenuService, never()).getUserColumnPermissions(eq(1L), eq("admin"));
verify(invalidAsinDataService).page(1L, 15L, "", "", "", 3L, 1L, true, null);
}
@Test
void forgedCompanyTabForNonSuperAdminIsNarrowedToItsOwnCompany() {
// 非超管传别人的公司 id:出口给的是 null(不筛)而不是那家 —— 这页的隔离靠分组权限,
// 叠公司会把「靠分组可见」的行整批删掉。钉住"传什么都不算"的现网口径。
MockHttpServletRequest request = new MockHttpServletRequest();
AdminUserEntity operator = user(9L, "admin");
when(adminAuthSupport.requireUser(request)).thenReturn(operator);
when(adminAuthSupport.currentRole(operator)).thenReturn("admin");
when(permissionMenuService.getUserColumnPermissions(9L, "admin"))
.thenReturn(List.of(invalidAsinDataPermission()));
when(dataReadScope.readCompanyId(operator, 5L)).thenReturn(null);
when(invalidAsinDataService.page(1L, 15L, "", "", "", 3L, 9L, false, null))
.thenReturn(new InvalidAsinDataPageVo());
controller.page(1L, 15L, "", "", "", 3L, 5L, request);
verify(invalidAsinDataService).page(1L, 15L, "", "", "", 3L, 9L, false, null);
}
private AdminUserEntity user(Long id, String role) {
@@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.service.CompanyScopeSupport;
import com.nanri.aiimage.modules.invalidasin.mapper.InvalidAsinDataMapper;
import com.nanri.aiimage.modules.invalidasin.model.dto.InvalidAsinDataCreateRequest;
import com.nanri.aiimage.modules.invalidasin.model.dto.InvalidAsinDataUpdateRequest;
@@ -39,14 +40,21 @@ import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class InvalidAsinDataServiceTest {
/** 操作者 7L 所属公司。故意取 2 不取 1:DEFAULT 1 那家也能通过"非空"这一断言,取 2 才钉得住"真从会话来"。 */
private static final Long OPERATOR_COMPANY_ID = 2L;
@Mock
private InvalidAsinDataMapper invalidAsinDataMapper;
@Mock
private ShopManageGroupService shopManageGroupService;
/** 归属从操作者会话推导(create 里那唯一一处 requireCompanyId):不 mock 就是构造注入不到、整个 service 空指针。 */
@Mock
private CompanyScopeSupport companyScopeSupport;
@InjectMocks
private InvalidAsinDataService service;
@Test
@SuppressWarnings({"rawtypes", "unchecked"})
void createManualRecordUsesAccessibleGroup() {
InvalidAsinDataCreateRequest request = new InvalidAsinDataCreateRequest();
request.setDataValue("B012345678");
@@ -55,6 +63,7 @@ class InvalidAsinDataServiceTest {
ShopManageGroupEntity group = group(9L, "group-a");
InvalidAsinDataEntity saved = data(91L, "MANUAL", 9L);
when(companyScopeSupport.requireCompanyId(7L)).thenReturn(OPERATOR_COMPANY_ID);
when(shopManageGroupService.listAccessibleGroupIds(7L, false)).thenReturn(Set.of(12L, 9L));
when(shopManageGroupService.getAccessibleById(9L, 7L, false)).thenReturn(group);
when(invalidAsinDataMapper.selectOne(any())).thenReturn(null);
@@ -74,6 +83,21 @@ class InvalidAsinDataServiceTest {
assertEquals("MANUAL", captor.getValue().getRecordSource());
assertEquals("group-a", item.getGroupName());
assertEquals("MANUAL", item.getRecordSource());
// 写侧归属:MANUAL 行的 company_id 必须真从操作者会话推导。V146 已摘掉该列的 DEFAULT 1,
// 没人推导就是 NULL —— 而 NULL 行在 readCompanyId 谓词下对所有公司 tab 都不可见(静默删除),
// 比"归属错一家"更难发现。
assertEquals(OPERATOR_COMPANY_ID, captor.getValue().getCompanyId());
assertEquals(7L, captor.getValue().getUploaderUserId());
// 重复预检必须与 V145 放宽后的唯一键 (company_id, data_value, brand) 同宽:少公司这一维,
// 第 2 家永远无法新增第 1 家已有的品牌(跨公司误报「ASIN 已存在」)。
ArgumentCaptor<LambdaQueryWrapper<InvalidAsinDataEntity>> unique =
ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
verify(invalidAsinDataMapper).selectOne(unique.capture());
TableInfoHelper.initTableInfo(
new MapperBuilderAssistant(new MybatisConfiguration(), ""),
InvalidAsinDataEntity.class);
assertTrue(unique.getValue().getSqlSegment().contains("company_id"));
assertTrue(unique.getValue().getParamNameValuePairs().containsValue(OPERATOR_COMPANY_ID));
}
@Test
@@ -85,7 +109,7 @@ class InvalidAsinDataServiceTest {
when(invalidAsinDataMapper.selectList(any())).thenReturn(List.of(manual));
when(shopManageGroupService.buildGroupNameMap(any())).thenReturn(Map.of(9L, "group-a"));
InvalidAsinDataPageVo page = service.page(1, 15, "", "", "", 10L, 7L, false);
InvalidAsinDataPageVo page = service.page(1, 15, "", "", "", 10L, 7L, false, null);
ArgumentCaptor<LambdaQueryWrapper<InvalidAsinDataEntity>> captor = ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
verify(invalidAsinDataMapper).selectCount(captor.capture());
@@ -109,7 +133,7 @@ class InvalidAsinDataServiceTest {
when(invalidAsinDataMapper.selectList(any())).thenReturn(List.of(automatic, orphan));
when(shopManageGroupService.buildGroupNameMap(any())).thenReturn(Map.of());
InvalidAsinDataPageVo page = service.page(1, 15, "", "", "", null, 1L, true);
InvalidAsinDataPageVo page = service.page(1, 15, "", "", "", null, 1L, true, null);
assertEquals(2, page.getItems().size());
assertEquals("AUTO", page.getItems().getFirst().getRecordSource());
@@ -123,7 +147,7 @@ class InvalidAsinDataServiceTest {
when(invalidAsinDataMapper.selectCount(any())).thenReturn(0L);
when(invalidAsinDataMapper.selectList(any())).thenReturn(List.of());
service.page(1, 15, "", "", "", 9L, 1L, true);
service.page(1, 15, "", "", "", 9L, 1L, true, null);
ArgumentCaptor<LambdaQueryWrapper<InvalidAsinDataEntity>> captor = ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
verify(invalidAsinDataMapper).selectCount(captor.capture());
@@ -140,7 +164,7 @@ class InvalidAsinDataServiceTest {
when(invalidAsinDataMapper.selectCount(any())).thenReturn(0L);
when(invalidAsinDataMapper.selectList(any())).thenReturn(List.of());
service.page(1, 15, "", "B01", "acme", null, 1L, true);
service.page(1, 15, "", "B01", "acme", null, 1L, true, null);
ArgumentCaptor<LambdaQueryWrapper<InvalidAsinDataEntity>> captor = ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
verify(invalidAsinDataMapper).selectCount(captor.capture());
@@ -0,0 +1,125 @@
package com.nanri.aiimage.modules.productcategory.controller;
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.productcategory.model.dto.ProductCategorySaveRequest;
import com.nanri.aiimage.modules.productcategory.service.ProductCategoryService;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.web.MockHttpServletRequest;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/**
* 「商品类目」controller 的正门接线(护栏 G2 断言 A 要求这些调用内联在 handler 块里,
* 本文件钉的是内联之后的<b>语义</b>:tab 的值确实进了出口、出口的结果确实交给了 service)。
*
* <p>G2 只看形状(有没有调、结果有没有被当实参用),看不见"把 service 那侧的实参改成 null"
* 这一记 —— 那一记由本文件的 {@code verify(service).list("面霜", 2L)} 负责。</p>
*/
@ExtendWith(MockitoExtension.class)
class ProductCategoryControllerCompanyScopeTest {
private static final Long OPERATOR_ID = 1L;
private static final Long COMPANY_ID = 2L;
@Mock
private ProductCategoryService productCategoryService;
@Mock
private AdminAuthSupport adminAuthSupport;
@Mock
private DataReadScope dataReadScope;
private ProductCategoryController controller() {
return new ProductCategoryController(productCategoryService, adminAuthSupport, dataReadScope);
}
@Test
@DisplayName("列表:tab 的公司 id 交给 readCompanyId,出口给什么 service 就用什么")
void listPassesTheTabValueThroughTheDoor() {
HttpServletRequest request = login();
when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(user());
when(dataReadScope.readCompanyId(any(AdminUserEntity.class), eq(COMPANY_ID))).thenReturn(COMPANY_ID);
controller().list(request, "面霜", COMPANY_ID);
verify(dataReadScope).readCompanyId(any(AdminUserEntity.class), eq(COMPANY_ID));
verify(productCategoryService).list("面霜", COMPANY_ID);
}
@Test
@DisplayName("列表:非超管由出口判成\"不筛\",controller 不许自己补一个公司 id 进去")
void listUsesTheDorsVerdictForNonSuperAdmin() {
HttpServletRequest request = login();
when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(user());
when(dataReadScope.readCompanyId(any(AdminUserEntity.class), eq(COMPANY_ID))).thenReturn(null);
controller().list(request, "面霜", COMPANY_ID);
verify(productCategoryService).list("面霜", null);
}
@Test
@DisplayName("children / search / export 三支同样走出口,漏一支就是那一处的 tab 仍是装饰")
void everyReadEndpointGoesThroughTheDoor() {
HttpServletRequest request = login();
when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(user());
when(dataReadScope.readCompanyId(any(AdminUserEntity.class), eq(COMPANY_ID))).thenReturn(COMPANY_ID);
// export 的返回要真喂给 ResponseEntity.contentLength(bytes.length):mock 给 null 会 NPE 在断言之前的装配里。
when(productCategoryService.export("面霜", COMPANY_ID)).thenReturn(new byte[0]);
ProductCategoryController controller = controller();
controller.children(request, 10L, 1L, 20L, COMPANY_ID);
controller.search(request, "面霜", 1L, 20L, COMPANY_ID);
controller.export(request, "面霜", COMPANY_ID);
verify(productCategoryService).children(10L, 1L, 20L, COMPANY_ID);
verify(productCategoryService).search("面霜", 1L, 20L, COMPANY_ID);
verify(productCategoryService).export("面霜", COMPANY_ID);
verify(dataReadScope, times(3))
.readCompanyId(any(AdminUserEntity.class), eq(COMPANY_ID));
}
/** 写侧口径(一期定案):归属由后端从操作者会话推导,请求体不带 company_id,controller 也不读 tab。 */
@Test
@DisplayName("新增:只把操作者 id 交给 service,公司由 service 从会话推导")
void createPassesOnlyTheOperator() {
HttpServletRequest request = login();
when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(user());
ProductCategorySaveRequest body = new ProductCategorySaveRequest();
body.setName("面霜套装");
body.setParentId(10L);
controller().create(request, body);
ArgumentCaptor<Long> operatorId = ArgumentCaptor.forClass(Long.class);
verify(productCategoryService).create(eq(body), operatorId.capture());
assertEquals(OPERATOR_ID, operatorId.getValue());
verifyNoInteractions(dataReadScope);
}
private MockHttpServletRequest login() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("X-Internal-Token", "irrelevant-here");
return request;
}
private AdminUserEntity user() {
AdminUserEntity user = new AdminUserEntity();
user.setId(OPERATOR_ID);
user.setRole("super_admin");
return user;
}
}
@@ -0,0 +1,310 @@
package com.nanri.aiimage.modules.productcategory.service;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.service.CompanyScopeSupport;
import com.nanri.aiimage.modules.productcategory.mapper.ProductCategoryMapper;
import com.nanri.aiimage.modules.productcategory.model.dto.ProductCategorySaveRequest;
import com.nanri.aiimage.modules.productcategory.model.entity.ProductCategoryEntity;
import com.nanri.aiimage.modules.productcategory.model.vo.ProductCategoryListVo;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
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.atLeastOnce;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* 「商品类目」按公司视图的那几条不变量(V147 / 需求 2026-10-05「切 tab 数据还一样」)。
*
* <p>这一页的归属是<b>物化列</b>而不是账号集合,所以判据形状与 readScope 那一族不同:
* 可见集 = {@code company_id IN (0, X)},其中 0 是内置节点的哨兵。两支最容易静默坏掉的形状
* 都由本文件钉住:① 哨兵那半不许丢(丢了第 2 家是一棵空树,连自建根都挂不上);
* ② 给 LLM 用的那棵全局树不许被顺手加上公司谓词(加了货源归类的候选就按公司分叉)。</p>
*/
@ExtendWith(MockitoExtension.class)
class ProductCategoryCompanyScopeTest {
private static final long BUILTIN = 0L;
private static final Long OPERATOR_ID = 7L;
/** 故意取 2:DEFAULT 1 那一家通不过"值等于会话公司"这种断言,取 2 才钉得住"真从会话推导"。 */
private static final Long COMPANY_ID = 2L;
private static final Long BUILTIN_PARENT_ID = 10L;
@Mock
private ProductCategoryMapper productCategoryMapper;
@Mock
private CompanyScopeSupport companyScopeSupport;
private ProductCategoryService service;
@BeforeAll
static void initTableInfo() {
// Lambda 条件要解析列名,没有 TableInfo 时 getSqlSegment() 里根本不会出现 company_id。
TableInfoHelper.initTableInfo(
new MapperBuilderAssistant(new MybatisConfiguration(), ""),
ProductCategoryEntity.class);
}
@BeforeEach
void setUp() {
service = new ProductCategoryService(productCategoryMapper, companyScopeSupport);
}
@Test
@DisplayName("公司视图带哨兵 0:可见集是 (0, 该公司),只查自建会让第 2 家连自建根都挂不上")
void companyViewIncludesTheBuiltinSentinel() {
when(productCategoryMapper.selectList(any())).thenReturn(List.of(row(1L, null, "护肤品", BUILTIN)));
service.list(null, COMPANY_ID);
LambdaQueryWrapper<ProductCategoryEntity> query = capturedListWrapper();
assertTrue(query.getSqlSegment().contains("company_id IN"), query.getSqlSegment());
Map<String, Object> params = paramsOf(query);
assertTrue(params.containsValue(BUILTIN), "哨兵 0 必须留在可见集里:" + params);
assertTrue(params.containsValue(COMPANY_ID), "公司谓词丢了 tab 就是装饰:" + params);
}
/**
* 反向钉(新维度不许顺手回流到别的通路):{@link ProductCategoryService#list()} 唯一的消费者是
* 货源/外观的类目归类({@code SimilarAsinLlmService} 读的是全局树)。给它加公司谓词会让同一个
* "面霜"有 N 个 category_key、LLM 分类结果按公司分叉,那是成本不只是口径。
*/
@Test
@DisplayName("给 LLM 用的全局树不带公司谓词:按公司切会让归类结果按公司分叉")
void globalTreeForTheLlmConsumerStaysUnscoped() {
when(productCategoryMapper.selectList(any())).thenReturn(List.of(row(1L, null, "护肤品", BUILTIN)));
service.list();
LambdaQueryWrapper<ProductCategoryEntity> query = capturedListWrapper();
String sql = query.getSqlSegment();
// 两条一起才算非恒真:只看"不含 company_id"时,一条空 segment(列名解析不到、wrapper 根本没拼)
// 也会通过,那条断言就变成恒绿。先证明 wrapper 真渲染了东西,再证明它一个实参都没带。
assertTrue(sql.contains("ORDER BY"), "wrapper 根本没渲染,下面的否证是空话:" + sql);
assertFalse(sql.contains("company_id"),
"无参 list() 被接上了公司谓词 —— 货源归类的候选树随之按公司分叉:" + sql);
assertTrue(query.getParamNameValuePairs().isEmpty(),
"全局树带出了实参(说明有谓词被塞进来):" + query.getParamNameValuePairs());
}
@Test
@DisplayName("搜索的公司谓词必须在整条 OR 之外:AND 结合更紧会让前两列命中不受公司约束")
void searchKeepsTheOrGroupWrappedBeforeTheCompanyPredicate() {
when(productCategoryMapper.selectCount(any())).thenReturn(0L);
when(productCategoryMapper.selectList(any())).thenReturn(List.of());
service.search("面霜", 1, 20, COMPANY_ID);
List<LambdaQueryWrapper<ProductCategoryEntity>> queries = capturedSearchWrappers();
for (LambdaQueryWrapper<ProductCategoryEntity> query : queries) {
String sql = query.getSqlSegment();
assertTrue(sql.contains(") AND company_id IN"),
"OR 组没有被包起来再 AND 公司(前两个 like 命中的行会跨公司):" + sql);
Map<String, Object> params = paramsOf(query);
assertTrue(params.containsValue("%面霜%"), sql);
assertTrue(params.containsValue(COMPANY_ID), sql);
}
assertEquals(2, queries.size(), "count 与 list 两条查询都要带公司谓词");
}
@Test
@DisplayName("分页 children 的 count 与 list 两条查询同源,且子类目数徽章也按可见集聚合")
void childrenScopeCountListAndChildBadgeTogether() {
when(productCategoryMapper.selectCount(any())).thenReturn(1L);
when(productCategoryMapper.selectList(any())).thenReturn(List.of(row(20L, BUILTIN_PARENT_ID, "面霜", COMPANY_ID)));
when(productCategoryMapper.selectMaps(any())).thenReturn(List.of());
service.children(BUILTIN_PARENT_ID, 1, 20, COMPANY_ID);
ArgumentCaptor<Wrapper<ProductCategoryEntity>> countCaptor = ArgumentCaptor.forClass(Wrapper.class);
verify(productCategoryMapper).selectCount(countCaptor.capture());
assertTrue(countCaptor.getValue().getSqlSegment().contains("company_id IN"));
LambdaQueryWrapper<ProductCategoryEntity> pageQuery = capturedListWrapper();
assertTrue(pageQuery.getSqlSegment().contains("company_id IN"));
assertTrue(pageQuery.getSqlSegment().contains("parent_id"));
// 「子类目数」徽章走全表聚合:不加公司谓词就会把别家子节点数算进来,数字与点开看到的树不一致。
ArgumentCaptor<Wrapper<ProductCategoryEntity>> badgeCaptor = ArgumentCaptor.forClass(Wrapper.class);
verify(productCategoryMapper).selectMaps(badgeCaptor.capture());
assertTrue(badgeCaptor.getValue().getSqlSegment().contains("company_id IN"),
badgeCaptor.getValue().getSqlSegment());
}
@Test
@DisplayName("新增:归属从操作者会话推导,不靠 V147 那个临时 DEFAULT 1")
void createStampsTheOperatorsCompany() {
when(companyScopeSupport.requireCompanyId(OPERATOR_ID)).thenReturn(COMPANY_ID);
when(productCategoryMapper.selectById(BUILTIN_PARENT_ID))
.thenReturn(row(BUILTIN_PARENT_ID, null, "护肤品", BUILTIN));
when(productCategoryMapper.selectCount(any())).thenReturn(0L);
when(productCategoryMapper.insert(any(ProductCategoryEntity.class))).thenAnswer(call -> {
call.getArgument(0, ProductCategoryEntity.class).setId(500L);
return 1;
});
when(productCategoryMapper.selectById(500L)).thenReturn(row(500L, BUILTIN_PARENT_ID, "面霜套装", COMPANY_ID));
service.create(saveRequest("面霜套装", BUILTIN_PARENT_ID), OPERATOR_ID);
ArgumentCaptor<ProductCategoryEntity> inserted = ArgumentCaptor.forClass(ProductCategoryEntity.class);
verify(productCategoryMapper).insert(inserted.capture());
assertEquals(COMPANY_ID, inserted.getValue().getCompanyId());
assertFalse(Boolean.TRUE.equals(inserted.getValue().getIsBuiltin()));
assertTrue(inserted.getValue().getCategoryKey().startsWith("custom_"));
// 同级重名预检的范围 = 可见集(自建 + 内置):漏了它,第 2 家能在内置"护肤品"下再建一个同名"面霜",
// 页面一排两个而货源归类不知落到哪个;反过来跨家同名必须放行(那正是 uk_company_category_key 要解的)。
// 第 0 条=同级重名预检;findItem 里那条「子类目数」聚合不在本断言射程内(它按 parent_id 数,
// 不带公司谓词——那是详情返回值的计数,与列表可见集两回事)。
LambdaQueryWrapper<ProductCategoryEntity> sibling = countWrappers().get(0);
assertTrue(sibling.getSqlSegment().contains("company_id IN"), sibling.getSqlSegment());
Map<String, Object> params = paramsOf(sibling);
assertTrue(params.containsValue(BUILTIN), "重名检查漏了内置那一半:" + params);
assertTrue(params.containsValue(COMPANY_ID), "重名检查漏了这一家自己:" + params);
}
@Test
@DisplayName("新增:父级挂在别家公司名下要 403,不能静默把行挪出可见集")
void createRejectsParentOwnedByAnotherCompany() {
Long foreignParentId = 77L;
when(companyScopeSupport.requireCompanyId(OPERATOR_ID)).thenReturn(COMPANY_ID);
when(productCategoryMapper.selectById(foreignParentId))
.thenReturn(row(foreignParentId, null, "别家的根", 3L));
BusinessException exception = assertThrows(BusinessException.class,
() -> service.create(saveRequest("面霜套装", foreignParentId), OPERATOR_ID));
assertEquals(403, exception.getCode());
verify(productCategoryMapper, never()).insert(any(ProductCategoryEntity.class));
}
@Test
@DisplayName("新增:内置节点(哨兵 0)当父级放行,否则第 2 家永远建不出子级")
void createAcceptsTheSharedBuiltinParent() {
when(companyScopeSupport.requireCompanyId(OPERATOR_ID)).thenReturn(COMPANY_ID);
when(productCategoryMapper.selectById(BUILTIN_PARENT_ID))
.thenReturn(row(BUILTIN_PARENT_ID, null, "护肤品", BUILTIN));
when(productCategoryMapper.selectCount(any())).thenReturn(0L);
when(productCategoryMapper.insert(any(ProductCategoryEntity.class))).thenAnswer(call -> {
call.getArgument(0, ProductCategoryEntity.class).setId(501L);
return 1;
});
when(productCategoryMapper.selectById(501L)).thenReturn(row(501L, BUILTIN_PARENT_ID, "自建子级", COMPANY_ID));
service.create(saveRequest("自建子级", BUILTIN_PARENT_ID), OPERATOR_ID);
ArgumentCaptor<ProductCategoryEntity> inserted = ArgumentCaptor.forClass(ProductCategoryEntity.class);
verify(productCategoryMapper).insert(inserted.capture());
assertEquals(COMPANY_ID, inserted.getValue().getCompanyId());
assertEquals(BUILTIN_PARENT_ID, inserted.getValue().getParentId());
}
@Test
@DisplayName("更新时按行自己的归属判可见集:内置行归 0、自建行归那一家,都不取 tab")
void updateUsesTheRowsOwnCompanyNotTheTab() {
ProductCategoryEntity custom = row(300L, BUILTIN_PARENT_ID, "面霜", COMPANY_ID);
when(productCategoryMapper.selectById(300L)).thenReturn(custom);
when(productCategoryMapper.selectById(BUILTIN_PARENT_ID))
.thenReturn(row(BUILTIN_PARENT_ID, null, "护肤品", BUILTIN));
when(productCategoryMapper.selectCount(any())).thenReturn(0L);
when(productCategoryMapper.updateById(any(ProductCategoryEntity.class))).thenReturn(1);
service.update(300L, saveRequest("面霜改名", BUILTIN_PARENT_ID));
LambdaQueryWrapper<ProductCategoryEntity> sibling = countWrappers().get(0);
assertTrue(sibling.getSqlSegment().contains("company_id IN"), sibling.getSqlSegment());
Map<String, Object> params = paramsOf(sibling);
assertTrue(params.containsValue(COMPANY_ID), params.toString());
assertFalse(params.containsValue(3L),
"把行挪到可见集外的节点下面会让它从原本看得见它的 tab 里消失:" + params);
}
private ProductCategorySaveRequest saveRequest(String name, Long parentId) {
ProductCategorySaveRequest request = new ProductCategorySaveRequest();
request.setName(name);
request.setParentId(parentId);
return request;
}
private static ProductCategoryEntity row(Long id, Long parentId, String name, Long companyId) {
ProductCategoryEntity entity = new ProductCategoryEntity();
entity.setId(id);
entity.setParentId(parentId);
entity.setName(name);
entity.setCategoryKey("cat_" + id);
entity.setSortOrder(100);
entity.setCompanyId(companyId);
entity.setIsBuiltin(companyId == BUILTIN);
return entity;
}
@SuppressWarnings("unchecked")
private LambdaQueryWrapper<ProductCategoryEntity> capturedListWrapper() {
ArgumentCaptor<Wrapper<ProductCategoryEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(productCategoryMapper).selectList(captor.capture());
return (LambdaQueryWrapper<ProductCategoryEntity>) captor.getValue();
}
/** create/update 之后 selectCount 至少两条(重名预检 + 详情里的子类目数),按调用顺序取。 */
@SuppressWarnings("unchecked")
private List<LambdaQueryWrapper<ProductCategoryEntity>> countWrappers() {
ArgumentCaptor<Wrapper<ProductCategoryEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(productCategoryMapper, atLeastOnce()).selectCount(captor.capture());
return captor.getAllValues().stream()
.map(wrapper -> (LambdaQueryWrapper<ProductCategoryEntity>) wrapper)
.toList();
}
/**
* MyBatis-Plus 的实参表是<b>惰性</b>填充的:不先求值 {@code getSqlSegment()},
* {@code getParamNameValuePairs()} 是个空 map——那会让"含 0"与"不含 3"两个方向的断言同时恒真。
* 读参数一律走这里,别在测试里各自记得。
*/
private static Map<String, Object> paramsOf(LambdaQueryWrapper<ProductCategoryEntity> query) {
query.getSqlSegment();
return query.getParamNameValuePairs();
}
@SuppressWarnings("unchecked")
private List<LambdaQueryWrapper<ProductCategoryEntity>> capturedSearchWrappers() {
ArgumentCaptor<Wrapper<ProductCategoryEntity>> count = ArgumentCaptor.forClass(Wrapper.class);
verify(productCategoryMapper).selectCount(count.capture());
ArgumentCaptor<Wrapper<ProductCategoryEntity>> list = ArgumentCaptor.forClass(Wrapper.class);
verify(productCategoryMapper).selectList(list.capture());
return List.of((LambdaQueryWrapper<ProductCategoryEntity>) count.getValue(),
(LambdaQueryWrapper<ProductCategoryEntity>) list.getValue());
}
@Test
@DisplayName("空关键字的直接搜索返回空页,不探库")
void blankKeywordSearchShortCircuits() {
ProductCategoryListVo vo = service.search(" ", 1, 20, COMPANY_ID);
assertEquals(0L, vo.getTotal());
verify(productCategoryMapper, never()).selectCount(any());
verify(productCategoryMapper, never()).selectMaps(any());
// CompanyScopeSupport 有 (Long) 与 (AdminUserEntity) 两形:any() 会撞上重载歧义(javac 直接拒绝)。
verify(companyScopeSupport, never()).requireCompanyId(anyLong());
}
}
@@ -0,0 +1,86 @@
package com.nanri.aiimage.modules.shopdatacrawl.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
import com.nanri.aiimage.modules.shopdatacrawl.mapper.ShopDataCrawlAdminTasksMapper;
import com.nanri.aiimage.modules.shopdatacrawl.mapper.ShopDataCrawlItemMapper;
import com.nanri.aiimage.modules.shopdatacrawl.spi.DuplicateCheckRefreshPort;
import com.nanri.aiimage.modules.shopdatacrawl.spi.ManagedShopNamesPort;
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* 店铺数据记录(D 类第二页)的公司 tab:可见店铺集的三条出口必须各不相同。
*
* <p>这一页的单位是「店铺」而不是行,所以公司条件落在店铺名集合上(与撞款页同一个 normalize);
* 两处最容易写错且都不报错的形状是:超管没切 tab 时给出空集合(整页突然空),
* 以及空成员集时给出 null(在这套语义里是"全量",等于把第 1 家的数据交给第 2 家)。</p>
*/
class ShopDataCrawlAdminTasksCompanyScopeTest {
private ManagedShopNamesPort port;
private ShopDataCrawlAdminTasksService service;
@BeforeEach
void setUp() {
port = mock(ManagedShopNamesPort.class);
service = new ShopDataCrawlAdminTasksService(
mock(ShopDataCrawlAdminTasksMapper.class), port,
mock(ShopDataCrawlItemMapper.class),
mock(FileResultMapper.class),
mock(ShopDataCrawlDailyFileService.class),
mock(OssStorageService.class),
mock(ShopDataCrawlTaskService.class),
mock(DuplicateCheckRefreshPort.class),
new ObjectMapper());
}
@Test
@DisplayName("超管没切公司 tab=null(全量),逐字等于接线前")
void superAdminWithoutCompanySeesEverything() {
assertThat(service.resolveVisibleShopKeys(1L, true, null)).isNull();
verify(port, never()).selectManagedShopNames(any());
verify(port, never()).selectShopNamesOwnedByMembers(anyList());
}
@Test
@DisplayName("超管切到某家公司=按店铺负责人取那家的店铺名,小写去空格")
void superAdminOnCompanyTabUsesShopOwnerRuler() {
when(port.selectShopNamesOwnedByMembers(List.of(7L, 8L)))
.thenReturn(List.of(" ShopA ", "shopa", "ShopB"));
assertThat(service.resolveVisibleShopKeys(1L, true, List.of(7L, 8L)))
.containsExactly("shopa", "shopb");
}
@Test
@DisplayName("空成员集=空列表而不是 null:这家没有店铺,不许退化成全量")
void emptyMemberSetIsNoShopsNotEverything() {
when(port.selectShopNamesOwnedByMembers(List.of())).thenReturn(List.of());
List<String> keys = service.resolveVisibleShopKeys(1L, true, List.of());
assertThat(keys).isNotNull();
assertThat(keys).isEmpty();
}
@Test
@DisplayName("非超管仍按分组关系推,公司成员集不参与(tab 不是安全边界)")
void nonSuperKeepsGroupBasedView() {
when(port.selectManagedShopNames(9L)).thenReturn(List.of("ShopC"));
assertThat(service.resolveVisibleShopKeys(9L, false, List.of(7L))).containsExactly("shopc");
verify(port, never()).selectShopNamesOwnedByMembers(anyList());
}
}
@@ -0,0 +1,180 @@
package com.nanri.aiimage.modules.shopduplicatecheck.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.nanri.aiimage.modules.shopduplicatecheck.TestFixtures;
import com.nanri.aiimage.modules.shopduplicatecheck.mapper.ShopDuplicateCheckSourceMapper;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.builder.annotation.MapperAnnotationBuilder;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.Configuration;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* 店铺撞款监控的公司 tab(D 类第一页)。
*
* <p>要钉住的不是"筛了没筛",而是三件各自会静默出错的事:</p>
* <ol>
* <li><b>公司这一支必须换尺子</b>,从"主管分组关系"换到"店铺行自己的负责人"
* ({@code biz_shop_manage.created_by_id})。留在分组尺子上,第 1 家 tab 会把 12 个分组
* 里只挂 user_id 的那 2 个也算进来,与已上线的「店铺管理」页对不上——同一个 tab 两家页面前后
* 给出不同的店铺集合,比空页更容易被当成 bug 报。</li>
* <li><b>{@code null} 在这一页是"全量"而不是"没筛出东西"</b>。空成员集若退化成 null,
* "切到一家还没有店铺的账号公司"= 看到全部数据(越界方向恰好是少隔离那一侧)。</li>
* <li><b>非超管不许跟着 tab 改口径</b>(spec §4:tab 是视图开关,不是安全边界)。</li>
* </ol>
*/
class ShopDataDuplicateCheckCompanyScopeTest {
private ShopDuplicateCheckSourceMapper mapper;
private ShopDataDuplicateCheckQueryService service;
private ShopDataDuplicateCheckScanService.DuplicateScanView view;
@BeforeEach
void setUp() {
mapper = mock(ShopDuplicateCheckSourceMapper.class);
service = new ShopDataDuplicateCheckQueryService(mapper);
view = TestFixtures.view();
}
@Test
@DisplayName("超管没切公司 tab=全量(null),与接线前逐字一致")
void superAdminWithoutCompanyTabSeesEverything() {
assertThat(service.resolveVisibleShopKeys(1L, true, null)).isNull();
verify(mapper, never()).selectManagedShopNames(any());
verify(mapper, never()).selectShopNamesOwnedBy(anyList());
}
@Test
@DisplayName("超管切到某家公司=只按店铺负责人推,且不再碰分组尺子")
void companyTabSwitchesToTheShopOwnerRuler() {
when(mapper.selectShopNamesOwnedBy(List.of(7L, 8L)))
.thenReturn(Arrays.asList(" ShopA ", "ShopB", " ", null));
when(mapper.selectManagedShopNames(1L)).thenReturn(List.of("ShopZ"));
Set<String> keys = service.resolveVisibleShopKeys(1L, true, List.of(7L, 8L));
// trim + 小写 + 丢空:与主管那一支同一个 normalize,否则交集会因为大小写漏掉整店
assertThat(keys).containsExactly("shopa", "shopb");
verify(mapper, never()).selectManagedShopNames(any());
}
@Test
@DisplayName("空成员集=这家一家店铺都没有:必须是空集合,绝不能是 null(null=全量)")
void emptyMemberSetMeansNoShopsNotEverything() {
Set<String> keys = service.resolveVisibleShopKeys(1L, true, List.of());
assertThat(keys).isNotNull();
assertThat(keys).isEmpty();
// 空列表真喂进 mapper 会产出非法的 IN ()(见 mapperScript 那两支),所以必须在这里就挡住
verify(mapper, never()).selectShopNamesOwnedBy(anyList());
}
@Test
@DisplayName("非超管的可见范围只由分组关系决定,传进来的公司成员集不参与")
void nonSuperKeepsTheGroupBasedView() {
when(mapper.selectManagedShopNames(9L)).thenReturn(List.of("ShopC"));
Set<String> keys = service.resolveVisibleShopKeys(9L, false, List.of(7L));
assertThat(keys).containsExactly("shopc");
verify(mapper, never()).selectShopNamesOwnedBy(anyList());
}
@Test
@DisplayName("分组筛选叠在公司集之后:同组里别家公司的店不许被放回来")
void groupFilterNeverWidensTheCompanySet() {
// 夹具里 GroupA 含 ShopA + ShopB。公司集只给 shopa ⇒ 选 GroupA 也只能看到 shopa。
assertThat(service.withGroupFilter(Set.of("shopa"), view, "GroupA")).containsExactly("shopa");
assertThat(service.withGroupFilter(Set.of(), view, "GroupA")).isEmpty();
// 反向对照:不存在的分组名给出空集——证明这条链真在求交,而不是原样把入参退回来
assertThat(service.withGroupFilter(Set.of("shopa"), view, "NoSuchGroup")).isEmpty();
}
// ------------------------------------------------------------------ 端口
@Test
@DisplayName("端口(店铺数据记录用的那一条)对空/ null 成员集直接给空列表,不落 SQL")
void portGuardsEmptyMemberSet() {
ManagedShopNamesPortAdapter adapter = new ManagedShopNamesPortAdapter(mapper);
assertThat(adapter.selectShopNamesOwnedByMembers(List.of())).isEmpty();
assertThat(adapter.selectShopNamesOwnedByMembers(null)).isEmpty();
verify(mapper, never()).selectShopNamesOwnedBy(anyList());
when(mapper.selectShopNamesOwnedBy(List.of(3L))).thenReturn(List.of("ShopD"));
assertThat(adapter.selectShopNamesOwnedByMembers(List.of(3L))).containsExactly("ShopD");
}
// ------------------------------------------------------- 注解 SQL 真的能解析
/**
* {@code @Select} 里的 {@code <script>} + {@code foreach} 只有运行期才会报错,mock 掉的 mapper
* 一条也测不到。这里把注解原文交给 MyBatis 自己的动态 SQL 引擎跑一遍——
* 破坏点包括:{@code <>} 忘了转义(XML 解析当场抛)、foreach 的 collection 名写错(参数取不到)、
* #{mid} 被写成 ${mid}(占位符数对不上=SQL 注入面)。
*/
@Test
@DisplayName("selectShopNamesOwnedBy 的动态 SQL:两个成员=两个占位符,且字面量仍是参数绑定")
void mapperScriptBindsEveryMemberIdAsParameter() throws Exception {
String sql = boundSqlFor(List.of(7L, 8L)).getSql();
assertThat(sql)
.contains("biz_shop_manage")
.contains("created_by_id IN")
.doesNotContain("<script>")
.doesNotContain("foreach")
.doesNotContain("$");
// 占位符个数=成员个数:写成 ${mid} 会在这里露出来(少一个 ? 而串里多出字面值)
assertThat(sql.chars().filter(c -> c == '?').count()).isEqualTo(2);
assertThat(boundSqlFor(List.of(7L, 8L)).getParameterMappings()).hasSize(2);
}
@Test
@DisplayName("同一支 SQL 对空成员集产出残缺语句(IN 后面什么都没有)——端口那支 return List.of() 是承重的")
void mapperScriptCannotSurviveEmptyMemberSet() throws Exception {
String sql = boundSqlFor(List.of()).getSql();
// 实测这一版 MyBatis 的 foreach 在零元素时连括号都不给,语句就停在 "... created_by_id IN" 上:
// 1064 语法错。所以"空成员=这家没有店铺"必须在 Java 侧兜住,不能把空列表喂进 SQL。
assertThat(sql.trim()).endsWith("created_by_id IN");
assertThat(sql.chars().filter(c -> c == '?').count()).isZero();
}
@Test
@DisplayName("转义后的 <> 在生成的 SQL 里必须是真比较符,不能被吃掉或留成实体")
void mapperScriptKeepsTheNotEmptyPredicate() throws Exception {
String sql = boundSqlFor(List.of(7L)).getSql();
assertThat(sql).contains("<>");
assertThat(sql).doesNotContain("&lt;");
}
private static BoundSql boundSqlFor(List<Long> memberIds) throws Exception {
Method method = ShopDuplicateCheckSourceMapper.class
.getMethod("selectShopNamesOwnedBy", List.class);
String script = String.join(" ", method.getAnnotation(Select.class).value());
Configuration configuration = new MybatisConfiguration();
// 走注解构建器的同一条路径:把这条语句注册进 configuration,再向它要 BoundSql
new MapperAnnotationBuilder(configuration, ShopDuplicateCheckSourceMapper.class)
.parse();
MappedStatement statement = configuration.getMappedStatement(
ShopDuplicateCheckSourceMapper.class.getName() + ".selectShopNamesOwnedBy");
return statement.getBoundSql(Map.of("memberIds", memberIds));
}
}
@@ -230,7 +230,7 @@ class SkipPriceAsinServiceTest {
when(skipPriceAsinMapper.selectList(any())).thenReturn(List.of());
service.page(1, 15, null, null, null, null,
new BigDecimal("10.00"), new BigDecimal("20.00"), null, true);
new BigDecimal("10.00"), new BigDecimal("20.00"), null, true, null);
ArgumentCaptor<Wrapper<SkipPriceAsinEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(skipPriceAsinMapper).selectCount(captor.capture());
@@ -252,7 +252,7 @@ class SkipPriceAsinServiceTest {
when(skipPriceAsinMapper.selectList(any())).thenReturn(List.of());
service.page(1, 15, null, null, null, "DE",
new BigDecimal("15.00"), null, null, true);
new BigDecimal("15.00"), null, null, true, null);
ArgumentCaptor<Wrapper<SkipPriceAsinEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(skipPriceAsinMapper).selectCount(captor.capture());