feat(账号到期+公司超管): 级联过期判定、过期停任务巡检与两端续费提醒弹窗

需求两条:站点超管可开设其他公司的超级管理员(站点超管看全站、公司超管只看本公司、
组内管理员仍只看本组);账号要有过期时间,管理员过期后名下普通账户一并停用、
正在跑的任务也要停掉。落库只有 users.expires_at(V146,NULL=永不过期),级联一律现算,
不写"上级过期就把下级置成过期"那种续费也救不回来的数据。

- AccountExpiryService:生效到期 = min(自身, 本公司公司超管, 成员表组长, 创建人)。
  登录拦 403(文案给续费提示)、每次请求鉴权拦 401(前端按下线踢回登录页),super_admin
  永不适用。级联口径与数据可见范围同源(成员表基本未用、实际按 created_by_id 派生)。
- ExpiredAccountTaskStopService:每分钟把过期账号(含级联成员)名下 biz_file_task
  PENDING/SCHEDULED/RUNNING → FAILED,含未领取的 PENDING(防内部通道继续派发)。原因文案
  刻意不以「客户端异常中断」开头,否则会被 TaskResumeService 自动复活。品牌采集与跟价循环
  不在那张表上,经 ExpiredAccountTaskStopSpi 由各自模块停:品牌 pending/running→cancelled
  且 UPDATE 的 WHERE 二次核对状态(抢到行后被客户端推进成完成的行不得误杀),跟价循环只置
  stop_requested=1、沿用用户点「停止循环」那条收尾路径,绝不动 status。任务心跳接口保持匿名
  不走 requireUser,所以过期账号的客户端仍能拿到 alive=false 协作停止。
- 角色 company_super_admin:由站点超管开设(唯一要显式选公司的建号场景),建号/授菜单/改用户/
  看数据四条链路都按"本公司"收口;公司超管之间、以及公司超管与站点超管互相碰不得。
- 续费提醒:剩余 <5 天在数富后台与用户端弹窗,只能收起不能关闭(无关闭按钮,收起态是右下角
  浮标),续费到 ≥5 天自动消失。后台读 /api/admin/current-user 的 expiresAt/daysToExpire;
  用户端无 Pinia,走 localStorage 的 account_expires_at(登录/check_login 落键、被顶下线清键,
  换账号不残留)。只反映账号自身到期,弹窗不做任何级联推断。
- V146 撞掉了 V145 那批的一条护栏:它按"db/ 里不许出现 V146__ 前缀"编死号位,被一条正常的
  前向迁移占用就红。改成钉动作——剥注释后的可执行 SQL 不得写 flyway_schema_history(回滚
  一律是扫描路径外的人工补丁),并把盘点文档改 V146 时丢掉的 V145 文件名补回去。

