feat(mcp): 新增出纸机查询工具 hardware.list/detail.query (REQ-20260910-0012)

This commit is contained in:
xiaoqu
2026-09-10 15:27:14 +08:00
parent 812c8e87f4
commit ff452d89d8
10 changed files with 1454 additions and 12 deletions
@@ -0,0 +1,283 @@
package me.iiv.agent.mcp.tool;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import me.iiv.agent.entity.m0.DistrictDistrictStrategy;
import me.iiv.agent.entity.m0.HardwareView;
import me.iiv.agent.entity.m0.Networkcard;
import me.iiv.agent.entity.m0.User;
import me.iiv.agent.mapper.m0.DistrictDistrictStrategyMapper;
import me.iiv.agent.mapper.m0.HardwareViewMapper;
import me.iiv.agent.mapper.m0.NetworkcardMapper;
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.ArgumentCaptor;
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.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
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.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class HardwareToolsTest {
@Mock
HardwareViewMapper hardwareViewMapper;
@Mock
NetworkcardMapper networkcardMapper;
@Mock
DistrictDistrictStrategyMapper districtMapper;
@Mock
PermissionService permissionService;
@Mock
StringRedisTemplate redisTemplate;
HardwareTools tools;
User user;
@BeforeEach
void setUp() {
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
HardwareView.class);
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
Networkcard.class);
tools = new HardwareTools(hardwareViewMapper, networkcardMapper, districtMapper,
permissionService, redisTemplate);
user = new User();
user.setId(7L);
AuthContextHolder.set(new AuthContext(null, user));
}
@AfterEach
void tearDown() {
AuthContextHolder.clear();
}
@Test
@SuppressWarnings("unchecked")
void listBuildsLegacyFiltersAndTruncatesRows() {
HardwareView hardware = new HardwareView();
hardware.setId(9L);
hardware.setSnCode("D2AB001");
hardware.setAgentId(12L);
hardware.setPropertyId(11L);
hardware.setDistrictId(5L);
hardware.setImsi("460001234567890");
when(hardwareViewMapper.selectCount(any())).thenReturn(1L);
when(hardwareViewMapper.selectList(any())).thenReturn(List.of(hardware));
ValueOperations<String, String> valueOperations = mock(ValueOperations.class);
when(redisTemplate.opsForValue()).thenReturn(valueOperations);
// name:Agent:12 / name:Properyt:11 / name:District:5 / Assignment:D2AB001:29
when(valueOperations.multiGet(anyList())).thenAnswer(invocation -> {
List<String> keys = invocation.getArgument(0);
return keys.stream().map(key -> switch (key) {
case "name:Agent:12" -> "测试代理";
case "name:Properyt:11" -> "测试物业";
case "name:District:5" -> "测试站点";
case "Assignment:D2AB001:29" -> "1";
default -> null;
}).collect(Collectors.toList());
});
Networkcard card = new Networkcard();
card.setImsi("460001234567890");
card.setFactoryType(1);
card.setCarrier("移动");
card.setDataBalance(new BigDecimal("512.5"));
card.setDataUsage(new BigDecimal("128.0"));
card.setIccid("8986001234");
card.setMsisdn("14412345678");
when(networkcardMapper.selectList(any())).thenReturn(List.of(card));
Map<String, Object> result = tools.hardwareListQuery(
"D2AB", 0, 1, 1, 0, 12L, 11L, 5L, 3L, "3F", "460001234567890", 1, 500);
assertEquals(1, result.get("page"));
assertEquals(100, result.get("rows"));
assertEquals("rows 超过上限 100,已截断为 100", result.get("notice"));
// 过滤拼装与老接口一一对应
ArgumentCaptor<LambdaQueryWrapper<HardwareView>> captor = ArgumentCaptor.forClass(LambdaQueryWrapper.class);
verify(hardwareViewMapper).selectList(captor.capture());
String sql = captor.getValue().getSqlSegment();
assertTrue(sql.contains("sn_code LIKE"));
assertTrue(sql.contains("device_type ="));
assertTrue(sql.contains("status ="));
assertTrue(sql.contains("online ="));
assertTrue(sql.contains("lock_machine_state ="));
assertTrue(sql.contains("agent_id ="));
assertTrue(sql.contains("property_id ="));
assertTrue(sql.contains("district_id ="));
assertTrue(sql.contains("building_id ="));
assertTrue(sql.contains("floor ="));
assertTrue(sql.contains("imsi ="));
assertTrue(sql.contains("soft_delete ="));
assertTrue(captor.getValue().getSqlSegment().contains("ORDER BY id DESC"));
verify(permissionService).applyHardwareRowFilter(any(), any());
// 富化:名称、断纸状态、物联网卡
Map<String, Object> record = ((List<Map<String, Object>>) result.get("records")).get(0);
assertEquals("测试代理", record.get("agentName"));
assertEquals("测试物业", record.get("propertyName"));
assertEquals("测试站点", record.get("districtName"));
assertEquals(1, record.get("piStatus"));
assertEquals(1, record.get("factoryType"));
assertEquals("移动", record.get("carrier"));
assertEquals(new BigDecimal("512.5"), record.get("dataBalance"));
assertEquals(new BigDecimal("128.0"), record.get("dataUsage"));
assertEquals("8986001234", record.get("iccid"));
assertEquals("14412345678", record.get("msisdn"));
}
@Test
@SuppressWarnings("unchecked")
void listDefaultsPiStatusToZeroWhenAssignmentKeyMissing() {
HardwareView hardware = new HardwareView();
hardware.setId(9L);
hardware.setSnCode("D2AB002");
when(hardwareViewMapper.selectCount(any())).thenReturn(1L);
when(hardwareViewMapper.selectList(any())).thenReturn(List.of(hardware));
ValueOperations<String, String> valueOperations = mock(ValueOperations.class);
when(redisTemplate.opsForValue()).thenReturn(valueOperations);
when(valueOperations.multiGet(anyList())).thenReturn(List.of());
Map<String, Object> result = tools.hardwareListQuery(
null, null, null, null, null, null, null, null, null, null, null, 1, 20);
Map<String, Object> record = ((List<Map<String, Object>>) result.get("records")).get(0);
assertEquals(0, record.get("piStatus"));
assertNull(record.get("agentName"));
// 无 imsi 不查物联网卡
verify(networkcardMapper, never()).selectList(any());
}
@Test
void detailRequiresSnCodeOrId() {
assertThrows(IllegalArgumentException.class, () -> tools.hardwareDetailQuery(null, null));
assertThrows(IllegalArgumentException.class, () -> tools.hardwareDetailQuery(" ", 0L));
verifyNoInteractions(hardwareViewMapper);
}
@Test
void detailReturnsNullRecordWithNoticeWhenMissingOrUnauthorized() {
when(hardwareViewMapper.selectOne(any())).thenReturn(null);
Map<String, Object> result = tools.hardwareDetailQuery("D2AB404", null);
assertNull(result.get("record"));
assertEquals("设备不存在或无权访问", result.get("notice"));
verify(permissionService).applyHardwareRowFilter(any(), any());
}
@Test
@SuppressWarnings("unchecked")
void detailBySnCodeReturnsFullRecordWithSiteAndEnrichment() {
HardwareView hardware = new HardwareView();
hardware.setId(9L);
hardware.setSnCode("D2AB001");
hardware.setDeviceType(0);
hardware.setStatus(1);
hardware.setOnline(1);
hardware.setLockMachineState(0);
hardware.setSysversion("v1.2.3");
hardware.setFirmwareVersion("hw-9");
hardware.setImsi("460001234567890");
hardware.setDistrictId(5L);
hardware.setBuildingId(3L);
hardware.setFloor("3F");
when(hardwareViewMapper.selectOne(any())).thenReturn(hardware);
ValueOperations<String, String> valueOperations = mock(ValueOperations.class);
when(redisTemplate.opsForValue()).thenReturn(valueOperations);
when(valueOperations.multiGet(anyList())).thenReturn(List.of());
when(networkcardMapper.selectList(any())).thenReturn(List.of());
DistrictDistrictStrategy district = new DistrictDistrictStrategy();
district.setId(5L);
district.setDistrictName("测试站点");
district.setProvince("广东省");
district.setCity("深圳市");
district.setCountyseat("南山区");
district.setAddress("科技园");
district.setContact("张三");
district.setPhone("13800000000");
when(districtMapper.selectById(5L)).thenReturn(district);
Map<String, Object> result = tools.hardwareDetailQuery("D2AB001", null);
Map<String, Object> record = (Map<String, Object>) result.get("record");
assertEquals("D2AB001", record.get("snCode"));
assertEquals(0, record.get("deviceType"));
assertEquals(1, record.get("status"));
assertEquals(1, record.get("online"));
assertEquals(0, record.get("lockMachineState"));
assertEquals("v1.2.3", record.get("sysversion"));
assertEquals("hw-9", record.get("firmwareVersion"));
assertEquals(0, record.get("piStatus"));
Map<String, Object> site = (Map<String, Object>) record.get("site");
assertEquals(5L, site.get("districtId"));
assertEquals("测试站点", site.get("districtName"));
assertEquals("广东省", site.get("province"));
assertEquals("深圳市", site.get("city"));
assertEquals("南山区", site.get("countyseat"));
assertEquals("科技园", site.get("address"));
assertEquals("张三", site.get("contact"));
assertEquals("13800000000", site.get("phone"));
assertEquals(3L, site.get("buildingId"));
assertEquals("3F", site.get("floor"));
}
@Test
void listRejectsUnknownEnumsBeforeQuerying() {
assertThrows(IllegalArgumentException.class, () -> tools.hardwareListQuery(
null, 2, null, null, null, null, null, null, null, null, null, 1, 20));
assertThrows(IllegalArgumentException.class, () -> tools.hardwareListQuery(
null, null, 0, null, null, null, null, null, null, null, null, 1, 20));
assertThrows(IllegalArgumentException.class, () -> tools.hardwareListQuery(
null, null, null, 3, null, null, null, null, null, null, null, 1, 20));
assertThrows(IllegalArgumentException.class, () -> tools.hardwareListQuery(
null, null, null, null, 2, null, null, null, null, null, null, 1, 20));
verifyNoInteractions(hardwareViewMapper);
}
@Test
void springAiPublishesBothReviewedToolSchemas() {
var callbacks = org.springframework.ai.tool.method.MethodToolCallbackProvider.builder()
.toolObjects(tools).build().getToolCallbacks();
Map<String, String> schemas = Arrays.stream(callbacks).collect(Collectors.toMap(
callback -> callback.getToolDefinition().name(),
callback -> callback.getToolDefinition().inputSchema()));
assertEquals(2, schemas.size());
assertTrue(schemas.containsKey("hardware.list.query"));
assertTrue(schemas.containsKey("hardware.detail.query"));
assertTrue(schemas.get("hardware.list.query").contains("lockMachineState"));
assertTrue(schemas.get("hardware.detail.query").contains("snCode"));
}
}
@@ -0,0 +1,197 @@
package me.iiv.agent.permission;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import me.iiv.agent.entity.m0.Agent;
import me.iiv.agent.entity.m0.AgentManageDistrictAuth;
import me.iiv.agent.entity.m0.Authority;
import me.iiv.agent.entity.m0.HardwareView;
import me.iiv.agent.entity.m0.Properyt;
import me.iiv.agent.entity.m0.User;
import me.iiv.agent.entity.m2.WarehouseAgentAuth;
import me.iiv.agent.mapper.m0.AgentManageDistrictAuthMapper;
import me.iiv.agent.mapper.m0.AgentMapper;
import me.iiv.agent.mapper.m0.AuthorityMapper;
import me.iiv.agent.mapper.m0.ProperytMapper;
import me.iiv.agent.mapper.m2.WarehouseAgentAuthMapper;
import org.apache.ibatis.builder.MapperBuilderAssistant;
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.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.util.Collection;
import java.util.List;
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.any;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/** PermissionService.applyHardwareRowFilter 直接单测:hardware_view 行级权限各分支(与站点同一 getByIsAgent 变体)。 */
@ExtendWith(MockitoExtension.class)
class PermissionServiceHardwareRowFilterTest {
@Mock
AuthorityMapper authorityMapper;
@Mock
AgentMapper agentMapper;
@Mock
WarehouseAgentAuthMapper warehouseAgentAuthMapper;
@Mock
AgentManageDistrictAuthMapper agentManageDistrictAuthMapper;
@Mock
ProperytMapper properytMapper;
@Mock
StringRedisTemplate redisTemplate;
@Mock
HashOperations<String, Object, Object> hashOperations;
PermissionService permissionService;
@BeforeEach
void setUp() {
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
HardwareView.class);
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
Properyt.class);
permissionService = new PermissionService(authorityMapper, agentMapper,
warehouseAgentAuthMapper, agentManageDistrictAuthMapper, properytMapper, redisTemplate);
}
@Test
void headquartersHardwareFilterAddsNoBoundary() {
User user = user(46L, 1L, null);
when(authorityMapper.selectById(1L)).thenReturn(authority(1L, 0));
LambdaQueryWrapper<HardwareView> wrapper = new LambdaQueryWrapper<>();
permissionService.applyHardwareRowFilter(wrapper, user);
assertTrue(wrapper.getSqlSegment().isBlank());
}
@Test
void agentHardwareFilterUsesSelfSubordinateAndManagedAgents() {
User user = user(1000L, 108L, 1L);
when(authorityMapper.selectById(108L)).thenReturn(authority(108L, 1));
Agent subordinate = new Agent();
subordinate.setId(2L);
when(agentMapper.selectList(any())).thenReturn(List.of(subordinate));
WarehouseAgentAuth managedAuth = new WarehouseAgentAuth();
managedAuth.setManagerAgentId(3L);
when(warehouseAgentAuthMapper.selectList(any())).thenReturn(List.of(managedAuth));
when(agentManageDistrictAuthMapper.selectList(any())).thenReturn(List.of());
LambdaQueryWrapper<HardwareView> wrapper = new LambdaQueryWrapper<>();
permissionService.applyHardwareRowFilter(wrapper, user);
String sql = wrapper.getSqlSegment();
Collection<Object> values = wrapper.getParamNameValuePairs().values();
assertTrue(sql.contains("agent_id IN"));
assertFalse(sql.contains("property_id"));
assertTrue(values.contains(1L));
assertTrue(values.contains(2L));
assertTrue(values.contains(3L));
}
@Test
void agentHardwareFilterAddsManagedPropertyOrBranch() {
User user = user(1000L, 108L, 1L);
when(authorityMapper.selectById(108L)).thenReturn(authority(108L, 1));
when(agentMapper.selectList(any())).thenReturn(List.of());
when(warehouseAgentAuthMapper.selectList(any())).thenReturn(List.of());
AgentManageDistrictAuth districtAuth = new AgentManageDistrictAuth();
districtAuth.setPropertyId(44L);
when(agentManageDistrictAuthMapper.selectList(any())).thenReturn(List.of(districtAuth));
LambdaQueryWrapper<HardwareView> wrapper = new LambdaQueryWrapper<>();
permissionService.applyHardwareRowFilter(wrapper, user);
String sql = wrapper.getSqlSegment();
Collection<Object> values = wrapper.getParamNameValuePairs().values();
assertTrue(sql.contains("agent_id IN"));
assertTrue(sql.contains("property_id IN"));
assertTrue(sql.contains("OR"));
assertTrue(values.contains(1L));
assertTrue(values.contains(44L));
}
@Test
void salesNonLeaderHardwareFilterUsesOwnCreatedPropertyIds() {
User user = user(1000L, 108L, 1L);
user.setDeptId(5L);
user.setPostId(7L);
when(authorityMapper.selectById(108L)).thenReturn(authority(108L, 1));
when(agentMapper.selectList(any())).thenReturn(List.of());
when(warehouseAgentAuthMapper.selectList(any())).thenReturn(List.of());
when(redisTemplate.opsForHash()).thenReturn(hashOperations);
when(hashOperations.get("Dictionary", "authDeptId")).thenReturn(",5,");
when(hashOperations.get("Dictionary", "authDeptPostId")).thenReturn("8,");
Properyt property = new Properyt();
property.setId(55L);
when(properytMapper.selectList(any())).thenReturn(List.of(property));
LambdaQueryWrapper<HardwareView> wrapper = new LambdaQueryWrapper<>();
permissionService.applyHardwareRowFilter(wrapper, user);
String sql = wrapper.getSqlSegment();
assertTrue(sql.contains("property_id IN"));
assertFalse(sql.contains("agent_id"));
assertTrue(wrapper.getParamNameValuePairs().values().contains(55L));
verifyNoInteractions(agentManageDistrictAuthMapper);
}
@Test
void salesNonLeaderWithoutVisiblePropertiesFiltersToZero() {
User user = user(1000L, 108L, 1L);
user.setDeptId(5L);
user.setPostId(7L);
when(authorityMapper.selectById(108L)).thenReturn(authority(108L, 1));
when(agentMapper.selectList(any())).thenReturn(List.of());
when(warehouseAgentAuthMapper.selectList(any())).thenReturn(List.of());
when(redisTemplate.opsForHash()).thenReturn(hashOperations);
when(hashOperations.get("Dictionary", "authDeptId")).thenReturn(",5,");
when(hashOperations.get("Dictionary", "authDeptPostId")).thenReturn("8,");
when(properytMapper.selectList(any())).thenReturn(List.of());
LambdaQueryWrapper<HardwareView> wrapper = new LambdaQueryWrapper<>();
permissionService.applyHardwareRowFilter(wrapper, user);
String sql = wrapper.getSqlSegment();
assertTrue(sql.contains("property_id IN"));
assertFalse(sql.contains("agent_id"));
assertTrue(wrapper.getParamNameValuePairs().values().contains(0L));
verifyNoInteractions(agentManageDistrictAuthMapper);
}
@Test
void agentUserWithoutAgentIdIsDeniedForHardwareFilter() {
User user = user(1000L, 108L, null);
when(authorityMapper.selectById(108L)).thenReturn(authority(108L, 1));
assertThrows(IllegalStateException.class,
() -> permissionService.applyHardwareRowFilter(new LambdaQueryWrapper<>(), user));
}
private static Authority authority(Long id, int isAgent) {
Authority authority = new Authority();
authority.setId(id);
authority.setIsagent(isAgent);
authority.setSoftDelete(0);
return authority;
}
private static User user(Long id, Long authorityId, Long agentId) {
User user = new User();
user.setId(id);
user.setAuthorityId(authorityId);
user.setAgentId(agentId);
return user;
}
}