feat(taskcenter): 设备花名册与在线状态接口

新增 GET /api/admin/task-center/devices:任务设备(近 30 天)∪ 客户端日志设备
(近 7 天、uid 非空)合并去重,设备名取日志侧、最近任务时间取任务侧;在线 =
最近活动(任务 updated_at ∪ 日志上报)≤ 5 分钟,在线优先排序。`web-` 前缀标
webDevice 供前端标注「网页」。

SQL 侧把原来的 ROSTER_ROWS 拆成 TASK_DEVICE_ROWS + LOG_DEVICE_ROWS 再组合,
统计口径与列表共用同一段并集,避免两处漂移;新增按设备统计进行中任务数
(空设备号不归属任何设备)。overview 的 deviceTotal/deviceOnline 继续走
COUNT 查询(同一并集常量派生),不再从列表二次计算。

测试:Service 合并/在线阈值/空设备号/排序/网页标记 8 项,Mapper 动态 SQL 9 项。
This commit is contained in:
2026-09-28 22:54:36 +08:00
parent 8485469137
commit cd9bf509ec
8 changed files with 425 additions and 17 deletions
@@ -4,6 +4,7 @@ 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.TaskCenterDeviceVo;
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;
@@ -16,6 +17,8 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 后台「客户端任务管理」:按账号 × 设备 × 业务统一看客户端任务,不必逐台排查。
*
@@ -41,6 +44,14 @@ public class AdminTaskCenterController {
return ApiResponse.success(queryService.overview(scope));
}
@GetMapping("/devices")
@Operation(summary = "设备列表",
description = "设备花名册(任务设备近 30 天 ∪ 客户端日志设备近 7 天)+ 在线/跑任务状态;在线优先排序。")
public ApiResponse<List<TaskCenterDeviceVo>> devices(HttpServletRequest request) {
TaskCenterScopeService.ScopeContext scope = resolveScope(request);
return ApiResponse.success(queryService.devices(scope));
}
private TaskCenterScopeService.ScopeContext resolveScope(HttpServletRequest request) {
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
permissionMenuService.requireClientTaskCenterAccess(operator);
@@ -1,5 +1,6 @@
package com.nanri.aiimage.modules.taskcenter.mapper;
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterDeviceRow;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
@@ -38,10 +39,11 @@ public interface TaskCenterQueryMapper {
String BRAND_TERMINAL_STATUSES = "'success','failed','cancelled'";
/**
* 设备花名册原始行:任务设备(近 N 天创建过任务)+ 日志设备(近 N 天有上报,uid 为空不归组)。
* 每行 {@code device_id + activity_at},同设备多行由外层聚合。
* 任务设备原始行:近 N 天创建过任务、设备号非空(biz_file_task ∪ brand_crawl_tasks)。
* {@code createdAt} 供「最近任务时间」,{@code activityAt} 供在线判定;任务侧没有设备名。
*/
String ROSTER_ROWS = "(SELECT t.device_id AS device_id, t.updated_at AS activity_at"
String TASK_DEVICE_ROWS = "(SELECT t.device_id AS deviceId, NULL AS deviceName,"
+ " t.updated_at AS activityAt, t.created_at AS createdAt"
+ " FROM biz_file_task t"
+ " WHERE t.module_type IN (" + CLIENT_MODULE_TYPES + ")"
+ " AND t.device_id IS NOT NULL AND t.device_id != ''"
@@ -49,13 +51,19 @@ public interface TaskCenterQueryMapper {
+ " <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"
+ " SELECT b.device_id, NULL, b.updated_at, b.created_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"
+ " <foreach collection='userIds' item='uid' open='(' separator=',' close=')'>#{uid}</foreach></if>)";
/**
* 日志设备原始行:客户端日志、uid 非空(为空无法归组)、近 N 天有上报。
* {@code createdAt} 恒空,只为了与任务侧列对齐。
*/
String LOG_DEVICE_ROWS = "(SELECT d.device_id AS deviceId, d.device_name AS deviceName,"
+ " COALESCE(d.last_upload_at, d.updated_at) AS activityAt, NULL AS createdAt"
+ " FROM device_log_file d"
+ " WHERE d.source = 'client'"
+ " AND d.device_id != ''"
+ " AND d.uid IS NOT NULL"
@@ -63,6 +71,24 @@ public interface TaskCenterQueryMapper {
+ " <if test='userIds != null'> AND d.uid IN"
+ " <foreach collection='userIds' item='uid' open='(' separator=',' close=')'>#{uid}</foreach></if>)";
/** 设备花名册:任务设备 ∪ 日志设备(同设备多行由外层聚合)。 */
String ROSTER_ROWS = "(" + TASK_DEVICE_ROWS + " UNION ALL " + LOG_DEVICE_ROWS + ")";
/** 进行中任务原始行(带设备号),供按设备计数。 */
String RUNNING_TASK_DEVICE_ROWS = "(SELECT t.device_id AS deviceId"
+ " FROM biz_file_task t"
+ " WHERE t.module_type IN (" + CLIENT_MODULE_TYPES + ")"
+ " AND t.status IN (" + ACTIVE_STATUSES + ")"
+ " AND t.device_id IS NOT NULL AND t.device_id != ''"
+ " <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 FROM brand_crawl_tasks b"
+ " WHERE b.status IN (" + BRAND_ACTIVE_STATUSES + ")"
+ " AND b.device_id IS NOT NULL AND b.device_id != ''"
+ " <if test='userIds != null'> AND b.user_id 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"
@@ -118,7 +144,7 @@ public interface TaskCenterQueryMapper {
@Param("since") LocalDateTime since);
@Select("<script>"
+ "SELECT COUNT(DISTINCT u.device_id) FROM " + ROSTER_ROWS + " u"
+ "SELECT COUNT(DISTINCT u.deviceId) FROM " + ROSTER_ROWS + " u"
+ "</script>")
long countRosterDevices(@Param("userIds") List<Long> userIds,
@Param("taskSince") LocalDateTime taskSince,
@@ -126,13 +152,32 @@ public interface TaskCenterQueryMapper {
@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}"
+ " SELECT u.deviceId, MAX(u.activityAt) AS lastActiveAt FROM " + ROSTER_ROWS + " u"
+ " GROUP BY u.deviceId"
+ " HAVING MAX(u.activityAt) >= #{onlineSince}"
+ ") online"
+ "</script>")
long countOnlineDevices(@Param("userIds") List<Long> userIds,
@Param("taskSince") LocalDateTime taskSince,
@Param("logSince") LocalDateTime logSince,
@Param("onlineSince") LocalDateTime onlineSince);
/** 设备花名册列表:名称取日志侧,活动时间取两侧最大,最近任务时间取任务侧最大创建时间。 */
@Select("<script>"
+ "SELECT u.deviceId AS deviceId, MAX(u.deviceName) AS deviceName,"
+ " MAX(u.activityAt) AS lastActiveAt, MAX(u.createdAt) AS recentTaskAt"
+ " FROM " + ROSTER_ROWS + " u"
+ " GROUP BY u.deviceId"
+ "</script>")
List<TaskCenterDeviceRow> listRosterDevices(@Param("userIds") List<Long> userIds,
@Param("taskSince") LocalDateTime taskSince,
@Param("logSince") LocalDateTime logSince);
/** 按设备统计进行中任务数(设备号为空的任务不归属任何设备)。 */
@Select("<script>"
+ "SELECT u.deviceId AS deviceId, COUNT(*) AS runningTasks"
+ " FROM " + RUNNING_TASK_DEVICE_ROWS + " u"
+ " GROUP BY u.deviceId"
+ "</script>")
List<TaskCenterDeviceRow> countRunningTasksByDevice(@Param("userIds") List<Long> userIds);
}
@@ -0,0 +1,27 @@
package com.nanri.aiimage.modules.taskcenter.model.dto;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 设备聚合行:三条查询各填一部分字段(MyBatis 自动映射,未选出的列留空)。
*
* <ul>
* <li>花名册查询(任务设备 ∪ 日志设备):deviceId / deviceName / lastActiveAt / recentTaskAt</li>
* <li>进行中统计(按设备):deviceId / runningTasks</li>
* </ul>
*/
@Data
public class TaskCenterDeviceRow {
private String deviceId;
/** 日志侧展示名(机器名/登录名);任务侧无此数据。 */
private String deviceName;
/** 最近活动:任务 updated_at ∪ 日志上报时间。 */
private LocalDateTime lastActiveAt;
/** 最近一次任务的创建时间(30 天窗口内)。 */
private LocalDateTime recentTaskAt;
/** 该设备进行中任务数。 */
private Long runningTasks;
}
@@ -0,0 +1,24 @@
package com.nanri.aiimage.modules.taskcenter.model.vo;
import lombok.Data;
import java.time.LocalDateTime;
/** 设备状态行:花名册内的设备 + 在线/跑任务状态。 */
@Data
public class TaskCenterDeviceVo {
private String deviceId;
/** 展示名(device_log_file 的主机名/登录名);任务侧设备无此字段,前端按 deviceId 截断显示。 */
private String deviceName;
/** 最近活动时间;为空表示只有进行中任务、窗口内无活动记录。 */
private LocalDateTime lastActiveAt;
/** 在线 = 最近活动 ≤ 5 分钟。 */
private boolean online;
/** 该设备进行中任务数。 */
private long runningTasks;
/** 最近一次任务创建时间(30 天窗口内)。 */
private LocalDateTime recentTaskAt;
/** 网页登录设备(device_id 前缀 web-)。 */
private boolean webDevice;
}
@@ -1,13 +1,19 @@
package com.nanri.aiimage.modules.taskcenter.service;
import com.nanri.aiimage.modules.taskcenter.mapper.TaskCenterQueryMapper;
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterDeviceRow;
import com.nanri.aiimage.modules.taskcenter.model.vo.TaskCenterDeviceVo;
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.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 客户端任务管理的只读查询。时间口径:卡住 10 分钟、在线 5 分钟、
@@ -39,4 +45,53 @@ public class TaskCenterQueryService {
now.minusMinutes(ONLINE_WINDOW_MINUTES)));
return vo;
}
/** 设备花名册:任务设备 ∪ 日志设备,在线优先、活动时间倒序。 */
public List<TaskCenterDeviceVo> devices(TaskCenterScopeService.ScopeContext scope) {
LocalDateTime now = LocalDateTime.now();
List<Long> userIds = scope.sqlUserIds();
Map<String, TaskCenterDeviceVo> byDevice = new LinkedHashMap<>();
for (TaskCenterDeviceRow row : queryMapper.listRosterDevices(userIds,
now.minusDays(TASK_DEVICE_WINDOW_DAYS), now.minusDays(LOG_DEVICE_WINDOW_DAYS))) {
TaskCenterDeviceVo vo = deviceOf(byDevice, row.getDeviceId());
if (vo != null) {
vo.setDeviceName(row.getDeviceName());
vo.setLastActiveAt(row.getLastActiveAt());
vo.setRecentTaskAt(row.getRecentTaskAt());
}
}
for (TaskCenterDeviceRow row : queryMapper.countRunningTasksByDevice(userIds)) {
TaskCenterDeviceVo vo = deviceOf(byDevice, row.getDeviceId());
if (vo != null && row.getRunningTasks() != null) {
vo.setRunningTasks(row.getRunningTasks());
}
}
LocalDateTime onlineSince = now.minusMinutes(ONLINE_WINDOW_MINUTES);
List<TaskCenterDeviceVo> devices = new ArrayList<>(byDevice.values());
for (TaskCenterDeviceVo vo : devices) {
vo.setOnline(vo.getLastActiveAt() != null && !vo.getLastActiveAt().isBefore(onlineSince));
}
devices.sort(Comparator
.comparing(TaskCenterDeviceVo::isOnline, Comparator.reverseOrder())
.thenComparing(TaskCenterDeviceVo::getLastActiveAt, Comparator.nullsLast(Comparator.reverseOrder()))
.thenComparing(vo -> vo.getDeviceName() == null ? "" : vo.getDeviceName())
.thenComparing(TaskCenterDeviceVo::getDeviceId));
return devices;
}
/** 空设备号入册无意义(SQL 已滤,这里挡住直调服务或脏数据)。 */
private static TaskCenterDeviceVo deviceOf(Map<String, TaskCenterDeviceVo> byDevice, String deviceId) {
if (deviceId == null || deviceId.isBlank()) {
return null;
}
String key = deviceId.trim();
return byDevice.computeIfAbsent(key, id -> {
TaskCenterDeviceVo vo = new TaskCenterDeviceVo();
vo.setDeviceId(id);
vo.setWebDevice(id.startsWith("web-"));
return vo;
});
}
}
@@ -111,7 +111,7 @@ class TaskCenterQueryMapperSqlTest {
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("SELECT COUNT(DISTINCT u.deviceId)"));
assertTrue(sql.contains("d.device_id != ''"), "空设备号不参与");
assertTrue(sql.contains("d.uid IS NOT NULL"), "无归属账号的日志设备不显示");
assertTrue(sql.contains("d.source = 'client'"), "只看客户端日志设备");
@@ -119,6 +119,33 @@ class TaskCenterQueryMapperSqlTest {
assertEquals(6, boundSql.getParameterMappings().size(), "任务窗口×2 + 日志窗口 + 账号集合×3");
}
@Test
void rosterListAggregatesNameAndRecencyPerDevice() {
LocalDateTime since = LocalDateTime.of(2026, 9, 1, 0, 0);
BoundSql boundSql = render("listRosterDevices",
params("userIds", null, "taskSince", since, "logSince", since));
String sql = sqlOf(boundSql);
assertTrue(sql.contains("MAX(u.deviceName) AS deviceName"), "设备名取日志侧");
assertTrue(sql.contains("MAX(u.activityAt) AS lastActiveAt"), "活动时间取两侧最大");
assertTrue(sql.contains("MAX(u.createdAt) AS recentTaskAt"), "最近任务时间取任务侧最大创建时间");
assertTrue(sql.contains("GROUP BY u.deviceId"));
assertTrue(sql.contains("NULL AS deviceName"), "任务侧没有设备名");
assertTrue(sql.contains("NULL AS createdAt"), "日志侧不贡献最近任务时间");
}
@Test
void runningCountByDeviceCountsOnlyDevicelessRows() {
BoundSql boundSql = render("countRunningTasksByDevice", params("userIds", List.of(5L)));
String sql = sqlOf(boundSql);
assertTrue(sql.contains("COUNT(*) AS runningTasks"));
assertTrue(sql.contains("GROUP BY u.deviceId"));
assertTrue(sql.contains("t.device_id IS NOT NULL AND t.device_id != ''"), "空设备号任务不归属设备");
assertTrue(sql.contains("b.device_id IS NOT NULL AND b.device_id != ''"));
assertEquals(2, boundSql.getParameterMappings().size(), "两张表各绑一次可见账号集合");
}
@Test
void onlineCountGroupsByDeviceAndKeepsOnlyFreshOnes() {
LocalDateTime since = LocalDateTime.of(2026, 9, 1, 0, 0);
@@ -127,8 +154,8 @@ class TaskCenterQueryMapperSqlTest {
"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) >= ?"));
assertTrue(sql.contains("GROUP BY u.deviceId"));
assertTrue(sql.contains("HAVING MAX(u.activityAt) >= ?"));
assertFalse(sql.contains("__frch"), "超管不渲染账号占位符");
assertEquals(4, boundSql.getParameterMappings().size(),
"任务窗口×2 + 日志窗口 + 在线阈值");
@@ -0,0 +1,219 @@
package com.nanri.aiimage.modules.taskcenter.service;
import com.nanri.aiimage.modules.taskcenter.mapper.TaskCenterQueryMapper;
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterDeviceRow;
import com.nanri.aiimage.modules.taskcenter.model.vo.TaskCenterDeviceVo;
import com.nanri.aiimage.modules.taskcenter.model.vo.TaskCenterOverviewVo;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.time.LocalDate;
import java.time.LocalDateTime;
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.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* 只读查询的 Java 侧口径:时间窗口(卡住 10 分钟 / 在线 5 分钟 / 任务 30 天 / 日志 7 天)、
* 设备花名册合并与在线判定、账号范围透传。SQL 本身由 TaskCenterQueryMapperSqlTest 守。
*/
@ExtendWith(MockitoExtension.class)
class TaskCenterQueryServiceTest {
@Mock private TaskCenterQueryMapper queryMapper;
@InjectMocks private TaskCenterQueryService service;
private static TaskCenterScopeService.ScopeContext superScope() {
return new TaskCenterScopeService.ScopeContext(true, Set.of());
}
private static TaskCenterScopeService.ScopeContext scoped(Long... userIds) {
return new TaskCenterScopeService.ScopeContext(false, Set.of(userIds));
}
private static TaskCenterDeviceRow rosterRow(String deviceId, String deviceName,
LocalDateTime lastActiveAt, LocalDateTime recentTaskAt) {
TaskCenterDeviceRow row = new TaskCenterDeviceRow();
row.setDeviceId(deviceId);
row.setDeviceName(deviceName);
row.setLastActiveAt(lastActiveAt);
row.setRecentTaskAt(recentTaskAt);
return row;
}
private static TaskCenterDeviceRow runningRow(String deviceId, long running) {
TaskCenterDeviceRow row = new TaskCenterDeviceRow();
row.setDeviceId(deviceId);
row.setRunningTasks(running);
return row;
}
private static boolean within(LocalDateTime value, LocalDateTime expected, long toleranceSeconds) {
return value != null
&& Math.abs(java.time.Duration.between(expected, value).getSeconds()) <= toleranceSeconds;
}
@Test
void overviewUsesDocumentedWindows() {
LocalDateTime before = LocalDateTime.now();
when(queryMapper.countRunningTasks(isNull())).thenReturn(3L);
when(queryMapper.countStuckTasks(isNull(), any())).thenReturn(1L);
when(queryMapper.countFinishedTasksSince(isNull(), any())).thenReturn(7L);
when(queryMapper.countRosterDevices(isNull(), any(), any())).thenReturn(9L);
when(queryMapper.countOnlineDevices(isNull(), any(), any(), any())).thenReturn(4L);
TaskCenterOverviewVo vo = service.overview(superScope());
assertEquals(3L, vo.getRunningTasks());
assertEquals(1L, vo.getStuckTasks());
assertEquals(7L, vo.getTodayFinishedTasks());
assertEquals(9L, vo.getDeviceTotal());
assertEquals(4L, vo.getDeviceOnline());
ArgumentCaptor<LocalDateTime> stuckAt = ArgumentCaptor.forClass(LocalDateTime.class);
verify(queryMapper).countStuckTasks(isNull(), stuckAt.capture());
assertTrue(within(stuckAt.getValue(), before.minusMinutes(10), 5), "卡住阈值 10 分钟");
ArgumentCaptor<LocalDateTime> finishedSince = ArgumentCaptor.forClass(LocalDateTime.class);
verify(queryMapper).countFinishedTasksSince(isNull(), finishedSince.capture());
assertEquals(LocalDate.now().atStartOfDay(), finishedSince.getValue(), "今日完成 = 今天 0 点起算");
ArgumentCaptor<LocalDateTime> taskSince = ArgumentCaptor.forClass(LocalDateTime.class);
ArgumentCaptor<LocalDateTime> logSince = ArgumentCaptor.forClass(LocalDateTime.class);
ArgumentCaptor<LocalDateTime> onlineSince = ArgumentCaptor.forClass(LocalDateTime.class);
verify(queryMapper)
.countOnlineDevices(isNull(), taskSince.capture(), logSince.capture(), onlineSince.capture());
assertTrue(within(taskSince.getValue(), before.minusDays(30), 5), "任务设备回看 30 天");
assertTrue(within(logSince.getValue(), before.minusDays(7), 5), "日志设备回看 7 天");
assertTrue(within(onlineSince.getValue(), before.minusMinutes(5), 5), "在线窗口 5 分钟");
}
@Test
void scopedOperatorPassesVisibleUsers() {
when(queryMapper.countRunningTasks(any())).thenReturn(0L);
when(queryMapper.countStuckTasks(any(), any())).thenReturn(0L);
when(queryMapper.countFinishedTasksSince(any(), any())).thenReturn(0L);
when(queryMapper.countRosterDevices(any(), any(), any())).thenReturn(0L);
when(queryMapper.countOnlineDevices(any(), any(), any(), any())).thenReturn(0L);
service.overview(scoped(5L, 11L));
verify(queryMapper).countRunningTasks(
argThat(ids -> ids != null && ids.size() == 2
&& ids.containsAll(List.of(5L, 11L))));
}
@Test
void mergeDeviceRosterAggregatesTaskAndLogDevices() {
LocalDateTime now = LocalDateTime.now();
when(queryMapper.listRosterDevices(any(), any(), any())).thenReturn(List.of(
rosterRow("dev-a", null, now.minusSeconds(30), now.minusMinutes(20)),
rosterRow("dev-b", "PC-B", now.minusMinutes(2), now.minusMinutes(40))));
when(queryMapper.countRunningTasksByDevice(any())).thenReturn(List.of(
runningRow("dev-a", 2L), runningRow("dev-c", 1L)));
List<TaskCenterDeviceVo> devices = service.devices(superScope());
assertEquals(3, devices.size(), "任务设备 ∪ 日志设备 ∪ 仅在跑任务的设备");
TaskCenterDeviceVo devA = devices.stream().filter(d -> "dev-a".equals(d.getDeviceId()))
.findFirst().orElseThrow();
assertEquals(2L, devA.getRunningTasks());
assertNull(devA.getDeviceName(), "任务侧没有设备名,留给前端按 device_id 截断展示");
TaskCenterDeviceVo devC = devices.stream().filter(d -> "dev-c".equals(d.getDeviceId()))
.findFirst().orElseThrow();
assertEquals(1L, devC.getRunningTasks());
assertNull(devC.getLastActiveAt(), "只有跑中任务、不在花名册窗口内的设备照常列出");
assertFalse(devC.isOnline());
}
@Test
void onlineThresholdIsFiveMinutes() {
LocalDateTime now = LocalDateTime.now();
when(queryMapper.listRosterDevices(any(), any(), any())).thenReturn(List.of(
rosterRow("fresh", "fresh", now.minusMinutes(4).minusSeconds(59), now),
rosterRow("stale", "stale", now.minusMinutes(5).minusSeconds(1), now)));
when(queryMapper.countRunningTasksByDevice(any())).thenReturn(List.of());
List<TaskCenterDeviceVo> devices = service.devices(superScope());
assertTrue(device(devices, "fresh").isOnline(), "4:59 → 在线");
assertFalse(device(devices, "stale").isOnline(), "5:01 → 离线");
}
@Test
void blankDeviceIdsAreSkipped() {
LocalDateTime now = LocalDateTime.now();
when(queryMapper.listRosterDevices(any(), any(), any())).thenReturn(java.util.Arrays.asList(
rosterRow(null, null, now, now), rosterRow("", null, now, now),
rosterRow("dev-a", "PC-A", now, now)));
when(queryMapper.countRunningTasksByDevice(any())).thenReturn(java.util.Arrays.asList(
runningRow(null, 1L), runningRow("dev-a", 1L)));
List<TaskCenterDeviceVo> devices = service.devices(superScope());
assertEquals(1, devices.size(), "空设备号不入册(SQL 已滤,服务侧再兜一层)");
assertEquals("dev-a", devices.get(0).getDeviceId());
assertEquals(1L, devices.get(0).getRunningTasks(), "空设备号的跑中任务不计入任何设备");
}
@Test
void devicesSortedOnlineFirstThenRecency() {
LocalDateTime now = LocalDateTime.now();
when(queryMapper.listRosterDevices(any(), any(), any())).thenReturn(List.of(
rosterRow("offline-new", "B", now.minusMinutes(30), now),
rosterRow("online-old", "C", now.minusMinutes(3), now.minusMinutes(20)),
rosterRow("online-new", "A", now.minusMinutes(2), now.minusMinutes(10))));
when(queryMapper.countRunningTasksByDevice(any())).thenReturn(List.of());
List<TaskCenterDeviceVo> devices = service.devices(superScope());
assertEquals(List.of("online-new", "online-old", "offline-new"),
devices.stream().map(TaskCenterDeviceVo::getDeviceId).toList(),
"在线优先,其次最近活动倒序");
}
@Test
void webLoginDeviceIsFlagged() {
LocalDateTime now = LocalDateTime.now();
when(queryMapper.listRosterDevices(any(), any(), any())).thenReturn(List.of(
rosterRow("web-1759000000-ab12", null, now, now),
rosterRow("pc-0001", null, now, now)));
when(queryMapper.countRunningTasksByDevice(any())).thenReturn(List.of());
List<TaskCenterDeviceVo> devices = service.devices(superScope());
assertTrue(device(devices, "web-1759000000-ab12").isWebDevice(), "网页登录标记");
assertFalse(device(devices, "pc-0001").isWebDevice());
assertEquals(2, devices.size(), "网页设备照常入册(是否隐藏由前端决定)");
}
private static TaskCenterDeviceVo device(List<TaskCenterDeviceVo> devices, String deviceId) {
return devices.stream().filter(d -> deviceId.equals(d.getDeviceId()))
.findFirst().orElseThrow(() -> new AssertionError("设备缺失: " + deviceId));
}
@Test
void scopedOperatorDevicesQueryUsesVisibleUsers() {
when(queryMapper.listRosterDevices(eq(List.of(5L)), any(), any())).thenReturn(List.of());
when(queryMapper.countRunningTasksByDevice(eq(List.of(5L)))).thenReturn(List.of());
service.devices(scoped(5L));
verify(queryMapper).listRosterDevices(eq(List.of(5L)), any(), any());
verify(queryMapper).countRunningTasksByDevice(eq(List.of(5L)));
}
}
+3 -3
View File
@@ -55,8 +55,8 @@
照记空 = 未记录);续跑任务(`TaskResumeService`)**继承原任务 device_id**。
- 新列:`biz_file_task.device_id`、`brand_crawl_tasks.device_id`(V138)。
- 历史任务 device_id 为空 → 显示「未记录」(不回填,无法追溯)。
- 设备展示名:`device_id` → `device_log_file` 该设备最新 `device_name`(主机名);
查不到时显示 device_id 截断值。
- 设备展示名:`device_id` → `device_log_file` 该设备 `device_name`(主机名,同设备多行聚合取 MAX,
与 `DeviceLogService.recentDevices` 同款);查不到时显示 device_id 截断值。
### 设备花名册(设备筛选器 + 设备状态卡)
@@ -130,7 +130,7 @@ SQL 用 `@Select` 注解 mapper + 手写 LIMIT/OFFSET 分页(先例 `ImageVide
| 接口 | 说明 |
|---|---|
| `GET /api/admin/task-center/overview` | 汇总卡:设备总数/在线数、进行中任务数、今日完成任务数、疑似卡住数 |
| `GET /api/admin/task-center/devices` | 设备列表:device_id、device_name、最近上报、在线、运行中任务数、最近任务时间 |
| `GET /api/admin/task-center/devices` | 设备列表:device_id、device_name、lastActiveAt(最近上报/任务活动)、online、runningTasks、recentTaskAt、webDevice(`web-` 前缀=网页登录) |
| `GET /api/admin/task-center/tasks` | 任务列表(分页 + 筛选:username、module_type、status、device_id、shop、start_time/end_time);字段:id、task_no、module_type、module_label、status、user_id、username、device_id、device_name、shop_name、shop_count、created_at、finished_at、progress{total,success,failed,current_scope,message}、stuck |
| `GET /api/admin/task-center/tasks/detail` | 任务详情(参数 `task_no`,品牌任务为 `brand-<id>`):基础信息 + 进度快照 + 店铺/文件明细 |
| `GET /api/admin/task-center/variant-tasks` | 变体采集列表(代理麦象 console):uid 集合 = 可见用户;page/page_size + status/task_type 筛选;字段:task_id、uid、username、status、res_mes、create_time、update_time |