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

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

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

验证(本会话亲跑,不是转述):后端定向 14 类 123/0(同一轮 mvn 里连批次③的 4 类 53 例、以及既有 ShopDataCrawl/SimilarAsin 两条回归对照 21 例一起跑,合计 197 例 0 红);admin-frontend-vue 本批定向 44/0(弹窗 7 +
公司建号/列表/入口/日期默认 21 + 角色 task-48/task-251 16),全量 1726 例里那 1 支红是另一条
会话刻意留的「公司 tab 接线缺口」尺子(点名 admin_task_center 等 6 页,与本批无关);
frontend-vue 弹窗 9/0、全量 710/0。变异自证两批共 34 点:弹窗语义 16 点全杀(阈值 5、只能收起
不能关闭、挂载点含"注释掉挂载"、落键/清键链路),本批 SPI+迁移护栏 17 点全杀(含 G2 反向:
前向迁移只在注释里提 flyway_schema_history 必须照样绿),注入文件还原 dirty=0、探针残留 0。
This commit is contained in:
2026-10-05 11:51:33 +08:00
parent 265f31681f
commit 95e2318c42
62 changed files with 2866 additions and 112 deletions
@@ -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;
/**
@@ -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;
}
@@ -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";
}
@@ -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));
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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());
@@ -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));
}
}
@@ -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) {
}
}
@@ -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());
}
@@ -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) {
@@ -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));
}
}
@@ -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));
}
}
@@ -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);
}
@@ -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 由建号接口
-- 此后写入,不是本迁移的产物
-- =============================================================