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:
@@ -144,6 +144,19 @@ public interface ShopManageGroupMapper extends BaseMapper<ShopManageGroupEntity>
|
||||
""")
|
||||
List<ShopManageGroupEntity> selectLedGroups(@Param("operatorId") Long operatorId);
|
||||
|
||||
/**
|
||||
* 某用户所属分组(成员表)的组长 id 集合(到期级联用,AccountExpiryService)。
|
||||
* 与数据可见范围同源:组长的旧字段 user_id 与新字段 created_by_id 都算(COALESCE 取新优先旧兜底)。
|
||||
*/
|
||||
@Select("""
|
||||
SELECT DISTINCT COALESCE(g.created_by_id, g.user_id) AS leader_id
|
||||
FROM biz_shop_manage_group_member gm
|
||||
INNER JOIN biz_shop_manage_group g ON g.id = gm.group_id
|
||||
WHERE gm.user_id = #{userId}
|
||||
AND COALESCE(g.created_by_id, g.user_id) IS NOT NULL
|
||||
""")
|
||||
List<Long> selectLeaderIdsByMemberUserId(@Param("userId") Long userId);
|
||||
|
||||
/** 全部分组(超管筛选项用)。 */
|
||||
@Select("""
|
||||
SELECT g.id AS id, g.group_name AS groupName
|
||||
|
||||
@@ -26,6 +26,12 @@ public class AdminUserEntity {
|
||||
/** 所属公司(company.id,V143 新增)。列 NOT NULL,建号必须显式写,见 AdminUserService#createUser。 */
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
/**
|
||||
* 到期时间(V146 新增):NULL=永不过期。管理员到期则组下普通账户跟随停用、公司超级管理员
|
||||
* 到期则全公司跟随停用——级联判定在 AccountExpiryService,库里不改值。super_admin 不适用。
|
||||
*/
|
||||
@TableField("expires_at")
|
||||
private LocalDateTime expiresAt;
|
||||
@TableField("created_at")
|
||||
private LocalDateTime createdAt;
|
||||
/**
|
||||
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
package com.nanri.aiimage.common.security;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
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.modules.auth.model.entity.LoginUserEntity;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 账号到期(expires_at,V146)的级联判定与拦截。
|
||||
*
|
||||
* <p><b>判定口径(库里不改值,全部现算):</b>生效到期 = 自身 expires_at 与所有上级约束里最早的那个。</p>
|
||||
* <ul>
|
||||
* <li>super_admin:永不适用(返回 null);</li>
|
||||
* <li>公司级:本公司所有 company_super_admin 的 expires_at 约束全公司(管理员/普通用户跟随);
|
||||
* 公司没有公司超管时无此约束(站点自己的公司通常如此);</li>
|
||||
* <li>组级:普通用户受两条链约束——所属分组组长(成员表)与创建人(管理员),
|
||||
* 与数据可见范围的派生口径一致(成员表基本未用、按创建人派生);</li>
|
||||
* <li>管理员(admin):自身 + 公司级。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>拦截点:登录(403,提示续费)与每次请求鉴权 {@code AdminAuthSupport.requireUser}
|
||||
* (401,前端按下线处理踢回登录页)。任务心跳接口刻意匿名、不走 requireUser,所以
|
||||
* {@code ExpiredAccountTaskStopService} 把任务置终态后,客户端心跳仍能拿到 alive=false
|
||||
* 协作停止——这是"过期停任务"不走 401 的原因。</p>
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AccountExpiryService {
|
||||
|
||||
private final AdminUserMapper adminUserMapper;
|
||||
private final ShopManageGroupMapper shopManageGroupMapper;
|
||||
|
||||
/** 生效到期时间;null=永不过期。入参见 {@link #computeEffective(Long, String, Integer, Long, Long, LocalDateTime)}。 */
|
||||
public LocalDateTime effectiveExpiresAt(AdminUserEntity user) {
|
||||
if (user == null) {
|
||||
return null;
|
||||
}
|
||||
return computeEffective(user.getId(), user.getRole(), user.getIsAdmin(), user.getCompanyId(),
|
||||
user.getCreatedById(), user.getExpiresAt());
|
||||
}
|
||||
|
||||
/** 同上,登录链路的 users 实体(与 {@code AdminUserEntity} 同表同列)。 */
|
||||
public LocalDateTime effectiveExpiresAt(LoginUserEntity user) {
|
||||
if (user == null) {
|
||||
return null;
|
||||
}
|
||||
return computeEffective(user.getId(), user.getRole(), user.getIsAdmin(), user.getCompanyId(),
|
||||
user.getCreatedById(), user.getExpiresAt());
|
||||
}
|
||||
|
||||
/** 登录拦截:已到期(含级联)抛 403,文案给续费提示。 */
|
||||
public void assertLoginAllowed(AdminUserEntity user) {
|
||||
assertNotExpired(effectiveExpiresAt(user), 403);
|
||||
}
|
||||
|
||||
/** 同上,登录链路的 users 实体。 */
|
||||
public void assertLoginAllowed(LoginUserEntity user) {
|
||||
assertNotExpired(effectiveExpiresAt(user), 403);
|
||||
}
|
||||
|
||||
/** 会话拦截:已到期(含级联)抛 401,前端踢回登录页。 */
|
||||
public void assertSessionAllowed(AdminUserEntity user) {
|
||||
assertNotExpired(effectiveExpiresAt(user), 401);
|
||||
}
|
||||
|
||||
/** 同上,登录链路的 users 实体(check_login 恢复会话时走这里)。 */
|
||||
public void assertSessionAllowed(LoginUserEntity user) {
|
||||
assertNotExpired(effectiveExpiresAt(user), 401);
|
||||
}
|
||||
|
||||
/** 弹窗用:自身 expires_at 还剩整天数(floor);无到期返回 null。只反映自身,不级联——续费是账号自己的事。 */
|
||||
public static Long ownDaysToExpire(LocalDateTime ownExpiresAt) {
|
||||
if (ownExpiresAt == null) {
|
||||
return null;
|
||||
}
|
||||
long seconds = java.time.Duration.between(LocalDateTime.now(), ownExpiresAt).getSeconds();
|
||||
return Math.floorDiv(seconds, 86400L);
|
||||
}
|
||||
|
||||
private void assertNotExpired(LocalDateTime effective, int code) {
|
||||
if (effective != null && effective.isBefore(LocalDateTime.now())) {
|
||||
throw new BusinessException(code, "账号已过期,请联系管理员续费");
|
||||
}
|
||||
}
|
||||
|
||||
private LocalDateTime computeEffective(Long userId, String storedRole, Integer isAdmin, Long companyId,
|
||||
Long createdById, LocalDateTime ownExpiresAt) {
|
||||
String role = DeviceSessionPolicy.resolveRole(storedRole, isAdmin, createdById);
|
||||
if ("super_admin".equals(role)) {
|
||||
return null;
|
||||
}
|
||||
LocalDateTime effective = ownExpiresAt;
|
||||
effective = min(effective, companyCascadeExpiresAt(companyId));
|
||||
if (role == null) {
|
||||
// 普通用户:组级约束(组长 + 创建人)。管理员不级联到组长(上级是公司超管/超管,走公司级)。
|
||||
effective = min(effective, leaderCascadeExpiresAt(userId));
|
||||
effective = min(effective, creatorCascadeExpiresAt(createdById));
|
||||
}
|
||||
return effective;
|
||||
}
|
||||
|
||||
/** 公司级:本公司公司超管里最早的 expires_at;没有公司超管(含 companyId 为空)返回 null。 */
|
||||
private LocalDateTime companyCascadeExpiresAt(Long companyId) {
|
||||
if (companyId == null || companyId <= 0) {
|
||||
return null;
|
||||
}
|
||||
List<AdminUserEntity> csas = adminUserMapper.selectList(new LambdaQueryWrapper<AdminUserEntity>()
|
||||
.select(AdminUserEntity::getExpiresAt)
|
||||
.eq(AdminUserEntity::getRole, "company_super_admin")
|
||||
.eq(AdminUserEntity::getCompanyId, companyId));
|
||||
LocalDateTime earliest = null;
|
||||
for (AdminUserEntity csa : csas) {
|
||||
earliest = min(earliest, csa.getExpiresAt());
|
||||
}
|
||||
return earliest;
|
||||
}
|
||||
|
||||
/** 组级:该用户所属分组(成员表)的组长(created_by_id/user_id)若是管理员,取其最早 expires_at。 */
|
||||
private LocalDateTime leaderCascadeExpiresAt(Long userId) {
|
||||
if (userId == null || userId <= 0) {
|
||||
return null;
|
||||
}
|
||||
LocalDateTime earliest = null;
|
||||
for (Long leaderId : shopManageGroupMapper.selectLeaderIdsByMemberUserId(userId)) {
|
||||
AdminUserEntity leader = adminUserMapper.selectById(leaderId);
|
||||
if (leader != null && "admin".equals(DeviceSessionPolicy.resolveRole(
|
||||
leader.getRole(), leader.getIsAdmin(), leader.getCreatedById()))) {
|
||||
earliest = min(earliest, leader.getExpiresAt());
|
||||
}
|
||||
}
|
||||
return earliest;
|
||||
}
|
||||
|
||||
/** 组级:创建人是管理员(普通账户的归属主管)时,取其 expires_at。 */
|
||||
private LocalDateTime creatorCascadeExpiresAt(Long createdById) {
|
||||
if (createdById == null || createdById <= 0) {
|
||||
return null;
|
||||
}
|
||||
AdminUserEntity creator = adminUserMapper.selectById(createdById);
|
||||
if (creator == null || !"admin".equals(DeviceSessionPolicy.resolveRole(
|
||||
creator.getRole(), creator.getIsAdmin(), creator.getCreatedById()))) {
|
||||
return null;
|
||||
}
|
||||
return creator.getExpiresAt();
|
||||
}
|
||||
|
||||
private static LocalDateTime min(LocalDateTime a, LocalDateTime b) {
|
||||
if (a == null) return b;
|
||||
if (b == null) return a;
|
||||
return b.isBefore(a) ? b : a;
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,7 @@ public class AdminAuthSupport {
|
||||
private final JwtService jwtService;
|
||||
private final AdminUserMapper adminUserMapper;
|
||||
private final AuthProperties authProperties;
|
||||
private final AccountExpiryService accountExpiryService;
|
||||
|
||||
@Value("${aiimage.security.internal-token:}")
|
||||
private String internalToken;
|
||||
@@ -67,6 +68,9 @@ public class AdminAuthSupport {
|
||||
DeviceSessionPolicy.isSuperAdmin(user.getRole(), user.getIsAdmin(), user.getCreatedById()),
|
||||
user.getId(), user.getUsername());
|
||||
}
|
||||
// 到期拦截(含级联):管理员过期→组下账户停、公司超管过期→全公司停。
|
||||
// 任务心跳接口刻意匿名、不走本方法,过期账号的在跑任务仍能靠 alive=false 协作停止。
|
||||
accountExpiryService.assertSessionAllowed(user);
|
||||
return user;
|
||||
}
|
||||
|
||||
|
||||
+6
-1
@@ -22,12 +22,17 @@ public final class DeviceSessionPolicy {
|
||||
private DeviceSessionPolicy() {
|
||||
}
|
||||
|
||||
/** 计算用户管理角色:super_admin / admin / null(含老数据 role 为空时按 created_by_id 推断)。 */
|
||||
/** 计算用户管理角色:super_admin / company_super_admin / admin / null(含老数据 role 为空时按 created_by_id 推断)。 */
|
||||
public static String resolveRole(String role, Integer isAdmin, Long createdById) {
|
||||
String storedRole = role == null ? "" : role.trim().toLowerCase();
|
||||
if ("super_admin".equals(storedRole)) {
|
||||
return "super_admin";
|
||||
}
|
||||
if ("company_super_admin".equals(storedRole)) {
|
||||
// 公司超级管理员(2026-10-05):单家公司内的最高账号,数据只看本公司,由站点
|
||||
// super_admin 创建。必须先于 is_admin 兼容推断返回,否则会被顶成站点超管。
|
||||
return "company_super_admin";
|
||||
}
|
||||
if ("admin".equals(storedRole)) {
|
||||
return "admin";
|
||||
}
|
||||
|
||||
+9
-3
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.admin.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.security.AccountExpiryService;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.modules.company.service.CompanyService;
|
||||
@@ -64,17 +65,22 @@ public class AdminConsoleController {
|
||||
}
|
||||
|
||||
@GetMapping("/api/admin/current-user")
|
||||
@Operation(summary = "当前登录管理员概要")
|
||||
@Operation(summary = "获取当前管理员信息")
|
||||
public ApiResponse<Map<String, Object>> currentUser(HttpServletRequest request) {
|
||||
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||
Map<String, Object> item = new LinkedHashMap<>();
|
||||
item.put("id", operator.getId());
|
||||
item.put("username", operator.getUsername() == null ? "" : operator.getUsername());
|
||||
item.put("role", adminAuthSupport.currentRole(operator));
|
||||
// 键名固定 camelCase:session.ts 把 item 原样当 AdminUser 用,没有字段映射层,
|
||||
// 拼错只会让顶栏静默少一行字(前端 || '' 兜底),不会报错。
|
||||
// 这里刻意用 camelCase:session.ts 把 item 当作 AdminUser 用,不再经解析器,
|
||||
// 所以这些键要与既有 companyId/companyName 的形状一致(前端 || '' 兜底)
|
||||
item.put("companyId", operator.getCompanyId());
|
||||
item.put("companyName", companyService.nameOrEmpty(operator.getCompanyId()));
|
||||
// 到期续费提醒(V146):只反映自身 expires_at,不级联——续费是账号自己的事。
|
||||
// expiresAt 为 yyyy-MM-dd HH:mm 或 null;daysToExpire 为剩余整天数或 null。
|
||||
item.put("expiresAt", operator.getExpiresAt() == null ? null
|
||||
: operator.getExpiresAt().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
|
||||
item.put("daysToExpire", AccountExpiryService.ownDaysToExpire(operator.getExpiresAt()));
|
||||
return ApiResponse.success(Map.of("item", item));
|
||||
}
|
||||
|
||||
|
||||
+5
@@ -11,5 +11,10 @@ public class AdminUserCreateRequest {
|
||||
private String role;
|
||||
private Long createdById;
|
||||
private Long companyId;
|
||||
/**
|
||||
* 到期时间(V146):支持 yyyy-MM-dd / yyyy-MM-dd HH:mm / yyyy-MM-dd HH:mm:ss。
|
||||
* 空/不传 = 永不过期;super_admin 目标不存在本字段语义(超管建不出超管)。
|
||||
*/
|
||||
private String expiresAt;
|
||||
private List<Long> columnIds;
|
||||
}
|
||||
|
||||
+5
@@ -11,4 +11,9 @@ public class AdminUserUpdateRequest {
|
||||
private List<Long> columnIds;
|
||||
/** 移人目标公司(V143 §2.2,仅超管可用);null 或与账号现公司相同都表示「不动」。 */
|
||||
private Long companyId;
|
||||
/**
|
||||
* 到期时间(V146):null=不动;空串=清除(恢复永不过期);否则为
|
||||
* yyyy-MM-dd[ HH:mm[:ss]],允许过去时间(立即到期 = 手工停用)。
|
||||
*/
|
||||
private String expiresAt;
|
||||
}
|
||||
|
||||
+3
@@ -22,6 +22,9 @@ public class AdminUserItemVo {
|
||||
private String createdAt;
|
||||
@JsonProperty("updated_at")
|
||||
private String updatedAt;
|
||||
/** 到期时间(yyyy-MM-dd HH:mm);空串=永不过期,前端按此渲染。 */
|
||||
@JsonProperty("expires_at")
|
||||
private String expiresAt;
|
||||
@JsonProperty("pinyin_abbr")
|
||||
private String pinyinAbbr;
|
||||
}
|
||||
|
||||
+98
-12
@@ -72,8 +72,9 @@ public class AdminUserService {
|
||||
query.eq(AdminUserEntity::getRole, roleFilterValue);
|
||||
}
|
||||
boolean isSuperAdmin = "super_admin".equals(role);
|
||||
boolean isCompanySuperAdmin = "company_super_admin".equals(role);
|
||||
if (companyIdFilter != null && !isSuperAdmin) {
|
||||
// 公司内管理员:筛自己公司 = 不加条件(他的可见范围本来就只有本公司),
|
||||
// 公司内管理员/公司超管:筛自己公司 = 不加条件(可见范围本来就只有本公司),
|
||||
// 筛别家公司 = 直接空页。这里故意不报错也不越权(设计文档 §2.3)。
|
||||
if (!companyIdFilter.equals(currentUser.getCompanyId())) {
|
||||
return emptyListVo(currentUser, role, safePage, safeSize);
|
||||
@@ -89,6 +90,13 @@ public class AdminUserService {
|
||||
if (companyIdFilter != null) {
|
||||
query.eq(AdminUserEntity::getCompanyId, companyIdFilter);
|
||||
}
|
||||
} else if (isCompanySuperAdmin) {
|
||||
// 公司超管看本公司全部账号(站点超管账号除外——那是平台自己的身份)
|
||||
query.eq(AdminUserEntity::getCompanyId, currentUser.getCompanyId())
|
||||
.ne(AdminUserEntity::getRole, "super_admin");
|
||||
if (!kw.isEmpty()) {
|
||||
query.like(AdminUserEntity::getUsername, kw);
|
||||
}
|
||||
} else {
|
||||
Long adminId = currentUser.getId();
|
||||
query.and(w -> w
|
||||
@@ -140,13 +148,13 @@ public class AdminUserService {
|
||||
ensureAdminUsersMenuAccess(currentUser, List.of("admin_users"));
|
||||
String username = request.getUsername() == null ? "" : request.getUsername().trim();
|
||||
String password = request.getPassword() == null ? "" : request.getPassword();
|
||||
String wantRole = request.getRole() == null ? "normal" : request.getRole().trim();
|
||||
if (wantRole.isEmpty()) wantRole = "normal";
|
||||
if (!"admin".equals(wantRole) && !"normal".equals(wantRole)) {
|
||||
wantRole = "normal";
|
||||
String wantRole = normalizeWantRole(request.getRole());
|
||||
if ("admin".equals(wantRole) && "admin".equals(role)) {
|
||||
throw new BusinessException("仅超级管理员或公司超级管理员可创建管理员");
|
||||
}
|
||||
if ("admin".equals(role) && "admin".equals(wantRole)) {
|
||||
throw new BusinessException("仅超级管理员可创建管理员");
|
||||
if ("company_super_admin".equals(wantRole) && !"super_admin".equals(role)) {
|
||||
// 公司超管是「某一家公司的最高账号」,只能由站点超管开设,谁都不能自己造一级
|
||||
throw new BusinessException(403, "只有超级管理员可以创建公司超级管理员");
|
||||
}
|
||||
if (username.isEmpty() || password.isEmpty()) {
|
||||
throw new BusinessException("用户名和密码不能为空");
|
||||
@@ -159,7 +167,8 @@ public class AdminUserService {
|
||||
}
|
||||
|
||||
Long wantCreatedBy;
|
||||
if ("admin".equals(wantRole)) {
|
||||
if ("admin".equals(wantRole) || "company_super_admin".equals(wantRole)) {
|
||||
// 组长/公司超管的创建人就是操作者本人:公司超管不能替别的主管“认领”管理员
|
||||
wantCreatedBy = currentUser.getId();
|
||||
} else if ("super_admin".equals(role)) {
|
||||
wantCreatedBy = request.getCreatedById();
|
||||
@@ -174,7 +183,8 @@ public class AdminUserService {
|
||||
wantCreatedBy = currentUser.getId();
|
||||
}
|
||||
|
||||
int isAdmin = ("super_admin".equals(wantRole) || "admin".equals(wantRole)) ? 1 : 0;
|
||||
int isAdmin = ("super_admin".equals(wantRole) || "admin".equals(wantRole)
|
||||
|| "company_super_admin".equals(wantRole)) ? 1 : 0;
|
||||
AdminUserEntity entity = new AdminUserEntity();
|
||||
entity.setUsername(username);
|
||||
entity.setPasswordHash(passwordEncoder.hash(password));
|
||||
@@ -182,6 +192,7 @@ public class AdminUserService {
|
||||
entity.setRole(wantRole);
|
||||
entity.setCreatedById(wantCreatedBy);
|
||||
entity.setCompanyId(resolveTargetCompanyId(role, currentUser, request.getCompanyId()));
|
||||
entity.setExpiresAt(parseExpiresAt(request.getExpiresAt()));
|
||||
try {
|
||||
adminUserMapper.insert(entity);
|
||||
} catch (DuplicateKeyException e) {
|
||||
@@ -191,6 +202,49 @@ public class AdminUserService {
|
||||
return entity.getId();
|
||||
}
|
||||
|
||||
/**
|
||||
* 建号角色归一:白名单 admin / company_super_admin / normal,其余一律归 normal。 */
|
||||
private static String normalizeWantRole(String rawRole) {
|
||||
String wantRole = rawRole == null ? "normal" : rawRole.trim();
|
||||
if (wantRole.isEmpty()) {
|
||||
wantRole = "normal";
|
||||
}
|
||||
if (!"admin".equals(wantRole) && !"normal".equals(wantRole)
|
||||
&& !"company_super_admin".equals(wantRole)) {
|
||||
wantRole = "normal";
|
||||
}
|
||||
return wantRole;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析请求里的到期时间:null/空白 = null(永不过期);支持 yyyy-MM-dd、
|
||||
* yyyy-MM-dd HH:mm、yyyy-MM-dd HH:mm:ss 与 ISO(yyyy-MM-ddTHH:mm)。
|
||||
* 格式不对直接报错,不静默归 null——那会把"想设到期"变成"设了永不过期"。
|
||||
*/
|
||||
private static LocalDateTime parseExpiresAt(String raw) {
|
||||
if (raw == null || raw.trim().isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
String value = raw.trim().replace('T', ' ');
|
||||
for (String pattern : new String[]{"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd"}) {
|
||||
try {
|
||||
java.time.format.DateTimeFormatter formatter =
|
||||
java.time.format.DateTimeFormatter.ofPattern(pattern);
|
||||
java.time.temporal.TemporalAccessor parsed = formatter.parseBest(value,
|
||||
LocalDateTime::from, java.time.LocalDate::from);
|
||||
if (parsed instanceof LocalDateTime dateTime) {
|
||||
return dateTime;
|
||||
}
|
||||
if (parsed instanceof java.time.LocalDate date) {
|
||||
return date.atStartOfDay();
|
||||
}
|
||||
} catch (java.time.format.DateTimeParseException ignored) {
|
||||
// 试下一个格式
|
||||
}
|
||||
}
|
||||
throw new BusinessException("到期时间格式不正确,请使用 yyyy-MM-dd 或 yyyy-MM-dd HH:mm");
|
||||
}
|
||||
|
||||
/**
|
||||
* 建号落哪家公司(设计文档 §2.2,与 createdById 同构):超管可指定任意启用中的公司,
|
||||
* 其余角色只能落自己所属公司——显式传别家即 403,不静默改写。
|
||||
@@ -266,7 +320,8 @@ public class AdminUserService {
|
||||
if ((password == null || password.isEmpty())
|
||||
&& (wantRole == null || wantRole.isEmpty())
|
||||
&& request.getColumnIds() == null
|
||||
&& request.getCompanyId() == null) {
|
||||
&& request.getCompanyId() == null
|
||||
&& request.getExpiresAt() == null) {
|
||||
throw new BusinessException("请提供要修改的内容");
|
||||
}
|
||||
|
||||
@@ -282,13 +337,27 @@ public class AdminUserService {
|
||||
}
|
||||
wantRole = null;
|
||||
} else {
|
||||
boolean operatorIsSiteSuperAdmin = "super_admin".equals(role);
|
||||
if ("super_admin".equals(targetRole)) {
|
||||
throw new BusinessException("不能修改超级管理员");
|
||||
}
|
||||
if ("company_super_admin".equals(role)) {
|
||||
// 公司超管只能编辑本公司管理员/普通用户;同公司的公司超管与站点超管都碰不得
|
||||
if ("company_super_admin".equals(targetRole)) {
|
||||
throw new BusinessException(403, "只有超级管理员可以修改公司超级管理员");
|
||||
}
|
||||
if (!currentUser.getCompanyId().equals(target.getCompanyId())) {
|
||||
throw new BusinessException(403, "只能编辑本公司名下的账号");
|
||||
}
|
||||
}
|
||||
if ("super_admin".equals(wantRole)) {
|
||||
throw new BusinessException("不能将用户设为超级管理员");
|
||||
}
|
||||
if (wantRole != null && !"admin".equals(wantRole) && !"normal".equals(wantRole) && !wantRole.isEmpty()) {
|
||||
if ("company_super_admin".equals(wantRole) && !operatorIsSiteSuperAdmin) {
|
||||
throw new BusinessException(403, "只有超级管理员可以设置公司超级管理员");
|
||||
}
|
||||
if (wantRole != null && !"admin".equals(wantRole) && !"normal".equals(wantRole)
|
||||
&& !"company_super_admin".equals(wantRole) && !wantRole.isEmpty()) {
|
||||
wantRole = null;
|
||||
}
|
||||
}
|
||||
@@ -314,11 +383,18 @@ public class AdminUserService {
|
||||
dirty = true;
|
||||
}
|
||||
if (wantRole != null && !wantRole.isEmpty()) {
|
||||
int isAdmin = "admin".equals(wantRole) ? 1 : 0;
|
||||
int isAdmin = ("admin".equals(wantRole) || "company_super_admin".equals(wantRole)) ? 1 : 0;
|
||||
update.set(AdminUserEntity::getIsAdmin, isAdmin);
|
||||
update.set(AdminUserEntity::getRole, wantRole);
|
||||
dirty = true;
|
||||
}
|
||||
if (request.getExpiresAt() != null) {
|
||||
// null=不动;空串=清除(恢复永不过期);有值=改期(允许过去时间,等于立即停用)。
|
||||
// super_admin / 同公司公司超管目标在上面的闸门里已拒绝,到不了这里。
|
||||
update.set(AdminUserEntity::getExpiresAt,
|
||||
request.getExpiresAt().trim().isEmpty() ? null : parseExpiresAt(request.getExpiresAt()));
|
||||
dirty = true;
|
||||
}
|
||||
if (dirty) {
|
||||
adminUserMapper.update(null, update);
|
||||
}
|
||||
@@ -387,6 +463,14 @@ public class AdminUserService {
|
||||
if (!"normal".equals(targetRole) || !currentUser.getId().equals(target.getCreatedById())) {
|
||||
throw new BusinessException(403, "只能删除自己创建的普通用户");
|
||||
}
|
||||
} else if ("company_super_admin".equals(role)) {
|
||||
// 公司超管可清退本公司的管理员/普通用户;公司超管之间互删与站点超管一样被拒
|
||||
if ("company_super_admin".equals(targetRole)) {
|
||||
throw new BusinessException(403, "只有超级管理员可以删除公司超级管理员");
|
||||
}
|
||||
if (!currentUser.getCompanyId().equals(target.getCompanyId())) {
|
||||
throw new BusinessException(403, "只能删除本公司名下的账号");
|
||||
}
|
||||
}
|
||||
int affected = adminUserMapper.deleteById(uid);
|
||||
if (affected == 0) {
|
||||
@@ -459,6 +543,8 @@ public class AdminUserService {
|
||||
vo.setCreatedAt(createdAt == null ? "" : createdAt.format(CREATED_AT_FORMATTER));
|
||||
LocalDateTime updatedAt = entity.getUpdatedAt();
|
||||
vo.setUpdatedAt(updatedAt == null ? "" : updatedAt.format(CREATED_AT_FORMATTER));
|
||||
// 到期时间:null(永不过期)与空字符串在列表里都要有明确渲染,前端按空串判"永不过期"
|
||||
vo.setExpiresAt(entity.getExpiresAt() == null ? "" : entity.getExpiresAt().format(CREATED_AT_FORMATTER));
|
||||
vo.setPinyinAbbr(PinyinAbbrUtil.abbr(entity.getUsername()));
|
||||
return vo;
|
||||
}
|
||||
|
||||
+8
@@ -6,6 +6,8 @@ import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("users")
|
||||
public class LoginUserEntity {
|
||||
@@ -29,4 +31,10 @@ public class LoginUserEntity {
|
||||
*/
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
/**
|
||||
* 到期时间(V146 新增,NULL=永不过期)。与 {@code AdminUserEntity.expiresAt} 同列:
|
||||
* 级联判定(管理员过期→组下账户停、公司超管过期→全公司停)在 AccountExpiryService。
|
||||
*/
|
||||
@TableField("expires_at")
|
||||
private LocalDateTime expiresAt;
|
||||
}
|
||||
|
||||
@@ -16,6 +16,10 @@ public class LoginResultVo {
|
||||
private Long companyId;
|
||||
/** 所属公司名,只显示用;查不到公司一律空串,绝不拿它当登录条件。 */
|
||||
private String companyName;
|
||||
/** 自身账号到期时间(yyyy-MM-dd HH:mm,V146);null=永不过期。只用于前端续费提醒,不级联。 */
|
||||
private String expiresAt;
|
||||
/** 自身到期剩余整天数(floor);null=永不过期。前端按 <5 天弹续费提醒。 */
|
||||
private Long daysToExpire;
|
||||
private String deviceId;
|
||||
private String token;
|
||||
private Long expiresIn;
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.auth.service;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
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;
|
||||
@@ -20,6 +21,8 @@ import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import com.nanri.aiimage.common.security.JwtService;
|
||||
@@ -29,12 +32,15 @@ import com.nanri.aiimage.common.security.JwtService;
|
||||
@Slf4j
|
||||
public class AuthService {
|
||||
|
||||
private static final DateTimeFormatter EXPIRES_AT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
|
||||
|
||||
private final LoginUserMapper loginUserMapper;
|
||||
private final WerkzeugPasswordEncoder passwordEncoder;
|
||||
private final JwtService jwtService;
|
||||
private final PermissionMenuService permissionMenuService;
|
||||
private final AuthProperties authProperties;
|
||||
private final CompanyService companyService;
|
||||
private final AccountExpiryService accountExpiryService;
|
||||
|
||||
/**
|
||||
* 登录失败计数与锁定(2026-09 全维度审查补):生产是公网域名,此前无任何失败限制
|
||||
@@ -102,6 +108,10 @@ public class AuthService {
|
||||
}
|
||||
clearLoginFailures(username);
|
||||
|
||||
// 到期拦截(含级联:管理员过期→组下账户、公司超管过期→全公司)。放在设备绑定之前:
|
||||
// 过期账号不应产生任何登录副作用,machine 保持原值即可。
|
||||
accountExpiryService.assertLoginAllowed(user);
|
||||
|
||||
boolean isAdmin = user.getIsAdmin() != null && user.getIsAdmin() == 1;
|
||||
// 单设备登录:登录成功即把账号绑定到当前设备(last-login-wins),原设备下一次请求被顶下线
|
||||
if (authProperties.isSingleDeviceEnabled()) {
|
||||
@@ -141,6 +151,8 @@ public class AuthService {
|
||||
DeviceSessionPolicy.isSuperAdmin(user.getRole(), user.getIsAdmin(), user.getCreatedById()),
|
||||
user.getId(), user.getUsername());
|
||||
}
|
||||
// 到期拦截(含级联):登录态在到期那一刻起全部失效,前端按 401 踢回登录页
|
||||
accountExpiryService.assertSessionAllowed(user);
|
||||
String headerDevice = trim(currentDeviceId);
|
||||
if (!headerDevice.isEmpty() && !claimDeviceId.isEmpty() && !headerDevice.equals(claimDeviceId)) {
|
||||
log.warn("[auth] check_login 请求头设备与登录态内设备不一致(以登录态为准)userId={} headerDevice={} loginDevice={}",
|
||||
@@ -185,6 +197,10 @@ public class AuthService {
|
||||
// 公司身份只做显示:nameOrEmpty 查不到就空串,登录不因此被打回
|
||||
vo.setCompanyId(user.getCompanyId());
|
||||
vo.setCompanyName(companyService.nameOrEmpty(user.getCompanyId()));
|
||||
// 到期信息只做弹窗提醒(剩余不足 5 天时前端展示),只反映自身 expires_at,不级联——
|
||||
// 续费是账号自己的事,组员不替组长看续费弹窗。
|
||||
vo.setExpiresAt(user.getExpiresAt() == null ? null : user.getExpiresAt().format(EXPIRES_AT_FORMATTER));
|
||||
vo.setDaysToExpire(AccountExpiryService.ownDaysToExpire(user.getExpiresAt()));
|
||||
vo.setDeviceId(deviceId);
|
||||
vo.setToken(token);
|
||||
vo.setExpiresIn(jwtService.ttlSeconds());
|
||||
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package com.nanri.aiimage.modules.brand.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.nanri.aiimage.modules.brand.mapper.BrandCrawlTaskMapper;
|
||||
import com.nanri.aiimage.modules.brand.model.entity.BrandCrawlTaskEntity;
|
||||
import com.nanri.aiimage.modules.task.spi.ExpiredAccountTaskStopSpi;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 账号过期时停止品牌采集任务(brand_crawl_tasks):pending/running 一律取消。
|
||||
* 客户端下一次心跳(≤60s)拿到 alive=false 自行收尾——与 markInterrupted 同一条协作停止通道。
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class BrandTaskExpiredStopSpiImpl implements ExpiredAccountTaskStopSpi {
|
||||
|
||||
private static final String STATUS_PENDING = "pending";
|
||||
private static final String STATUS_RUNNING = "running";
|
||||
private static final String STATUS_CANCELLED = "cancelled";
|
||||
|
||||
private final BrandCrawlTaskMapper brandCrawlTaskMapper;
|
||||
|
||||
@Override
|
||||
public String moduleType() {
|
||||
return "BRAND";
|
||||
}
|
||||
|
||||
@Override
|
||||
public int stopActiveTasks(Collection<Long> userIds, String reason) {
|
||||
if (userIds == null || userIds.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
List<Long> ids = brandCrawlTaskMapper.selectList(new LambdaQueryWrapper<BrandCrawlTaskEntity>()
|
||||
.select(BrandCrawlTaskEntity::getId)
|
||||
.in(BrandCrawlTaskEntity::getUserId, userIds)
|
||||
.in(BrandCrawlTaskEntity::getStatus, STATUS_PENDING, STATUS_RUNNING)
|
||||
.last("limit 500"))
|
||||
.stream().map(BrandCrawlTaskEntity::getId).toList();
|
||||
if (ids.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
return brandCrawlTaskMapper.update(null, new LambdaUpdateWrapper<BrandCrawlTaskEntity>()
|
||||
.in(BrandCrawlTaskEntity::getId, ids)
|
||||
.in(BrandCrawlTaskEntity::getStatus, STATUS_PENDING, STATUS_RUNNING)
|
||||
.set(BrandCrawlTaskEntity::getStatus, STATUS_CANCELLED)
|
||||
.set(BrandCrawlTaskEntity::getErrorMessage, reason));
|
||||
}
|
||||
}
|
||||
+29
-3
@@ -19,6 +19,7 @@ import com.nanri.aiimage.common.mapper.AdminUserMapper;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.mapper.ShopManageGroupMapper;
|
||||
import com.nanri.aiimage.common.model.entity.ShopManageGroupEntity;
|
||||
import com.nanri.aiimage.common.service.CompanyScopeSupport;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
@@ -80,6 +81,7 @@ public class DedupeTotalDataService {
|
||||
private final DedupeTotalDataMapper dedupeTotalDataMapper;
|
||||
private final AdminUserMapper adminUserMapper;
|
||||
private final ShopManageGroupMapper shopManageGroupMapper;
|
||||
private final CompanyScopeSupport companyScopeSupport;
|
||||
private final PlatformTransactionManager transactionManager;
|
||||
|
||||
// 2026-09 全维度审查 D2:进度/归属/分组改由 NodeSharedStore 承载(本地快路径 + Redis 跨节点),
|
||||
@@ -96,12 +98,14 @@ public class DedupeTotalDataService {
|
||||
public DedupeTotalDataService(DedupeTotalDataMapper dedupeTotalDataMapper,
|
||||
AdminUserMapper adminUserMapper,
|
||||
ShopManageGroupMapper shopManageGroupMapper,
|
||||
CompanyScopeSupport companyScopeSupport,
|
||||
PlatformTransactionManager transactionManager,
|
||||
org.springframework.data.redis.core.StringRedisTemplate stringRedisTemplate,
|
||||
ObjectMapper objectMapper) {
|
||||
this.dedupeTotalDataMapper = dedupeTotalDataMapper;
|
||||
this.adminUserMapper = adminUserMapper;
|
||||
this.shopManageGroupMapper = shopManageGroupMapper;
|
||||
this.companyScopeSupport = companyScopeSupport;
|
||||
this.transactionManager = transactionManager;
|
||||
this.importProgressMap = progressStore("aiimage:dedupe:import:progress", stringRedisTemplate, objectMapper);
|
||||
this.deleteImportProgressMap = progressStore("aiimage:dedupe:delete-import:progress", stringRedisTemplate, objectMapper);
|
||||
@@ -1179,7 +1183,18 @@ public class DedupeTotalDataService {
|
||||
private AccessScope resolveAccessScope(Long operatorId) {
|
||||
AdminUserEntity operator = getOperator(operatorId);
|
||||
if (isSuperAdmin(operator)) {
|
||||
return new AccessScope(true, Set.of(), Set.of());
|
||||
return new AccessScope(true, Set.of(), Set.of(), false);
|
||||
}
|
||||
if ("company_super_admin".equals(operator.getRole() == null
|
||||
? "" : operator.getRole().trim().toLowerCase(Locale.ROOT))) {
|
||||
LinkedHashSet<Long> companyUserIds = new LinkedHashSet<>();
|
||||
companyUserIds.add(operator.getId());
|
||||
for (Long memberId : companyScopeSupport.memberUserIds(operator.getCompanyId())) {
|
||||
if (memberId != null && memberId > 0) {
|
||||
companyUserIds.add(memberId);
|
||||
}
|
||||
}
|
||||
return new AccessScope(false, Set.of(), Set.copyOf(companyUserIds), true);
|
||||
}
|
||||
List<Long> accessibleGroupIds = shopManageGroupMapper.selectAccessibleGroupIds(operator.getId());
|
||||
LinkedHashSet<Long> visibleUserIds = new LinkedHashSet<>();
|
||||
@@ -1201,7 +1216,8 @@ public class DedupeTotalDataService {
|
||||
return new AccessScope(
|
||||
false,
|
||||
Set.copyOf(accessibleGroupIds == null ? List.of() : accessibleGroupIds),
|
||||
Set.copyOf(visibleUserIds));
|
||||
Set.copyOf(visibleUserIds),
|
||||
false);
|
||||
}
|
||||
|
||||
private void applyGroupScope(LambdaQueryWrapper<DedupeTotalDataEntity> query,
|
||||
@@ -1221,6 +1237,11 @@ public class DedupeTotalDataService {
|
||||
if (scope.allUsers()) {
|
||||
return;
|
||||
}
|
||||
if (scope.wholeCompany()) {
|
||||
// 公司超管:整家公司成员上传的行全可见,不再按 group_id 切
|
||||
query.in(DedupeTotalDataEntity::getUploaderUserId, scope.userIds());
|
||||
return;
|
||||
}
|
||||
query.and(wrapper -> {
|
||||
if (!scope.groupIds().isEmpty()) {
|
||||
wrapper.in(DedupeTotalDataEntity::getGroupId, scope.groupIds())
|
||||
@@ -1402,6 +1423,11 @@ public class DedupeTotalDataService {
|
||||
return vo;
|
||||
}
|
||||
|
||||
private record AccessScope(boolean allUsers, Set<Long> groupIds, Set<Long> userIds) {
|
||||
/**
|
||||
* @param allUsers 超管直通
|
||||
* @param wholeCompany 公司超管:不做分组维度裁剪,userIds = 本公司全体成员,
|
||||
* 查询条件退化为 uploader_user_id IN (成员)——公司超管的"组"就是整家公司
|
||||
*/
|
||||
private record AccessScope(boolean allUsers, Set<Long> groupIds, Set<Long> userIds, boolean wholeCompany) {
|
||||
}
|
||||
}
|
||||
|
||||
+16
-2
@@ -944,6 +944,18 @@ public class PermissionMenuService {
|
||||
if (!isAdmin(operator)) {
|
||||
throw new BusinessException(403, "需要管理员权限");
|
||||
}
|
||||
if ("company_super_admin".equals(normalizeRole(operator.getRole()))) {
|
||||
// 公司超管:本公司管理员/普通用户都可授;同公司的公司超管与站点超管碰不得
|
||||
String targetRole = normalizeRole(target.getRole());
|
||||
if ("company_super_admin".equals(targetRole) || "super_admin".equals(targetRole)) {
|
||||
throw new BusinessException(403, "只有超级管理员可以修改公司超级管理员");
|
||||
}
|
||||
if (operator.getCompanyId() == null
|
||||
|| !operator.getCompanyId().equals(target.getCompanyId())) {
|
||||
throw new BusinessException(403, "只能授权本公司名下的账号");
|
||||
}
|
||||
return;
|
||||
}
|
||||
boolean ownedNormal = isNormalUser(target)
|
||||
&& operator.getId() != null
|
||||
&& operator.getId().equals(target.getCreatedById());
|
||||
@@ -1030,7 +1042,8 @@ public class PermissionMenuService {
|
||||
}
|
||||
String role = normalizeRole(user.getRole());
|
||||
if (!role.isEmpty()) {
|
||||
return "super_admin".equals(role) || "admin".equals(role);
|
||||
// company_super_admin 也是授权链上的一级主管(可给本公司的管理员/普通用户授权)
|
||||
return "super_admin".equals(role) || "admin".equals(role) || "company_super_admin".equals(role);
|
||||
}
|
||||
return Integer.valueOf(1).equals(user.getIsAdmin());
|
||||
}
|
||||
@@ -1054,7 +1067,8 @@ public class PermissionMenuService {
|
||||
}
|
||||
String role = normalizeRole(user.getRole());
|
||||
if (!role.isEmpty()) {
|
||||
return !"admin".equals(role) && !"super_admin".equals(role);
|
||||
return !"admin".equals(role) && !"super_admin".equals(role)
|
||||
&& !"company_super_admin".equals(role);
|
||||
}
|
||||
return !Integer.valueOf(1).equals(user.getIsAdmin());
|
||||
}
|
||||
|
||||
+25
@@ -5,6 +5,8 @@ import com.nanri.aiimage.common.mapper.AdminUserMapper;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.mapper.ShopManageGroupMapper;
|
||||
import com.nanri.aiimage.common.model.entity.ShopManageGroupEntity;
|
||||
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
|
||||
import com.nanri.aiimage.common.service.CompanyScopeSupport;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
@@ -18,6 +20,9 @@ import java.util.Set;
|
||||
* 数据权限范围解析:由主管(admin)uid 得到其可见/管辖的用户 id 集合。
|
||||
* 与后台密钥管理页(UserApiSecretService.adminPage)同源规则:
|
||||
* 自己带的「数据权限分组」成员(组长本人 + 名下子账户),无分组记录时回退按「名下子账户」兜底。
|
||||
*
|
||||
* <p>公司超级管理员(2026-10-05)看<b>本公司全部成员</b>:不分组长,公司就是他们的"组"。
|
||||
* 由 {@link #resolveVisibleUserIds(AdminUserEntity)} 统一判角色,调用方无需各自 if。</p>
|
||||
*/
|
||||
@Component
|
||||
@Slf4j
|
||||
@@ -28,12 +33,32 @@ public class UserDataScopeSupport {
|
||||
|
||||
private final AdminUserMapper adminUserMapper;
|
||||
private final ShopManageGroupMapper shopManageGroupMapper;
|
||||
private final CompanyScopeSupport companyScopeSupport;
|
||||
|
||||
/** 主管可见用户:自己 + 自己带的分组下的子账户(名下 users.created_by_id=自己)。 */
|
||||
public List<Long> resolveVisibleUserIds(Long operatorId) {
|
||||
if (operatorId == null) {
|
||||
return List.of();
|
||||
}
|
||||
return resolveVisibleUserIds(adminUserMapper.selectById(operatorId));
|
||||
}
|
||||
|
||||
/** 按操作者实体解析;公司超管 → 本公司全部成员,其余与旧口径一致。 */
|
||||
public List<Long> resolveVisibleUserIds(AdminUserEntity operator) {
|
||||
if (operator == null || operator.getId() == null) {
|
||||
return List.of();
|
||||
}
|
||||
if ("company_super_admin".equals(DeviceSessionPolicy.resolveRole(
|
||||
operator.getRole(), operator.getIsAdmin(), operator.getCreatedById()))) {
|
||||
Set<Long> userIds = new LinkedHashSet<>(
|
||||
companyScopeSupport.memberUserIds(operator.getCompanyId()));
|
||||
userIds.add(operator.getId());
|
||||
return new ArrayList<>(userIds);
|
||||
}
|
||||
return resolveByGroupScope(operator.getId());
|
||||
}
|
||||
|
||||
private List<Long> resolveByGroupScope(Long operatorId) {
|
||||
List<Long> ledGroupIds = listLedGroupIds(operatorId);
|
||||
Set<Long> userIds = new LinkedHashSet<>();
|
||||
for (Long groupId : ledGroupIds) {
|
||||
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.nanri.aiimage.modules.pricetrack.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.nanri.aiimage.modules.pricetrack.mapper.PriceTrackLoopRunMapper;
|
||||
import com.nanri.aiimage.modules.pricetrack.model.entity.PriceTrackLoopRunEntity;
|
||||
import com.nanri.aiimage.modules.task.spi.ExpiredAccountTaskStopSpi;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
/**
|
||||
* 账号过期时请求停止跟价循环(biz_price_track_loop_run):只置 stop_requested=1,
|
||||
* 不直接改状态——与用户点「停止循环」的 {@code requestStop} 同一条收尾路径,
|
||||
* 循环在下一个派发/子任务收尾点落 STOPPED。当前在跑的子任务是 biz_file_task 行,
|
||||
* 由 ExpiredAccountTaskStopService 直接置终态后经心跳 alive=false 协作停止。
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class PriceTrackLoopExpiredStopSpiImpl implements ExpiredAccountTaskStopSpi {
|
||||
|
||||
private static final String STATUS_RUNNING = "RUNNING";
|
||||
|
||||
private final PriceTrackLoopRunMapper loopRunMapper;
|
||||
|
||||
@Override
|
||||
public String moduleType() {
|
||||
return "PRICE_TRACK_LOOP";
|
||||
}
|
||||
|
||||
@Override
|
||||
public int stopActiveTasks(Collection<Long> userIds, String reason) {
|
||||
if (userIds == null || userIds.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
return loopRunMapper.update(null, new LambdaUpdateWrapper<PriceTrackLoopRunEntity>()
|
||||
.in(PriceTrackLoopRunEntity::getUserId, userIds)
|
||||
.eq(PriceTrackLoopRunEntity::getStatus, STATUS_RUNNING)
|
||||
.eq(PriceTrackLoopRunEntity::getStopRequested, false)
|
||||
.set(PriceTrackLoopRunEntity::getStopRequested, true));
|
||||
}
|
||||
}
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
package com.nanri.aiimage.modules.task.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
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 lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 账号过期停任务巡检(V146,2026-10-05)。
|
||||
*
|
||||
* <p>到期那一刻起,登录与全部鉴权请求已被 {@code AccountExpiryService} 拦下;但客户端
|
||||
* <b>已经在跑的任务</b>不会自己停——客户端唯一的"服务端发令"停止通道是心跳返回 alive=false,
|
||||
* 而它只看任务状态。本巡检每分钟把过期账号(含级联成员)名下的活跃任务置终态:
|
||||
* biz_file_task PENDING/SCHEDULED/RUNNING → FAILED(含未领取的 PENDING,防内部通道继续派发);
|
||||
* 品牌/跟价循环经 {@link ExpiredAccountTaskStopSpi} 由各业务模块自行停止。</p>
|
||||
*
|
||||
* <p>级联口径与登录侧 {@code AccountExpiryService} 严格一致:管理员过期 → 名下子账户
|
||||
* (created_by_id)+ 所带分组的成员表成员;公司超管过期 → 全公司成员。置终态原因固定为
|
||||
* {@link #STOP_REASON}(刻意不以「客户端异常中断」开头,绝不触发 TaskResumeService 自动续跑)。
|
||||
* 续费后任务不会复活,需要用户重新发起。</p>
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ExpiredAccountTaskStopService {
|
||||
|
||||
/** ASCII 标记,供 _prod_watch.py 按 docker logs grep(中文在容器里可能变编码,签名必须 ASCII)。 */
|
||||
static final String MARKER = "EXPIRED_ACCOUNT_TASKS_STOPPED";
|
||||
/** 刻意避开 TaskResumeService 的「客户端异常中断」前缀,过期停止的任务不许被自动复活。 */
|
||||
public static final String STOP_REASON = "账号已过期,任务已自动停止";
|
||||
|
||||
private static final String STATUS_PENDING = "PENDING";
|
||||
private static final String STATUS_SCHEDULED = "SCHEDULED";
|
||||
private static final String STATUS_RUNNING = "RUNNING";
|
||||
private static final String STATUS_FAILED = "FAILED";
|
||||
private static final int BATCH_LIMIT = 500;
|
||||
|
||||
private final AdminUserMapper adminUserMapper;
|
||||
private final ShopManageGroupMapper shopManageGroupMapper;
|
||||
private final CompanyScopeSupport companyScopeSupport;
|
||||
private final FileTaskMapper fileTaskMapper;
|
||||
private final DistributedJobLockService distributedJobLockService;
|
||||
private final List<ExpiredAccountTaskStopSpi> moduleStops;
|
||||
|
||||
@Scheduled(fixedDelay = 60 * 1000, initialDelay = 45 * 1000)
|
||||
public void stopTasksOfExpiredAccounts() {
|
||||
var lock = distributedJobLockService.tryLock("expired-account-task-stop", Duration.ofSeconds(55));
|
||||
if (lock == null) {
|
||||
return;
|
||||
}
|
||||
try (lock) {
|
||||
runOnce();
|
||||
} catch (Exception ex) {
|
||||
log.warn("[expired-account-stop] 巡检失败 msg={}", ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
|
||||
void runOnce() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
List<AdminUserEntity> boundary = adminUserMapper.selectList(new LambdaQueryWrapper<AdminUserEntity>()
|
||||
.select(AdminUserEntity::getId, AdminUserEntity::getRole,
|
||||
AdminUserEntity::getCompanyId, AdminUserEntity::getCreatedById)
|
||||
.isNotNull(AdminUserEntity::getExpiresAt)
|
||||
.le(AdminUserEntity::getExpiresAt, now)
|
||||
.ne(AdminUserEntity::getRole, "super_admin"));
|
||||
if (boundary.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Set<Long> affected = resolveAffectedUserIds(boundary);
|
||||
if (affected.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
int fileTaskCount = stopFileTasks(affected, now);
|
||||
int moduleCount = 0;
|
||||
for (ExpiredAccountTaskStopSpi spi : moduleStops) {
|
||||
moduleCount += spi.stopActiveTasks(affected, STOP_REASON);
|
||||
}
|
||||
if (fileTaskCount > 0 || moduleCount > 0) {
|
||||
log.warn("{} 账号过期已停止任务 expiredUsers={} fileTasks={} moduleStops={}",
|
||||
MARKER, affected.size(), fileTaskCount, moduleCount);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 过期账号 → 需要连带停任务的成员集合。与登录侧级联判定同口径:
|
||||
* 公司超管过期圈全公司;管理员过期圈名下子账户 + 所带分组的成员表成员;普通用户只有自己。
|
||||
*/
|
||||
private Set<Long> resolveAffectedUserIds(List<AdminUserEntity> boundary) {
|
||||
LinkedHashSet<Long> affected = new LinkedHashSet<>();
|
||||
for (AdminUserEntity account : boundary) {
|
||||
if (account.getId() == null) {
|
||||
continue;
|
||||
}
|
||||
affected.add(account.getId());
|
||||
String role = account.getRole() == null ? "" : account.getRole();
|
||||
if ("company_super_admin".equals(role)) {
|
||||
if (account.getCompanyId() != null && account.getCompanyId() > 0) {
|
||||
affected.addAll(companyScopeSupport.memberUserIds(account.getCompanyId()));
|
||||
}
|
||||
} else if ("admin".equals(role) || role.isEmpty()) {
|
||||
// 名下子账户(组员归属的主链路:按创建人派生)
|
||||
adminUserMapper.selectList(new LambdaQueryWrapper<AdminUserEntity>()
|
||||
.select(AdminUserEntity::getId)
|
||||
.eq(AdminUserEntity::getCreatedById, account.getId()))
|
||||
.forEach(member -> {
|
||||
if (member.getId() != null) {
|
||||
affected.add(member.getId());
|
||||
}
|
||||
});
|
||||
// 成员表直挂的成员(手工绑进分组、创建人不是该管理员的兜底)
|
||||
affected.addAll(shopManageGroupMapper.selectManagedMemberUserIds(account.getId()));
|
||||
}
|
||||
}
|
||||
return affected;
|
||||
}
|
||||
|
||||
/** biz_file_task:PENDING/SCHEDULED/RUNNING → FAILED。先查 id 再条件更新,照 StaleTaskRepairService 的写法。 */
|
||||
private int stopFileTasks(Set<Long> userIds, LocalDateTime now) {
|
||||
List<FileTaskEntity> active = fileTaskMapper.selectList(new LambdaQueryWrapper<FileTaskEntity>()
|
||||
.select(FileTaskEntity::getId)
|
||||
.in(FileTaskEntity::getUserId, userIds)
|
||||
.in(FileTaskEntity::getStatus, STATUS_PENDING, STATUS_SCHEDULED, STATUS_RUNNING)
|
||||
.last("limit " + BATCH_LIMIT));
|
||||
if (active.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
return fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
|
||||
.in(FileTaskEntity::getId, active.stream().map(FileTaskEntity::getId).toList())
|
||||
.in(FileTaskEntity::getStatus, STATUS_PENDING, STATUS_SCHEDULED, STATUS_RUNNING)
|
||||
.set(FileTaskEntity::getStatus, STATUS_FAILED)
|
||||
.set(FileTaskEntity::getErrorMessage, STOP_REASON)
|
||||
.set(FileTaskEntity::getFinishedAt, now));
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.nanri.aiimage.modules.task.spi;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
/**
|
||||
* 账号过期时停止「独立于 biz_file_task 的任务载体」(2026-10-05,G5 同款:task 模块不 import 业务模块)。
|
||||
*
|
||||
* <p>{@code ExpiredAccountTaskStopService} 每分钟把过期账号(含级联)名下的 biz_file_task
|
||||
* 置终态;品牌任务(brand_crawl_tasks)与跟价循环(biz_price_track_loop_run)不在那张表里,
|
||||
* 由各业务模块实现本 SPI 自行停止——谁的数据谁停,task 侧只发令。</p>
|
||||
*/
|
||||
public interface ExpiredAccountTaskStopSpi {
|
||||
|
||||
/** 实现负责的模块标识(日志归因用)。 */
|
||||
String moduleType();
|
||||
|
||||
/**
|
||||
* 把属于这些用户的活跃任务停止。要求幂等:非活跃状态的行一律不动。
|
||||
*
|
||||
* @param userIds 过期账号及其级联成员(登录侧会全部拦截,这里只负责在跑的任务)
|
||||
* @param reason 写进 errorMessage 的统一文案(勿以「客户端异常中断」开头,避免被自动续跑复活)
|
||||
* @return 实际发生变更的行数(0 = 本轮无事发生,调用方据此决定是否打日志)
|
||||
*/
|
||||
int stopActiveTasks(Collection<Long> userIds, String reason);
|
||||
}
|
||||
+15
@@ -4,6 +4,7 @@ import com.nanri.aiimage.common.exception.BusinessException;
|
||||
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 lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@@ -23,12 +24,21 @@ public class TaskCenterScopeService {
|
||||
|
||||
private final AdminUserMapper adminUserMapper;
|
||||
private final ShopManageGroupMapper shopManageGroupMapper;
|
||||
private final CompanyScopeSupport companyScopeSupport;
|
||||
|
||||
public ScopeContext resolve(Long operatorId) {
|
||||
AdminUserEntity operator = requireOperator(operatorId);
|
||||
if (isSuperAdmin(operator)) {
|
||||
return new ScopeContext(true, Set.of());
|
||||
}
|
||||
if ("company_super_admin".equals(normalizeRole(operator))) {
|
||||
// 公司超管看本公司全部成员的任务;空公司按 [-1] 兜底,不放大成全量
|
||||
List<Long> memberIds = companyScopeSupport.memberUserIds(operator.getCompanyId());
|
||||
LinkedHashSet<Long> visibleUserIds = new LinkedHashSet<>();
|
||||
visibleUserIds.add(operator.getId());
|
||||
addAll(visibleUserIds, memberIds);
|
||||
return new ScopeContext(false, Set.copyOf(visibleUserIds));
|
||||
}
|
||||
List<Long> accessibleGroupIds = shopManageGroupMapper.selectAccessibleGroupIds(operator.getId());
|
||||
LinkedHashSet<Long> visibleUserIds = new LinkedHashSet<>();
|
||||
visibleUserIds.add(operator.getId());
|
||||
@@ -63,6 +73,11 @@ public class TaskCenterScopeService {
|
||||
|| (role.isEmpty() && Integer.valueOf(1).equals(user.getIsAdmin()) && user.getCreatedById() == null);
|
||||
}
|
||||
|
||||
/** 公司超管判定(老数据 role 为空不参与:公司超管是新角色,只认显式取值)。 */
|
||||
private static String normalizeRole(AdminUserEntity user) {
|
||||
return user.getRole() == null ? "" : user.getRole().trim().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param allUsers 超管直通,不按用户裁剪
|
||||
* @param visibleUserIds 非超管的可见用户集合(至少含本人)
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
-- =============================================================
|
||||
-- 迁移 V146__users_expires_at_admin_expiry
|
||||
-- 模板:docs/flyway-migration-template.md
|
||||
-- 设计:本文件「变更目的」段给口径;判定与停任务的实现分别承载在
|
||||
-- AccountExpiryService(生效到期=自身∧公司超管∧组长/创建人)与
|
||||
-- ExpiredAccountTaskStopService(过期账号的在跑任务置终态)的类注释里。
|
||||
--
|
||||
-- 1. 变更目的:给 users 加 expires_at(datetime NULL),支撑「管理员到期停用」:
|
||||
-- - NULL = 永不过期(全部存量账号回填后仍为 NULL,行为零变化);
|
||||
-- - 管理员(admin)到期 ⇒ 组下普通账户跟着停(级联判定在 AccountExpiryService,落库不改值);
|
||||
-- - 公司超级管理员(company_super_admin,角色值本身不加列,随本批 Java 代码启用)到期 ⇒ 全公司停;
|
||||
-- - 到期账号的进行中任务由 ExpiredAccountTaskStopService 扫描置终态(业务表零 DDL)。
|
||||
-- 只加一列:角色的新取值 company_super_admin 是 users.role 的数据行级取值,不需要 DDL;
|
||||
-- company 表、columns 表、57 张业务表一律不动。
|
||||
-- 2. 影响表与数据量:仅 users 一列。生产实查 139+ 行 / data 0.06MB + index 0.03MB 量级。
|
||||
-- 3. 锁表风险:低。MySQL 8 的 ADD COLUMN(无默认值)走 INSTANT,users 是百行量级。
|
||||
-- 不碰 biz_task_file_job 等锁热点表。
|
||||
-- 4. 验证 SQL:见文件末尾「验证」段。
|
||||
-- 5. 回滚步骤:人工补丁,不写成版本化迁移(那样 Flyway 会在下次启动时自动执行)。
|
||||
-- 顺序:停两台应用 → 执行
|
||||
-- ALTER TABLE `users` DROP COLUMN `expires_at`;
|
||||
-- → 删 flyway_schema_history 里 version='146' 那一行 → 回滚 jar → 起应用。
|
||||
-- 漏掉删历史那步,将来重装时 Flyway 判定"已应用"而跳过,Java 实体读写 expires_at
|
||||
-- 会在运行期报 unknown column。丢弃 expires_at 即放弃全部到期设置(本来也只影响新功能)。
|
||||
-- 6. 上线窗口:随 jar 双节点同窗口发布。加列对旧 jar 无影响(旧代码不认识新列),
|
||||
-- 混合版本窗口零行为差异;新代码读该列前 Flyway 已保证列存在。
|
||||
--
|
||||
-- 【可重跑性】加列前先查 information_schema(照 V143 的条件 DDL 惯例):迁移中途失败时
|
||||
-- flyway repair + 重启会让 Flyway 从第一条语句重跑整个文件,裸 ADD COLUMN 会撞 1060。
|
||||
-- =============================================================
|
||||
|
||||
SET @col_exists := (
|
||||
SELECT COUNT(*) FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'users'
|
||||
AND COLUMN_NAME = 'expires_at'
|
||||
);
|
||||
SET @ddl := IF(@col_exists = 0,
|
||||
'ALTER TABLE `users` ADD COLUMN `expires_at` datetime NULL COMMENT ''到期时间(NULL=永不过期)。管理员到期则其组下普通账户与所在公司整体跟随停用,见 AccountExpiryService。super_admin 恒不适用''',
|
||||
'SELECT ''users.expires_at already exists, skipped'' AS note');
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- =============================================================
|
||||
-- 验证 SQL(迁移后在库上执行)
|
||||
-- SHOW COLUMNS FROM `users` LIKE 'expires_at';
|
||||
-- -> 期望 Null = YES、Default = NULL
|
||||
-- SELECT COUNT(*) AS total, SUM(expires_at IS NOT NULL) AS with_expiry FROM `users`;
|
||||
-- -> 期望 with_expiry = 0(本迁移只加列,不回填任何到期值)
|
||||
-- SELECT DISTINCT role FROM `users`;
|
||||
-- -> 现存取值不变(super_admin / admin / normal);company_super_admin 由建号接口
|
||||
-- 此后写入,不是本迁移的产物
|
||||
-- =============================================================
|
||||
+210
@@ -0,0 +1,210 @@
|
||||
package com.nanri.aiimage.common.security;
|
||||
|
||||
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.mapper.AdminUserMapper;
|
||||
import com.nanri.aiimage.common.mapper.ShopManageGroupMapper;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.modules.auth.model.entity.LoginUserEntity;
|
||||
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.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.catchThrowableOfType;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 到期级联判定(V146)口径钉:
|
||||
* super_admin 永不适用;公司超管到期 → 全公司跟随;管理员到期 → 创建人链上的普通用户跟随;
|
||||
* 普通用户同时受自身/创建人/组长/公司超管四条约束取最早;库里不改值,全部现算。
|
||||
*/
|
||||
class AccountExpiryServiceTest {
|
||||
|
||||
private AdminUserMapper adminUserMapper;
|
||||
private ShopManageGroupMapper groupMapper;
|
||||
private AccountExpiryService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
|
||||
AdminUserEntity.class);
|
||||
adminUserMapper = mock(AdminUserMapper.class);
|
||||
groupMapper = mock(ShopManageGroupMapper.class);
|
||||
service = new AccountExpiryService(adminUserMapper, groupMapper);
|
||||
// 默认:无公司超管、无组长、无创建人约束
|
||||
when(adminUserMapper.selectList(any())).thenReturn(List.of());
|
||||
when(adminUserMapper.selectById(any(Long.class))).thenReturn(null);
|
||||
when(groupMapper.selectLeaderIdsByMemberUserId(any())).thenReturn(List.of());
|
||||
}
|
||||
|
||||
// ---------- 基本口径 ----------
|
||||
|
||||
@Test
|
||||
void superAdminNeverExpires() {
|
||||
assertThat(service.effectiveExpiresAt(entity(1L, "super_admin", null, 1L, past()))).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void ownExpiryAppliesToAdminDirectly() {
|
||||
LocalDateTime expiry = LocalDateTime.now().plusDays(3);
|
||||
assertThat(service.effectiveExpiresAt(entity(2L, "admin", null, 1L, expiry))).isEqualTo(expiry);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullExpiryMeansNeverWithoutSuperiorConstraints() {
|
||||
assertThat(service.effectiveExpiresAt(entity(2L, "admin", null, 1L, null))).isNull();
|
||||
}
|
||||
|
||||
// ---------- 公司级联:公司超管到期 → 全公司 ----------
|
||||
|
||||
@Test
|
||||
void companySuperAdminExpiryCapsEveryoneInTheCompany() {
|
||||
LocalDateTime companyExpiry = LocalDateTime.now().plusDays(2);
|
||||
AdminUserEntity csa = new AdminUserEntity();
|
||||
csa.setId(9L);
|
||||
csa.setRole("company_super_admin");
|
||||
csa.setExpiresAt(companyExpiry);
|
||||
when(adminUserMapper.selectList(any())).thenReturn(List.of(csa));
|
||||
|
||||
// 普通用户(自身无到期)被公司超管的到期拉进去
|
||||
assertThat(service.effectiveExpiresAt(entity(3L, "normal", null, 1L, null))).isEqualTo(companyExpiry);
|
||||
// 管理员同样被拉进去
|
||||
assertThat(service.effectiveExpiresAt(entity(2L, "admin", null, 1L, null))).isEqualTo(companyExpiry);
|
||||
}
|
||||
|
||||
@Test
|
||||
void companySuperAdminWithoutExpiryLeavesCompanyUnaffected() {
|
||||
AdminUserEntity csa = new AdminUserEntity();
|
||||
csa.setId(9L);
|
||||
csa.setRole("company_super_admin");
|
||||
csa.setExpiresAt(null);
|
||||
when(adminUserMapper.selectList(any())).thenReturn(List.of(csa));
|
||||
|
||||
assertThat(service.effectiveExpiresAt(entity(3L, "normal", null, 1L, null))).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void earliestConstraintWinsOverOwnExpiry() {
|
||||
LocalDateTime own = LocalDateTime.now().plusDays(10);
|
||||
LocalDateTime company = LocalDateTime.now().plusDays(1);
|
||||
AdminUserEntity csa = new AdminUserEntity();
|
||||
csa.setId(9L);
|
||||
csa.setRole("company_super_admin");
|
||||
csa.setExpiresAt(company);
|
||||
when(adminUserMapper.selectList(any())).thenReturn(List.of(csa));
|
||||
|
||||
assertThat(service.effectiveExpiresAt(entity(3L, "normal", null, 1L, own))).isEqualTo(company);
|
||||
}
|
||||
|
||||
// ---------- 组级联:管理员到期 → 名下/组内普通用户 ----------
|
||||
|
||||
@Test
|
||||
void expiredCreatorAdminCascadesToNormalUser() {
|
||||
LocalDateTime adminExpiry = LocalDateTime.now().plusDays(4);
|
||||
AdminUserEntity creator = new AdminUserEntity();
|
||||
creator.setId(2L);
|
||||
creator.setRole("admin");
|
||||
creator.setExpiresAt(adminExpiry);
|
||||
when(adminUserMapper.selectById(2L)).thenReturn(creator);
|
||||
|
||||
assertThat(service.effectiveExpiresAt(entity(3L, "normal", 2L, 1L, null))).isEqualTo(adminExpiry);
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiredGroupLeaderCascadesToGroupMember() {
|
||||
LocalDateTime leaderExpiry = LocalDateTime.now().plusDays(6);
|
||||
AdminUserEntity leader = new AdminUserEntity();
|
||||
leader.setId(5L);
|
||||
leader.setRole("admin");
|
||||
leader.setExpiresAt(leaderExpiry);
|
||||
when(groupMapper.selectLeaderIdsByMemberUserId(3L)).thenReturn(List.of(5L));
|
||||
when(adminUserMapper.selectById(5L)).thenReturn(leader);
|
||||
|
||||
assertThat(service.effectiveExpiresAt(entity(3L, "normal", 8L, 1L, null))).isEqualTo(leaderExpiry);
|
||||
}
|
||||
|
||||
@Test
|
||||
void normalUserIsNotCascadedByNormalCreator() {
|
||||
// 创建人自己是普通用户(历史脏数据):不构成组级约束
|
||||
AdminUserEntity creator = new AdminUserEntity();
|
||||
creator.setId(8L);
|
||||
creator.setRole("normal");
|
||||
creator.setExpiresAt(past());
|
||||
when(adminUserMapper.selectById(8L)).thenReturn(creator);
|
||||
|
||||
assertThat(service.effectiveExpiresAt(entity(3L, "normal", 8L, 1L, null))).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void adminIsNotCascadedByItsCreatorAdmin() {
|
||||
// 管理员的上级是公司超管/超管(走公司级),不按"创建人是管理员"级联——否则两家管理员互相锁
|
||||
AdminUserEntity creator = new AdminUserEntity();
|
||||
creator.setId(2L);
|
||||
creator.setRole("admin");
|
||||
creator.setExpiresAt(past());
|
||||
when(adminUserMapper.selectById(2L)).thenReturn(creator);
|
||||
|
||||
assertThat(service.effectiveExpiresAt(entity(6L, "admin", 2L, 1L, null))).isNull();
|
||||
}
|
||||
|
||||
// ---------- 拦截行为 ----------
|
||||
|
||||
@Test
|
||||
void expiredLoginIsRejectedWithRenewalMessage() {
|
||||
AccountExpiryService raw = new AccountExpiryService(adminUserMapper, groupMapper);
|
||||
AdminUserEntity expired = entity(3L, "admin", null, 1L, past());
|
||||
|
||||
BusinessException ex = catchThrowableOfType(() -> raw.assertLoginAllowed(expired), BusinessException.class);
|
||||
assertThat(ex).isNotNull();
|
||||
assertThat(ex.getMessage()).contains("已过期").contains("续费");
|
||||
}
|
||||
|
||||
@Test
|
||||
void liveAccountPassesSessionCheck() {
|
||||
AdminUserEntity live = entity(3L, "admin", null, 1L, LocalDateTime.now().plusDays(9));
|
||||
assertThatCode(() -> service.assertSessionAllowed(live)).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
// ---------- 弹窗口径:只看自身 ----------
|
||||
|
||||
@Test
|
||||
void ownDaysToExpireFloorsToWholeDays() {
|
||||
assertThat(AccountExpiryService.ownDaysToExpire(null)).isNull();
|
||||
LocalDateTime inSixDays = LocalDateTime.now().plusDays(6);
|
||||
Long days = AccountExpiryService.ownDaysToExpire(inSixDays);
|
||||
assertThat(days).isNotNull();
|
||||
assertThat(days).isBetween(5L, 6L);
|
||||
// 已过期是负数(调用方按 <5 判展示,登录侧已被 403 拦住,负数不会出现在弹窗里)
|
||||
assertThat(AccountExpiryService.ownDaysToExpire(past())).isNegative();
|
||||
}
|
||||
|
||||
// ---------- helpers ----------
|
||||
|
||||
private static LocalDateTime past() {
|
||||
return LocalDateTime.now().minusDays(1);
|
||||
}
|
||||
|
||||
private static AdminUserEntity entity(Long id, String role, Long createdById, Long companyId,
|
||||
LocalDateTime expiresAt) {
|
||||
AdminUserEntity user = new AdminUserEntity();
|
||||
user.setId(id);
|
||||
user.setUsername("u" + id);
|
||||
user.setRole(role);
|
||||
user.setIsAdmin("super_admin".equals(role) || "admin".equals(role)
|
||||
|| "company_super_admin".equals(role) ? 1 : 0);
|
||||
user.setCreatedById(createdById);
|
||||
user.setCompanyId(companyId);
|
||||
user.setExpiresAt(expiresAt);
|
||||
return user;
|
||||
}
|
||||
}
|
||||
+8
-5
@@ -29,7 +29,7 @@ class AdminAuthSupportTest {
|
||||
void explicitLowestIdAdminIsNotPromotedToSuperAdmin() {
|
||||
AdminUserMapper userMapper = mock(AdminUserMapper.class);
|
||||
AdminAuthSupport support = new AdminAuthSupport(
|
||||
mock(JwtService.class), userMapper, mock(AuthProperties.class));
|
||||
mock(JwtService.class), userMapper, mock(AuthProperties.class), mock(AccountExpiryService.class));
|
||||
AdminUserEntity user = user(1L, "admin", 1, null);
|
||||
|
||||
assertThat(support.currentRole(user)).isEqualTo("admin");
|
||||
@@ -39,7 +39,8 @@ class AdminAuthSupportTest {
|
||||
@Test
|
||||
void legacyBlankRoleRootRemainsSuperAdmin() {
|
||||
AdminAuthSupport support = new AdminAuthSupport(
|
||||
mock(JwtService.class), mock(AdminUserMapper.class), mock(AuthProperties.class));
|
||||
mock(JwtService.class), mock(AdminUserMapper.class), mock(AuthProperties.class),
|
||||
mock(AccountExpiryService.class));
|
||||
|
||||
assertThat(support.currentRole(user(1L, null, 1, null))).isEqualTo("super_admin");
|
||||
}
|
||||
@@ -47,7 +48,8 @@ class AdminAuthSupportTest {
|
||||
@Test
|
||||
void explicitNormalRoleIsNotPromotedByLegacyAdminFields() {
|
||||
AdminAuthSupport support = new AdminAuthSupport(
|
||||
mock(JwtService.class), mock(AdminUserMapper.class), mock(AuthProperties.class));
|
||||
mock(JwtService.class), mock(AdminUserMapper.class), mock(AuthProperties.class),
|
||||
mock(AccountExpiryService.class));
|
||||
|
||||
assertThat(support.currentRole(user(1L, "normal", 1, null))).isNull();
|
||||
}
|
||||
@@ -188,7 +190,8 @@ class AdminAuthSupportTest {
|
||||
|
||||
private AdminAuthSupport tokenSupport(String current, String previous, String tokenFile) {
|
||||
AdminAuthSupport support = new AdminAuthSupport(
|
||||
mock(JwtService.class), mock(AdminUserMapper.class), mock(AuthProperties.class));
|
||||
mock(JwtService.class), mock(AdminUserMapper.class), mock(AuthProperties.class),
|
||||
mock(AccountExpiryService.class));
|
||||
ReflectionTestUtils.setField(support, "internalToken", current);
|
||||
ReflectionTestUtils.setField(support, "internalTokenPrevious", previous);
|
||||
ReflectionTestUtils.setField(support, "internalTokenFile", tokenFile);
|
||||
@@ -207,7 +210,7 @@ class AdminAuthSupportTest {
|
||||
when(userMapper.selectById(user.getId())).thenReturn(user);
|
||||
when(props.isSingleDeviceEnabled()).thenReturn(singleDeviceEnabled);
|
||||
|
||||
return new AdminAuthSupport(jwtService, userMapper, props);
|
||||
return new AdminAuthSupport(jwtService, userMapper, props, mock(AccountExpiryService.class));
|
||||
}
|
||||
|
||||
private HttpServletRequest requestWithBearer(String token) {
|
||||
|
||||
+11
@@ -19,6 +19,17 @@ class DeviceSessionPolicyTest {
|
||||
assertThat(DeviceSessionPolicy.resolveRole("super_admin", 1, 9L)).isEqualTo("super_admin");
|
||||
}
|
||||
|
||||
@Test
|
||||
void companySuperAdminResolvedWithoutBeingPromotedToSiteAdmin() {
|
||||
assertThat(DeviceSessionPolicy.resolveRole("company_super_admin", 1, 1L))
|
||||
.isEqualTo("company_super_admin");
|
||||
// 大小写/空白容错与既有取值一致
|
||||
assertThat(DeviceSessionPolicy.resolveRole(" Company_Super_Admin ", 1, 1L))
|
||||
.isEqualTo("company_super_admin");
|
||||
// 关键反向钉:公司超管绝不能被顶成站点超管(isSuperAdmin 是单设备豁免+全站判定的入口)
|
||||
assertThat(DeviceSessionPolicy.isSuperAdmin("company_super_admin", 1, null)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void explicitAdminNotPromotedToSuperAdmin() {
|
||||
assertThat(DeviceSessionPolicy.resolveRole("admin", 1, null)).isEqualTo("admin");
|
||||
|
||||
+12
-4
@@ -295,14 +295,22 @@ class CompanyScopeMigrationV145Test {
|
||||
}
|
||||
|
||||
/**
|
||||
* 破坏点:回滚被编成 V146(Flyway 扫描路径里的任何 V*.sql 都会在下次启动自动执行),
|
||||
* 破坏点:回滚被编成版本化迁移(Flyway 扫描路径里的任何 V*.sql 都会在下次启动自动执行),
|
||||
* 或者回滚脚本没删历史行(重装时 Flyway 判定"已应用"而跳过重建)。
|
||||
*
|
||||
* <p>钉的是<b>动作</b>不是号位:这里原本写的是"db/ 里不许出现 V146__ 前缀",而 V146 随后被一条
|
||||
* 毫不相关的前向迁移(users.expires_at)正常占用,用例便红了。不变的是"回滚不得版本化",
|
||||
* 所以断言打在剥注释后的可执行 SQL 上:谁在迁移文件里写 flyway_schema_history,谁就是在偷偷自动回滚。</p>
|
||||
*/
|
||||
@Test
|
||||
void rollbackStaysOutOfFlywayScanAndCoversTheHistoryRow() throws IOException {
|
||||
try (Stream<Path> s = Files.list(DB_DIR)) {
|
||||
assertTrue(s.noneMatch(p -> p.getFileName().toString().startsWith("V146__")),
|
||||
"回滚不许编成版本化迁移:V146 会被 Flyway 在下次启动自动执行");
|
||||
Pattern writesHistoryTable = Pattern.compile(
|
||||
"\\b(DELETE|UPDATE|INSERT|TRUNCATE|ALTER|DROP)\\b[^;]*\\bflyway_schema_history\\b",
|
||||
Pattern.CASE_INSENSITIVE);
|
||||
for (Path file : versionFiles()) {
|
||||
String executable = normalize(stripComments(raw(file)));
|
||||
assertFalse(writesHistoryTable.matcher(executable).find(),
|
||||
"回滚不许编成版本化迁移:" + file.getFileName() + " 的执行段写了 flyway_schema_history");
|
||||
}
|
||||
Path rollback = ROOT.resolve("docs/rollback-V145-company-scope.sql");
|
||||
assertTrue(Files.isRegularFile(rollback), "回滚人工补丁必须存在:" + rollback);
|
||||
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
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;
|
||||
|
||||
/**
|
||||
* V146(users.expires_at,管理员到期停用的数据模型)的文件审计。
|
||||
* 设计口径见 AccountExpiryService(级联判定)与 ExpiredAccountTaskStopService(过期停任务)的类注释。
|
||||
*
|
||||
* <p>本仓 pom 无 H2、无 testcontainers,迁移跑不起来,文件审计是唯一能守住的层——
|
||||
* 与 {@link CompanyMigrationV144Test} / {@link CompanyScopeMigrationV145Test} 同口径:
|
||||
* 断言打在剥掉注释后的可执行 SQL 上。</p>
|
||||
*/
|
||||
class UsersExpiryMigrationV146Test {
|
||||
|
||||
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 Path migration() throws IOException {
|
||||
List<Path> hits;
|
||||
try (Stream<Path> s = Files.list(DB_DIR)) {
|
||||
hits = s.filter(p -> p.getFileName().toString().matches("^V\\d+(?:_\\d+)?__.*\\.sql$"))
|
||||
.filter(p -> p.getFileName().toString().startsWith("V146__"))
|
||||
.toList();
|
||||
}
|
||||
assertFalse(hits.isEmpty(), "缺少 V146__*.sql:users.expires_at 还没落盘");
|
||||
assertEquals(1, hits.size(), "V146 只允许一个迁移文件(撞号会让 Flyway 启动失败)");
|
||||
return hits.get(0);
|
||||
}
|
||||
|
||||
private static String rawMigration() throws IOException {
|
||||
return Files.readString(migration(), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/** 粗剥离注释后的可执行 SQL(本迁移无字符串内 -- 字面量,简化实现即可,勿复制到含 -- 的迁移)。 */
|
||||
private static String statements() throws IOException {
|
||||
String body = rawMigration();
|
||||
// 防呆:字符串字面量里若出现 "--"(如注释文案),先按行处理会误伤——这里断言它不存在
|
||||
assertFalse(body.contains("'--"), "字符串字面量内出现 -- 时不能用简化剥离,请改用逐字扫描");
|
||||
return body.replaceAll("(?m)^\\s*--.*$", "")
|
||||
.replaceAll("\\s+", " ")
|
||||
.trim();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 断言
|
||||
|
||||
@Test
|
||||
void versionIsUniqueAndSequential() throws IOException {
|
||||
assertEquals("V146__users_expires_at_admin_expiry.sql",
|
||||
migration().getFileName().toString(), "迁移名与描述须一致");
|
||||
}
|
||||
|
||||
@Test
|
||||
void headerCarriesTemplateFields() throws IOException {
|
||||
String head = rawMigration().substring(0, Math.min(2400, rawMigration().length()));
|
||||
assertTrue(head.contains("变更目的"), "头注释缺「变更目的」");
|
||||
assertTrue(head.contains("影响表与数据量"), "头注释缺「影响表与数据量」");
|
||||
assertTrue(head.contains("锁表风险"), "头注释缺「锁表风险」");
|
||||
assertTrue(head.contains("验证 SQL"), "头注释缺「验证 SQL」");
|
||||
assertTrue(head.contains("回滚步骤"), "头注释缺「回滚步骤」");
|
||||
assertTrue(head.contains("上线窗口"), "头注释缺「上线窗口」");
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyTouchesUsersTable() throws IOException {
|
||||
String sql = statements();
|
||||
assertTrue(sql.contains("ALTER TABLE `users` ADD COLUMN `expires_at`"), "必须给 users 加 expires_at");
|
||||
// 业务表零 DDL:这条迁移不得 CREATE TABLE / DROP,也不得碰 company / columns
|
||||
assertFalse(sql.toUpperCase().contains("CREATE TABLE"), "本迁移不应建表");
|
||||
assertFalse(sql.toUpperCase().contains("DROP "), "本迁移不应删任何对象");
|
||||
assertFalse(sql.contains("`company`") || sql.contains("`columns`"), "company/columns 不许动");
|
||||
assertFalse(sql.contains("biz_"), "业务表零 DDL(57 张业务表不许出现在本迁移)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void addColumnIsConditionalAndRerunnable() throws IOException {
|
||||
String sql = statements();
|
||||
assertTrue(sql.contains("information_schema.COLUMNS"), "加列前必须查 information_schema(可重跑性)");
|
||||
assertTrue(sql.contains("PREPARE stmt FROM @ddl"), "条件 DDL 要走 PREPARE");
|
||||
assertTrue(sql.contains("DEALLOCATE PREPARE stmt"), "PREPARE 之后必须 DEALLOCATE");
|
||||
assertTrue(sql.contains("already exists"), "列已存在时要有跳过分支(flyway repair 重跑不撞 1060)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void columnIsNullableWithoutDefault() throws IOException {
|
||||
String sql = statements();
|
||||
assertTrue(sql.contains("datetime NULL"), "expires_at 必须可空且无默认值:NULL=永不过期");
|
||||
assertFalse(sql.contains("NOT NULL"), "不许 NOT NULL:全部存量账号必须保持永不过期");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shipsVerificationSql() throws IOException {
|
||||
String sql = rawMigration();
|
||||
assertTrue(sql.contains("SHOW COLUMNS FROM `users` LIKE 'expires_at'"), "验证段要能核对列存在性");
|
||||
assertTrue(sql.contains("with_expiry"), "验证段要断言没有任何存量回填(with_expiry = 0)");
|
||||
}
|
||||
}
|
||||
+28
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
+251
@@ -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
-1
@@ -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
-1
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
+165
@@ -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;
|
||||
}
|
||||
}
|
||||
+126
@@ -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;
|
||||
}
|
||||
}
|
||||
+182
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user