feat(mcp): 新增站点备用机列表查询工具 hardware.back.list.query

- 复刻老系统(xiaoqu-complex)/districtHardwareBack/queryHardwareBackListByDistrictId,
  返回 LLM 友好记录列表,selectCount 修复老接口分页 records 取页大小的 bug
- districtId 与 snCode 至少传一个;onlineStatus 取自 hardware_view.status 按页批量 IN 查询
- 新增 applyHardwareBackRowFilter 镜像 hardware_view 行权限,补齐老接口缺失的权限过滤
- prod 启动绑定研发专用 scope 6(code=code),dev 种子绑「测试专用」(code=test)
This commit is contained in:
wangheng
2026-12-02 11:39:48 +08:00
parent 8b985a4696
commit 5650f6732e
9 changed files with 3234 additions and 2640 deletions
File diff suppressed because it is too large Load Diff
+7
View File
@@ -125,6 +125,13 @@ SELECT s.id, t.id, 0 FROM agent_scope s JOIN tool t
WHERE s.code = 'test' AND t.name = 'sms.vercode.latest.query'
AND NOT EXISTS (SELECT 1 FROM scope_tool st WHERE st.scope_id = s.id AND st.tool_id = t.id);
-- 站点备用机列表(hardware.back.list.query):拍板 prod 只绑研发专用 scope 6,
-- dev 等价绑「测试专用」(code='test');不进入 operation/hardware/ops-query/sync。
INSERT INTO scope_tool (scope_id, tool_id, create_id)
SELECT s.id, t.id, 0 FROM agent_scope s JOIN tool t
WHERE s.code = 'test' AND t.name = 'hardware.back.list.query'
AND NOT EXISTS (SELECT 1 FROM scope_tool st WHERE st.scope_id = s.id AND st.tool_id = t.id);
COMMIT;
-- 校验
@@ -0,0 +1,20 @@
-- =============================================================
-- prod 种子:hardware.back.list.query 绑定(只绑研发专用 scope 6,2026-12-02 拍板)
-- 前置:应用已完成部署启动(tool 表由 ToolSyncService 同步)后再执行本脚本。
-- 执行方式:在 prod svc 库上执行(mysql 客户端需已选中 svc 库,本脚本不含 USE)。
-- 幂等:按 (scope_id, tool_id) 判重,可重复执行;scope_tool 行按拍板显式使用 id=469。
-- =============================================================
START TRANSACTION;
INSERT INTO scope_tool (id, scope_id, tool_id, create_id)
SELECT 469, 6, t.id, 0 FROM tool t
WHERE t.name = 'hardware.back.list.query'
AND NOT EXISTS (SELECT 1 FROM scope_tool st WHERE st.scope_id = 6 AND st.tool_id = t.id);
COMMIT;
-- 校验:应返回 scope_id=6 绑定 hardware.back.list.query 一行
SELECT st.id, st.scope_id, t.id AS tool_id, t.name
FROM scope_tool st JOIN tool t ON st.tool_id = t.id
WHERE t.name = 'hardware.back.list.query';
@@ -0,0 +1,40 @@
package me.iiv.agent.entity.m0;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
import java.util.Date;
/** 站点备用机(m0.hardware_back)。 */
@Getter
@Setter
@ToString
@TableName("hardware_back")
public class HardwareBack implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private Long createId;
private Date createTime;
private Long modifyId;
private Date modifyTime;
private Integer softDelete;
private String snCode;
/** 是否备用机(0:否;1:是) */
private Integer backType;
/** 状态(0:可用;1:待修;2:返修) */
private Integer state;
private Long districtId;
/** 设备类型(0:厕纸机;1:擦手纸机) */
private Integer deviceType;
private Long propertyId;
private Long agentId;
private String memo;
}
@@ -0,0 +1,7 @@
package me.iiv.agent.mapper.m0;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import me.iiv.agent.entity.m0.HardwareBack;
public interface HardwareBackMapper extends BaseMapper<HardwareBack> {
}
@@ -0,0 +1,280 @@
package me.iiv.agent.mcp.tool;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import me.iiv.agent.entity.m0.HardwareBack;
import me.iiv.agent.entity.m0.HardwareView;
import me.iiv.agent.entity.m0.User;
import me.iiv.agent.entity.svc.AgentApiKey;
import me.iiv.agent.mapper.m0.HardwareBackMapper;
import me.iiv.agent.mapper.m0.HardwareViewMapper;
import me.iiv.agent.mcp.McpErrorCode;
import me.iiv.agent.mcp.ToolCallException;
import me.iiv.agent.mcp.ToolObject;
import me.iiv.agent.mcp.XqTool;
import me.iiv.agent.permission.PermissionService;
import me.iiv.agent.security.AuthContext;
import me.iiv.agent.security.AuthContextHolder;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* 站点备用机查询工具,复刻老系统(xiaoqu-complex)/districtHardwareBack/queryHardwareBackListByDistrictId。
* 老接口无任何权限过滤,MCP 侧按 hardware_view 同一行权限语义补齐(applyHardwareBackRowFilter);
* 分页修复老接口 records 取页大小的 bug(selectCount 取真实总数)。
*/
@Component
public class HardwareBackTools implements ToolObject {
private static final int DEFAULT_ROWS = 20;
private static final int MAX_ROWS = 100;
/** 老接口 Redis 字典 key(与 HardwareTools 同一字典) */
private static final String NAME_DISTRICT_PREFIX = "name:District:";
final HardwareBackMapper hardwareBackMapper;
final HardwareViewMapper hardwareViewMapper;
final PermissionService permissionService;
final StringRedisTemplate redisTemplate;
public HardwareBackTools(HardwareBackMapper hardwareBackMapper,
HardwareViewMapper hardwareViewMapper,
PermissionService permissionService,
StringRedisTemplate redisTemplate) {
this.hardwareBackMapper = hardwareBackMapper;
this.hardwareViewMapper = hardwareViewMapper;
this.permissionService = permissionService;
this.redisTemplate = redisTemplate;
}
@XqTool(category = "hardware", kind = "read")
@Tool(name = "hardware.back.list.query", description = "分页查询当前用户可见的站点备用机列表,"
+ "对应老系统 /districtHardwareBack/queryHardwareBackListByDistrictId。"
+ "districtId 与 snCode 至少传一个;snCode 模糊匹配,districtId、deviceType、state 精确匹配。"
+ "page 默认 1,rows 默认 20、上限 100,固定按 id 倒序。"
+ "onlineStatus 取自 hardware_view.status(1=在线 2=故障 3=离线),备用机未装机时无该记录,返回 null。"
+ "districtName 使用 Redis 批量富化;行级权限与 hardware.list.query 一致。")
public Map<String, Object> hardwareBackListQuery(
@ToolParam(required = false, description = "站点 id,正整数,精确匹配;与 snCode 至少传一个") Long districtId,
@ToolParam(required = false, description = "设备 SN,模糊匹配;与 districtId 至少传一个") String snCode,
@ToolParam(required = false, description = "设备类型:0=厕纸机 1=擦手纸机,缺省不过滤") Integer deviceType,
@ToolParam(required = false, description = "状态:0=可用 1=待修 2=返修,缺省不过滤") Integer state,
@ToolParam(required = false, description = "页码,从 1 开始,默认 1") Integer page,
@ToolParam(required = false, description = "每页条数,默认 20,上限 100") Integer rows) {
if (districtId == null && !StringUtils.hasText(snCode)) {
throw new IllegalArgumentException("districtId 与 snCode 至少传一个");
}
validatePositive(districtId, "districtId");
validateEnum(deviceType, "deviceType", 0, 1);
validateEnum(state, "state", 0, 1, 2);
User user = currentUser();
int pageNo = page == null || page < 1 ? 1 : page;
boolean truncated = rows != null && rows > MAX_ROWS;
int pageSize = rows == null || rows < 1 ? DEFAULT_ROWS : Math.min(rows, MAX_ROWS);
LambdaQueryWrapper<HardwareBack> wrapper = new LambdaQueryWrapper<HardwareBack>()
.eq(HardwareBack::getSoftDelete, 0);
if (districtId != null) {
wrapper.eq(HardwareBack::getDistrictId, districtId);
}
if (StringUtils.hasText(snCode)) {
wrapper.like(HardwareBack::getSnCode, snCode.trim());
}
if (deviceType != null) {
wrapper.eq(HardwareBack::getDeviceType, deviceType);
}
if (state != null) {
wrapper.eq(HardwareBack::getState, state);
}
permissionService.applyHardwareBackRowFilter(wrapper, user);
Long total = hardwareBackMapper.selectCount(wrapper);
wrapper.orderByDesc(HardwareBack::getId)
.last("LIMIT " + (long) (pageNo - 1) * pageSize + "," + pageSize);
List<HardwareBack> list = hardwareBackMapper.selectList(wrapper);
Map<String, Integer> onlineStatusBySn = onlineStatusBySn(list);
Map<Long, String> districtNames = districtNames(list);
List<Map<String, Object>> records = new ArrayList<>();
boolean missingOnlineStatus = false;
for (HardwareBack back : list) {
Integer onlineStatus = back.getSnCode() == null ? null : onlineStatusBySn.get(back.getSnCode());
missingOnlineStatus |= back.getSnCode() != null && !onlineStatusBySn.containsKey(back.getSnCode());
records.add(toRecord(back, onlineStatus, districtNames));
}
Map<String, Object> result = new LinkedHashMap<>();
result.put("total", total);
result.put("page", pageNo);
result.put("rows", pageSize);
List<String> notices = new ArrayList<>();
if (truncated) {
notices.add("rows 超过上限 100,已截断为 100");
}
if (missingOnlineStatus) {
notices.add("部分 SN 在 hardware_view 无记录(备用机未装机/未上线),onlineStatus 为 null");
}
if (!notices.isEmpty()) {
result.put("notice", String.join(";", notices));
}
result.put("records", records);
return result;
}
private User currentUser() {
AuthContext context = AuthContextHolder.get();
if (context == null || (context.getUser() == null && !isServicePrincipal(context))) {
throw new ToolCallException(McpErrorCode.UNAUTHENTICATED, "缺少有效身份上下文");
}
return context.getUser();
}
/** 按页批量查 hardware_view 的 status(对应老接口 Redis 在线判断的 MCP 口径),一次 IN 查询替代逐条 Redis。 */
private Map<String, Integer> onlineStatusBySn(List<HardwareBack> list) {
List<String> snCodes = list.stream().map(HardwareBack::getSnCode)
.filter(StringUtils::hasText).distinct().collect(Collectors.toList());
if (snCodes.isEmpty()) {
return Map.of();
}
List<HardwareView> views = hardwareViewMapper.selectList(new LambdaQueryWrapper<HardwareView>()
.eq(HardwareView::getSoftDelete, 0)
.in(HardwareView::getSnCode, snCodes)
.select(HardwareView::getSnCode, HardwareView::getStatus));
Map<String, Integer> statusBySn = new LinkedHashMap<>();
for (HardwareView view : views) {
statusBySn.putIfAbsent(view.getSnCode(), view.getStatus());
}
return statusBySn;
}
private Map<Long, String> districtNames(List<HardwareBack> list) {
List<Long> ids = list.stream().map(HardwareBack::getDistrictId)
.filter(Objects::nonNull).distinct().collect(Collectors.toList());
if (ids.isEmpty()) {
return Map.of();
}
List<String> keys = ids.stream().map(id -> NAME_DISTRICT_PREFIX + id).collect(Collectors.toList());
List<String> values = redisTemplate.opsForValue().multiGet(keys);
Map<Long, String> names = new LinkedHashMap<>();
for (int i = 0; i < ids.size(); i++) {
names.put(ids.get(i), values == null || i >= values.size() ? null : values.get(i));
}
return names;
}
private Map<String, Object> toRecord(HardwareBack back, Integer onlineStatus,
Map<Long, String> districtNames) {
Map<String, Object> record = new LinkedHashMap<>();
record.put("id", back.getId());
record.put("snCode", back.getSnCode());
record.put("backType", back.getBackType());
record.put("backTypeText", backTypeText(back.getBackType()));
record.put("state", back.getState());
record.put("stateText", stateText(back.getState()));
record.put("deviceType", back.getDeviceType());
record.put("deviceTypeText", deviceTypeText(back.getDeviceType()));
record.put("districtId", back.getDistrictId());
record.put("districtName", back.getDistrictId() == null
? null : districtNames.get(back.getDistrictId()));
record.put("propertyId", back.getPropertyId());
record.put("agentId", back.getAgentId());
record.put("onlineStatus", onlineStatus);
record.put("onlineStatusText", onlineStatusText(onlineStatus));
record.put("memo", back.getMemo());
record.put("createTime", format(back.getCreateTime()));
record.put("modifyTime", format(back.getModifyTime()));
return record;
}
private static boolean isServicePrincipal(AuthContext context) {
return context.getToken() != null
&& AgentApiKey.PRINCIPAL_TYPE_SERVICE.equals(context.getToken().getPrincipalType());
}
private static String format(Date value) {
return value == null ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(value);
}
private static void validatePositive(Long value, String name) {
if (value != null && value < 1) {
throw new IllegalArgumentException(name + " 必须为正整数");
}
}
private static void validateEnum(Integer value, String name, int... allowed) {
if (value == null) {
return;
}
for (int candidate : allowed) {
if (value == candidate) {
return;
}
}
StringBuilder options = new StringBuilder();
for (int candidate : allowed) {
if (options.length() > 0) {
options.append('、');
}
options.append(candidate);
}
throw new IllegalArgumentException(name + " 仅支持 " + options);
}
private static String backTypeText(Integer backType) {
if (backType == null) {
return null;
}
return switch (backType) {
case 0 -> "否";
case 1 -> "是";
default -> "未知(" + backType + ")";
};
}
private static String stateText(Integer state) {
if (state == null) {
return null;
}
return switch (state) {
case 0 -> "可用";
case 1 -> "待修";
case 2 -> "返修";
default -> "未知(" + state + ")";
};
}
private static String deviceTypeText(Integer deviceType) {
if (deviceType == null) {
return null;
}
return switch (deviceType) {
case 0 -> "厕纸机";
case 1 -> "擦手纸机";
default -> "未知(" + deviceType + ")";
};
}
private static String onlineStatusText(Integer status) {
if (status == null) {
return null;
}
return switch (status) {
case 1 -> "在线";
case 2 -> "故障";
case 3 -> "离线";
default -> "未知(" + status + ")";
};
}
}
File diff suppressed because it is too large Load Diff
@@ -1,57 +1,58 @@
# prd 环境:阿里云 RDS / Redis(拓扑沿用 xiaoqu-franchisee pom.xml prd profile)
# 敏感值一律走环境变量,不写明文、不入库;
# 服务器上由 /data/xiaoqu-agent-service/app.env 注入(deploy.sh 启动前 source)
# MCP 作用域-工具绑定:启动时幂等写入 scope_tool(只新增不删除)。
# 2026-10-21 用户授权:CRM 客户画像需要"用量(换纸/用纸)"与"设备统计"工具,
# 我们的同步 token 使用 sync 作用域,故绑定到 sync。
# 多条用 ; 分隔,同一绑定的多个工具用 , 分隔。
mcp:
scope-tool-bindings: ${MCP_SCOPE_TOOL_BINDINGS:sync=district.paper.statistics.query,district.paper.device_average.query,district.paper.trace.list.query,hardware.statistics.query}
app:
open:
api-key: ${OPEN_API_KEY}
# ak 明文 AES-GCM 加密密钥,prd 必须与 dev 不同值
token-cipher-key: ${TOKEN_CIPHER_KEY}
datasource:
m0: # 权限库 xiaoqu_complex(user/agent/authority 等)
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: ${SVC_DB_M0_URL}
username: ${SVC_DB_M0_USER}
password: ${SVC_DB_M0_PASSWORD}
m1: # 商城库 xiaoqu_mall(按需启用)
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: ${SVC_DB_M1_URL}
username: ${SVC_DB_M1_USER}
password: ${SVC_DB_M1_PASSWORD}
m2: # 业务库 xiaoqu_franchisee
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: ${SVC_DB_M2_URL}
username: ${SVC_DB_M2_USER}
password: ${SVC_DB_M2_PASSWORD}
svc: # 自有库 xiaoqu_agent_svc(token/scope/tool/audit,读写,Flyway 自动建表)
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: ${SVC_DB_SVC_URL}
username: ${SVC_DB_SVC_USER}
password: ${SVC_DB_SVC_PASSWORD}
# ES 双集群:cloud=云集群、local=本地化集群(hosts 支持逗号多节点)
es:
cloud:
hosts: ${SVC_ES_CLOUD_HOSTS}
port: ${SVC_ES_CLOUD_PORT:9200}
username: ${SVC_ES_CLOUD_USERNAME:}
password: ${SVC_ES_CLOUD_PASSWORD:}
local:
hosts: ${SVC_ES_LOCAL_HOSTS}
port: ${SVC_ES_LOCAL_PORT:9200}
username: ${SVC_ES_LOCAL_USERNAME:}
password: ${SVC_ES_LOCAL_PASSWORD:}
spring:
data:
redis:
host: ${SVC_REDIS_HOST}
port: ${SVC_REDIS_PORT:6379}
password: ${SVC_REDIS_PASSWORD}
database: ${SVC_REDIS_DB:5}
timeout: 5s
# prd 环境:阿里云 RDS / Redis(拓扑沿用 xiaoqu-franchisee pom.xml prd profile)
# 敏感值一律走环境变量,不写明文、不入库;
# 服务器上由 /data/xiaoqu-agent-service/app.env 注入(deploy.sh 启动前 source)
# MCP 作用域-工具绑定:启动时幂等写入 scope_tool(只新增不删除)。
# 2026-10-21 用户授权:CRM 客户画像需要"用量(换纸/用纸)"与"设备统计"工具,
# 我们的同步 token 使用 sync 作用域,故绑定到 sync。
# 2026-12-02 拍板:站点备用机列表只绑研发专用 scope 6(code=code)。
# 多条用 ; 分隔,同一绑定的多个工具用 , 分隔。
mcp:
scope-tool-bindings: ${MCP_SCOPE_TOOL_BINDINGS:sync=district.paper.statistics.query,district.paper.device_average.query,district.paper.trace.list.query,hardware.statistics.query;code=hardware.back.list.query}
app:
open:
api-key: ${OPEN_API_KEY}
# ak 明文 AES-GCM 加密密钥,prd 必须与 dev 不同值
token-cipher-key: ${TOKEN_CIPHER_KEY}
datasource:
m0: # 权限库 xiaoqu_complex(user/agent/authority 等)
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: ${SVC_DB_M0_URL}
username: ${SVC_DB_M0_USER}
password: ${SVC_DB_M0_PASSWORD}
m1: # 商城库 xiaoqu_mall(按需启用)
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: ${SVC_DB_M1_URL}
username: ${SVC_DB_M1_USER}
password: ${SVC_DB_M1_PASSWORD}
m2: # 业务库 xiaoqu_franchisee
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: ${SVC_DB_M2_URL}
username: ${SVC_DB_M2_USER}
password: ${SVC_DB_M2_PASSWORD}
svc: # 自有库 xiaoqu_agent_svc(token/scope/tool/audit,读写,Flyway 自动建表)
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: ${SVC_DB_SVC_URL}
username: ${SVC_DB_SVC_USER}
password: ${SVC_DB_SVC_PASSWORD}
# ES 双集群:cloud=云集群、local=本地化集群(hosts 支持逗号多节点)
es:
cloud:
hosts: ${SVC_ES_CLOUD_HOSTS}
port: ${SVC_ES_CLOUD_PORT:9200}
username: ${SVC_ES_CLOUD_USERNAME:}
password: ${SVC_ES_CLOUD_PASSWORD:}
local:
hosts: ${SVC_ES_LOCAL_HOSTS}
port: ${SVC_ES_LOCAL_PORT:9200}
username: ${SVC_ES_LOCAL_USERNAME:}
password: ${SVC_ES_LOCAL_PASSWORD:}
spring:
data:
redis:
host: ${SVC_REDIS_HOST}
port: ${SVC_REDIS_PORT:6379}
password: ${SVC_REDIS_PASSWORD}
database: ${SVC_REDIS_DB:5}
timeout: 5s
@@ -0,0 +1,192 @@
package me.iiv.agent.mcp.tool;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import me.iiv.agent.entity.m0.HardwareBack;
import me.iiv.agent.entity.m0.HardwareView;
import me.iiv.agent.entity.m0.User;
import me.iiv.agent.entity.svc.AgentApiKey;
import me.iiv.agent.mapper.m0.HardwareBackMapper;
import me.iiv.agent.mapper.m0.HardwareViewMapper;
import me.iiv.agent.mcp.McpErrorCode;
import me.iiv.agent.mcp.ToolCallException;
import me.iiv.agent.permission.PermissionService;
import me.iiv.agent.security.AuthContext;
import me.iiv.agent.security.AuthContextHolder;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import java.util.Date;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class HardwareBackToolsTest {
@Mock
HardwareBackMapper hardwareBackMapper;
@Mock
HardwareViewMapper hardwareViewMapper;
@Mock
PermissionService permissionService;
@Mock
StringRedisTemplate redisTemplate;
@Mock
ValueOperations<String, String> valueOperations;
HardwareBackTools tools;
@BeforeEach
void setUp() {
MapperBuilderAssistant assistant = new MapperBuilderAssistant(new MybatisConfiguration(), "");
TableInfoHelper.initTableInfo(assistant, HardwareBack.class);
TableInfoHelper.initTableInfo(assistant, HardwareView.class);
tools = new HardwareBackTools(hardwareBackMapper, hardwareViewMapper,
permissionService, redisTemplate);
User user = new User();
user.setId(7L);
AuthContextHolder.set(new AuthContext(null, user));
lenient().when(redisTemplate.opsForValue()).thenReturn(valueOperations);
}
@AfterEach
void tearDown() {
AuthContextHolder.clear();
}
@Test
void rejectsInvalidArgumentsBeforeQuerying() {
assertThrows(IllegalArgumentException.class,
() -> query(null, null, null, null, null, null));
assertThrows(IllegalArgumentException.class,
() -> query(0L, null, null, null, null, null));
assertThrows(IllegalArgumentException.class,
() -> query(9L, null, 2, null, null, null));
assertThrows(IllegalArgumentException.class,
() -> query(9L, null, null, 3, null, null));
assertThrows(IllegalArgumentException.class,
() -> query(null, " ", null, null, null, null));
verifyNoInteractions(hardwareBackMapper, hardwareViewMapper);
}
@Test
void rejectsMissingIdentity() {
AuthContextHolder.clear();
ToolCallException error = assertThrows(ToolCallException.class,
() -> query(9L, null, null, null, null, null));
assertEquals(McpErrorCode.UNAUTHENTICATED, error.getCode());
verifyNoInteractions(hardwareBackMapper, hardwareViewMapper);
}
@Test
void appliesRowFilterAndBuildsPagedResult() {
when(hardwareBackMapper.selectCount(any())).thenReturn(2L);
when(hardwareBackMapper.selectList(any())).thenReturn(List.of(
back(2L, "SN002", 1, 0, 1, 12L),
back(1L, "SN001", 1, 1, 0, 12L)));
when(hardwareViewMapper.selectList(any())).thenReturn(List.of(view("SN002", 1)));
when(valueOperations.multiGet(anyList())).thenReturn(List.of("测试站点"));
Map<String, Object> result = query(9L, null, null, null, 1, 20);
assertEquals(2L, result.get("total"));
assertEquals(1, result.get("page"));
assertEquals(20, result.get("rows"));
List<Map<String, Object>> records = records(result);
Map<String, Object> first = records.get(0);
assertEquals("SN002", first.get("snCode"));
assertEquals("是", first.get("backTypeText"));
assertEquals("可用", first.get("stateText"));
assertEquals("擦手纸机", first.get("deviceTypeText"));
assertEquals("测试站点", first.get("districtName"));
assertEquals(1, first.get("onlineStatus"));
assertEquals("在线", first.get("onlineStatusText"));
Map<String, Object> second = records.get(1);
assertEquals("待修", second.get("stateText"));
assertEquals("厕纸机", second.get("deviceTypeText"));
assertNull(second.get("onlineStatus"));
assertNull(second.get("onlineStatusText"));
assertTrue(result.get("notice").toString().contains("无记录"));
User user = (User) AuthContextHolder.get().getUser();
verify(permissionService).applyHardwareBackRowFilter(any(), eq(user));
}
@Test
void queriesBySnCodeOnlyAndTruncatesRows() {
when(hardwareBackMapper.selectCount(any())).thenReturn(0L);
when(hardwareBackMapper.selectList(any())).thenReturn(List.of());
Map<String, Object> result = query(null, "SN00", null, null, null, 500);
assertEquals(0L, result.get("total"));
assertEquals(100, result.get("rows"));
assertTrue(result.get("notice").toString().contains("截断为 100"));
assertTrue(records(result).isEmpty());
}
@Test
void allowsServicePrincipal() {
AgentApiKey serviceToken = new AgentApiKey();
serviceToken.setPrincipalType(AgentApiKey.PRINCIPAL_TYPE_SERVICE);
AuthContextHolder.set(new AuthContext(serviceToken, null));
when(hardwareBackMapper.selectCount(any())).thenReturn(0L);
when(hardwareBackMapper.selectList(any())).thenReturn(List.of());
Map<String, Object> result = query(9L, null, null, null, null, null);
assertEquals(0L, result.get("total"));
verify(permissionService).applyHardwareBackRowFilter(any(), eq(null));
}
private Map<String, Object> query(Long districtId, String snCode, Integer deviceType,
Integer state, Integer page, Integer rows) {
return tools.hardwareBackListQuery(districtId, snCode, deviceType, state, page, rows);
}
private static HardwareBack back(Long id, String snCode, Integer backType, Integer state,
Integer deviceType, Long districtId) {
HardwareBack back = new HardwareBack();
back.setId(id);
back.setSnCode(snCode);
back.setBackType(backType);
back.setState(state);
back.setDeviceType(deviceType);
back.setDistrictId(districtId);
back.setCreateTime(new Date());
return back;
}
private static HardwareView view(String snCode, Integer status) {
HardwareView view = new HardwareView();
view.setSnCode(snCode);
view.setStatus(status);
return view;
}
@SuppressWarnings("unchecked")
private static List<Map<String, Object>> records(Map<String, Object> result) {
return (List<Map<String, Object>>) result.get("records");
}
}