feat(taskcenter): 客户端任务管理模块骨架、菜单授权与汇总接口
新增 modules/taskcenter:组范围裁剪(超管直通 / 非超管取本组用户)、 两表 UNION 统计(biz_file_task 12 模块 + brand_crawl_tasks)、设备花名册 (任务设备近 30 天 + 客户端日志设备近 7 天且 uid 非空)。overview 返回 设备总数/在线数/进行中/今日完成/疑似卡住五项。 权限复用既有菜单授权:PermissionMenuService.requireClientTaskCenterAccess (超管直通,非超管要求 admin_task_center 授权,无记录即 403)。 测试:ScopeService 7 项 + Mapper 动态 SQL 渲染 7 项(不连库,守住 XML 实体转义与可见账号占位符数量)。
This commit is contained in:
+20
@@ -480,6 +480,26 @@ public class PermissionMenuService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 「客户端任务管理」菜单访问检查:超管直通,管理员需被超管授权该菜单。
|
||||
*
|
||||
* <p>与 {@link #requireShopDataCrawlTaskAccess} 同口径:无 {@code user_column_permission}
|
||||
* 授权记录即拒绝,因此新菜单默认只有超管可见。</p>
|
||||
*/
|
||||
public void requireClientTaskCenterAccess(AdminUserEntity operator) {
|
||||
ensureAdminOperatorIfPresent(operator);
|
||||
if (operator == null || operator.getId() == null || operator.getId() <= 0) {
|
||||
throw new BusinessException(403, "需要管理员权限");
|
||||
}
|
||||
if (isSuperAdmin(operator)) {
|
||||
return;
|
||||
}
|
||||
PermissionMenuEntity menu = requireDataPermission("admin_task_center", "客户端任务管理菜单");
|
||||
if (!hasEffectiveColumnPermission(operator.getId(), menu.getId())) {
|
||||
throw new BusinessException(403, "无权查看客户端任务管理");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断操作者是否可见任一所给后台菜单(按 column_key,限定 admin 菜单类型)。
|
||||
* 超管直通;其余取直接授权递归展开后的有效菜单做交集。
|
||||
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package com.nanri.aiimage.modules.taskcenter.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||
import com.nanri.aiimage.modules.taskcenter.model.vo.TaskCenterOverviewVo;
|
||||
import com.nanri.aiimage.modules.taskcenter.service.TaskCenterQueryService;
|
||||
import com.nanri.aiimage.modules.taskcenter.service.TaskCenterScopeService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* 后台「客户端任务管理」:按账号 × 设备 × 业务统一看客户端任务,不必逐台排查。
|
||||
*
|
||||
* <p>仅超管默认可见;管理员需超管在「用户管理 → 菜单权限」授权 {@code admin_task_center}
|
||||
* 后才能访问。数据范围 = 本人 + 本组用户 + 自己管理的成员(超管不裁剪)。</p>
|
||||
*/
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
@RequestMapping("/api/admin/task-center")
|
||||
@Tag(name = "客户端任务管理(后台)", description = "客户端任务与设备状态看板;设备号取自 JWT 签名 claim。")
|
||||
public class AdminTaskCenterController {
|
||||
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
private final PermissionMenuService permissionMenuService;
|
||||
private final TaskCenterScopeService scopeService;
|
||||
private final TaskCenterQueryService queryService;
|
||||
|
||||
@GetMapping("/overview")
|
||||
@Operation(summary = "汇总卡", description = "设备总数/在线数、进行中任务数、今日完成任务数、疑似卡住数(>10 分钟无更新)。")
|
||||
public ApiResponse<TaskCenterOverviewVo> overview(HttpServletRequest request) {
|
||||
TaskCenterScopeService.ScopeContext scope = resolveScope(request);
|
||||
return ApiResponse.success(queryService.overview(scope));
|
||||
}
|
||||
|
||||
private TaskCenterScopeService.ScopeContext resolveScope(HttpServletRequest request) {
|
||||
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||
permissionMenuService.requireClientTaskCenterAccess(operator);
|
||||
return scopeService.resolve(operator.getId());
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
package com.nanri.aiimage.modules.taskcenter.mapper;
|
||||
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 客户端任务管理(后台看板)只读查询。
|
||||
*
|
||||
* <p>数据源两张表:{@code biz_file_task}(12 个客户端模块)+ {@code brand_crawl_tasks}
|
||||
* (品牌检测自建表,不写 biz_file_task)。状态口径:biz_file_task 大写、brand_crawl_tasks
|
||||
* 小写,这里统一在 SQL 内各自匹配,不依赖外层转换。</p>
|
||||
*
|
||||
* <p>范围裁剪:{@code userIds == null} 表示超管(不过滤);非超管传可见用户集合
|
||||
* (空集由调用方兜底为 {@code [-1]},保证选中零行)。</p>
|
||||
*/
|
||||
@Mapper
|
||||
public interface TaskCenterQueryMapper {
|
||||
|
||||
/** 12 个客户端模块(不含纯服务端执行的 DEDUPE / SPLIT / CONVERT)。 */
|
||||
String CLIENT_MODULE_TYPES = "'PUBLISH','DELETE_BRAND','PRODUCT_RISK_RESOLVE','PRICE_TRACK',"
|
||||
+ "'SHOP_MATCH','PATROL_DELETE','QUERY_ASIN','WITHDRAW','APPEARANCE_PATENT',"
|
||||
+ "'SIMILAR_ASIN','COLLECT_DATA','SHOP_DATA_CRAWL'";
|
||||
|
||||
/** biz_file_task 进行中状态。 */
|
||||
String ACTIVE_STATUSES = "'PENDING','RUNNING','SCHEDULED'";
|
||||
|
||||
/** biz_file_task 终态。 */
|
||||
String TERMINAL_STATUSES = "'SUCCESS','FAILED','CANCELLED','CANCELED'";
|
||||
|
||||
/** brand_crawl_tasks 进行中(该表状态小写)。 */
|
||||
String BRAND_ACTIVE_STATUSES = "'pending','running'";
|
||||
|
||||
/** brand_crawl_tasks 终态。 */
|
||||
String BRAND_TERMINAL_STATUSES = "'success','failed','cancelled'";
|
||||
|
||||
/**
|
||||
* 设备花名册原始行:任务设备(近 N 天创建过任务)+ 日志设备(近 N 天有上报,uid 为空不归组)。
|
||||
* 每行 {@code device_id + activity_at},同设备多行由外层聚合。
|
||||
*/
|
||||
String ROSTER_ROWS = "(SELECT t.device_id AS device_id, t.updated_at AS activity_at"
|
||||
+ " FROM biz_file_task t"
|
||||
+ " WHERE t.module_type IN (" + CLIENT_MODULE_TYPES + ")"
|
||||
+ " AND t.device_id IS NOT NULL AND t.device_id != ''"
|
||||
+ " AND t.created_at >= #{taskSince}"
|
||||
+ " <if test='userIds != null'> AND t.user_id IN"
|
||||
+ " <foreach collection='userIds' item='uid' open='(' separator=',' close=')'>#{uid}</foreach></if>"
|
||||
+ " UNION ALL"
|
||||
+ " SELECT b.device_id, b.updated_at FROM brand_crawl_tasks b"
|
||||
+ " WHERE b.device_id IS NOT NULL AND b.device_id != ''"
|
||||
+ " AND b.created_at >= #{taskSince}"
|
||||
+ " <if test='userIds != null'> AND b.user_id IN"
|
||||
+ " <foreach collection='userIds' item='uid' open='(' separator=',' close=')'>#{uid}</foreach></if>"
|
||||
+ " UNION ALL"
|
||||
+ " SELECT d.device_id, COALESCE(d.last_upload_at, d.updated_at) FROM device_log_file d"
|
||||
+ " WHERE d.source = 'client'"
|
||||
+ " AND d.device_id != ''"
|
||||
+ " AND d.uid IS NOT NULL"
|
||||
+ " AND d.last_upload_at >= #{logSince}"
|
||||
+ " <if test='userIds != null'> AND d.uid IN"
|
||||
+ " <foreach collection='userIds' item='uid' open='(' separator=',' close=')'>#{uid}</foreach></if>)";
|
||||
|
||||
@Select("<script>"
|
||||
+ "SELECT COUNT(*) FROM ("
|
||||
+ " SELECT t.id FROM biz_file_task t"
|
||||
+ " WHERE t.module_type IN (" + CLIENT_MODULE_TYPES + ")"
|
||||
+ " AND t.status IN (" + ACTIVE_STATUSES + ")"
|
||||
+ " <if test='userIds != null'> AND t.user_id IN"
|
||||
+ " <foreach collection='userIds' item='uid' open='(' separator=',' close=')'>#{uid}</foreach></if>"
|
||||
+ " UNION ALL"
|
||||
+ " SELECT b.id FROM brand_crawl_tasks b"
|
||||
+ " WHERE b.status IN (" + BRAND_ACTIVE_STATUSES + ")"
|
||||
+ " <if test='userIds != null'> AND b.user_id IN"
|
||||
+ " <foreach collection='userIds' item='uid' open='(' separator=',' close=')'>#{uid}</foreach></if>"
|
||||
+ ") u"
|
||||
+ "</script>")
|
||||
long countRunningTasks(@Param("userIds") List<Long> userIds);
|
||||
|
||||
@Select("<script>"
|
||||
+ "SELECT COUNT(*) FROM ("
|
||||
+ " SELECT t.id FROM biz_file_task t"
|
||||
+ " WHERE t.module_type IN (" + CLIENT_MODULE_TYPES + ")"
|
||||
+ " AND t.status IN (" + ACTIVE_STATUSES + ")"
|
||||
+ " AND t.updated_at < #{idleBefore}"
|
||||
+ " <if test='userIds != null'> AND t.user_id IN"
|
||||
+ " <foreach collection='userIds' item='uid' open='(' separator=',' close=')'>#{uid}</foreach></if>"
|
||||
+ " UNION ALL"
|
||||
+ " SELECT b.id FROM brand_crawl_tasks b"
|
||||
+ " WHERE b.status IN (" + BRAND_ACTIVE_STATUSES + ")"
|
||||
+ " AND b.updated_at < #{idleBefore}"
|
||||
+ " <if test='userIds != null'> AND b.user_id IN"
|
||||
+ " <foreach collection='userIds' item='uid' open='(' separator=',' close=')'>#{uid}</foreach></if>"
|
||||
+ ") u"
|
||||
+ "</script>")
|
||||
long countStuckTasks(@Param("userIds") List<Long> userIds,
|
||||
@Param("idleBefore") LocalDateTime idleBefore);
|
||||
|
||||
@Select("<script>"
|
||||
+ "SELECT COUNT(*) FROM ("
|
||||
+ " SELECT t.id FROM biz_file_task t"
|
||||
+ " WHERE t.module_type IN (" + CLIENT_MODULE_TYPES + ")"
|
||||
+ " AND t.status IN (" + TERMINAL_STATUSES + ")"
|
||||
+ " AND COALESCE(t.finished_at, t.updated_at) >= #{since}"
|
||||
+ " <if test='userIds != null'> AND t.user_id IN"
|
||||
+ " <foreach collection='userIds' item='uid' open='(' separator=',' close=')'>#{uid}</foreach></if>"
|
||||
+ " UNION ALL"
|
||||
+ " SELECT b.id FROM brand_crawl_tasks b"
|
||||
+ " WHERE b.status IN (" + BRAND_TERMINAL_STATUSES + ")"
|
||||
+ " AND b.updated_at >= #{since}"
|
||||
+ " <if test='userIds != null'> AND b.user_id IN"
|
||||
+ " <foreach collection='userIds' item='uid' open='(' separator=',' close=')'>#{uid}</foreach></if>"
|
||||
+ ") u"
|
||||
+ "</script>")
|
||||
long countFinishedTasksSince(@Param("userIds") List<Long> userIds,
|
||||
@Param("since") LocalDateTime since);
|
||||
|
||||
@Select("<script>"
|
||||
+ "SELECT COUNT(DISTINCT u.device_id) FROM " + ROSTER_ROWS + " u"
|
||||
+ "</script>")
|
||||
long countRosterDevices(@Param("userIds") List<Long> userIds,
|
||||
@Param("taskSince") LocalDateTime taskSince,
|
||||
@Param("logSince") LocalDateTime logSince);
|
||||
|
||||
@Select("<script>"
|
||||
+ "SELECT COUNT(*) FROM ("
|
||||
+ " SELECT u.device_id, MAX(u.activity_at) AS last_active FROM " + ROSTER_ROWS + " u"
|
||||
+ " GROUP BY u.device_id"
|
||||
+ " HAVING MAX(u.activity_at) >= #{onlineSince}"
|
||||
+ ") online"
|
||||
+ "</script>")
|
||||
long countOnlineDevices(@Param("userIds") List<Long> userIds,
|
||||
@Param("taskSince") LocalDateTime taskSince,
|
||||
@Param("logSince") LocalDateTime logSince,
|
||||
@Param("onlineSince") LocalDateTime onlineSince);
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.nanri.aiimage.modules.taskcenter.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 客户端任务管理汇总卡。设备口径见设备花名册(任务设备近 30 天 ∪ 日志设备近 7 天)。
|
||||
*/
|
||||
@Data
|
||||
public class TaskCenterOverviewVo {
|
||||
|
||||
/** 花名册设备总数。 */
|
||||
private long deviceTotal;
|
||||
/** 在线设备数(最近上报 ≤ 5 分钟)。 */
|
||||
private long deviceOnline;
|
||||
/** 进行中任务数(含品牌检测)。 */
|
||||
private long runningTasks;
|
||||
/** 今日完成任务数(终态且完成时间在今日)。 */
|
||||
private long todayFinishedTasks;
|
||||
/** 疑似卡住:进行中且超过 10 分钟无更新。 */
|
||||
private long stuckTasks;
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.nanri.aiimage.modules.taskcenter.service;
|
||||
|
||||
import com.nanri.aiimage.modules.taskcenter.mapper.TaskCenterQueryMapper;
|
||||
import com.nanri.aiimage.modules.taskcenter.model.vo.TaskCenterOverviewVo;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 客户端任务管理的只读查询。时间口径:卡住 10 分钟、在线 5 分钟、
|
||||
* 任务设备回看 30 天、日志设备回看 7 天。
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class TaskCenterQueryService {
|
||||
|
||||
private static final long STUCK_IDLE_MINUTES = 10;
|
||||
private static final long ONLINE_WINDOW_MINUTES = 5;
|
||||
private static final long TASK_DEVICE_WINDOW_DAYS = 30;
|
||||
private static final long LOG_DEVICE_WINDOW_DAYS = 7;
|
||||
|
||||
private final TaskCenterQueryMapper queryMapper;
|
||||
|
||||
public TaskCenterOverviewVo overview(TaskCenterScopeService.ScopeContext scope) {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
LocalDateTime taskSince = now.minusDays(TASK_DEVICE_WINDOW_DAYS);
|
||||
LocalDateTime logSince = now.minusDays(LOG_DEVICE_WINDOW_DAYS);
|
||||
List<Long> userIds = scope.sqlUserIds();
|
||||
|
||||
TaskCenterOverviewVo vo = new TaskCenterOverviewVo();
|
||||
vo.setRunningTasks(queryMapper.countRunningTasks(userIds));
|
||||
vo.setStuckTasks(queryMapper.countStuckTasks(userIds, now.minusMinutes(STUCK_IDLE_MINUTES)));
|
||||
vo.setTodayFinishedTasks(queryMapper.countFinishedTasksSince(userIds, LocalDate.now().atStartOfDay()));
|
||||
vo.setDeviceTotal(queryMapper.countRosterDevices(userIds, taskSince, logSince));
|
||||
vo.setDeviceOnline(queryMapper.countOnlineDevices(userIds, taskSince, logSince,
|
||||
now.minusMinutes(ONLINE_WINDOW_MINUTES)));
|
||||
return vo;
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package com.nanri.aiimage.modules.taskcenter.service;
|
||||
|
||||
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 lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 客户端任务管理的数据范围:超管看全部,管理员看「本人 + 本组用户 + 自己管理的成员」。
|
||||
* 口径与 {@code DedupeTotalDataService.resolveAccessScope} 一致——范围按任务发起账号
|
||||
* (biz_file_task.user_id)判定,不按设备归属,设备跨组使用也不会串组。
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class TaskCenterScopeService {
|
||||
|
||||
private final AdminUserMapper adminUserMapper;
|
||||
private final ShopManageGroupMapper shopManageGroupMapper;
|
||||
|
||||
public ScopeContext resolve(Long operatorId) {
|
||||
AdminUserEntity operator = requireOperator(operatorId);
|
||||
if (isSuperAdmin(operator)) {
|
||||
return new ScopeContext(true, Set.of());
|
||||
}
|
||||
List<Long> accessibleGroupIds = shopManageGroupMapper.selectAccessibleGroupIds(operator.getId());
|
||||
LinkedHashSet<Long> visibleUserIds = new LinkedHashSet<>();
|
||||
visibleUserIds.add(operator.getId());
|
||||
if (accessibleGroupIds != null && !accessibleGroupIds.isEmpty()) {
|
||||
addAll(visibleUserIds, shopManageGroupMapper.selectUserIdsByGroupIds(accessibleGroupIds));
|
||||
}
|
||||
addAll(visibleUserIds, shopManageGroupMapper.selectManagedMemberUserIds(operator.getId()));
|
||||
return new ScopeContext(false, Set.copyOf(visibleUserIds));
|
||||
}
|
||||
|
||||
private static void addAll(LinkedHashSet<Long> target, List<Long> ids) {
|
||||
if (ids == null) {
|
||||
return;
|
||||
}
|
||||
ids.stream().filter(id -> id != null && id > 0).forEach(target::add);
|
||||
}
|
||||
|
||||
private AdminUserEntity requireOperator(Long operatorId) {
|
||||
if (operatorId == null || operatorId <= 0) {
|
||||
throw new BusinessException(403, "需要管理员权限");
|
||||
}
|
||||
AdminUserEntity operator = adminUserMapper.selectById(operatorId);
|
||||
if (operator == null) {
|
||||
throw new BusinessException(403, "需要管理员权限");
|
||||
}
|
||||
return operator;
|
||||
}
|
||||
|
||||
private boolean isSuperAdmin(AdminUserEntity user) {
|
||||
String role = user.getRole() == null ? "" : user.getRole().trim().toLowerCase(Locale.ROOT);
|
||||
return "super_admin".equals(role)
|
||||
|| (role.isEmpty() && Integer.valueOf(1).equals(user.getIsAdmin()) && user.getCreatedById() == null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param allUsers 超管直通,不按用户裁剪
|
||||
* @param visibleUserIds 非超管的可见用户集合(至少含本人)
|
||||
*/
|
||||
public record ScopeContext(boolean allUsers, Set<Long> visibleUserIds) {
|
||||
|
||||
/** 可见用户是否包含该账号;用户号为空一律不可见。 */
|
||||
public boolean visible(Long userId) {
|
||||
return allUsers || (userId != null && userId > 0 && visibleUserIds.contains(userId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 传给 SQL 的用户白名单:超管返回 null(不加过滤);非超管空集用 {@code [-1]} 兜底,
|
||||
* 保证 {@code IN} 选中零行而不是整表。
|
||||
*/
|
||||
public List<Long> sqlUserIds() {
|
||||
if (allUsers) {
|
||||
return null;
|
||||
}
|
||||
return visibleUserIds.isEmpty() ? List.of(-1L) : List.copyOf(visibleUserIds);
|
||||
}
|
||||
}
|
||||
}
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
package com.nanri.aiimage.modules.taskcenter.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import org.apache.ibatis.mapping.BoundSql;
|
||||
import org.apache.ibatis.mapping.MappedStatement;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* 由 MyBatis 真正解析 {@code @Select} 脚本,验证动态 SQL 模板可渲染、范围占位符数量正确。
|
||||
* 不连库:只断言生成的 SQL 文本与参数绑定,防住「脚本写坏到启动期才炸」。
|
||||
*
|
||||
* <p>注意:{@code <} 必须写成 XML 实体、{@code <>} 不能直接出现在脚本里(非法 XML),
|
||||
* 本类同时是这两条约束的回归网。</p>
|
||||
*/
|
||||
class TaskCenterQueryMapperSqlTest {
|
||||
|
||||
private static MybatisConfiguration configuration;
|
||||
|
||||
@BeforeAll
|
||||
static void setUp() {
|
||||
configuration = new MybatisConfiguration();
|
||||
configuration.addMapper(TaskCenterQueryMapper.class);
|
||||
}
|
||||
|
||||
private static BoundSql render(String method, Map<String, Object> params) {
|
||||
MappedStatement statement = configuration.getMappedStatement(
|
||||
TaskCenterQueryMapper.class.getName() + "." + method);
|
||||
return statement.getBoundSql(params);
|
||||
}
|
||||
|
||||
private static Map<String, Object> params(Object... keyValues) {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
for (int i = 0; i < keyValues.length; i += 2) {
|
||||
map.put((String) keyValues[i], keyValues[i + 1]);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/** 折叠空白:脚本渲染会保留缩进与 foreach 内补的空白,断言只看语义,不看排版。 */
|
||||
private static String sqlOf(BoundSql boundSql) {
|
||||
return boundSql.getSql().replaceAll("\\s+", " ").trim()
|
||||
.replaceAll("\\s*\\(\\s*", "(")
|
||||
.replaceAll("\\s*\\)", ")")
|
||||
.replaceAll("\\s*,\\s*", ",");
|
||||
}
|
||||
|
||||
@Test
|
||||
void runningCountWithoutScopeFiltersNothing() {
|
||||
BoundSql boundSql = render("countRunningTasks", params("userIds", null));
|
||||
String sql = sqlOf(boundSql);
|
||||
|
||||
assertTrue(sql.contains("biz_file_task"));
|
||||
assertTrue(sql.contains("brand_crawl_tasks"));
|
||||
assertTrue(sql.contains("AND t.status IN('PENDING','RUNNING','SCHEDULED')"));
|
||||
assertTrue(sql.contains("WHERE b.status IN('pending','running')"), "品牌表状态小写");
|
||||
assertFalse(sql.contains("user_id IN"), "超管不按账号裁剪");
|
||||
assertEquals(0, boundSql.getParameterMappings().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void runningCountScopedBindsEveryVisibleUser() {
|
||||
BoundSql boundSql = render("countRunningTasks", params("userIds", List.of(5L, 11L)));
|
||||
String sql = sqlOf(boundSql);
|
||||
|
||||
assertTrue(sql.contains("AND t.user_id IN(?,?)"));
|
||||
assertTrue(sql.contains("AND b.user_id IN(?,?)"));
|
||||
assertEquals(4, boundSql.getParameterMappings().size(), "两张表各绑一次可见账号集合");
|
||||
assertEquals(5L, boundSql.getAdditionalParameter("__frch_uid_0"), "第一个可见账号");
|
||||
assertEquals(11L, boundSql.getAdditionalParameter("__frch_uid_1"), "第二个可见账号");
|
||||
}
|
||||
|
||||
@Test
|
||||
void stuckCountAppliesIdleThresholdToBothSources() {
|
||||
LocalDateTime idleBefore = LocalDateTime.of(2026, 9, 28, 10, 0);
|
||||
BoundSql boundSql = render("countStuckTasks",
|
||||
params("userIds", List.of(7L), "idleBefore", idleBefore));
|
||||
String sql = sqlOf(boundSql);
|
||||
|
||||
assertTrue(sql.contains("AND t.updated_at < ?"), "卡住判定按 updated_at 阈值");
|
||||
assertTrue(sql.contains("AND b.updated_at < ?"));
|
||||
assertEquals(4, boundSql.getParameterMappings().size(), "阈值在两张表各绑一次 + 两张表各绑一次可见账号");
|
||||
assertEquals(7L, boundSql.getAdditionalParameter("__frch_uid_0"), "可见账号集合生效");
|
||||
}
|
||||
|
||||
@Test
|
||||
void finishedCountUsesFinishedAtWithUpdatedAtFallback() {
|
||||
BoundSql boundSql = render("countFinishedTasksSince",
|
||||
params("userIds", List.of(5L), "since", LocalDateTime.of(2026, 9, 28, 0, 0)));
|
||||
String sql = sqlOf(boundSql);
|
||||
|
||||
assertTrue(sql.contains("AND COALESCE(t.finished_at,t.updated_at) >= ?"),
|
||||
"biz_file_task 优先 finished_at");
|
||||
assertTrue(sql.contains("AND b.updated_at >= ?"), "品牌表无 finished_at 用 updated_at");
|
||||
assertEquals(4, boundSql.getParameterMappings().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rosterExcludesBlankDeviceAndUngroupedLogDevices() {
|
||||
LocalDateTime since = LocalDateTime.of(2026, 9, 1, 0, 0);
|
||||
BoundSql boundSql = render("countRosterDevices",
|
||||
params("userIds", List.of(5L), "taskSince", since, "logSince", since));
|
||||
String sql = sqlOf(boundSql);
|
||||
|
||||
assertTrue(sql.contains("SELECT COUNT(DISTINCT u.device_id)"));
|
||||
assertTrue(sql.contains("d.device_id != ''"), "空设备号不参与");
|
||||
assertTrue(sql.contains("d.uid IS NOT NULL"), "无归属账号的日志设备不显示");
|
||||
assertTrue(sql.contains("d.source = 'client'"), "只看客户端日志设备");
|
||||
assertTrue(sql.contains("AND d.last_upload_at >= ?"), "日志设备回看窗口");
|
||||
assertEquals(6, boundSql.getParameterMappings().size(), "任务窗口×2 + 日志窗口 + 账号集合×3");
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlineCountGroupsByDeviceAndKeepsOnlyFreshOnes() {
|
||||
LocalDateTime since = LocalDateTime.of(2026, 9, 1, 0, 0);
|
||||
BoundSql boundSql = render("countOnlineDevices",
|
||||
params("userIds", null, "taskSince", since, "logSince", since,
|
||||
"onlineSince", LocalDateTime.of(2026, 9, 28, 10, 0)));
|
||||
String sql = sqlOf(boundSql);
|
||||
|
||||
assertTrue(sql.contains("GROUP BY u.device_id"));
|
||||
assertTrue(sql.contains("HAVING MAX(u.activity_at) >= ?"));
|
||||
assertFalse(sql.contains("__frch"), "超管不渲染账号占位符");
|
||||
assertEquals(4, boundSql.getParameterMappings().size(),
|
||||
"任务窗口×2 + 日志窗口 + 在线阈值");
|
||||
}
|
||||
|
||||
@Test
|
||||
void excludedServerSideModulesNeverAppear() {
|
||||
String sql = sqlOf(render("countRunningTasks", params("userIds", null)));
|
||||
|
||||
assertFalse(sql.contains("'DEDUPE'"), "去重为服务端执行,无客户端设备归属");
|
||||
assertFalse(sql.contains("'SPLIT'"));
|
||||
assertFalse(sql.contains("'CONVERT'"));
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
package com.nanri.aiimage.modules.taskcenter.service;
|
||||
|
||||
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 org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 客户端任务管理的组范围裁剪:超管直通,管理员 = 本人 + 本组用户 + 自己管理的成员。
|
||||
* 口径与 DedupeTotalDataService.resolveAccessScope 一致。
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class TaskCenterScopeServiceTest {
|
||||
|
||||
@Mock private AdminUserMapper adminUserMapper;
|
||||
@Mock private ShopManageGroupMapper shopManageGroupMapper;
|
||||
@InjectMocks private TaskCenterScopeService service;
|
||||
|
||||
private AdminUserEntity user(Long id, String role) {
|
||||
AdminUserEntity user = new AdminUserEntity();
|
||||
user.setId(id);
|
||||
user.setRole(role);
|
||||
user.setIsAdmin(1);
|
||||
return user;
|
||||
}
|
||||
|
||||
@Test
|
||||
void superAdminSeesAll() {
|
||||
when(adminUserMapper.selectById(1L)).thenReturn(user(1L, "super_admin"));
|
||||
|
||||
TaskCenterScopeService.ScopeContext scope = service.resolve(1L);
|
||||
|
||||
assertTrue(scope.allUsers(), "超管不裁剪");
|
||||
assertTrue(scope.visibleUserIds().isEmpty(), "超管无需可见用户集合");
|
||||
assertTrue(scope.visible(999L), "超管对任意用户可见");
|
||||
}
|
||||
|
||||
@Test
|
||||
void legacyAdminWithoutRoleCountsAsSuperAdmin() {
|
||||
AdminUserEntity legacy = new AdminUserEntity();
|
||||
legacy.setId(2L);
|
||||
legacy.setIsAdmin(1);
|
||||
legacy.setCreatedById(null);
|
||||
when(adminUserMapper.selectById(2L)).thenReturn(legacy);
|
||||
|
||||
assertTrue(service.resolve(2L).allUsers(), "历史超管(无 role)直通");
|
||||
}
|
||||
|
||||
@Test
|
||||
void adminGetsSelfPlusGroupUsersPlusManaged() {
|
||||
when(adminUserMapper.selectById(5L)).thenReturn(user(5L, "admin"));
|
||||
when(shopManageGroupMapper.selectAccessibleGroupIds(5L)).thenReturn(List.of(3L));
|
||||
when(shopManageGroupMapper.selectUserIdsByGroupIds(List.of(3L))).thenReturn(List.of(11L, 12L));
|
||||
when(shopManageGroupMapper.selectManagedMemberUserIds(5L)).thenReturn(List.of(13L));
|
||||
|
||||
TaskCenterScopeService.ScopeContext scope = service.resolve(5L);
|
||||
|
||||
assertFalse(scope.allUsers());
|
||||
assertEquals(Set.of(5L, 11L, 12L, 13L), scope.visibleUserIds());
|
||||
assertTrue(scope.visible(11L));
|
||||
assertFalse(scope.visible(99L), "组外用户不可见");
|
||||
assertFalse(scope.visible(null), "空用户号不可见");
|
||||
}
|
||||
|
||||
@Test
|
||||
void adminWithNoGroupHasOnlySelf() {
|
||||
when(adminUserMapper.selectById(5L)).thenReturn(user(5L, "admin"));
|
||||
when(shopManageGroupMapper.selectAccessibleGroupIds(5L)).thenReturn(List.of());
|
||||
when(shopManageGroupMapper.selectManagedMemberUserIds(5L)).thenReturn(List.of());
|
||||
|
||||
TaskCenterScopeService.ScopeContext scope = service.resolve(5L);
|
||||
|
||||
assertEquals(Set.of(5L), scope.visibleUserIds(), "无组无成员时不越权");
|
||||
assertFalse(scope.allUsers());
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidAndDuplicateIdsAreDropped() {
|
||||
when(adminUserMapper.selectById(5L)).thenReturn(user(5L, "admin"));
|
||||
when(shopManageGroupMapper.selectAccessibleGroupIds(5L)).thenReturn(List.of(3L));
|
||||
when(shopManageGroupMapper.selectUserIdsByGroupIds(anyList()))
|
||||
.thenReturn(java.util.Arrays.asList(5L, null, 0L, -1L, 11L));
|
||||
when(shopManageGroupMapper.selectManagedMemberUserIds(anyLong())).thenReturn(List.of(11L));
|
||||
|
||||
TaskCenterScopeService.ScopeContext scope = service.resolve(5L);
|
||||
|
||||
assertEquals(Set.of(5L, 11L), scope.visibleUserIds(), "空号/负数丢弃,重复去重");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullMapperResultDegradesToSelf() {
|
||||
lenient().when(adminUserMapper.selectById(5L)).thenReturn(user(5L, "admin"));
|
||||
lenient().when(shopManageGroupMapper.selectAccessibleGroupIds(5L)).thenReturn(List.of(3L));
|
||||
lenient().when(shopManageGroupMapper.selectUserIdsByGroupIds(anyList())).thenReturn(null);
|
||||
lenient().when(shopManageGroupMapper.selectManagedMemberUserIds(5L)).thenReturn(null);
|
||||
|
||||
assertEquals(Set.of(5L), service.resolve(5L).visibleUserIds());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownOperatorRejected() {
|
||||
when(adminUserMapper.selectById(404L)).thenReturn(null);
|
||||
assertThrows(BusinessException.class, () -> service.resolve(404L));
|
||||
assertThrows(BusinessException.class, () -> service.resolve(null));
|
||||
}
|
||||
}
|
||||
@@ -107,7 +107,7 @@
|
||||
|
||||
对齐 V119/V127/V130 幂等写法,可重复执行:
|
||||
|
||||
1. `biz_file_task` ADD COLUMN `device_id VARCHAR(128) NULL`(+ `KEY idx_file_task_device (device_id, created_at)`)
|
||||
1. `biz_file_task` ADD COLUMN `device_id VARCHAR(128) NULL`(+ `KEY idx_file_task_device_created (device_id, created_at)`)
|
||||
2. `brand_crawl_tasks` ADD COLUMN `device_id VARCHAR(128) NULL`
|
||||
3. 菜单行:`column_key='admin_task_center'`,name='客户端任务管理',`menu_type='admin'`,
|
||||
`route_path='task-center/board'`,parent=`admin_group_record`,sort_order=84
|
||||
|
||||
Reference in New Issue
Block a user