feat(brandgating): 品牌Gating库后端模块并入管理后台

直连主库既有 biz_brand_gating 表(原独立小网页后台 8090 下线的前置),
六端点挂 /api/admin/brand-gating,权限键 admin_brand_gating,走 admin
第一道门前缀守卫无需额外登记。列表/统计/新增/删除/启停用对齐桌面版
(停用记 disabled_at、恒刷 updated_at);批量导入 { text } 按桌面版
parse_batch 逐条同款解析,去重靠唯一键+批内四键预检。
SQL 账本 115→124、select 账本 78→86,8 条 select 点入 NOT_MIGRATED。
This commit is contained in:
2026-10-23 21:56:45 +08:00
parent 2d408199d6
commit 2c85f47c3b
20 changed files with 1283 additions and 7 deletions
@@ -56,9 +56,10 @@ class MigratedSqlEquivalenceTest {
private static final int LEDGER_SELECTS = 60;
/** 全部 mapper XML 里的 select 总数:账本 60 + TaskImageCache 5 + AsinResultCache 1。 */
/** 66 → 67:会话容忍新增的 {@code AdminUserMapper#countLiveWorkFor} 也是一条 select。 */
// 67 → 78:keywordshare 模块新写 11 条 select,逐条登记进下方 NOT_MIGRATED
// (与 SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 99 → 115)。
private static final int XML_SELECT_TOTAL = 78;
// 67 → 78:keywordshare 模块新写 11 条 select,逐条登记进下方 NOT_MIGRATED。
// 78 → 86:brandgating 模块新写 8 条 select,同样逐条点入
// (与 SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 99 → 115 → 124)。
private static final int XML_SELECT_TOTAL = 86;
/**
* 不是「从注解搬过来」的语句:注解时代没有原文可对撞,等价性这支只能跳过它们。
@@ -82,7 +83,16 @@ class MigratedSqlEquivalenceTest {
"KeywordShareMapper#selectCategoryCounts",
"KeywordShareMapper#selectSubCategoryCounts",
"KeywordShareMapper#selectCategoryL3Counts",
"KeywordShareMapper#selectExistingKeywords");
"KeywordShareMapper#selectExistingKeywords",
// brandgating 模块(品牌Gating库并入管理后台,2026-10-23)新写 8 条 select。
"BrandGatingMapper#countByFilter",
"BrandGatingMapper#selectRows",
"BrandGatingMapper#countAll",
"BrandGatingMapper#countByStatus",
"BrandGatingMapper#countDistinctBrands",
"BrandGatingMapper#countGroupByType",
"BrandGatingMapper#countGroupByCountry",
"BrandGatingMapper#countGroupBySource");
/** 账本 5 列:接口 / 方法 / @Select 种类 / 是否含常量插值 / 注解原文(Java 反转义后那条串)。 */
private static final int LEDGER_COLUMNS = 5;
@@ -72,9 +72,10 @@ class SqlLayeringConventionTest {
// 计次发生在发请求之前(含重试),token 只有响应回来才有读数,合成一条 upsert 就会漏计超时的那次。
// 98 → 99:失败任务重试新增 {@code CollectDataItemMapper#copyItemsForRetry}
// (INSERT ... SELECT 复制明细行),同样登记进 NOT_MIGRATED。
// 99 → 115:keywordshare 模块(五国关键词共享网页化,5 份 XML 16 条)新写语句,
// 11 条 select 逐条登记进 MigratedSqlEquivalenceTest.NOT_MIGRATED(与本格同轮 67 → 78)。
private static final int XML_STATEMENT_TOTAL = 115;
// 99 → 115:keywordshare 模块(五国关键词共享网页化,5 份 XML 16 条)新写语句。
// 115 → 124:brandgating 模块(品牌Gating库并入管理后台,1 份 XML 9 条)新写语句;
// 两批 19 条 select 逐条登记进 MigratedSqlEquivalenceTest.NOT_MIGRATED(67 → 78 → 86)。
private static final int XML_STATEMENT_TOTAL = 124;
/**
* wrapper 里夹带函数级 SQL 的现状("这不是简单单表"的证据),文件名 → 条数:
@@ -0,0 +1,479 @@
package com.nanri.aiimage.modules.brandgating.service;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.brandgating.mapper.BrandGatingMapper;
import com.nanri.aiimage.modules.brandgating.model.dto.BrandGatingAddRequest;
import com.nanri.aiimage.modules.brandgating.model.dto.BrandGatingFilterQuery;
import com.nanri.aiimage.modules.brandgating.model.dto.BrandGatingImportRequest;
import com.nanri.aiimage.modules.brandgating.model.dto.BrandGatingNameCountRow;
import com.nanri.aiimage.modules.brandgating.model.entity.BrandGatingEntity;
import com.nanri.aiimage.modules.brandgating.model.vo.BrandGatingImportResultVo;
import com.nanri.aiimage.modules.brandgating.model.vo.BrandGatingPageVo;
import com.nanri.aiimage.modules.brandgating.model.vo.BrandGatingRowVo;
import com.nanri.aiimage.modules.brandgating.model.vo.BrandGatingStatsVo;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.dao.DuplicateKeyException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* 品牌Gating库 Service 单测:列表筛选/分页归一化、stats 三组分组、新增默认值与唯一键跳过、
* 启停(disabled_at 语义由 XML 契约钉住)、删除、批量导入(照桌面版行格式:正常行/缺字段行/重复行)。
* 另以源码契约测试把 Mapper XML 与控制器的权限键把门钉住。
*/
@ExtendWith(MockitoExtension.class)
class BrandGatingServiceTest {
@Mock
private BrandGatingMapper brandGatingMapper;
private BrandGatingService newService() {
return new BrandGatingService(brandGatingMapper);
}
private static BrandGatingRowVo row(long id, String brand) {
BrandGatingRowVo vo = new BrandGatingRowVo();
vo.setId(id);
vo.setBrand(brand);
vo.setStatus(1);
return vo;
}
private static BrandGatingImportRequest.Item item(String brand, String country, String gatingType,
String asin, String remark) {
BrandGatingImportRequest.Item item = new BrandGatingImportRequest.Item();
item.setBrand(brand);
item.setCountry(country);
item.setGatingType(gatingType);
item.setAsin(asin);
item.setRemark(remark);
return item;
}
// ---------------------------------------------------------------- 列表
@Test
@DisplayName("列表:筛选条件与分页进 Mapper 载体,page/size 归一化(page<1→1、size 缺省 10、上限 200)")
void pageCarriesFilterAndNormalizedPaging() {
when(brandGatingMapper.countByFilter(any(BrandGatingFilterQuery.class))).thenReturn(0L);
when(brandGatingMapper.selectRows(any(BrandGatingFilterQuery.class))).thenReturn(List.of());
newService().page(0L, 1000L, " Anker ", " 英国 ", "品牌gating", "1", "AUTO");
ArgumentCaptor<BrandGatingFilterQuery> captor = ArgumentCaptor.forClass(BrandGatingFilterQuery.class);
verify(brandGatingMapper).selectRows(captor.capture());
BrandGatingFilterQuery filter = captor.getValue();
assertThat(filter.getKeyword()).isEqualTo("Anker");
assertThat(filter.getCountry()).isEqualTo("英国");
assertThat(filter.getGatingType()).isEqualTo("品牌gating");
assertThat(filter.getStatus()).isEqualTo(1);
assertThat(filter.getSource()).isEqualTo("AUTO");
// page=0→1、size=1000→200(上限截断)
assertThat(filter.getOffset()).isZero();
assertThat(filter.getLimit()).isEqualTo(200L);
}
@Test
@DisplayName("列表:缺省分页 = 桌面版口径(page 1、size 10);status 非 0/1(含「全部」)→ 不限")
void pageDefaultsFollowDesktop() {
when(brandGatingMapper.countByFilter(any(BrandGatingFilterQuery.class))).thenReturn(0L);
when(brandGatingMapper.selectRows(any(BrandGatingFilterQuery.class))).thenReturn(List.of());
newService().page(null, null, null, "全部", null, "全部", null);
ArgumentCaptor<BrandGatingFilterQuery> captor = ArgumentCaptor.forClass(BrandGatingFilterQuery.class);
verify(brandGatingMapper).selectRows(captor.capture());
assertThat(captor.getValue().getOffset()).isZero();
assertThat(captor.getValue().getLimit()).isEqualTo(10L);
assertThat(captor.getValue().getStatus()).isNull();
}
@Test
@DisplayName("列表:total 取同条件命中数,行按 Mapper 返回顺序透传(SQL 侧已 ORDER BY id DESC)")
void pageReturnsTotalAndRows() {
when(brandGatingMapper.countByFilter(any(BrandGatingFilterQuery.class))).thenReturn(42L);
when(brandGatingMapper.selectRows(any(BrandGatingFilterQuery.class))).thenReturn(List.of(row(9, "B"), row(3, "A")));
BrandGatingPageVo vo = newService().page(2L, 10L, null, null, null, null, null);
assertThat(vo.getTotal()).isEqualTo(42L);
assertThat(vo.getRows()).extracting(BrandGatingRowVo::getId).containsExactly(9L, 3L);
}
@ParameterizedTest
@ValueSource(strings = {"2", "生效", "abc"})
@DisplayName("列表:status 非法值一律按不限处理(桌面版下拉只有 生效/停用/全部)")
void pageTreatsIllegalStatusAsNoFilter(String status) {
when(brandGatingMapper.countByFilter(any(BrandGatingFilterQuery.class))).thenReturn(0L);
when(brandGatingMapper.selectRows(any(BrandGatingFilterQuery.class))).thenReturn(List.of());
newService().page(1L, 10L, null, null, null, status, null);
verify(brandGatingMapper).selectRows(any(BrandGatingFilterQuery.class));
ArgumentCaptor<BrandGatingFilterQuery> captor = ArgumentCaptor.forClass(BrandGatingFilterQuery.class);
verify(brandGatingMapper).selectRows(captor.capture());
assertThat(captor.getValue().getStatus()).isNull();
}
// ---------------------------------------------------------------- 统计
@Test
@DisplayName("stats:total/active/disabled/brands 与 byType/byCountry/bySource 三组分组透传")
void statsAggregatesAllGroups() {
when(brandGatingMapper.countAll()).thenReturn(100L);
when(brandGatingMapper.countByStatus(1)).thenReturn(80L);
when(brandGatingMapper.countByStatus(0)).thenReturn(20L);
when(brandGatingMapper.countDistinctBrands()).thenReturn(31L);
BrandGatingNameCountRow typeRow = new BrandGatingNameCountRow();
typeRow.setName("品牌gating");
typeRow.setCount(60);
BrandGatingNameCountRow countryRow = new BrandGatingNameCountRow();
countryRow.setName("英国");
countryRow.setCount(50);
BrandGatingNameCountRow sourceRow = new BrandGatingNameCountRow();
sourceRow.setName("MANUAL");
sourceRow.setCount(30);
when(brandGatingMapper.countGroupByType()).thenReturn(List.of(typeRow));
when(brandGatingMapper.countGroupByCountry()).thenReturn(List.of(countryRow));
when(brandGatingMapper.countGroupBySource()).thenReturn(List.of(sourceRow));
BrandGatingStatsVo vo = newService().stats();
assertThat(vo.getTotal()).isEqualTo(100L);
assertThat(vo.getActive()).isEqualTo(80L);
assertThat(vo.getDisabled()).isEqualTo(20L);
assertThat(vo.getBrands()).isEqualTo(31L);
assertThat(vo.getByType()).extracting(BrandGatingNameCountRow::getName).containsExactly("品牌gating");
assertThat(vo.getByCountry()).extracting(BrandGatingNameCountRow::getName).containsExactly("英国");
assertThat(vo.getBySource()).extracting(BrandGatingNameCountRow::getName).containsExactly("MANUAL");
// 桌面版口径:分组计数各查一遍,且 active/disabled 分别按 1/0 数
verify(brandGatingMapper).countByStatus(1);
verify(brandGatingMapper).countByStatus(0);
}
// ---------------------------------------------------------------- 新增
@Test
@DisplayName("新增:缺省字段落桌面版同款默认(asin/shopName→NULL、country=全部、type=品牌gating、source=MANUAL、remark=空串)")
void addAppliesDesktopDefaults() {
BrandGatingAddRequest request = new BrandGatingAddRequest();
request.setBrand(" Anker ");
var result = newService().add(request);
assertThat(result.getAdded()).isEqualTo(1);
ArgumentCaptor<BrandGatingEntity> captor = ArgumentCaptor.forClass(BrandGatingEntity.class);
verify(brandGatingMapper).insert(captor.capture());
BrandGatingEntity entity = captor.getValue();
assertThat(entity.getBrand()).isEqualTo("Anker");
assertThat(entity.getAsin()).isNull();
assertThat(entity.getShopName()).isNull();
assertThat(entity.getCountry()).isEqualTo("全部");
assertThat(entity.getGatingType()).isEqualTo("品牌gating");
assertThat(entity.getSource()).isEqualTo("MANUAL");
assertThat(entity.getRemark()).isEmpty();
// created_at/updated_at 由库默认维护:INSERT 不显式写时间
assertThat(entity.getCreatedAt()).isNull();
assertThat(entity.getUpdatedAt()).isNull();
}
@Test
@DisplayName("新增:请求显式给 source/shopName/asin 时按请求值落库")
void addKeepsExplicitFields() {
BrandGatingAddRequest request = new BrandGatingAddRequest();
request.setBrand("Anker");
request.setAsin("B0ABCDEFG");
request.setCountry("德国");
request.setGatingType("类目gating");
request.setSource("AUTO");
request.setShopName("店铺A");
request.setRemark("备注");
newService().add(request);
ArgumentCaptor<BrandGatingEntity> captor = ArgumentCaptor.forClass(BrandGatingEntity.class);
verify(brandGatingMapper).insert(captor.capture());
assertThat(captor.getValue().getAsin()).isEqualTo("B0ABCDEFG");
assertThat(captor.getValue().getCountry()).isEqualTo("德国");
assertThat(captor.getValue().getGatingType()).isEqualTo("类目gating");
assertThat(captor.getValue().getSource()).isEqualTo("AUTO");
assertThat(captor.getValue().getShopName()).isEqualTo("店铺A");
assertThat(captor.getValue().getRemark()).isEqualTo("备注");
}
@Test
@DisplayName("新增:品牌为空(含纯空白)→ 400「品牌不能为空」,不动库")
void addRejectsBlankBrand() {
BrandGatingAddRequest request = new BrandGatingAddRequest();
request.setBrand(" ");
assertThatThrownBy(() -> newService().add(request))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("品牌不能为空")
.extracting(e -> ((BusinessException) e).getCode())
.isEqualTo(400);
verify(brandGatingMapper, never()).insert(any(BrandGatingEntity.class));
}
@Test
@DisplayName("新增:撞唯一键(已存在同口径行)→ added=0,不抛错(桌面版 add_gating 返回 False 的同语义)")
void addReturnsZeroOnDuplicate() {
BrandGatingAddRequest request = new BrandGatingAddRequest();
request.setBrand("Anker");
when(brandGatingMapper.insert(any(BrandGatingEntity.class)))
.thenThrow(new DuplicateKeyException("dup"));
var result = newService().add(request);
assertThat(result.getAdded()).isZero();
}
// ---------------------------------------------------------------- 启停 / 删除
@Test
@DisplayName("启停:status 0/1 透传 Mapper(disabled_at 语义由 XML 契约钉住),返回实际更新数")
void updateStatusDelegatesToMapper() {
when(brandGatingMapper.updateStatus(7L, 0)).thenReturn(1);
when(brandGatingMapper.updateStatus(8L, 1)).thenReturn(0);
assertThat(newService().updateStatus(7L, 0).getUpdated()).isEqualTo(1);
assertThat(newService().updateStatus(8L, 1).getUpdated()).isZero();
verify(brandGatingMapper).updateStatus(7L, 0);
verify(brandGatingMapper).updateStatus(8L, 1);
}
@Test
@DisplayName("启停:status 非 0/1 → 400,不动库")
void updateStatusRejectsIllegalValue() {
assertThatThrownBy(() -> newService().updateStatus(7L, 2))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("status");
assertThatThrownBy(() -> newService().updateStatus(7L, null))
.isInstanceOf(BusinessException.class);
verify(brandGatingMapper, never()).updateStatus(any(), eq(2));
}
@Test
@DisplayName("删除:透传 Mapper,返回实际删除数(0=该 id 不存在)")
void deleteReturnsAffectedRows() {
when(brandGatingMapper.deleteById(7L)).thenReturn(1);
when(brandGatingMapper.deleteById(99L)).thenReturn(0);
assertThat(newService().delete(7L).getDeleted()).isEqualTo(1);
assertThat(newService().delete(99L).getDeleted()).isZero();
}
// ---------------------------------------------------------------- 批量导入:文本解析(照桌面版 parse_batch)
@Test
@DisplayName("导入解析:正常行全字段按 品牌/国家/类型/ASIN/备注 切列")
void parseBatchTextKeepsAllFiveFields() {
List<BrandGatingImportRequest.Item> items =
BrandGatingService.parseBatchText("Anker,英国,品牌gating,B0ABCDEFG,跟卖重灾区");
assertThat(items).hasSize(1);
assertThat(items.get(0).getBrand()).isEqualTo("Anker");
assertThat(items.get(0).getCountry()).isEqualTo("英国");
assertThat(items.get(0).getGatingType()).isEqualTo("品牌gating");
assertThat(items.get(0).getAsin()).isEqualTo("B0ABCDEFG");
assertThat(items.get(0).getRemark()).isEqualTo("跟卖重灾区");
}
@Test
@DisplayName("导入解析:缺字段行落桌面版默认(国家=全部、类型=品牌gating、ASIN/备注空),空段丢弃、第 5 列之后丢弃")
void parseBatchTextAppliesDefaultsAndDropsExtraColumns() {
List<BrandGatingImportRequest.Item> items = BrandGatingService.parseBatchText(
"Anker\nAnker2,德国\nAnker3,法国,类目gating\n"
+ "Anker4,西班牙,类目gating,B09ZZZZZZZ,多余列1,多余列2\n"
+ "Anker5,,英国");
assertThat(items).hasSize(5);
assertThat(items.get(0).getCountry()).isEqualTo("全部");
assertThat(items.get(0).getGatingType()).isEqualTo("品牌gating");
assertThat(items.get(0).getAsin()).isEmpty();
assertThat(items.get(1).getCountry()).isEqualTo("德国");
assertThat(items.get(1).getGatingType()).isEqualTo("品牌gating");
assertThat(items.get(2).getGatingType()).isEqualTo("类目gating");
assertThat(items.get(2).getAsin()).isEmpty();
assertThat(items.get(3).getCountry()).isEqualTo("西班牙");
assertThat(items.get(3).getGatingType()).isEqualTo("类目gating");
assertThat(items.get(3).getAsin()).isEqualTo("B09ZZZZZZZ");
assertThat(items.get(3).getRemark()).isEqualTo("多余列1");
// 空段被丢弃(桌面版 filter p.strip() 同口径):Anker5 行的 ASIN 位空掉后,英国顶上来当国家
assertThat(items.get(4).getCountry()).isEqualTo("英国");
assertThat(items.get(4).getGatingType()).isEqualTo("品牌gating");
}
@Test
@DisplayName("导入解析:中英文逗号/分号/制表符都切列,各段去空白、空段丢弃;BOM 与 # 注释行/空行跳过")
void parseBatchTextSplitsOnAllSeparatorsAndSkipsNoiseLines() {
String text = "\uFEFFAnker\t英国;品牌gating\n"
+ "# 注释行\n"
+ " \n"
+ " Anker2 , 德国 ,类目gating, B0X ,备注带空格 \n"
+ ",,,\n";
List<BrandGatingImportRequest.Item> items = BrandGatingService.parseBatchText(text);
assertThat(items).hasSize(2);
assertThat(items.get(0).getBrand()).isEqualTo("Anker");
assertThat(items.get(0).getCountry()).isEqualTo("英国");
assertThat(items.get(0).getGatingType()).isEqualTo("品牌gating");
assertThat(items.get(1).getBrand()).isEqualTo("Anker2");
assertThat(items.get(1).getCountry()).isEqualTo("德国");
assertThat(items.get(1).getGatingType()).isEqualTo("类目gating");
assertThat(items.get(1).getAsin()).isEqualTo("B0X");
assertThat(items.get(1).getRemark()).isEqualTo("备注带空格");
}
@Test
@DisplayName("导入解析:null/空文本 → 空清单")
void parseBatchTextHandlesBlankInput() {
assertThat(BrandGatingService.parseBatchText(null)).isEmpty();
assertThat(BrandGatingService.parseBatchText(" \n # x")).isEmpty();
}
// ---------------------------------------------------------------- 批量导入:写库与去重
@Test
@DisplayName("导入写库:逐条按单条新增同语义落库(source=MANUAL、shopName=NULL、缺省字段落默认)")
void importWritesRowsWithSameSemanticsAsAdd() {
BrandGatingImportRequest request = new BrandGatingImportRequest();
request.setText("Anker,英国\nAnker2,德国,类目gating,B09ZZZZZZZ,备注");
BrandGatingImportResultVo result = newService().importRows(request);
assertThat(result.getAdded()).isEqualTo(2);
assertThat(result.getSkipped()).isZero();
ArgumentCaptor<BrandGatingEntity> captor = ArgumentCaptor.forClass(BrandGatingEntity.class);
verify(brandGatingMapper, times(2)).insert(captor.capture());
List<BrandGatingEntity> rows = captor.getAllValues();
assertThat(rows.get(0).getBrand()).isEqualTo("Anker");
assertThat(rows.get(0).getCountry()).isEqualTo("英国");
assertThat(rows.get(0).getGatingType()).isEqualTo("品牌gating");
assertThat(rows.get(0).getAsin()).isNull();
assertThat(rows.get(0).getSource()).isEqualTo("MANUAL");
assertThat(rows.get(0).getShopName()).isNull();
assertThat(rows.get(1).getRemark()).isEqualTo("备注");
}
@Test
@DisplayName("导入去重:批内重复行(同品牌+国家+类型+ASIN)只写第一条,其余计入 skipped")
void importSkipsInBatchDuplicates() {
BrandGatingImportRequest request = new BrandGatingImportRequest();
request.setText("Anker,英国\nAnker,英国\nAnker,英国,品牌gating,B0X\nAnker,英国,品牌gating,B0X\nAnker,德国");
BrandGatingImportResultVo result = newService().importRows(request);
assertThat(result.getAdded()).isEqualTo(3);
assertThat(result.getSkipped()).isEqualTo(2);
verify(brandGatingMapper, times(3)).insert(any(BrandGatingEntity.class));
}
@Test
@DisplayName("导入去重:撞库内唯一键(已存在同口径行)计入 skipped,不中断后续行")
void importSkipsDbDuplicatesAndContinues() {
BrandGatingImportRequest request = new BrandGatingImportRequest();
request.setText("Anker,英国\nAnker2,德国");
when(brandGatingMapper.insert(any(BrandGatingEntity.class)))
.thenThrow(new DuplicateKeyException("dup"))
.thenReturn(1);
BrandGatingImportResultVo result = newService().importRows(request);
assertThat(result.getAdded()).isEqualTo(1);
assertThat(result.getSkipped()).isEqualTo(1);
}
@Test
@DisplayName("导入 items 直传:缺省字段同语义落默认,空品牌行跳过")
void importAcceptsDirectItems() {
BrandGatingImportRequest request = new BrandGatingImportRequest();
request.setItems(List.of(
item("Anker", "英国", null, "B0X", null),
item(" ", "德国", null, null, null)));
BrandGatingImportResultVo result = newService().importRows(request);
assertThat(result.getAdded()).isEqualTo(1);
assertThat(result.getSkipped()).isEqualTo(1);
ArgumentCaptor<BrandGatingEntity> captor = ArgumentCaptor.forClass(BrandGatingEntity.class);
verify(brandGatingMapper).insert(captor.capture());
assertThat(captor.getValue().getGatingType()).isEqualTo("品牌gating");
assertThat(captor.getValue().getRemark()).isEmpty();
}
@Test
@DisplayName("导入:text 优先于 items;两者都缺 → 400「导入内容为空」,不动库")
void importPrefersTextAndRejectsEmptyPayload() {
BrandGatingImportRequest both = new BrandGatingImportRequest();
both.setText("Anker,英国");
both.setItems(List.of(item("Anker2", "德国", null, null, null)));
assertThat(newService().importRows(both).getAdded()).isEqualTo(1);
verify(brandGatingMapper, times(1)).insert(any(BrandGatingEntity.class));
assertThatThrownBy(() -> newService().importRows(new BrandGatingImportRequest()))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("导入内容为空");
assertThatThrownBy(() -> newService().importRows(null))
.isInstanceOf(BusinessException.class);
verify(brandGatingMapper, times(1)).insert(any(BrandGatingEntity.class));
}
// ---------------------------------------------------------------- 契约钉子(SQL / 权限键)
@Test
@DisplayName("Mapper XML 契约:ORDER BY id DESC、#{} 占位符禁 ${}、启停的 disabled_at/updated_at 语义、统计分组只数生效行且国家按 count DESC")
void mapperXmlKeepsSqlContract() throws Exception {
String xml = Files.readString(
Path.of("src/main/resources/mapper/brandgating/BrandGatingMapper.xml"), StandardCharsets.UTF_8);
// 列表:桌面版 list_gating 的排序与分页
assertThat(xml).contains("ORDER BY id DESC").contains("LIMIT #{f.offset}, #{f.limit}");
// 严禁拼接筛选值
assertThat(xml).doesNotContain("${");
// 关键词:brand/asin 双列 LIKE(桌面版同口径)
assertThat(xml).contains("brand LIKE CONCAT('%', #{f.keyword}, '%')")
.contains("asin LIKE CONCAT('%', #{f.keyword}, '%')");
// 启停:status=1 清 disabled_at、=0 记 NOW(),都刷 updated_at=NOW()(桌面版 set_status_gating)
assertThat(xml).contains("disabled_at = IF(#{status} = 1, NULL, NOW())").contains("updated_at = NOW()");
// 统计:分组只数生效行(status=1),国家按 count DESC(桌面版 by_country)
assertThat(xml).contains("WHERE status = 1").doesNotContain("WHERE status = 1 AND");
assertThat(xml).contains("ORDER BY count DESC");
// 「全部」哨兵不过滤(桌面版 country != "全部" 同口径)
assertThat(xml).contains("f.country != '全部'").contains("f.gatingType != '全部'").contains("f.source != '全部'");
}
@Test
@DisplayName("控制器契约:权限键 admin_brand_gating、逐端点 requireUser + requireConsolePageAccess 把门")
void controllerGatesEveryEndpointWithPermissionKey() throws Exception {
String source = Files.readString(Path.of(
"src/main/java/com/nanri/aiimage/modules/brandgating/controller/BrandGatingController.java"),
StandardCharsets.UTF_8);
assertThat(source).contains("PERMISSION_KEY = \"admin_brand_gating\"");
assertThat(source).contains("adminAuthSupport.requireUser(request)");
assertThat(source).contains("requireConsolePageAccess(operator, DENIAL_MESSAGE, PERMISSION_KEY)");
// 6 个端点方法都必须先过把门助手
long gated = source.split("requireBrandGatingAccess\\(request\\);", -1).length - 1;
assertThat(gated).isEqualTo(6);
}
}