验证(本会话亲跑,不是转述):后端定向 14 类 123/0(同一轮 mvn 里连批次③的 4 类 53 例、以及既有 ShopDataCrawl/SimilarAsin 两条回归对照 21 例一起跑,合计 197 例 0 红);admin-frontend-vue 本批定向 44/0(弹窗 7 +
公司建号/列表/入口/日期默认 21 + 角色 task-48/task-251 16),全量 1726 例里那 1 支红是另一条
会话刻意留的「公司 tab 接线缺口」尺子(点名 admin_task_center 等 6 页,与本批无关);
frontend-vue 弹窗 9/0、全量 710/0。变异自证两批共 34 点:弹窗语义 16 点全杀(阈值 5、只能收起
不能关闭、挂载点含"注释掉挂载"、落键/清键链路),本批 SPI+迁移护栏 17 点全杀(含 G2 反向:
前向迁移只在注释里提 flyway_schema_history 必须照样绿),注入文件还原 dirty=0、探针残留 0。
This commit is contained in:
2026-10-05 11:51:33 +08:00
parent 265f31681f
commit 95e2318c42
62 changed files with 2866 additions and 112 deletions
@@ -100,4 +100,32 @@ class AdminConsoleCurrentUserCompanyTest {
.containsEntry("companyName", "")
.containsEntry("username", "op");
}
/**
* 续费提醒弹窗(V146)的数据源:admin-frontend-vue 的 {@code components/ExpiryNotice.vue}
* 直接读 store 里 user 的 {@code daysToExpire/expiresAt},没有映射层也没有本地兜底计算。
* 键名拼错或格式化改了,表现是「快到期了界面一声不响」——不报错,只能由用例盯着。
*/
@Test
@DisplayName("current-user 带 expiresAt(yyyy-MM-dd HH:mm)与 daysToExpire(floor 整天)")
void currentUserCarriesExpiryFieldsForTheRenewalNotice() {
operator.setExpiresAt(java.time.LocalDateTime.now().plusDays(4).plusHours(12));
assertThat(item())
.containsKeys("expiresAt", "daysToExpire")
.containsEntry("daysToExpire", 4L);
assertThat((String) item().get("expiresAt"))
.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}");
}
@Test
@DisplayName("永不过期的账号:两个键照样写、值为 null,前端按 null 一律不弹")
void accountWithoutExpiryStillWritesBothKeysAsNull() {
operator.setExpiresAt(null);
assertThat(item())
.containsKeys("expiresAt", "daysToExpire")
.containsEntry("expiresAt", null)
.containsEntry("daysToExpire", null);
}
}
@@ -0,0 +1,251 @@
package com.nanri.aiimage.modules.admin.service;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.admin.model.dto.AdminUserCreateRequest;
import com.nanri.aiimage.modules.admin.model.dto.AdminUserUpdateRequest;
import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
import com.nanri.aiimage.modules.company.service.CompanyService;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.time.LocalDateTime;
import java.util.List;
import static org.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.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* 公司超级管理员角色(2026-10-05)与管理员到期设置(V146)的服务层口径钉。
* 镜像 Java 约束:公司超管由站点超管开设;公司超管可在本公司建管理员/普通账号;
* 到期时间谁可编辑目标就谁可设置,格式不对必须报错而不是静默归「永不过期」。
*/
class AdminUserServiceCompanySuperAdminTest {
private AdminUserMapper userMapper;
private WerkzeugPasswordEncoder passwordEncoder;
private AdminAuthSupport authSupport;
private PermissionMenuService permissionService;
private CompanyService companyService;
private AdminUserService service;
@BeforeEach
void setUp() {
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
AdminUserEntity.class);
userMapper = mock(AdminUserMapper.class);
passwordEncoder = mock(WerkzeugPasswordEncoder.class);
authSupport = mock(AdminAuthSupport.class);
permissionService = mock(PermissionMenuService.class);
companyService = mock(CompanyService.class);
service = new AdminUserService(userMapper, passwordEncoder, authSupport, permissionService,
mock(UserApiSecretService.class), companyService);
when(passwordEncoder.hash(any())).thenReturn("hashed");
when(permissionService.hasAnyAdminMenu(any(), any())).thenReturn(true);
}
// ---------- 建号 ----------
@Test
void superAdminCreatesCompanySuperAdminInTargetCompanyWithExpiry() {
AdminUserEntity operator = user(1L, "super_admin", 1L, null);
AdminUserCreateRequest request = new AdminUserCreateRequest();
request.setUsername("boss-b");
request.setPassword("secret1");
request.setRole("company_super_admin");
request.setCompanyId(2L);
request.setExpiresAt("2026-12-31 23:59");
when(authSupport.currentRole(operator)).thenReturn("super_admin");
service.createUser(operator, request);
ArgumentCaptor<AdminUserEntity> captor = ArgumentCaptor.forClass(AdminUserEntity.class);
verify(userMapper).insert(captor.capture());
AdminUserEntity saved = captor.getValue();
assertThat(saved.getRole()).isEqualTo("company_super_admin");
assertThat(saved.getIsAdmin()).isEqualTo(1);
assertThat(saved.getCompanyId()).isEqualTo(2L);
assertThat(saved.getCreatedById()).isEqualTo(1L);
assertThat(saved.getExpiresAt()).isEqualTo(LocalDateTime.of(2026, 12, 31, 23, 59));
verify(companyService).requireActive(2L);
}
@Test
void companySuperAdminCreatesAdminInOwnCompany() {
// helper 签名:user(id, role, companyId, createdById) —— 公司超管挂公司 2
AdminUserEntity operator = user(9L, "company_super_admin", 2L, null);
AdminUserCreateRequest request = new AdminUserCreateRequest();
request.setUsername("team-lead");
request.setPassword("secret1");
request.setRole("admin");
when(authSupport.currentRole(operator)).thenReturn("company_super_admin");
service.createUser(operator, request);
ArgumentCaptor<AdminUserEntity> captor = ArgumentCaptor.forClass(AdminUserEntity.class);
verify(userMapper).insert(captor.capture());
assertThat(captor.getValue().getRole()).isEqualTo("admin");
assertThat(captor.getValue().getCompanyId()).isEqualTo(2L);
assertThat(captor.getValue().getCreatedById()).isEqualTo(9L);
}
@Test
void plainAdminStillCannotCreateAdmin() {
AdminUserEntity operator = user(10L, "admin", 1L, 1L);
AdminUserCreateRequest request = new AdminUserCreateRequest();
request.setUsername("someone");
request.setPassword("secret1");
request.setRole("admin");
when(authSupport.currentRole(operator)).thenReturn("admin");
assertThatThrownBy(() -> service.createUser(operator, request))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("公司超级管理员")
.hasMessageContaining("管理员");
}
@Test
void companySuperAdminCannotMintAnotherCompanySuperAdmin() {
AdminUserEntity operator = user(9L, "company_super_admin", 1L, 2L);
AdminUserCreateRequest request = new AdminUserCreateRequest();
request.setUsername("rival-boss");
request.setPassword("secret1");
request.setRole("company_super_admin");
request.setCompanyId(3L);
when(authSupport.currentRole(operator)).thenReturn("company_super_admin");
assertThatThrownBy(() -> service.createUser(operator, request))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("只有超级管理员可以创建公司超级管理员");
}
@Test
void badExpiryFormatIsRejectedLoudly() {
AdminUserEntity operator = user(1L, "super_admin", 1L, null);
AdminUserCreateRequest request = new AdminUserCreateRequest();
request.setUsername("someone");
request.setPassword("secret1");
request.setRole("admin");
request.setExpiresAt("12/31/2026");
when(authSupport.currentRole(operator)).thenReturn("super_admin");
assertThatThrownBy(() -> service.createUser(operator, request))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("到期时间格式不正确");
}
// ---------- 列表 ----------
@Test
void companySuperAdminListsOwnCompanyWithoutSiteSuperAdmin() {
AdminUserEntity operator = user(9L, "company_super_admin", 2L, null);
when(authSupport.currentRole(operator)).thenReturn("company_super_admin");
when(userMapper.selectCount(any())).thenReturn(0L);
when(userMapper.selectList(any())).thenReturn(List.of());
service.listUsers(operator, 1, 15, null, null, null, null);
ArgumentCaptor<LambdaQueryWrapper<AdminUserEntity>> captor =
ArgumentCaptor.forClass(LambdaQueryWrapper.class);
verify(userMapper).selectCount(captor.capture());
// 先碰一次 SqlSegment 才会铺出参数(MP 惯例)
captor.getValue().getSqlSegment();
assertThat(captor.getValue().getParamNameValuePairs().values()).contains(2L);
}
// ---------- 编辑 ----------
@Test
void siteSuperAdminRenewsCompanySuperAdminExpiryWithoutTouchingRole() {
AdminUserEntity operator = user(1L, "super_admin", 1L, null);
AdminUserEntity target = user(9L, "company_super_admin", 1L, 2L);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
when(userMapper.selectById(9L)).thenReturn(target);
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
request.setExpiresAt("2027-01-31 00:00");
service.updateUser(operator, 9L, request);
ArgumentCaptor<LambdaUpdateWrapper<AdminUserEntity>> captor =
ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
verify(userMapper).update(org.mockito.ArgumentMatchers.isNull(), captor.capture());
String sqlSet = captor.getValue().getSqlSet();
assertThat(sqlSet).contains("expires_at");
assertThat(sqlSet).doesNotContain("role");
assertThat(sqlSet).doesNotContain("is_admin");
}
@Test
void clearingExpiryWritesNull() {
AdminUserEntity operator = user(1L, "super_admin", 1L, null);
AdminUserEntity target = user(9L, "company_super_admin", 1L, 2L);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
when(userMapper.selectById(9L)).thenReturn(target);
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
request.setExpiresAt("");
service.updateUser(operator, 9L, request);
ArgumentCaptor<LambdaUpdateWrapper<AdminUserEntity>> captor =
ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
verify(userMapper).update(org.mockito.ArgumentMatchers.isNull(), captor.capture());
assertThat(captor.getValue().getSqlSet()).contains("expires_at");
}
@Test
void companySuperAdminCannotEditCompanySuperAdminTarget() {
AdminUserEntity operator = user(9L, "company_super_admin", 1L, 2L);
AdminUserEntity target = user(11L, "company_super_admin", 1L, 2L);
when(authSupport.currentRole(operator)).thenReturn("company_super_admin");
when(userMapper.selectById(11L)).thenReturn(target);
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
request.setPassword("secret1");
assertThatThrownBy(() -> service.updateUser(operator, 11L, request))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("只有超级管理员可以修改公司超级管理员");
}
@Test
void companySuperAdminCannotDeleteCompanySuperAdminTarget() {
AdminUserEntity operator = user(9L, "company_super_admin", 1L, 2L);
AdminUserEntity target = user(11L, "company_super_admin", 1L, 2L);
when(authSupport.currentRole(operator)).thenReturn("company_super_admin");
when(userMapper.selectById(11L)).thenReturn(target);
assertThatThrownBy(() -> service.deleteUser(operator, 11L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("只有超级管理员可以删除公司超级管理员");
}
// ---------- helpers ----------
private static AdminUserEntity user(Long id, String role, Long companyId, Long createdById) {
AdminUserEntity user = new AdminUserEntity();
user.setId(id);
user.setUsername("u" + id);
user.setRole(role);
user.setIsAdmin(1);
user.setCompanyId(companyId);
user.setCreatedById(createdById);
return user;
}
}
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.auth.service;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.security.AccountExpiryService;
import com.nanri.aiimage.common.security.AuthProperties;
import com.nanri.aiimage.common.security.JwtService;
import com.nanri.aiimage.modules.auth.mapper.LoginUserMapper;
@@ -57,7 +58,8 @@ class AuthServiceCompanyTest {
when(authProperties.isSingleDeviceEnabled()).thenReturn(false);
when(jwtService.ttlSeconds()).thenReturn(604800L);
service = new AuthService(loginUserMapper, passwordEncoder, jwtService,
mock(PermissionMenuService.class), authProperties, companyService);
mock(PermissionMenuService.class), authProperties, companyService,
mock(AccountExpiryService.class));
}
private LoginUserEntity user(Long companyId) {
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.auth.service;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.security.AccountExpiryService;
import com.nanri.aiimage.common.security.AuthProperties;
import com.nanri.aiimage.modules.auth.mapper.LoginUserMapper;
import com.nanri.aiimage.modules.auth.model.dto.LoginRequest;
@@ -158,7 +159,8 @@ class AuthServiceTest {
when(authProperties.isSingleDeviceEnabled()).thenReturn(singleDeviceEnabled);
when(jwtService.ttlSeconds()).thenReturn(604800L);
AuthService service = new AuthService(loginUserMapper, passwordEncoder, jwtService,
permissionMenuService, authProperties, mock(CompanyService.class));
permissionMenuService, authProperties, mock(CompanyService.class),
mock(AccountExpiryService.class));
return new Fixture(service, loginUserMapper, passwordEncoder, jwtService);
}
@@ -0,0 +1,165 @@
package com.nanri.aiimage.modules.brand.service;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.modules.brand.mapper.BrandCrawlTaskMapper;
import com.nanri.aiimage.modules.brand.model.entity.BrandCrawlTaskEntity;
import com.nanri.aiimage.modules.task.service.ExpiredAccountTaskStopService;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/**
* 品牌采集任务的「过期即停」实现口径钉(V146 的 SPI 一侧)。
*
* <p>巡检主类那份用例只用了假 SPI,所以这里补真实现的两条边界:
* <b>该圈的圈到</b>——只有这批用户名下 pending/running 的行进入 SELECT 与 UPDATE;
* <b>不该碰的不碰</b>——已完成的行不得被改写(UPDATE 的 WHERE 二次核对状态,抢到行后状态被
* 客户端推进也不会误杀),且只写 status/error_message 两列,不碰结果与进度。</p>
*/
class BrandTaskExpiredStopSpiImplTest {
private static final String REASON = ExpiredAccountTaskStopService.STOP_REASON;
private static final Pattern WHERE_PARAM = Pattern.compile("#\\{ew\\.paramNameValuePairs\\.(\\w+)}");
private BrandCrawlTaskMapper mapper;
private BrandTaskExpiredStopSpiImpl spi;
@BeforeEach
void setUp() {
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
BrandCrawlTaskEntity.class);
mapper = mock(BrandCrawlTaskMapper.class);
spi = new BrandTaskExpiredStopSpiImpl(mapper);
}
@Test
@DisplayName("moduleType 固定 BRAND:巡检日志按它归因,改名等于丢掉归因")
void moduleTypeIsTheBrandKey() {
assertThat(spi.moduleType()).isEqualTo("BRAND");
}
@Test
@DisplayName("没有过期用户:不查也不写(null 与空集一样短路)")
void emptyUserScopeTouchesNothing() {
assertThat(spi.stopActiveTasks(List.of(), REASON)).isZero();
assertThat(spi.stopActiveTasks(null, REASON)).isZero();
verifyNoInteractions(mapper);
}
@Test
@DisplayName("SELECT 只圈这批用户名下的 pending/running,且带批量上限")
void selectionIsScopedToTheseUsersAndOnlyActiveStates() {
when(mapper.selectList(any())).thenReturn(List.of(brandTask(11L), brandTask(12L)));
when(mapper.update(any(), any())).thenReturn(2);
spi.stopActiveTasks(List.of(7L, 8L), REASON);
LambdaQueryWrapper<BrandCrawlTaskEntity> query = captureQuery();
assertThat(query.getSqlSegment()).contains("user_id").contains("status").contains("limit 500");
assertThat(query.getParamNameValuePairs().values())
.contains(7L, 8L, "pending", "running");
// 已完成/已取消的状态不许进集合:否则过期巡检会把历史行刷成 cancelled
assertThat(query.getParamNameValuePairs().values())
.doesNotContain("success", "completed", "failed", "cancelled");
}
@Test
@DisplayName("UPDATE 按 id 收口并二次核对 pending/running,SET 只写 status/error_message")
void updateCancelsOnlyRowsStillActiveAndWritesOnlyTwoColumns() {
when(mapper.selectList(any())).thenReturn(List.of(brandTask(11L)));
when(mapper.update(any(), any())).thenReturn(1);
spi.stopActiveTasks(List.of(7L), REASON);
LambdaUpdateWrapper<BrandCrawlTaskEntity> update = captureUpdate();
assertThat(update.getSqlSet()).contains("status").contains("error_message")
.doesNotContain("result_paths", "progress_current", "progress_total", "user_id");
assertThat(update.getParamNameValuePairs().values())
.contains("cancelled", REASON);
List<Object> where = whereValues(update);
assertThat(where).contains("pending", "running");
// WHERE 里出现 cancelled/success 意味着"把已终态的行再刷一遍",行数与归因都会失真
assertThat(where).doesNotContain("cancelled", "success", "completed", "failed");
assertThat(update.getSqlSegment()).contains("id").contains("status");
}
@Test
@DisplayName("停止原因照原样透传:不得以「客户端异常中断」开头,否则被自动续跑复活")
void reasonIsPassedThroughUnchangedAndStaysNonResumable() {
when(mapper.selectList(any())).thenReturn(List.of(brandTask(11L)));
when(mapper.update(any(), any())).thenReturn(1);
spi.stopActiveTasks(List.of(7L), REASON);
assertThat(captureUpdate().getParamNameValuePairs().values()).contains(REASON);
assertThat(REASON).doesNotStartWith("客户端异常中断");
}
@Test
@DisplayName("名下没有活跃品牌任务:零写库、返回 0(巡检据此决定打不打日志)")
void nothingActiveMeansNoUpdateAndZero() {
when(mapper.selectList(any())).thenReturn(List.of());
assertThat(spi.stopActiveTasks(List.of(7L), REASON)).isZero();
org.mockito.Mockito.verify(mapper, org.mockito.Mockito.never()).update(any(), any());
}
@Test
@DisplayName("返回值 = mapper 实际影响行数,供巡检汇总")
void affectedRowsComeBackFromMapper() {
when(mapper.selectList(any())).thenReturn(List.of(brandTask(1L), brandTask(2L), brandTask(3L)));
when(mapper.update(any(), any())).thenReturn(3);
assertThat(spi.stopActiveTasks(List.of(7L), REASON)).isEqualTo(3);
}
// ---------- helpers ----------
private static BrandCrawlTaskEntity brandTask(Long id) {
BrandCrawlTaskEntity task = new BrandCrawlTaskEntity();
task.setId(id);
return task;
}
@SuppressWarnings("unchecked")
private LambdaQueryWrapper<BrandCrawlTaskEntity> captureQuery() {
ArgumentCaptor<LambdaQueryWrapper> captor = ArgumentCaptor.forClass(LambdaQueryWrapper.class);
verify(mapper).selectList(captor.capture());
return captor.getValue();
}
@SuppressWarnings("unchecked")
private LambdaUpdateWrapper<BrandCrawlTaskEntity> captureUpdate() {
ArgumentCaptor<LambdaUpdateWrapper> captor = ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
verify(mapper).update(org.mockito.ArgumentMatchers.isNull(), captor.capture());
return captor.getValue();
}
/** 只取 WHERE 段引用的参数值:SET 侧的值也躺在同一个 paramNameValuePairs 里,整表断言分不开两侧。 */
private static List<Object> whereValues(LambdaUpdateWrapper<BrandCrawlTaskEntity> wrapper) {
List<Object> values = new ArrayList<>();
Matcher matcher = WHERE_PARAM.matcher(wrapper.getSqlSegment());
while (matcher.find()) {
values.add(wrapper.getParamNameValuePairs().get(matcher.group(1)));
}
assertThat(values).as("WHERE 段没解析到任何参数=正则或 MP 占位符格式变了,本用例断言恒真").isNotEmpty();
return values;
}
}
@@ -0,0 +1,126 @@
package com.nanri.aiimage.modules.pricetrack.service;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.modules.pricetrack.mapper.PriceTrackLoopRunMapper;
import com.nanri.aiimage.modules.pricetrack.model.entity.PriceTrackLoopRunEntity;
import com.nanri.aiimage.modules.task.service.ExpiredAccountTaskStopService;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/**
* 跟价循环的「过期即停」实现口径钉(V146 的 SPI 一侧)。
*
* <p>这条的实现刻意<b>不</b>直接落终态:只把 stop_requested 置 1,走用户点「停止循环」那条收尾路径,
* 循环自己在下一个派发点落 STOPPED。所以本用例集最要紧的两条是——
* status 一列不许出现在 SET 里(否则在跑的子任务的收尾会被打断),
* 以及已停止/已完成的循环(stop_requested 已为 1,或状态不是 RUNNING)不得被再次圈进 WHERE。</p>
*/
class PriceTrackLoopExpiredStopSpiImplTest {
private static final String REASON = ExpiredAccountTaskStopService.STOP_REASON;
private static final Pattern WHERE_PARAM = Pattern.compile("#\\{ew\\.paramNameValuePairs\\.(\\w+)}");
private PriceTrackLoopRunMapper mapper;
private PriceTrackLoopExpiredStopSpiImpl spi;
@BeforeEach
void setUp() {
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
PriceTrackLoopRunEntity.class);
mapper = mock(PriceTrackLoopRunMapper.class);
spi = new PriceTrackLoopExpiredStopSpiImpl(mapper);
}
@Test
@DisplayName("moduleType 固定 PRICE_TRACK_LOOP:巡检日志按它归因")
void moduleTypeIsTheLoopKey() {
assertThat(spi.moduleType()).isEqualTo("PRICE_TRACK_LOOP");
}
@Test
@DisplayName("没有过期用户:一条 UPDATE 都不发(null 与空集一样短路)")
void emptyUserScopeWritesNothing() {
assertThat(spi.stopActiveTasks(List.of(), REASON)).isZero();
assertThat(spi.stopActiveTasks(null, REASON)).isZero();
verifyNoInteractions(mapper);
}
@Test
@DisplayName("只圈这批用户「RUNNING 且还没请求停止」的循环")
void predicateIsRunningAndStopNotRequestedYet() {
when(mapper.update(any(), any())).thenReturn(1);
spi.stopActiveTasks(List.of(7L, 8L), REASON);
LambdaUpdateWrapper<PriceTrackLoopRunEntity> update = captureUpdate();
assertThat(update.getSqlSegment()).contains("user_id").contains("status").contains("stop_requested");
List<Object> where = whereValues(update);
assertThat(where).contains("RUNNING", false);
// 用户收口必须真的进 WHERE:换成 isNotNull(user_id) 时列名照样在、谓词值也照样在,
// 只断上面两条抓不到——那是一条把「停这批过期账号」写成「停全站 RUNNING 循环」的路径。
assertThat(where).contains(7L, 8L);
// 已请求停止/已结束的循环再刷一次=幂等性破了,也会把巡检的计数虚高
assertThat(where).doesNotContain("STOPPED", "SUCCESS", "FAILED", "CANCELLED", true);
}
@Test
@DisplayName("SET 只写 stop_requested:status 一列由收尾路径自己落")
void setWritesOnlyTheStopRequestFlag() {
when(mapper.update(any(), any())).thenReturn(1);
spi.stopActiveTasks(List.of(7L), REASON);
LambdaUpdateWrapper<PriceTrackLoopRunEntity> update = captureUpdate();
assertThat(update.getSqlSet()).contains("stop_requested");
assertThat(update.getSqlSet()).doesNotContain("status", "error_message", "finished_at", "current_round");
assertThat(update.getParamNameValuePairs().values()).containsExactly(true);
}
@Test
@DisplayName("返回值 = mapper 实际影响行数;零行时不谎报")
void affectedRowsComeBackFromMapper() {
when(mapper.update(any(), any())).thenReturn(4);
assertThat(spi.stopActiveTasks(List.of(7L), REASON)).isEqualTo(4);
when(mapper.update(any(), any())).thenReturn(0);
assertThat(spi.stopActiveTasks(List.of(9L), REASON)).isZero();
}
// ---------- helpers ----------
@SuppressWarnings("unchecked")
private LambdaUpdateWrapper<PriceTrackLoopRunEntity> captureUpdate() {
ArgumentCaptor<LambdaUpdateWrapper> captor = ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
verify(mapper).update(org.mockito.ArgumentMatchers.isNull(), captor.capture());
return captor.getValue();
}
/** 只取 WHERE 段引用的参数值:SET 侧的值也躺在同一个 paramNameValuePairs 里,整表断言分不开两侧。 */
private static List<Object> whereValues(LambdaUpdateWrapper<PriceTrackLoopRunEntity> wrapper) {
List<Object> values = new ArrayList<>();
Matcher matcher = WHERE_PARAM.matcher(wrapper.getSqlSegment());
while (matcher.find()) {
values.add(wrapper.getParamNameValuePairs().get(matcher.group(1)));
}
assertThat(values).as("WHERE 段没解析到任何参数=正则或 MP 占位符格式变了,本用例断言恒真").isNotEmpty();
return values;
}
}
@@ -0,0 +1,182 @@
package com.nanri.aiimage.modules.task.service;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.mapper.ShopManageGroupMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.service.CompanyScopeSupport;
import com.nanri.aiimage.common.service.DistributedJobLockService;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.spi.ExpiredAccountTaskStopSpi;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* 过期停任务巡检(V146)口径钉:
* 边界账号(expires_at ≤ now 且非超管)→ 级联成员集合与登录侧一致;
* biz_file_task 的 PENDING/SCHEDULED/RUNNING 全部置终态(PENDING 也要,防内部通道继续派发);
* 置终态原因绝不以「客户端异常中断」开头(否则被 TaskResumeService 自动复活);
* SPI 由业务模块各自实现,一个用户都没有时全链路零写库。
*/
class ExpiredAccountTaskStopServiceTest {
private AdminUserMapper adminUserMapper;
private ShopManageGroupMapper groupMapper;
private CompanyScopeSupport companyScopeSupport;
private FileTaskMapper fileTaskMapper;
private DistributedJobLockService jobLockService;
private RecordingSpi spi;
private ExpiredAccountTaskStopService service;
@BeforeEach
void setUp() {
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
AdminUserEntity.class);
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
FileTaskEntity.class);
adminUserMapper = mock(AdminUserMapper.class);
groupMapper = mock(ShopManageGroupMapper.class);
companyScopeSupport = mock(CompanyScopeSupport.class);
fileTaskMapper = mock(FileTaskMapper.class);
jobLockService = mock(DistributedJobLockService.class);
when(jobLockService.tryLock(anyString(), any()))
.thenReturn(mock(DistributedJobLockService.LockHandle.class));
when(adminUserMapper.selectList(any())).thenReturn(List.of());
when(groupMapper.selectManagedMemberUserIds(any())).thenReturn(List.of());
spi = new RecordingSpi();
service = new ExpiredAccountTaskStopService(adminUserMapper, groupMapper, companyScopeSupport,
fileTaskMapper, jobLockService, List.of(spi));
}
@Test
void noExpiredAccountsMeansZeroWrites() {
service.runOnce();
verify(fileTaskMapper, never()).update(any(), any());
assertThat(spi.calls).isZero();
}
@Test
void expiredAdminCollectsCreatedNormalsAndGroupMembers() {
AdminUserEntity admin = boundary(2L, "admin");
AdminUserEntity createdNormal = new AdminUserEntity();
createdNormal.setId(30L);
// 第一次调用是边界扫描(返回过期的管理员),第二次是「名下子账户」查询
AtomicInteger call = new AtomicInteger();
when(adminUserMapper.selectList(any())).thenAnswer(inv -> {
int n = call.incrementAndGet();
return n == 1 ? List.of(admin) : List.of(createdNormal);
});
when(groupMapper.selectManagedMemberUserIds(2L)).thenReturn(List.of(31L));
when(fileTaskMapper.selectList(any())).thenReturn(List.of(fileTask(11L)));
when(fileTaskMapper.update(any(), any())).thenReturn(1);
service.runOnce();
assertThat(spi.lastUserIds).containsExactlyInAnyOrder(2L, 30L, 31L);
verify(fileTaskMapper).update(any(), any());
}
@Test
void expiredCompanySuperAdminCollectsWholeCompany() {
AdminUserEntity csa = boundary(9L, "company_super_admin");
csa.setCompanyId(2L);
when(adminUserMapper.selectList(any())).thenReturn(List.of(csa));
when(companyScopeSupport.memberUserIds(2L)).thenReturn(List.of(101L, 102L));
when(fileTaskMapper.selectList(any())).thenReturn(List.of());
service.runOnce();
assertThat(spi.lastUserIds).containsExactlyInAnyOrder(9L, 101L, 102L);
}
@Test
void fileTaskUpdateCarriesTerminalStateWithNonResumeReason() {
AdminUserEntity admin = boundary(2L, "admin");
when(adminUserMapper.selectList(any())).thenReturn(List.of(admin));
when(fileTaskMapper.selectList(any())).thenReturn(List.of(fileTask(11L)));
when(fileTaskMapper.update(any(), any())).thenReturn(1);
service.runOnce();
var wrapperCaptor = org.mockito.ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
verify(fileTaskMapper).update(org.mockito.ArgumentMatchers.isNull(), wrapperCaptor.capture());
LambdaUpdateWrapper<FileTaskEntity> wrapper = wrapperCaptor.getValue();
// SET 子句在 getSqlSet()(只有列名=占位符),写入值在参数表里——两边一起断
String sqlSet = wrapper.getSqlSet();
assertThat(sqlSet).contains("status").contains("error_message").contains("finished_at");
// WHERE 条件更新钉住状态集合(user_id 在 SELECT 侧过滤、UPDATE 按 id 收口),
// 避免并发下把刚续跑的新任务误杀
String where = wrapper.getSqlSegment();
assertThat(where).contains("status").contains("id IN");
Collection<Object> params = wrapper.getParamNameValuePairs().values();
assertThat(params).contains("FAILED", "PENDING", "SCHEDULED", "RUNNING",
ExpiredAccountTaskStopService.STOP_REASON);
// 原因文案绝不以「客户端异常中断」开头,否则会被 TaskResumeService 自动续跑复活
assertThat(ExpiredAccountTaskStopService.STOP_REASON).doesNotStartWith("客户端异常中断");
}
@Test
void nothingActiveLeavesModuleSpisWithoutWorkButStillNotified() {
// file_task 全是终态 → fileTaskMapper.update 不发生;SPI 仍会被询问一次(幂等、0 行)
AdminUserEntity admin = boundary(2L, "admin");
when(adminUserMapper.selectList(any())).thenReturn(List.of(admin));
when(fileTaskMapper.selectList(any())).thenReturn(List.of());
service.runOnce();
verify(fileTaskMapper, never()).update(any(), any());
assertThat(spi.calls).isEqualTo(1);
assertThat(spi.lastUserIds).containsExactly(2L);
}
// ---------- helpers ----------
private static AdminUserEntity boundary(Long id, String role) {
AdminUserEntity user = new AdminUserEntity();
user.setId(id);
user.setRole(role);
user.setCompanyId(1L);
user.setExpiresAt(LocalDateTime.now().minusMinutes(1));
return user;
}
private static FileTaskEntity fileTask(Long id) {
FileTaskEntity task = new FileTaskEntity();
task.setId(id);
return task;
}
private static final class RecordingSpi implements ExpiredAccountTaskStopSpi {
private int calls;
private Collection<Long> lastUserIds = List.of();
@Override
public String moduleType() {
return "RECORDING";
}
@Override
public int stopActiveTasks(Collection<Long> userIds, String reason) {
calls++;
lastUserIds = userIds == null ? List.of() : List.copyOf(userIds);
return 0;
}
}
}