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
@@ -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)));
}
}